コード例 #1
0
        public async Task ReadAsStreamAsync_ReadWithCancelableToken_MatchesInput(bool useArray)
        {
            const int ContentLength = 100;

            Memory <byte>         memory;
            OwnedMemory <byte>    ownedMemory;
            ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);

            var buffer = new byte[1];
            var cts    = new CancellationTokenSource();
            int bytesRead;

            using (Stream stream = await content.ReadAsStreamAsync())
            {
                for (int i = 0; i < ContentLength; i++)
                {
                    switch (i % 2)
                    {
                    case 0:
                        bytesRead = await stream.ReadAsync(buffer, 0, 1, cts.Token);

                        break;

                    default:
                        bytesRead = await stream.ReadAsync(new Memory <byte>(buffer), cts.Token);

                        break;
                    }
                    Assert.Equal(1, bytesRead);
                    Assert.Equal(memory.Span[i], buffer[0]);
                }
            }

            ownedMemory?.Dispose();
        }
        public async Task ReadAsStreamAsync_Seek(bool useArray, bool readStreamAsync)
        {
            const int     ContentLength = 42;
            Memory <byte> memory;

            using (ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out IMemoryOwner <byte> memoryOwner))
            {
                using (Stream s = await content.ReadAsStreamAsync(readStreamAsync))
                {
                    foreach (int pos in new[] { 0, ContentLength / 2, ContentLength - 1 })
                    {
                        s.Position = pos;
                        Assert.Equal(pos, s.Position);
                        Assert.Equal(memory.Span[pos], s.ReadByte());
                    }

                    foreach (int pos in new[] { 0, ContentLength / 2, ContentLength - 1 })
                    {
                        Assert.Equal(0, s.Seek(0, SeekOrigin.Begin));
                        Assert.Equal(memory.Span[0], s.ReadByte());
                    }

                    Assert.Equal(ContentLength, s.Seek(0, SeekOrigin.End));
                    Assert.Equal(s.Position, s.Length);
                    Assert.Equal(-1, s.ReadByte());

                    Assert.Equal(0, s.Seek(-ContentLength, SeekOrigin.End));
                    Assert.Equal(0, s.Position);
                    Assert.Equal(memory.Span[0], s.ReadByte());

                    s.Position = 0;
                    Assert.Equal(0, s.Seek(0, SeekOrigin.Current));
                    Assert.Equal(0, s.Position);

                    Assert.Equal(1, s.Seek(1, SeekOrigin.Current));
                    Assert.Equal(1, s.Position);
                    Assert.Equal(memory.Span[1], s.ReadByte());
                    Assert.Equal(2, s.Position);
                    Assert.Equal(3, s.Seek(1, SeekOrigin.Current));
                    Assert.Equal(1, s.Seek(-2, SeekOrigin.Current));

                    Assert.Equal(int.MaxValue, s.Seek(int.MaxValue, SeekOrigin.Begin));
                    Assert.Equal(int.MaxValue, s.Position);
                    Assert.Equal(int.MaxValue, s.Seek(0, SeekOrigin.Current));
                    Assert.Equal(int.MaxValue, s.Position);
                    Assert.Equal(int.MaxValue, s.Seek(int.MaxValue - ContentLength, SeekOrigin.End));
                    Assert.Equal(int.MaxValue, s.Position);
                    Assert.Equal(-1, s.ReadByte());
                    Assert.Equal(int.MaxValue, s.Position);

                    Assert.Throws <ArgumentOutOfRangeException>("value", () => s.Position = -1);
                    Assert.Throws <IOException>(() => s.Seek(-1, SeekOrigin.Begin));

                    AssertExtensions.Throws <ArgumentOutOfRangeException>("value", () => s.Position = (long)int.MaxValue + 1);
                    AssertExtensions.Throws <ArgumentOutOfRangeException>("offset", () => s.Seek((long)int.MaxValue + 1, SeekOrigin.Begin));

                    Assert.ThrowsAny <ArgumentException>(() => s.Seek(0, (SeekOrigin)42));
                }
            }
        }
コード例 #3
0
        public async Task <IEnumerable <Face> > DetectFaces(ReadOnlyMemory <byte> sourcePhoto)
        {
            // Request parameters
            var queryString = HttpUtility.ParseQueryString(string.Empty);

            queryString["returnFaceAttributes"] = "age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";
            queryString["recognitionModel"]     = "recognition_02";

            // Request body
            using var content           = new ReadOnlyMemoryContent(sourcePhoto);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            using var response = await _httpClient.PostAsync("/face/v1.0/detect?" + queryString, content);

            if (response.StatusCode == HttpStatusCode.BadRequest)
            {
                var errorResponse = await response.Content.ReadAsAsync <ErrorResponse>();

                throw new FaceApiException(errorResponse);
            }

            response.EnsureSuccessStatusCode();

            return(await response.Content.ReadAsAsync <IEnumerable <Face> >());
        }
コード例 #4
0
ファイル: JsonRequestContent.cs プロジェクト: Anu6is/Disqord
        public static HttpContent PrepareFor(object obj, IJsonSerializer serializer, RestRequestOptions options)
        {
            Dictionary <string, object> additionalFields = null;

            if (options != null)
            {
                if (options.Password != null || options.MfaCode != null)
                {
                    additionalFields = new Dictionary <string, object>(2);
                    if (options.Password != null)
                    {
                        additionalFields.Add("password", options.Password);
                    }

                    if (options.MfaCode != null)
                    {
                        additionalFields.Add("code", options.MfaCode);
                    }
                }
            }

            var bytes = serializer.Serialize(obj, additionalFields);

#if DEBUG
            System.Console.WriteLine(Encoding.UTF8.GetString(bytes.Span));
#endif
            var content = new ReadOnlyMemoryContent(bytes);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json")
            {
                CharSet = Encoding.UTF8.WebName
            };
            return(content);
        }
コード例 #5
0
        public async Task ReadAsStreamAsync_CopyTo_InvalidArguments(bool useArray)
        {
            const int             ContentLength = 42;
            Memory <byte>         memory;
            OwnedMemory <byte>    ownedMemory;
            ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);

            using (Stream s = await content.ReadAsStreamAsync())
            {
                AssertExtensions.Throws <ArgumentNullException>("destination", () => s.CopyTo(null));
                AssertExtensions.Throws <ArgumentNullException>("destination", () => { s.CopyToAsync(null); });

                AssertExtensions.Throws <ArgumentOutOfRangeException>("bufferSize", () => s.CopyTo(new MemoryStream(), 0));
                AssertExtensions.Throws <ArgumentOutOfRangeException>("bufferSize", () => { s.CopyToAsync(new MemoryStream(), 0); });

                Assert.Throws <NotSupportedException>(() => s.CopyTo(new MemoryStream(new byte[1], writable: false)));
                Assert.Throws <NotSupportedException>(() => { s.CopyToAsync(new MemoryStream(new byte[1], writable: false)); });

                var disposedDestination = new MemoryStream();
                disposedDestination.Dispose();
                Assert.Throws <ObjectDisposedException>(() => s.CopyTo(disposedDestination));
                Assert.Throws <ObjectDisposedException>(() => { s.CopyToAsync(disposedDestination); });
            }

            ownedMemory?.Dispose();
        }
コード例 #6
0
        public HttpContent CreateHttpContent()
        {
            var httpContent = new ReadOnlyMemoryContent(this.bytes);

            httpContent.Headers.ContentType = MediaTypeHeaderValue;
            return(httpContent);
        }
コード例 #7
0
        public async Task ReadAsStreamAsync_TrivialMembersHaveExpectedValuesAndBehavior(bool useArray)
        {
            const int             ContentLength = 42;
            Memory <byte>         memory;
            OwnedMemory <byte>    ownedMemory;
            ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);

            using (Stream stream = await content.ReadAsStreamAsync())
            {
                // property values
                Assert.Equal(ContentLength, stream.Length);
                Assert.Equal(0, stream.Position);
                Assert.True(stream.CanRead);
                Assert.True(stream.CanSeek);
                Assert.False(stream.CanWrite);

                // not supported
                Assert.Throws <NotSupportedException>(() => stream.SetLength(12345));
                Assert.Throws <NotSupportedException>(() => stream.WriteByte(0));
                Assert.Throws <NotSupportedException>(() => stream.Write(new byte[1], 0, 1));
                Assert.Throws <NotSupportedException>(() => stream.Write(new ReadOnlySpan <byte>(new byte[1])));
                await Assert.ThrowsAsync <NotSupportedException>(() => stream.WriteAsync(new byte[1], 0, 1));

                await Assert.ThrowsAsync <NotSupportedException>(() => stream.WriteAsync(new ReadOnlyMemory <byte>(new byte[1])));

                // nops
                stream.Flush();
                await stream.FlushAsync();
            }

            ownedMemory?.Dispose();
        }
コード例 #8
0
        public async Task ReadAsStreamAsync_Read_InvalidArguments(bool useArray)
        {
            const int             ContentLength = 42;
            Memory <byte>         memory;
            OwnedMemory <byte>    ownedMemory;
            ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);

            using (Stream stream = await content.ReadAsStreamAsync())
            {
                AssertExtensions.Throws <ArgumentNullException>("buffer", () => stream.Read(null, 0, 0));
                AssertExtensions.Throws <ArgumentNullException>("buffer", () => { stream.ReadAsync(null, 0, 0); });

                AssertExtensions.Throws <ArgumentOutOfRangeException>("offset", () => stream.Read(new byte[1], -1, 1));
                AssertExtensions.Throws <ArgumentOutOfRangeException>("offset", () => stream.Read(new byte[1], -1, 1));

                AssertExtensions.Throws <ArgumentOutOfRangeException>("count", () => stream.Read(new byte[1], 0, -1));
                AssertExtensions.Throws <ArgumentOutOfRangeException>("count", () => stream.Read(new byte[1], 0, -1));

                Assert.ThrowsAny <ArgumentException>(() => { stream.ReadAsync(new byte[1], 2, 0); });
                Assert.ThrowsAny <ArgumentException>(() => { stream.ReadAsync(new byte[1], 2, 0); });
                Assert.ThrowsAny <ArgumentException>(() => { stream.ReadAsync(new byte[1], 0, 2); });
                Assert.ThrowsAny <ArgumentException>(() => { stream.ReadAsync(new byte[1], 0, 2); });
            }

            ownedMemory?.Dispose();
        }
コード例 #9
0
 public void ContentLength_LengthMatchesArrayLength(int contentLength, bool useArray)
 {
     using (ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out _, out IMemoryOwner <byte> memoryOwner))
         using (memoryOwner)
         {
             Assert.Equal(contentLength, content.Headers.ContentLength);
         }
 }
コード例 #10
0
        public void ContentLength_LengthMatchesArrayLength(int contentLength, bool useArray)
        {
            Memory <byte> memory;

            using (ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out memory, out MemoryManager <byte> ownedMemory))
            {
                Assert.Equal(contentLength, content.Headers.ContentLength);
            }
        }
コード例 #11
0
        public void ContentLength_LengthMatchesArrayLength(int contentLength, bool useArray)
        {
            Memory <byte>         memory;
            OwnedMemory <byte>    ownedMemory;
            ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out memory, out ownedMemory);

            Assert.Equal(contentLength, content.Headers.ContentLength);

            ownedMemory?.Dispose();
        }
コード例 #12
0
        public async Task CopyToAsync_AllContentCopied(int contentLength, bool useArray)
        {
            using (ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out Memory <byte> memory, out IMemoryOwner <byte> memoryOwner))
                using (memoryOwner)
                {
                    var destination = new MemoryStream();
                    await content.CopyToAsync(destination);

                    Assert.Equal <byte>(memory.ToArray(), destination.ToArray());
                }
        }
コード例 #13
0
        public async Task <Rfc3161TimestampToken> GetAndSetRfc3161Timestamp(SignedCms signedData, Uri timeStampAuthorityUri)
        {
            if (timeStampAuthorityUri == null)
            {
                throw new ArgumentNullException(nameof(timeStampAuthorityUri));
            }

            // This example figures out which signer is new by it being "the only signer"
            if (signedData.SignerInfos.Count > 1)
            {
                throw new ArgumentException(Resources.TooManySignInfos, nameof(signedData));
            }

            var newSignerInfo = signedData.SignerInfos[0];

            byte[] nonce = new byte[8];

            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(nonce);
            }

            var request = Rfc3161TimestampRequest.CreateFromSignerInfo(
                newSignerInfo,
                HashAlgorithmName.SHA384,
                requestSignerCertificates: true,
                nonce: nonce);

            var client  = _httpClientFunc.Invoke();
            var content = new ReadOnlyMemoryContent(request.Encode());

            content.Headers.ContentType = new MediaTypeHeaderValue("application/timestamp-query");
            var httpResponse = await client.PostAsync(timeStampAuthorityUri, content).ConfigureAwait(false);

            if (!httpResponse.IsSuccessStatusCode)
            {
                throw new SignClientException(
                          $"There was a error from the timestamp authority. It responded with {httpResponse.StatusCode} {(int)httpResponse.StatusCode}");
            }

            if (httpResponse.Content.Headers.ContentType.MediaType != "application/timestamp-reply")
            {
                throw new SignClientException(Resources.InvalidTimestampReply);
            }

            var data = await httpResponse.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

            var timestampToken = request.ProcessResponse(data, out _);

            newSignerInfo.UnsignedAttributes.Add(new AsnEncodedData(CertificateHelper.SignatureTimeStampOin, timestampToken.AsSignedCms().Encode()));

            return(timestampToken);
        }
コード例 #14
0
    public static async Task <byte[]> SignWithRfc3161(byte[] bytesToSign, bool isDetached, X509Certificate2 certificate, Uri timeStampAuthorityUri)
    {
        // Sign our contents.
        var contentInfo = new ContentInfo(bytesToSign);
        var cms         = new SignedCms(contentInfo, isDetached);
        var signer      = new CmsSigner(certificate); // { IncludeOption = X509IncludeOption.WholeChain }; //X509IncludeOption.EndCertOnly;

        signer.SignedAttributes.Add(new Pkcs9SigningTime());

        cms.ComputeSignature(signer, false);

        // Generate our nonce
        byte[] nonce = new byte[8];

        using (var rng = RandomNumberGenerator.Create())
        {
            rng.GetBytes(nonce);
        }

        // Get our signing information and create the RFC3161 request
        SignerInfo newSignerInfo = cms.SignerInfos[0];

        // Now we generate our request for us to send to our RFC3161 signing authority.
        Rfc3161TimestampRequest request = Rfc3161TimestampRequest.CreateFromSignerInfo(newSignerInfo, HashAlgorithmName.SHA256, requestSignerCertificates: true, nonce: nonce);

        // You can use your own web request system, in this example we are just going to use a `HttpClient` class.
        var client  = new HttpClient();
        var content = new ReadOnlyMemoryContent(request.Encode());

        content.Headers.ContentType = new MediaTypeHeaderValue("application/timestamp-query");
        var httpResponse = await client.PostAsync(timeStampAuthorityUri, content).ConfigureAwait(false);

        // Process our response
        if (!httpResponse.IsSuccessStatusCode)
        {
            throw new CryptographicException("There was a error from the timestamp authority. It responded with {httpResponse.StatusCode} {(int)httpResponse.StatusCode}: {httpResponse.Content}");
        }

        if (httpResponse.Content.Headers.ContentType.MediaType != "application/timestamp-reply")
        {
            throw new CryptographicException("The reply from the time stamp server was in a invalid format.");
        }

        var data = await httpResponse.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

        var timestampToken = request.ProcessResponse(data, out _);

        // The RFC3161 sign certificate is separate to the contents that was signed, we need to add it to the unsigned attributes.
        newSignerInfo.UnsignedAttributes.Add(new AsnEncodedData(SignatureTimeStampOin, timestampToken.AsSignedCms().Encode()));

        return(cms.Encode());
    }
コード例 #15
0
        public async Task CopyToAsync_AllContentCopied(int contentLength, bool useArray)
        {
            Memory <byte>         memory;
            OwnedMemory <byte>    ownedMemory;
            ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out memory, out ownedMemory);

            var destination = new MemoryStream();
            await content.CopyToAsync(destination);

            Assert.Equal <byte>(memory.ToArray(), destination.ToArray());

            ownedMemory?.Dispose();
        }
コード例 #16
0
        public async Task ReadAsStreamAsync_CopyTo_AllContentCopied(int contentLength, bool useArray, bool readStreamAsync)
        {
            using (ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out Memory <byte> memory, out IMemoryOwner <byte> memoryOwner))
                using (memoryOwner)
                {
                    var destination = new MemoryStream();
                    using (Stream s = await content.ReadAsStreamAsync(readStreamAsync))
                    {
                        s.CopyTo(destination);
                    }

                    Assert.Equal <byte>(memory.ToArray(), destination.ToArray());
                }
        }
コード例 #17
0
        public async Task <IRfc3161TimestampToken> SubmitRequestAsync(Uri timestampUri, TimeSpan timeout)
        {
            if (timestampUri == null)
            {
                throw new ArgumentNullException(nameof(timestampUri));
            }

            if (!timestampUri.IsAbsoluteUri)
            {
                throw new ArgumentException(
                          Strings.AnAbsoluteUriIsRequired, nameof(timestampUri));
            }

            if (timestampUri.Scheme != Uri.UriSchemeHttp && timestampUri.Scheme != Uri.UriSchemeHttps)
            {
                throw new ArgumentException(
                          Strings.HttpOrHttpsIsRequired, nameof(timestampUri));
            }

            using (var content = new ReadOnlyMemoryContent(_rfc3161TimestampRequest.Encode()))
            {
                content.Headers.ContentType = new MediaTypeHeaderValue("application/timestamp-query");
                using (HttpResponseMessage httpResponse = await HttpClient.PostAsync(timestampUri, content))
                {
                    if (!httpResponse.IsSuccessStatusCode)
                    {
                        throw new CryptographicException(
                                  string.Format(
                                      CultureInfo.CurrentCulture,
                                      Strings.TimestampServiceRespondedError,
                                      (int)httpResponse.StatusCode,
                                      httpResponse.ReasonPhrase));
                    }

                    if (!string.Equals(httpResponse.Content.Headers.ContentType.MediaType, "application/timestamp-response", StringComparison.OrdinalIgnoreCase))
                    {
                        throw new CryptographicException(Strings.TimestampServiceRespondedInvalidFormat);
                    }

                    var data = await httpResponse.Content.ReadAsByteArrayAsync();

                    System.Security.Cryptography.Pkcs.Rfc3161TimestampToken response = _rfc3161TimestampRequest.ProcessResponse(data, out var _);

                    var timestampToken = new Rfc3161TimestampTokenNetstandard21Wrapper(response);

                    return(timestampToken);
                }
            }
        }
コード例 #18
0
 public async Task ReadAsStreamAsync_ReadByte_MatchesInput(int contentLength, bool useArray, bool readStreamAsync)
 {
     using (ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out Memory <byte> memory, out IMemoryOwner <byte> memoryOwner))
         using (memoryOwner)
             using (Stream stream = await content.ReadAsStreamAsync(readStreamAsync))
             {
                 for (int i = 0; i < contentLength; i++)
                 {
                     Assert.Equal(memory.Span[i], stream.ReadByte());
                     Assert.Equal(i + 1, stream.Position);
                 }
                 Assert.Equal(-1, stream.ReadByte());
                 Assert.Equal(stream.Length, stream.Position);
             }
 }
コード例 #19
0
        public async Task ReadAsStreamAsync_CopyToAsync_AllContentCopied(int contentLength, bool useArray)
        {
            Memory <byte> memory;

            using (ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out memory, out MemoryManager <byte> ownedMemory))
            {
                var destination = new MemoryStream();
                using (Stream s = await content.ReadAsStreamAsync())
                {
                    await s.CopyToAsync(destination);
                }

                Assert.Equal <byte>(memory.ToArray(), destination.ToArray());
            }
        }
コード例 #20
0
                protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
                {
                    var contentString = "{\"proxy\": true}";
                    var bytes         = Encoding.UTF8.GetBytes(contentString);
                    var content       = new ReadOnlyMemoryContent(new ReadOnlyMemory <byte>(bytes));

                    var response = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = content
                    };

                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                    return(Task.FromResult(response));
                }
コード例 #21
0
        async Task <HttpResponseMessage> SendChunkAsync(int size, bool final, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            var targetSize = _sent + size;
            var content    = new ReadOnlyMemoryContent(size == _buffer.Size ? _buffer.Memory : _buffer.Memory.Slice(0, size));
            var headers    = content.Headers;

            headers.ContentLength = size;
            headers.ContentType   = ContentType;
            headers.ContentRange  = !final ? new ContentRangeHeaderValue(_sent, targetSize - 1L) : new ContentRangeHeaderValue(_sent, targetSize - 1L, targetSize);
            using var request     = new HttpRequestMessage(HttpMethod.Put, EndPoint)
                  {
                      Content = content
                  };
            return(await Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false));
        }
コード例 #22
0
        public async Task ReadAsStreamAsync_ReadWithCanceledToken_MatchesInput(bool useArray)
        {
            const int ContentLength = 2;

            Memory<byte> memory;
            OwnedMemory<byte> ownedMemory;
            ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);

            using (Stream stream = await content.ReadAsStreamAsync())
            {
                await Assert.ThrowsAnyAsync<OperationCanceledException>(() => stream.ReadAsync(new byte[1], 0, 1, new CancellationToken(true)));
                await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await stream.ReadAsync(new Memory<byte>(new byte[1]), new CancellationToken(true)));
                await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await stream.CopyToAsync(new MemoryStream(), 1, new CancellationToken(true)));
            }

            ownedMemory?.Dispose();
        }
コード例 #23
0
        public static HttpContent PrepareFor(object model, IJsonSerializer serializer, RestRequestOptions options)
        {
            var bytes = serializer.Serialize(model);

            if (Library.Debug.DumpJson)
            {
                Library.Debug.DumpWriter.WriteLine(Encoding.UTF8.GetString(bytes.Span));
            }

            var content = new ReadOnlyMemoryContent(bytes);

            content.Headers.ContentType = new MediaTypeHeaderValue("application/json")
            {
                CharSet = Encoding.UTF8.WebName
            };
            return(content);
        }
コード例 #24
0
        public async Task ReadAsStreamAsync_ReadWithCanceledToken_MatchesInput(bool useArray, bool readStreamAsync)
        {
            const int ContentLength = 2;

            using (ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out Memory <byte> memory, out IMemoryOwner <byte> memoryOwner))
                using (memoryOwner)
                {
                    using (Stream stream = await content.ReadAsStreamAsync(readStreamAsync))
                    {
                        await Assert.ThrowsAnyAsync <OperationCanceledException>(() => stream.ReadAsync(new byte[1], 0, 1, new CancellationToken(true)));

                        await Assert.ThrowsAnyAsync <OperationCanceledException>(async() => await stream.ReadAsync(new Memory <byte>(new byte[1]), new CancellationToken(true)));

                        await Assert.ThrowsAnyAsync <OperationCanceledException>(async() => await stream.CopyToAsync(new MemoryStream(), 1, new CancellationToken(true)));
                    }
                }
        }
コード例 #25
0
        private async Task CreateTimeStamp(SignedCms signedCms)
        {
            // See: https://www.glennwatson.net/posts/rfc-3161-signing

            const string timeStampAuthorityUri = "http://time.certum.pl/";

            byte[] nonce = new byte[8];
            using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(nonce);
            }

            SignerInfo newSignerInfo        = signedCms.SignerInfos[0];
            Rfc3161TimestampRequest?request = Rfc3161TimestampRequest.CreateFromSignerInfo(
                newSignerInfo,
                HashAlgorithmName.SHA256,
                requestSignerCertificates: true,
                nonce: nonce);

            using HttpClient client             = new HttpClient();
            using ReadOnlyMemoryContent content = new ReadOnlyMemoryContent(request.Encode());
            content.Headers.ContentType         = new MediaTypeHeaderValue("application/timestamp-query");

            using HttpResponseMessage? httpResponse = await client.PostAsync(timeStampAuthorityUri, content).ConfigureAwait(false);

            if (!httpResponse.IsSuccessStatusCode)
            {
                throw new CryptographicException($"There was a error from the timestamp authority. It responded with {httpResponse.StatusCode} {(int)httpResponse.StatusCode}: {httpResponse.Content}");
            }

            if (httpResponse.Content.Headers.ContentType.MediaType != "application/timestamp-reply")
            {
                throw new CryptographicException("The reply from the time stamp server was in a invalid format.");
            }

            byte[]? data = await httpResponse.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

            Rfc3161TimestampToken?timestampToken = request.ProcessResponse(data, out _);

            Oid signatureTimeStampOid = new Oid("1.2.840.113549.1.9.16.2.14");

            newSignerInfo.AddUnsignedAttribute(new AsnEncodedData(signatureTimeStampOid, timestampToken.AsSignedCms().Encode()));
        }
コード例 #26
0
        public async Task ReadAsStreamAsync_ReadByte_MatchesInput(int contentLength, bool useArray)
        {
            Memory <byte>         memory;
            OwnedMemory <byte>    ownedMemory;
            ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out memory, out ownedMemory);

            using (Stream stream = await content.ReadAsStreamAsync())
            {
                for (int i = 0; i < contentLength; i++)
                {
                    Assert.Equal(memory.Span[i], stream.ReadByte());
                    Assert.Equal(i + 1, stream.Position);
                }
                Assert.Equal(-1, stream.ReadByte());
                Assert.Equal(stream.Length, stream.Position);
            }

            ownedMemory?.Dispose();
        }
コード例 #27
0
        public async Task Def()
        {
            var content = new ReadOnlyMemoryContent(_data.AsMemory());

            Assert.Equal(_data.Length, content.Headers.ContentLength !.Value);
            using (var buffer = new MemoryStream())
            {
                await content.CopyToAsync(buffer);

                Assert.True(_data.SequenceEqual(buffer.ToArray()));
            }
            using (var buffer = new MemoryStream())
            {
                using var stream = await content.ReadAsStreamAsync();

                Assert.Equal(_data.Length, stream.Length);
                await stream.CopyToAsync(buffer);

                Assert.True(_data.SequenceEqual(buffer.ToArray()));
            }
        }
コード例 #28
0
        /// <summary>
        /// Get the HttpContent object that is returned from HTTP request.<br/>
        /// This method is available only when "AfterSend" event is fired.<br/>
        /// You can call this method multiple times.
        /// </summary>
        public async ValueTask <HttpContent> GetCapturedContentAsync()
        {
            if (this.Response == null)
            {
                throw new InvalidOperationException("You can call GetCapturedContentAsync() only when \"AfterSend\" event is fired.");
            }

            if (this._CapturedContentBytes == null)
            {
                this._AsyncTask = this.CaptureContentAsync();
                await this._AsyncTask;
            }

            var httpContent = new ReadOnlyMemoryContent(this._CapturedContentBytes);

            foreach (var contentHeader in this._CapturedContentHeaders)
            {
                httpContent.Headers.Add(contentHeader.Key, contentHeader.Value);
            }
            return(httpContent);
        }
コード例 #29
0
        [InlineData(4, true)]  // Begin/EndRead(byte[],...)
        public async Task ReadAsStreamAsync_ReadMultipleBytes_MatchesInput(int mode, bool useArray)
        {
            const int ContentLength = 1024;

            Memory <byte>         memory;
            OwnedMemory <byte>    ownedMemory;
            ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);

            var buffer = new byte[3];

            using (Stream stream = await content.ReadAsStreamAsync())
            {
                for (int i = 0; i < ContentLength; i += buffer.Length)
                {
                    int bytesRead =
                        mode == 0 ? stream.Read(buffer, 0, buffer.Length) :
                        mode == 1 ? stream.Read(new Span <byte>(buffer)) :
                        mode == 2 ? await stream.ReadAsync(buffer, 0, buffer.Length) :
                        mode == 3 ? await stream.ReadAsync(new Memory <byte>(buffer)) :
                        await Task.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, 0, buffer.Length, null);

                    Assert.Equal(Math.Min(buffer.Length, ContentLength - i), bytesRead);
                    for (int j = 0; j < bytesRead; j++)
                    {
                        Assert.Equal(memory.Span[i + j], buffer[j]);
                    }

                    Assert.Equal(i + bytesRead, stream.Position);
                }

                Assert.Equal(0,
                             mode == 0 ? stream.Read(buffer, 0, buffer.Length) :
                             mode == 1 ? stream.Read(new Span <byte>(buffer)) :
                             mode == 2 ? await stream.ReadAsync(buffer, 0, buffer.Length) :
                             mode == 3 ? await stream.ReadAsync(new Memory <byte>(buffer)) :
                             await Task.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, 0, buffer.Length, null));
            }

            ownedMemory?.Dispose();
        }
コード例 #30
0
        /// <inheritdoc />
        public Task <HttpResponseMessage> TryParse(BasicDeliverEventArgs args)
        {
            _validator.Validate(args);

            try
            {
                var props                    = args.BasicProperties;
                var content                  = new ReadOnlyMemoryContent(args.Body);
                var contentHeaders           = content.Headers;
                var contentTypeHeader        = props.Headers.ExtractHeader(HeaderNames.ContentType);
                var expiresHeader            = props.Headers.ExtractHeader(HeaderNames.Expires);
                var contentDispositionHeader = props.Headers.ExtractHeader(HeaderNames.ContentDisposition);
                var contentMd5Header         = props.Headers.GetOrDefault(HeaderNames.ContentMD5) as byte[];
                props.Headers.Remove(HeaderNames.ContentMD5);
                var contentRangeHeader        = props.Headers.ExtractHeader(HeaderNames.Range);
                var contentLastModifiedHeader = props.Headers.ExtractHeader(HeaderNames.LastModified);
                var contentLocationHeader     = props.Headers.ExtractHeader(HeaderNames.ContentLocation);

                if (!MediaTypeHeaderValue.TryParse(contentTypeHeader, out var mediaType))
                {
                    _log.LogError($"Не удалось распознать заголовок {HeaderNames.ContentType}:{contentTypeHeader}");
                }
                contentHeaders.ContentType = mediaType;

                contentHeaders.Expires            = DateTimeOffset.TryParse(expiresHeader, out var expires) ? expires : (DateTimeOffset?)null;
                contentHeaders.LastModified       = DateTimeOffset.TryParse(contentLastModifiedHeader, out var lastModified) ? lastModified : (DateTimeOffset?)null;
                contentHeaders.ContentRange       = ContentRangeHeaderValue.TryParse(contentRangeHeader, out var contentRange) ? contentRange : null;
                contentHeaders.ContentDisposition = ContentDispositionHeaderValue.TryParse(contentDispositionHeader, out var contentDisposition) ? contentDisposition : null;
                if (Uri.TryCreate(contentLocationHeader, UriKind.RelativeOrAbsolute, out var contentLocation))
                {
                    contentHeaders.ContentLocation = contentLocation;
                }

                if (contentMd5Header != null)
                {
                    contentHeaders.ContentMD5 = contentMd5Header;
                }

                var statusCodeHeader = props.Headers.GetOrDefaultString(HeaderNames.Status);
                props.Headers.Remove(HeaderNames.Status);

                props.Headers.Remove(HeaderNames.ContentLength);

                if (!int.TryParse(statusCodeHeader, out var statusCode))
                {
                    statusCode = DefaultStatusCode;
                }

                var response = new HttpResponseMessage
                {
                    StatusCode = (HttpStatusCode)statusCode,
                    Content    = content
                };
                response.Headers.AddCorrelation(props.CorrelationId);

                foreach (var header in props.Headers)
                {
                    response.Headers.Add(header.Key, ReadHeader(header));
                }

                return(Task.FromResult(response));
            }
            catch (Exception e)
            {
                _log.LogError(e, "Ошибка при парсинге ответа");

                return(null);
            }
        }