public override async Task ProcessAsync(PipelineCallContext context, ReadOnlyMemory <PipelinePolicy> pipeline)
        {
            _logged.Append($"REQUEST: {context.ToString()}\n");
            await ProcessNextAsync(pipeline, context).ConfigureAwait(false);

            _logged.Append($"RESPONSE: {context.Response.Status}\n");
        }
Beispiel #2
0
        public async Task <Response <ConfigurationSetting> > SetAsync(ConfigurationSetting setting, CancellationToken cancellation = default)
        {
            if (setting == null)
            {
                throw new ArgumentNullException(nameof(setting));
            }
            if (string.IsNullOrEmpty(setting.Key))
            {
                throw new ArgumentNullException($"{nameof(setting)}.{nameof(setting.Key)}");
            }

            Uri uri = BuildUrlForKvRoute(setting);

            using (PipelineCallContext context = Pipeline.CreateContext(_options, cancellation))
            {
                ReadOnlyMemory <byte> content = Serialize(setting);

                context.SetRequestLine(ServiceMethod.Put, uri);

                context.AddHeader("Host", uri.Host);
                context.AddHeader(MediaTypeKeyValueApplicationHeader);
                context.AddHeader(Header.Common.JsonContentType);
                context.AddHeader(Header.Common.CreateContentLength(content.Length));
                AddAuthenticationHeaders(context, uri, ServiceMethod.Put, content, _secret, _credential);

                context.SetContent(PipelineContent.Create(content));

                await Pipeline.ProcessAsync(context).ConfigureAwait(false);

                return(await CreateResponse(context));
            }
        }
Beispiel #3
0
        internal static void AddAuthenticationHeaders(PipelineCallContext context, Uri uri, ServiceMethod method, ReadOnlyMemory <byte> content, byte[] secret, string credential)
        {
            string contentHash = null;

            using (var alg = SHA256.Create())
            {
                // TODO (pri 3): ToArray should nopt be called here. Instead, TryGetArray, or PipelineContent should do hashing on the fly
                contentHash = Convert.ToBase64String(alg.ComputeHash(content.ToArray()));
            }

            using (var hmac = new HMACSHA256(secret))
            {
                var host         = uri.Host;
                var pathAndQuery = uri.PathAndQuery;

                string         verb          = method.ToString().ToUpper();
                DateTimeOffset utcNow        = DateTimeOffset.UtcNow;
                var            utcNowString  = utcNow.ToString("r");
                var            stringToSign  = $"{verb}\n{pathAndQuery}\n{utcNowString};{host};{contentHash}";
                var            signature     = Convert.ToBase64String(hmac.ComputeHash(Encoding.ASCII.GetBytes(stringToSign))); // Calculate the signature
                string         signedHeaders = "date;host;x-ms-content-sha256";                                                 // Semicolon separated header names

                context.AddHeader("Date", utcNowString);
                context.AddHeader("x-ms-content-sha256", contentHash);
                context.AddHeader("Authorization", $"HMAC-SHA256 Credential={credential}, SignedHeaders={signedHeaders}, Signature={signature}");
            }
        }
        public async Task <Response <Stream> > DetectLazyAsync(CancellationToken cancellation, Uri image, FaceDetectOptions options = default)
        {
            if (options == null)
            {
                options = new FaceDetectOptions();
            }
            Uri uri = BuildUri(options);

            PipelineCallContext context = null;

            try
            {
                context = _client.CreateContext(_options, cancellation);
                context.SetRequestLine(ServiceMethod.Post, uri);

                context.AddHeader(_keyHeader);
                context.AddHeader(Header.Common.JsonContentType);
                context.SetContent(new FaceContent(image, context));

                await _client.ProcessAsync(context).ConfigureAwait(false);

                return(new Response <Stream>(context.Response, context.Response.ContentStream));
            }
            catch
            {
                if (context != null)
                {
                    context.Dispose();
                }
                throw;
            }
        }
        static void SetContentStream(PipelineCallContext context, string imagePath)
        {
            byte[] temp   = new byte[4096];
            var    stream = new FileStream(imagePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true);

            context.SetContent(PipelineContent.Create(stream));
            context.AddHeader(Header.Common.CreateContentLength(stream.Length));
        }
 public sealed override async Task ProcessAsync(PipelineCallContext context, ReadOnlyMemory <PipelinePolicy> next)
 {
     if (next.Length == 0)
     {
         await ProcessAsync(context).ConfigureAwait(false);
     }
     else
     {
         throw new ArgumentOutOfRangeException(nameof(next));
     }
 }
Beispiel #7
0
 protected override bool ShouldRetry(PipelineCallContext context, int retry, out TimeSpan delay)
 {
     delay = TimeSpan.Zero;
     if (retry > 5)
     {
         return(false);
     }
     if (context.Response.Status == 1)
     {
         return(false);
     }
     return(true);
 }
 protected override bool ShouldRetry(PipelineCallContext context, int attempted, out TimeSpan delay)
 {
     delay = _delay;
     if (attempted > _maxRetries)
     {
         return(false);
     }
     if (Array.BinarySearch(_retriableCodes, context.Response.Status) < 0)
     {
         return(false);
     }
     return(true);
 }
Beispiel #9
0
        static async Task <Response <ConfigurationSetting> > CreateResponse(PipelineCallContext context)
        {
            ServiceResponse response = context.Response;

            if (response.Status != 200)
            {
                return(new Response <ConfigurationSetting>(response));
            }

            var result = await ConfigurationServiceSerializer.ParseSettingAsync(response.ContentStream, context.Cancellation);

            return(new Response <ConfigurationSetting>(response, result));
        }
Beispiel #10
0
        public sealed override async Task ProcessAsync(PipelineCallContext context)
        {
            var httpTransportContext = context as Context;

            if (httpTransportContext == null)
            {
                throw new InvalidOperationException("the context is not compatible with the transport");
            }

            HttpRequestMessage httpRequest = httpTransportContext.BuildRequestMessage();

            HttpResponseMessage responseMessage = await ProcessCoreAsync(context.Cancellation, httpRequest).ConfigureAwait(false);

            httpTransportContext.ProcessResponseMessage(responseMessage);
        }
Beispiel #11
0
        public async Task <Response <ConfigurationSetting> > DeleteAsync(string key, SettingFilter filter = null, CancellationToken cancellation = default)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(nameof(key));
            }

            Uri uri = BuildUrlForKvRoute(key, filter);

            using (PipelineCallContext context = Pipeline.CreateContext(_options, cancellation))
            {
                context.SetRequestLine(ServiceMethod.Delete, uri);

                context.AddHeader("Host", uri.Host);
                AddFilterHeaders(filter, context);
                AddAuthenticationHeaders(context, uri, ServiceMethod.Delete, content: default, _secret, _credential);
        public async Task <Response <FaceDetectResult> > DetectAsync(CancellationToken cancellation, string imagePath, FaceDetectOptions options)
        {
            if (options == null)
            {
                options = new FaceDetectOptions();
            }
            Uri uri = BuildUri(options);

            PipelineCallContext context = null;

            try
            {
                context = _client.CreateContext(_options, cancellation);
                context.SetRequestLine(ServiceMethod.Post, uri);

                context.AddHeader(_keyHeader);
                context.AddHeader(Header.Common.OctetStreamContentType);

                SetContentStream(context, imagePath);

                await _client.ProcessAsync(context).ConfigureAwait(false);

                ServiceResponse response = context.Response;
                if (!response.TryGetHeader(s_contentLength, out long contentLength))
                {
                    throw new Exception("bad response: no content length header");
                }

                var buffer = new byte[contentLength];
                var read   = await response.ContentStream.ReadAsync(buffer, cancellation);

                Func <ServiceResponse, FaceDetectResult> contentParser = null;
                if (response.Status == 200)
                {
                    contentParser = (rsp) => { return(FaceDetectResult.Parse(new ReadOnlySequence <byte>(buffer, 0, read))); };
                }
                return(new Response <FaceDetectResult>(response, contentParser));
            }
            catch
            {
                if (context != null)
                {
                    context.Dispose();
                }
                throw;
            }
        }
Beispiel #13
0
        public async Task <Response> PutRangeAsync(long index, int length, Stream content, CancellationToken cancellation)
        {
            if (index < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(index));
            }
            if (length < 0 || length > 4 * 1024 * 1024)
            {
                throw new ArgumentOutOfRangeException(nameof(length));
            }
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }
            if (content.CanRead == false)
            {
                throw new ArgumentOutOfRangeException(nameof(content));
            }
            if (content.CanSeek == false)
            {
                throw new ArgumentOutOfRangeException(nameof(content));
            }

            PipelineCallContext context = null;

            try {
                context = Pipeline.CreateContext(_options, cancellation);
                context.SetRequestLine(ServiceMethod.Put, _baseUri);

                context.AddHeader(Header.Common.CreateContentLength(content.Length));
                context.AddHeader(Header.Common.OctetStreamContentType);
                context.SetContent(PipelineContent.Create(content));

                await Pipeline.ProcessAsync(context).ConfigureAwait(false);

                return(new Response(context.Response));
            }
            catch {
                if (context != null)
                {
                    context.Dispose();
                }
                throw;
            }
        }
        public override async Task ProcessAsync(PipelineCallContext context, ReadOnlyMemory <PipelinePolicy> pipeline)
        {
            int attempt = 1;

            while (true)
            {
                await ProcessNextAsync(pipeline, context).ConfigureAwait(false);

                if (!ShouldRetry(context, attempt++, out var delay))
                {
                    return;
                }
                if (delay > TimeSpan.Zero)
                {
                    await Task.Delay(delay, context.Cancellation).ConfigureAwait(false);
                }
            }
        }
Beispiel #15
0
        // TODO (pri 3): do all the methods that call this accept revisions?
        static void AddFilterHeaders(SettingFilter filter, PipelineCallContext context)
        {
            if (filter == null)
            {
                return;
            }

            if (filter.ETag.IfMatch != default)
            {
                context.AddHeader(IfMatchName, $"\"{filter.ETag.IfMatch}\"");
            }

            if (filter.Revision.HasValue)
            {
                var dateTime = filter.Revision.Value.UtcDateTime.ToString(AcceptDateTimeFormat);
                context.AddHeader(AcceptDatetimeHeader, dateTime);
            }
        }
Beispiel #16
0
        public async Task <Response> CreateAsync(CancellationToken cancellation)
        {
            PipelineCallContext context = null;

            try {
                context = Pipeline.CreateContext(_options, cancellation);
                context.SetRequestLine(ServiceMethod.Put, _baseUri);

                await Pipeline.ProcessAsync(context).ConfigureAwait(false);

                return(new Response(context.Response));
            }
            catch {
                if (context != null)
                {
                    context.Dispose();
                }
                throw;
            }
        }
 public FaceContent(Uri image, PipelineCallContext context)
 {
     _image   = image;
     _context = context;
 }
 protected abstract bool ShouldRetry(PipelineCallContext context, int attempted, out TimeSpan delay);
 public abstract Task ProcessAsync(PipelineCallContext context, ReadOnlyMemory <PipelinePolicy> pipeline);
 public abstract Task ProcessAsync(PipelineCallContext context);
 protected internal static async Task ProcessNextAsync(ReadOnlyMemory <PipelinePolicy> pipeline, PipelineCallContext context)
 {
     var next = pipeline.Span[0];
     await next.ProcessAsync(context, pipeline.Slice(1)).ConfigureAwait(false);
 }
 public override async Task ProcessAsync(PipelineCallContext context, ReadOnlyMemory <PipelinePolicy> pipeline)
 {
     context.AddHeader(_uaHeader);
     await ProcessNextAsync(pipeline, context).ConfigureAwait(false);
 }