public async Task ThresholdExceeded_ThrowsException(string responseHeaders, int maxResponseHeadersLength, bool shouldSucceed)
        {
            using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                s.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                s.Listen(1);
                var ep = (IPEndPoint)s.LocalEndPoint;

                using (var handler = new HttpClientHandler() { MaxResponseHeadersLength = maxResponseHeadersLength })
                using (var client = new HttpClient(handler))
                {
                    Task<HttpResponseMessage> getAsync = client.GetAsync($"http://{ep.Address}:{ep.Port}", HttpCompletionOption.ResponseHeadersRead);

                    using (Socket server = s.Accept())
                    using (Stream serverStream = new NetworkStream(server, ownsSocket: false))
                    using (StreamReader reader = new StreamReader(serverStream, Encoding.ASCII))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null && !string.IsNullOrEmpty(line)) ;

                        byte[] headerData = Encoding.ASCII.GetBytes(responseHeaders);
                        serverStream.Write(headerData, 0, headerData.Length);
                    }

                    if (shouldSucceed)
                    {
                        (await getAsync).Dispose();
                    }
                    else
                    {
                        await Assert.ThrowsAsync<HttpRequestException>(() => getAsync);
                    }
                }
            }
        }
        public async Task HttpClient_ClientUsesAuxRecord_Ok()
        {
            X509Certificate2 serverCert = Configuration.Certificates.GetServerCertificate();

            var server = new SchSendAuxRecordTestServer(serverCert);
            int port = server.StartServer();

            string requestString = "https://localhost:" + port.ToString();
            
            using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
            using (var client = new HttpClient(handler))
            {
                var tasks = new Task[2];
                tasks[0] = server.RunTest();
                tasks[1] = client.GetStringAsync(requestString);
            
                await Task.WhenAll(tasks).TimeoutAfter(15 * 1000);
            
                if (server.IsInconclusive)
                {
                    _output.WriteLine("Test inconclusive: The Operating system preferred a non-CBC or Null cipher.");
                }
                else
                {
                    Assert.True(server.AuxRecordDetected, "Server reports: Client auxiliary record not detected.");
                }
            }
        }
 public void Default_Get_Null()
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Null(handler.DefaultProxyCredentials);
     }
 }
        public void ProxyExplicitlyProvided_DefaultCredentials_Ignored()
        {
            int port;
            Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(out port, requireAuth: true, expectCreds: true);
            Uri proxyUrl = new Uri($"http://localhost:{port}");

            var rightCreds = new NetworkCredential("rightusername", "rightpassword");
            var wrongCreds = new NetworkCredential("wrongusername", "wrongpassword");

            using (var handler = new HttpClientHandler())
            using (var client = new HttpClient(handler))
            {
                handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, rightCreds);
                handler.DefaultProxyCredentials = wrongCreds;

                Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer);
                Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap();
                Task.WaitAll(proxyTask, responseTask, responseStringTask);

                TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
                Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result);

                string expectedAuth = $"{rightCreds.UserName}:{rightCreds.Password}";
                Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue);
            }
        }
Esempio n. 5
0
 public void Ctor_ExpectedDefaultPropertyValues()
 {
     using (var handler = new HttpClientHandler())
     {
         // Same as .NET Framework (Desktop).
         Assert.True(handler.AllowAutoRedirect);
         Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOptions);
         CookieContainer cookies = handler.CookieContainer;
         Assert.NotNull(cookies);
         Assert.Equal(0, cookies.Count);
         Assert.Null(handler.Credentials);
         Assert.Equal(50, handler.MaxAutomaticRedirections);
         Assert.False(handler.PreAuthenticate);
         Assert.Equal(null, handler.Proxy);
         Assert.True(handler.SupportsAutomaticDecompression);
         Assert.True(handler.SupportsProxy);
         Assert.True(handler.SupportsRedirectConfiguration);
         Assert.True(handler.UseCookies);
         Assert.False(handler.UseDefaultCredentials);
         Assert.True(handler.UseProxy);
         
         // Changes from .NET Framework (Desktop).
         Assert.Equal(DecompressionMethods.GZip | DecompressionMethods.Deflate, handler.AutomaticDecompression);
         Assert.Equal(0, handler.MaxRequestContentBufferSize);
     }
 }
#pragma warning restore 0618
        public void DisabledProtocols_SetSslProtocols_ThrowsException(SslProtocols disabledProtocols)
        {
            using (var handler = new HttpClientHandler())
            {
                Assert.Throws<NotSupportedException>(() => handler.SslProtocols = disabledProtocols);
            }
        }
        [PlatformSpecific(PlatformID.AnyUnix)] // proxies set via the http_proxy environment variable are specific to Unix
        public void ProxySetViaEnvironmentVariable_DefaultProxyCredentialsUsed()
        {
            int port;
            Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(out port, requireAuth: true, expectCreds: true);

            const string ExpectedUsername = "******";
            const string ExpectedPassword = "******";

            // libcurl will read a default proxy from the http_proxy environment variable.  Ensure that when it does,
            // our default proxy credentials are used.  To avoid messing up anything else in this process, we run the
            // test in another process.
            var psi = new ProcessStartInfo();
            psi.Environment.Add("http_proxy", $"http://localhost:{port}");
            RemoteInvoke(() =>
            {
                using (var handler = new HttpClientHandler())
                using (var client = new HttpClient(handler))
                {
                    var creds = new NetworkCredential(ExpectedUsername, ExpectedPassword);
                    handler.DefaultProxyCredentials = creds;

                    Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer);
                    Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap();
                    Task.WaitAll(responseTask, responseStringTask);

                    TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
                }
                return SuccessExitCode;
            }, new RemoteInvokeOptions { StartInfo = psi }).Dispose();

            Assert.Equal($"{ExpectedUsername}:{ExpectedPassword}", proxyTask.Result.AuthenticationHeaderValue);
        }
 public void InvalidValue_ThrowsException(int invalidValue)
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxResponseHeadersLength = invalidValue);
     }
 }
        public async Task ThresholdExceeded_ThrowsException(string responseHeaders, int maxResponseHeadersLength, bool shouldSucceed)
        {
            await LoopbackServer.CreateServerAsync(async (server, url) =>
            {
                using (var handler = new HttpClientHandler() { MaxResponseHeadersLength = maxResponseHeadersLength })
                using (var client = new HttpClient(handler))
                {
                    Task<HttpResponseMessage> getAsync = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);

                    await LoopbackServer.AcceptSocketAsync(server, async (s, serverStream, reader, writer) =>
                    {
                        using (s) using (serverStream) using (reader) using (writer)
                        {
                            string line;
                            while ((line = reader.ReadLine()) != null && !string.IsNullOrEmpty(line)) ;

                            byte[] headerData = Encoding.ASCII.GetBytes(responseHeaders);
                            serverStream.Write(headerData, 0, headerData.Length);
                        }

                        if (shouldSucceed)
                        {
                            (await getAsync).Dispose();
                        }
                        else
                        {
                            await Assert.ThrowsAsync<HttpRequestException>(() => getAsync);
                        }
                        
                        return null;
                    });
                }
            });

        }
 public void ConnectTimeout_Default()
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Equal(Timeout.InfiniteTimeSpan, handler.ConnectTimeout);
     }
 }
        public async Task UseCallback_ValidCertificate_ExpectedValuesDuringCallback(Uri url, bool checkRevocation)
        {
            var handler = new HttpClientHandler();
            using (var client = new HttpClient(handler))
            {
                bool callbackCalled = false;
                handler.CheckCertificateRevocationList = checkRevocation;
                handler.ServerCertificateValidationCallback = (request, cert, chain, errors) => {
                    callbackCalled = true;
                    Assert.NotNull(request);
                    Assert.Equal(SslPolicyErrors.None, errors);
                    Assert.True(chain.ChainElements.Count > 0);
                    Assert.NotEmpty(cert.Subject);
                    Assert.Equal(checkRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, chain.ChainPolicy.RevocationMode);
                    return true;
                };

                using (HttpResponseMessage response = await client.GetAsync(url))
                {
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                }

                Assert.True(callbackCalled);
            }
        }
 public void ClientCertificateOptions_InvalidArg_ThrowsException(ClientCertificateOption option)
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Throws<ArgumentOutOfRangeException>("value", () => handler.ClientCertificateOptions = option);
     }
 }
 public void DefaultProtocols_MatchesExpected()
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Equal(SslProtocols.None, handler.SslProtocols);
     }
 }
 public void Default_ExpectedValue()
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Equal(int.MaxValue, handler.MaxConnectionsPerServer);
     }
 }
 public void Set_InvalidValues_Throws(int invalidValue)
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Throws<ArgumentOutOfRangeException>(() => handler.MaxConnectionsPerServer = invalidValue);
     }
 }
 public void ClientCertificateOptions_Default()
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOptions);
     }
 }
 public void Default_MaxResponseHeadersLength()
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Equal(64 * 1024, handler.MaxResponseHeadersLength);
     }
 }
 public void ConnectTimeout_InvalidValues(long ms)
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Throws<ArgumentOutOfRangeException>(() => handler.ConnectTimeout = TimeSpan.FromMilliseconds(ms));
     }
 }
 public void ValidValue_SetGet_Roundtrips(int validValue)
 {
     using (var handler = new HttpClientHandler())
     {
         handler.MaxResponseHeadersLength = validValue;
         Assert.Equal(validValue, handler.MaxResponseHeadersLength);
     }
 }
 public void DefaultProtocols_MatchesExpected()
 {
     using (var handler = new HttpClientHandler())
     {
         const SslProtocols expectedDefault = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
         Assert.Equal(expectedDefault, handler.SslProtocols);
     }
 }
 public void ConnectTimeout_ValidValues_Roundtrip(long ms)
 {
     using (var handler = new HttpClientHandler())
     {
         handler.ConnectTimeout = TimeSpan.FromMilliseconds(ms);
         Assert.Equal(TimeSpan.FromMilliseconds(ms), handler.ConnectTimeout);
     }
 }
 public void SetGetProtocols_Roundtrips(SslProtocols protocols)
 {
     using (var handler = new HttpClientHandler())
     {
         handler.SslProtocols = protocols;
         Assert.Equal(protocols, handler.SslProtocols);
     }
 }
 public void ClientCertificateOptions_ValueArg_Roundtrips(ClientCertificateOption option)
 {
     using (var handler = new HttpClientHandler())
     {
         handler.ClientCertificateOptions = option;
         Assert.Equal(option, handler.ClientCertificateOptions);
     }
 }
        public async Task Manual_CertificateSentMatchesCertificateReceived_Success(
            int numberOfRequests,
            bool reuseClient) // validate behavior with and without connection pooling, which impacts client cert usage
        {
            var options = new LoopbackServer.Options { UseSsl = true };
            using (X509Certificate2 cert = Configuration.Certificates.GetClientCertificate())
            {
                Func<HttpClient> createClient = () =>
                {
                    var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = delegate { return true; } };
                    handler.ClientCertificates.Add(cert);
                    return new HttpClient(handler);
                };

                Func<HttpClient, Socket, Uri, Task> makeAndValidateRequest = async (client, server, url) =>
                {
                    await TestHelper.WhenAllCompletedOrAnyFailed(
                        client.GetStringAsync(url),
                        LoopbackServer.AcceptSocketAsync(server, async (socket, stream, reader, writer) =>
                        {
                            SslStream sslStream = Assert.IsType<SslStream>(stream);
                            Assert.Equal(cert, sslStream.RemoteCertificate);
                            await LoopbackServer.ReadWriteAcceptedAsync(socket, reader, writer);
                            return null;
                        }, options));
                };

                await LoopbackServer.CreateServerAsync(async (server, url) =>
                {
                    if (reuseClient)
                    {
                        using (HttpClient client = createClient())
                        {
                            for (int i = 0; i < numberOfRequests; i++)
                            {
                                await makeAndValidateRequest(client, server, url);

                                GC.Collect();
                                GC.WaitForPendingFinalizers();
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < numberOfRequests; i++)
                        {
                            using (HttpClient client = createClient())
                            {
                                await makeAndValidateRequest(client, server, url);
                            }

                            GC.Collect();
                            GC.WaitForPendingFinalizers();
                        }
                    }
                }, options);
            }
        }
 public async Task Manual_SSLBackendNotSupported_ThrowsPlatformNotSupportedException()
 {
     var handler = new HttpClientHandler();
     handler.ClientCertificates.Add(Configuration.Certificates.GetClientCertificate());
     using (var client = new HttpClient(handler))
     {
         await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
     }
 }
 public async Task GetAsync_AllowedSSLVersion_Succeeds(SslProtocols acceptedProtocol, string url)
 {
     using (var handler = new HttpClientHandler())
     using (var client = new HttpClient(handler))
     {
         handler.SslProtocols = acceptedProtocol;
         using (await client.GetAsync(url)) { }
     }
 }
 public async Task SetProtcols_AfterRequest_ThrowsException()
 {
     using (var handler = new HttpClientHandler())
     using (var client = new HttpClient(handler))
     {
         (await client.GetAsync(HttpTestServers.RemoteEchoServer)).Dispose();
         Assert.Throws<InvalidOperationException>(() => handler.SslProtocols = SslProtocols.Tls12);
     }
 }
 public async Task SetAfterUse_Throws()
 {
     using (var handler = new HttpClientHandler())
     using (var client = new HttpClient(handler))
     {
         handler.MaxResponseHeadersLength = int.MaxValue;
         await client.GetStreamAsync(Configuration.Http.RemoteEchoServer);
         Assert.Throws<InvalidOperationException>(() => handler.MaxResponseHeadersLength = int.MaxValue);
     }
 }
Esempio n. 29
0
        public async Task UseDefaultCredentials_SetFalse_Unauthorized(bool useProxy)
        {
            var handler = new HttpClientHandler { UseProxy = useProxy, UseDefaultCredentials = false };

            using (var client = new HttpClient(handler))
            using (HttpResponseMessage response = await client.GetAsync(s_authenticatedServer))
            {
                Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
            }
        }
 public LuisRecognizer(LuisApplication application, IBotTelemetryClient telemetryClient, bool logPersonalInformation, LuisPredictionOptions predictionOptions = null, bool includeApiResults = false, HttpClientHandler clientHandler = null)
 : this(BuildLuisRecognizerOptionsV2(application, predictionOptions, includeApiResults), clientHandler)
 {
 }
 /// <inheritdoc/>
 public void Configure(HttpClientHandler httpClientHandler)
 {
 }
Esempio n. 32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MockHttpClientHandlerGen"/> class.
 /// </summary>
 public MockHttpClientHandlerGen()
 {
     this.httpClientHandler = this.GenerateMockHttpClientHandler();
 }
Esempio n. 33
0
 public WebClient(HttpClientHandler Handler) : base(Handler)
 {
 }
        private void HentDataFraDiskAsync(string BilMaerke)
        {
            OC_bilmaerker.Clear();
            List <Bil> nyListe = new List <Bil>();

            //nyListe = await PersistencyService.HentDataFraDiskAsyncPS();

            OC_forhandlere.Clear();
            List <Forhandler> forhandlerListe = new List <Forhandler>();

            OC_bookings.Clear();
            List <Booking> bookingListe = new List <Booking>();

            //Setup client handler
            HttpClientHandler handler = new HttpClientHandler();

            handler.UseDefaultCredentials = true;

            using (var client = new HttpClient(handler))
            {
                //Initialize client
                client.BaseAddress = new Uri(serverUrl);
                client.DefaultRequestHeaders.Clear();

                //Request JSON format
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                try
                {
                    //Get all the flower orders from the database
                    var flowerOrderResponse     = client.GetAsync("api/bils").Result;
                    var forhandlerOrderResponse = client.GetAsync("api/forhandlers").Result;
                    var bookingOrderResponse    = client.GetAsync("api/bookings").Result;

                    //Check response -> throw exception if NOT successful
                    flowerOrderResponse.EnsureSuccessStatusCode();
                    forhandlerOrderResponse.EnsureSuccessStatusCode();
                    bookingOrderResponse.EnsureSuccessStatusCode();

                    //Get the hotels as a ICollection
                    var orders  = flowerOrderResponse.Content.ReadAsAsync <ICollection <Bil> >().Result;
                    var orders2 = forhandlerOrderResponse.Content.ReadAsAsync <ICollection <Forhandler> >().Result;
                    var orders3 = bookingOrderResponse.Content.ReadAsAsync <ICollection <Booking> >().Result;

                    foreach (var order in orders)
                    {
                        if (order.BilMaerke == BilMaerke)
                        {
                            this.OC_bilmaerker.Add(new Bil(order.BilID, order.ForhandlerID, order.BilMaerke, order.BilModel, order.BilUdstyr, order.BilMotor));
                        }
                    }

                    foreach (var order in orders2)
                    {
                        this.OC_forhandlere.Add(new Forhandler(order.ForhandlerID, order.ForhandlerNavn, order.ForhandlerAdresse, order.ForhandlerBy, order.ForhandlerTelefon, order.ForhandlerEmail));
                    }

                    foreach (var order in orders3)
                    {
                        this.OC_bookings.Add(new Booking(order.BookingID, order.KundeNavn, order.KundeEmail, order.BilModel, order.ForhandlerNavn, order.BookTime));
                    }
                }
                catch
                {
                }
            }

            /*public void SelectBilMaerke()
             * {
             *  if
             * }*/
        }
Esempio n. 35
0
        /// <summary>
        /// Registers a device described by the message.
        /// </summary>
        /// <param name="message">The provisioning message.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The registration result.</returns>
        public async override Task <DeviceRegistrationResult> RegisterAsync(
            ProvisioningTransportRegisterMessage message,
            CancellationToken cancellationToken)
        {
            if (Logging.IsEnabled)
            {
                Logging.Enter(this, $"{nameof(ProvisioningTransportHandlerHttp)}.{nameof(RegisterAsync)}");
            }

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

            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                HttpAuthStrategy authStrategy;

                if (message.Security is SecurityProviderTpm)
                {
                    authStrategy = new HttpAuthStrategyTpm((SecurityProviderTpm)message.Security);
                }
                else if (message.Security is SecurityProviderX509)
                {
                    authStrategy = new HttpAuthStrategyX509((SecurityProviderX509)message.Security);
                }
                else if (message.Security is SecurityProviderSymmetricKey)
                {
                    authStrategy = new HttpAuthStrategySymmetricKey((SecurityProviderSymmetricKey)message.Security);
                }
                else
                {
                    if (Logging.IsEnabled)
                    {
                        Logging.Error(this, $"Invalid {nameof(SecurityProvider)} type.");
                    }

                    throw new NotSupportedException(
                              $"{nameof(message.Security)} must be of type {nameof(SecurityProviderTpm)}, " +
                              $"{nameof(SecurityProviderX509)} or {nameof(SecurityProviderSymmetricKey)}");
                }

                if (Logging.IsEnabled)
                {
                    Logging.Associate(authStrategy, this);
                }

                var builder = new UriBuilder
                {
                    Scheme = Uri.UriSchemeHttps,
                    Host   = message.GlobalDeviceEndpoint,
                    Port   = Port,
                };

                var httpClientHandler = new HttpClientHandler
                {
                    // Cannot specify a specific protocol here, as desired due to an error:
                    //   ProvisioningDeviceClient_ValidRegistrationId_AmqpWithProxy_SymmetricKey_RegisterOk_GroupEnrollment failing for me with System.PlatformNotSupportedException: Operation is not supported on this platform.
                    // When revisiting TLS12 work for DPS, we should figure out why. Perhaps the service needs to support it.

                    //SslProtocols = TlsVersions.Preferred,
                };

                if (Proxy != DefaultWebProxySettings.Instance)
                {
                    httpClientHandler.UseProxy = (Proxy != null);
                    httpClientHandler.Proxy    = Proxy;
                    if (Logging.IsEnabled)
                    {
                        Logging.Info(this, $"{nameof(RegisterAsync)} Setting HttpClientHandler.Proxy");
                    }
                }

                DeviceProvisioningServiceRuntimeClient client = authStrategy.CreateClient(builder.Uri, httpClientHandler);
                client.HttpClient.DefaultRequestHeaders.Add("User-Agent", message.ProductInfo);
                if (Logging.IsEnabled)
                {
                    Logging.Info(this, $"Uri: {builder.Uri}; User-Agent: {message.ProductInfo}");
                }

                DeviceRegistration deviceRegistration = authStrategy.CreateDeviceRegistration();
                if (message.Payload != null && message.Payload.Length > 0)
                {
                    deviceRegistration.Payload = new JRaw(message.Payload);
                }
                string registrationId = message.Security.GetRegistrationID();

                RegistrationOperationStatus operation =
                    await client.RuntimeRegistration.RegisterDeviceAsync(
                        registrationId,
                        message.IdScope,
                        deviceRegistration).ConfigureAwait(false);

                int    attempts    = 0;
                string operationId = operation.OperationId;

                if (Logging.IsEnabled)
                {
                    Logging.RegisterDevice(
                        this,
                        registrationId,
                        message.IdScope,
                        deviceRegistration.Tpm == null ? "X509" : "TPM",
                        operation.OperationId,
                        operation.RetryAfter,
                        operation.Status);
                }

                // Poll with operationId until registration complete.
                while (string.CompareOrdinal(operation.Status, RegistrationOperationStatus.OperationStatusAssigning) == 0 ||
                       string.CompareOrdinal(operation.Status, RegistrationOperationStatus.OperationStatusUnassigned) == 0)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    TimeSpan?serviceRecommendedDelay = operation.RetryAfter;
                    if (serviceRecommendedDelay != null && serviceRecommendedDelay?.TotalSeconds < s_defaultOperationPoolingIntervalMilliseconds.TotalSeconds)
                    {
                        if (Logging.IsEnabled)
                        {
                            Logging.Error(this, $"Service recommended unexpected retryAfter of {operation.RetryAfter?.TotalSeconds}, defaulting to delay of {s_defaultOperationPoolingIntervalMilliseconds.ToString()}", nameof(RegisterAsync));
                        }

                        serviceRecommendedDelay = s_defaultOperationPoolingIntervalMilliseconds;
                    }

                    await Task.Delay(serviceRecommendedDelay ?? RetryJitter.GenerateDelayWithJitterForRetry(s_defaultOperationPoolingIntervalMilliseconds)).ConfigureAwait(false);

                    cancellationToken.ThrowIfCancellationRequested();

                    try
                    {
                        operation = await client.RuntimeRegistration.OperationStatusLookupAsync(
                            registrationId,
                            operationId,
                            message.IdScope).ConfigureAwait(false);
                    }
                    catch (HttpOperationException oe)
                    {
                        bool isTransient = oe.Response.StatusCode >= HttpStatusCode.InternalServerError ||
                                           (int)oe.Response.StatusCode == 429;
                        try
                        {
                            var errorDetails = JsonConvert.DeserializeObject <ProvisioningErrorDetailsHttp>(oe.Response.Content);
                            if (isTransient)
                            {
                                serviceRecommendedDelay = errorDetails.RetryAfter;
                            }
                            else
                            {
                                if (Logging.IsEnabled)
                                {
                                    Logging.Error(
                                        this,
                                        $"{nameof(ProvisioningTransportHandlerHttp)} threw exception {oe}",
                                        nameof(RegisterAsync));
                                }

                                throw new ProvisioningTransportException(oe.Response.Content, oe, isTransient, errorDetails);
                            }
                        }
                        catch (JsonException ex)
                        {
                            if (Logging.IsEnabled)
                            {
                                Logging.Error(
                                    this,
                                    $"{nameof(ProvisioningTransportHandlerHttp)} server returned malformed error response." +
                                    $"Parsing error: {ex}. Server response: {oe.Response.Content}",
                                    nameof(RegisterAsync));
                            }

                            throw new ProvisioningTransportException(
                                      $"HTTP transport exception: malformed server error message: '{oe.Response.Content}'",
                                      ex,
                                      false);
                        }
                    }

                    if (Logging.IsEnabled)
                    {
                        Logging.OperationStatusLookup(
                            this,
                            registrationId,
                            operation.OperationId,
                            operation.RetryAfter,
                            operation.Status,
                            attempts);
                    }

                    attempts++;
                }

                if (string.CompareOrdinal(operation.Status, RegistrationOperationStatus.OperationStatusAssigned) == 0)
                {
                    authStrategy.SaveCredentials(operation);
                }

                return(ConvertToProvisioningRegistrationResult(operation.RegistrationState));
            }
            catch (HttpOperationException oe)
            {
                if (Logging.IsEnabled)
                {
                    Logging.Error(
                        this,
                        $"{nameof(ProvisioningTransportHandlerHttp)} threw exception {oe}",
                        nameof(RegisterAsync));
                }

                bool isTransient = oe.Response.StatusCode >= HttpStatusCode.InternalServerError ||
                                   (int)oe.Response.StatusCode == 429;

                try
                {
                    var errorDetails = JsonConvert.DeserializeObject <ProvisioningErrorDetailsHttp>(oe.Response.Content);
                    throw new ProvisioningTransportException(oe.Response.Content, oe, isTransient, errorDetails);
                }
                catch (JsonException ex)
                {
                    if (Logging.IsEnabled)
                    {
                        Logging.Error(
                            this,
                            $"{nameof(ProvisioningTransportHandlerHttp)} server returned malformed error response." +
                            $"Parsing error: {ex}. Server response: {oe.Response.Content}",
                            nameof(RegisterAsync));
                    }

                    throw new ProvisioningTransportException(
                              $"HTTP transport exception: malformed server error message: '{oe.Response.Content}'",
                              ex,
                              false);
                }
            }
            catch (Exception ex) when(!(ex is ProvisioningTransportException))
            {
                if (Logging.IsEnabled)
                {
                    Logging.Error(
                        this,
                        $"{nameof(ProvisioningTransportHandlerHttp)} threw exception {ex}",
                        nameof(RegisterAsync));
                }

                throw new ProvisioningTransportException($"HTTP transport exception", ex, true);
            }
            finally
            {
                if (Logging.IsEnabled)
                {
                    Logging.Exit(this, $"{nameof(ProvisioningTransportHandlerHttp)}.{nameof(RegisterAsync)}");
                }
            }
        }
Esempio n. 36
0
        internal static async Task RunTestsAsync(DeploymentResult deploymentResult, ILogger logger)
        {
            var httpClientHandler = new HttpClientHandler();
            var httpClient        = deploymentResult.CreateHttpClient(httpClientHandler);

            httpClient.Timeout = TimeSpan.FromSeconds(15);

            // Request to base address and check if various parts of the body are rendered
            // & measure the cold startup time.
            var response = await RetryHelper.RetryRequest(async() =>
            {
                return(await httpClient.GetAsync(string.Empty));
            }, logger, cancellationToken : deploymentResult.HostShutdownToken);

            Assert.False(response == null, "Response object is null because the client could not " +
                         "connect to the server after multiple retries");

            var validator = new Validator(httpClient, httpClientHandler, logger, deploymentResult);

            logger.LogInformation("Verifying home page");
            await validator.VerifyHomePage(response);

            logger.LogInformation("Verifying static files are served from static file middleware");
            await validator.VerifyStaticContentServed();

            logger.LogInformation("Verifying access to a protected resource should automatically redirect to login page.");
            await validator.AccessStoreWithoutPermissions();

            logger.LogInformation("Verifying mismatched passwords trigger validaton errors during user registration");
            await validator.RegisterUserWithNonMatchingPasswords();

            logger.LogInformation("Verifying valid user registration");
            var generatedEmail = await validator.RegisterValidUser();

            logger.LogInformation("Verifying duplicate user email registration");
            await validator.RegisterExistingUser(generatedEmail);

            logger.LogInformation("Verifying incorrect password login");
            await validator.SignInWithInvalidPassword(generatedEmail, "InvalidPassword~1");

            logger.LogInformation("Verifying valid user log in");
            await validator.SignInWithUser(generatedEmail, "Password~1");

            logger.LogInformation("Verifying change password");
            await validator.ChangePassword(generatedEmail);

            logger.LogInformation("Verifying old password is not valid anymore");
            await validator.SignOutUser(generatedEmail);

            await validator.SignInWithInvalidPassword(generatedEmail, "Password~1");

            await validator.SignInWithUser(generatedEmail, "Password~2");

            logger.LogInformation("Verifying authenticated user trying to access unauthorized resource");
            await validator.AccessStoreWithoutPermissions(generatedEmail);

            logger.LogInformation("Verifying user log out");
            await validator.SignOutUser(generatedEmail);

            logger.LogInformation("Verifying admin user login");
            await validator.SignInWithUser("*****@*****.**", "YouShouldChangeThisPassword1!");

            logger.LogInformation("Verifying admin user's access to store manager page");
            await validator.AccessStoreWithPermissions();

            logger.LogInformation("Verifying creating a new album");
            var albumName = await validator.CreateAlbum();

            var albumId = await validator.FetchAlbumIdFromName(albumName);

            logger.LogInformation("Verifying retrieved album details");
            await validator.VerifyAlbumDetails(albumId, albumName);

            logger.LogInformation("Verifying status code pages for non-existing items");
            await validator.VerifyStatusCodePages();

            logger.LogInformation("Verifying non-admin view of an album");
            await validator.GetAlbumDetailsFromStore(albumId, albumName);

            logger.LogInformation("Verifying adding album to a cart");
            await validator.AddAlbumToCart(albumId, albumName);

            logger.LogInformation("Verifying cart checkout");
            await validator.CheckOutCartItems();

            logger.LogInformation("Verifying deletion of album from a cart");
            await validator.DeleteAlbum(albumId, albumName);

            logger.LogInformation("Verifying administrator log out");
            await validator.SignOutUser("Administrator");

            logger.LogInformation("Variation completed successfully.");
        }
Esempio n. 37
0
 /// <summary>
 /// Initializes a new instance of the ContactsListAPI class.
 /// </summary>
 /// <param name='rootHandler'>
 /// Optional. The http client handler used to handle http transport.
 /// </param>
 /// <param name='handlers'>
 /// Optional. The set of delegating handlers to insert in the http
 /// client pipeline.
 /// </param>
 public ContactsListAPI(HttpClientHandler rootHandler, params DelegatingHandler[] handlers)
     : base(rootHandler, handlers)
 {
     this._contacts = new Contacts(this);
     this._baseUri  = new Uri("http://localhost:51864");
 }
Esempio n. 38
0
 public void SingletonReturnsTrue()
 {
     Assert.NotNull(HttpClientHandler.DangerousAcceptAnyServerCertificateValidator);
     Assert.Same(HttpClientHandler.DangerousAcceptAnyServerCertificateValidator, HttpClientHandler.DangerousAcceptAnyServerCertificateValidator);
     Assert.True(HttpClientHandler.DangerousAcceptAnyServerCertificateValidator(null, null, null, SslPolicyErrors.None));
 }
Esempio n. 39
0
 /// <summary>
 /// Initializes a new instance of the DynamicsClient class.
 /// </summary>
 /// <param name='baseUri'>
 /// Optional. The base URI of the service.
 /// </param>
 /// <param name='credentials'>
 /// Required. Subscription credentials which uniquely identify client subscription.
 /// </param>
 /// <param name='rootHandler'>
 /// Optional. The http client handler used to handle http transport.
 /// </param>
 /// <param name='handlers'>
 /// Optional. The delegating handlers to add to the http client pipeline.
 /// </param>
 /// <exception cref="System.ArgumentNullException">
 /// Thrown when a required parameter is null
 /// </exception>
 public DynamicsClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
 {
     if (baseUri == null)
     {
         throw new System.ArgumentNullException("baseUri");
     }
     if (credentials == null)
     {
         throw new System.ArgumentNullException("credentials");
     }
     BaseUri     = baseUri;
     Credentials = credentials;
     if (Credentials != null)
     {
         Credentials.InitializeServiceClient(this);
     }
 }
 public LuisRecognizer(LuisService service, LuisPredictionOptions predictionOptions = null, bool includeApiResults = false, HttpClientHandler clientHandler = null)
     : this(new LuisApplication(service), predictionOptions, includeApiResults, clientHandler)
 {
 }
 public LuisRecognizer(string applicationEndpoint, LuisPredictionOptions predictionOptions = null, bool includeApiResults = false, HttpClientHandler clientHandler = null)
     : this(new LuisApplication(applicationEndpoint), predictionOptions, includeApiResults, clientHandler)
 {
 }
Esempio n. 42
0
 /// <summary>
 /// Initializes a new instance of the EmailFormattingService class.
 /// </summary>
 /// <param name='rootHandler'>
 /// Optional. The http client handler used to handle http transport.
 /// </param>
 /// <param name='handlers'>
 /// Optional. The delegating handlers to add to the http client pipeline.
 /// </param>
 public EmailFormattingService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
 {
     Initialize();
 }
Esempio n. 43
0
 /// <summary>
 /// Initializes a new instance of the DynamicsClient class.
 /// </summary>
 /// <param name='rootHandler'>
 /// Optional. The http client handler used to handle http transport.
 /// </param>
 /// <param name='handlers'>
 /// Optional. The delegating handlers to add to the http client pipeline.
 /// </param>
 protected DynamicsClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
 {
     Initialize();
 }
        public static async Task DownloadDb(DownloadItem downloadItem)
        {
            try
            {
                var ext        = Android.OS.Environment.ExternalStorageDirectory.Path + "/Downloads";
                var rootfolder = FileSystem.Current.LocalStorage;
                var appfolder  = await rootfolder.CreateFolderAsync(ext, CreationCollisionOption.OpenIfExists);

                var dbfolder = await appfolder.CreateFolderAsync("Db", CreationCollisionOption.OpenIfExists);

                var file = await dbfolder.CreateFileAsync(downloadItem.FileName, CreationCollisionOption.ReplaceExisting);

                using (var fileHandler = await file.OpenAsync(FileAccess.ReadAndWrite))
                {
                    var cookieContainer = new CookieContainer();

                    using (var handler = new HttpClientHandler {
                        CookieContainer = cookieContainer
                    })
                        using (var client = new HttpClient(handler)
                        {
                            BaseAddress = new Uri(downloadItem.Url)
                        })
                        {
                            foreach (var header in downloadItem.Headers)
                            {
                                cookieContainer.Add(new Uri(downloadItem.Url), new Cookie(header.Key, header.Value));
                            }

                            var request = new HttpRequestMessage(HttpMethod.Head, downloadItem.Url);

                            var resp = await client.SendAsync(request);

                            if (resp != null && resp.IsSuccessStatusCode && resp.Content?.Headers?.ContentLength != null)
                            {
                                var dataBuffer = await resp.Content.ReadAsByteArrayAsync();

                                var dataBuffer1 = await resp.Content.ReadAsStreamAsync();

                                var dataBuffer2 = resp.Content.LoadIntoBufferAsync();
                                await fileHandler.WriteAsync(dataBuffer, 0, dataBuffer.Length);
                            }


                            //var resp2 = await client.GetAsync(request.RequestUri.AbsolutePath);
                            //if (resp2.IsSuccessStatusCode)
                            //{
                            //    var content = await resp2.Content.ReadAsByteArrayAsync();
                            //    await fileHandler.WriteAsync(content, 0, content.Length);
                            //}
                        }
                    //var _progressBar = new ProgressBar();
                    //_progressBar.Progress = 0;
                    //var progressReporter = new Progress<DownloadBytesProgress>();
                    //progressReporter.ProgressChanged +=
                    //    (s, args) => _progressBar.Progress = (int) (100 * args.PercentComplete);

                    //var downloadTask = CreateDownloadTask(ImageToDownload,
                    //    progressReporter);
                    //var bytesDownloaded = await downloadTask;
                    //Debug.WriteLine("Downloaded {0} bytes.", bytesDownloaded);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 45
0
 public SocksProgressMessageHandler(HttpClientHandler innerHandler)
     : base(innerHandler)
 {
 }
 /// <summary>
 /// Initializes a new instance of the SecurityCenterClient class.
 /// </summary>
 /// <param name='rootHandler'>
 /// Optional. The http client handler used to handle http transport.
 /// </param>
 /// <param name='handlers'>
 /// Optional. The delegating handlers to add to the http client pipeline.
 /// </param>
 protected SecurityCenterClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
 {
     Initialize();
 }
 /// <summary>
 /// Initializes a new instance of the CosmosDBManagementClient class.
 /// </summary>
 /// <param name='rootHandler'>
 /// Optional. The http client handler used to handle http transport.
 /// </param>
 /// <param name='handlers'>
 /// Optional. The delegating handlers to add to the http client pipeline.
 /// </param>
 protected CosmosDBManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
 {
     Initialize();
 }
Esempio n. 48
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddProtectWebApiWithMicrosoftIdentityPlatformV2(Configuration);

            services.Configure <KeyVaultAd>(options => Configuration.GetSection(nameof(KeyVaultAd)).Bind(options));
            services.AddMvc(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddResponseCompression(options =>
            {
                options.Providers.Add <GzipCompressionProvider>();
                options.MimeTypes =
                    ResponseCompressionDefaults.MimeTypes.Concat(
                        new[] { "text/json" });
            });

            services.Configure <GzipCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Fastest;
            });

            services.AddMemoryCache();
            services.AddCors();
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllHeaders",
                                  builder =>
                {
                    builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader().WithExposedHeaders();
                });
            });

            var keyVaultAd = new KeyVaultAd();

            Configuration.GetSection(nameof(KeyVaultAd)).Bind(keyVaultAd);
            var handler = new HttpClientHandler
            {
                Proxy = new WebProxy
                {
                    Address               = new Uri(keyVaultAd.ProxyUrl),
                    BypassProxyOnLocal    = false,
                    UseDefaultCredentials = false,

                    // *** These creds are given to the proxy server, not the web server ***
                    Credentials = new NetworkCredential(keyVaultAd.ProxyUsername, keyVaultAd.ProxyPassword)
                }
            };

            var kv = new KeyVaultClient(
                async(string authority, string resource, string scope) =>
            {
                var authContext             = new AuthenticationContext(authority);
                var clientId                = Configuration.GetSection("AzureAd").GetValue <string>("ClientId");
                var clientSecret            = Configuration.GetSection("AzureAd").GetValue <string>("ClientSecret");
                ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
                AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);
                if (result == null)
                {
                    throw new InvalidOperationException("Failed to retrieve access token for Key Vault");
                }

                return(result.AccessToken);
            }, new HttpClient(handler, true)
                );



            services.AddSingleton <IKeyVaultClient>(kv);

            // Register DA
            services.AddTransient <ICountryDataAccess, CountryDataAccess>();

            // Register Services
            services.AddTransient <ICountryService, CountryService>();
        }
Esempio n. 49
0
 /// <summary>
 /// Initializes a new instance of the AutoRestRFC1123DateTimeTestService class.
 /// </summary>
 /// <param name='rootHandler'>
 /// Optional. The http client handler used to handle http transport.
 /// </param>
 /// <param name='handlers'>
 /// Optional. The delegating handlers to add to the http client pipeline.
 /// </param>
 public AutoRestRFC1123DateTimeTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
 {
     this.Initialize();
 }
Esempio n. 50
0
        /// <summary>
        /// Performs a query on the Twitter Stream.
        /// </summary>
        /// <param name="request">Request with url endpoint and all query parameters.</param>
        /// <returns>
        /// Caller expects an JSON formatted string response, but
        /// real response(s) with streams is fed to the callback.
        /// </returns>
        public async Task <string> QueryTwitterStreamAsync(Request request)
        {
            WriteLog(request.FullUrl, "QueryTwitterStreamAsync");

            var handler = new HttpClientHandler();

            if (Authorizer.Proxy != null && handler.SupportsProxy)
            {
                handler.Proxy = Authorizer.Proxy;
            }

            using (StreamingClient = new HttpClient(handler))
            {
                StreamingClient.Timeout = TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite);

                var httpRequest = ConfigureRequest(request);

                var response = await StreamingClient.SendAsync(
                    httpRequest, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

                await TwitterErrorHandler.ThrowIfErrorAsync(response).ConfigureAwait(false);

                Stream stream = await CreateStream(response);

                const int CarriageReturn = 0x0D;
                const int LineFeed       = 0x0A;

                var    memStr = new MemoryStream();
                byte[] readByte;

                while (stream.CanRead && !IsStreamClosed)
                {
                    readByte = new byte[1];
                    await stream.ReadAsync(readByte, 0, 1, CancellationToken).ConfigureAwait(false);

                    byte nextByte = readByte.SingleOrDefault();

                    CancellationToken.ThrowIfCancellationRequested();

                    if (IsStreamClosed)
                    {
                        break;
                    }

                    if (nextByte == -1)
                    {
                        break;
                    }

                    if (nextByte != CarriageReturn && nextByte != LineFeed)
                    {
                        memStr.WriteByte(nextByte);
                    }

                    if (nextByte == LineFeed)
                    {
                        int    byteCount  = (int)memStr.Length;
                        byte[] tweetBytes = new byte[byteCount];

                        memStr.Position = 0;
                        await memStr.ReadAsync(tweetBytes, 0, byteCount, CancellationToken).ConfigureAwait(false);

                        string tweet       = Encoding.UTF8.GetString(tweetBytes, 0, byteCount);
                        var    strmContent = new StreamContent(this, tweet);

                        await StreamingCallbackAsync(strmContent).ConfigureAwait(false);

                        memStr.Dispose();
                        memStr = new MemoryStream();
                    }
                }
            }

            IsStreamClosed = false;

            return("{}");
        }
Esempio n. 51
0
        /// <summary>
        /// Sends the specified text to be spoken to the TTS service and saves the response audio to a file.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A Task</returns>
        public Task Speak(CancellationToken cancellationToken)
        {
            var cookieContainer = new CookieContainer();
            var handler         = new HttpClientHandler()
            {
                CookieContainer = cookieContainer
            };
            var client = new HttpClient(handler);

            foreach (var header in this.inputOptions.Headers)
            {
                client.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
            }

            var genderValue = "";

            switch (this.inputOptions.VoiceType)
            {
            case Gender.Male:
                genderValue = "Male";
                break;

            case Gender.Female:
            default:
                genderValue = "Female";
                break;
            }

            var request = new HttpRequestMessage(HttpMethod.Post, this.inputOptions.RequestUri)
            {
                Content = new StringContent(String.Format(SsmlTemplate, this.inputOptions.Locale, genderValue, this.inputOptions.VoiceName, this.inputOptions.Text))
            };

            var httpTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);

            Console.WriteLine("Response status code: [{0}]", httpTask.Result.StatusCode);

            var saveTask = httpTask.ContinueWith(
                async(responseMessage, token) =>
            {
                try
                {
                    if (responseMessage.IsCompleted && responseMessage.Result != null && responseMessage.Result.IsSuccessStatusCode)
                    {
                        var httpStream = await responseMessage.Result.Content.ReadAsStreamAsync().ConfigureAwait(false);
                        this.AudioAvailable(new GenericEventArgs <Stream>(httpStream));
                    }
                    else
                    {
                        this.Error(new GenericEventArgs <Exception>(new Exception(String.Format("Service returned {0}", responseMessage.Result.StatusCode))));
                    }
                }
                catch (Exception e)
                {
                    this.Error(new GenericEventArgs <Exception>(e.GetBaseException()));
                }
                finally
                {
                    responseMessage.Dispose();
                    request.Dispose();
                    client.Dispose();
                    handler.Dispose();
                }
            },
                TaskContinuationOptions.AttachedToParent,
                cancellationToken);

            return(saveTask);
        }
Esempio n. 52
0
 /// <summary>
 /// Initializes a new instance of the AutoRestValidationTest class.
 /// </summary>
 /// <param name='rootHandler'>
 /// Optional. The http client handler used to handle http transport.
 /// </param>
 /// <param name='handlers'>
 /// Optional. The delegating handlers to add to the http client pipeline.
 /// </param>
 public AutoRestValidationTest(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
 {
     this.Initialize();
 }
 /// <summary>
 /// Initializes a new instance of the AutoRestSwaggerBATByteService class.
 /// </summary>
 /// <param name='rootHandler'>
 /// Optional. The http client handler used to handle http transport.
 /// </param>
 /// <param name='handlers'>
 /// Optional. The delegating handlers to add to the http client pipeline.
 /// </param>
 public AutoRestSwaggerBATByteService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
 {
     this.Initialize();
 }
Esempio n. 54
0
 public GhostBuster()
 {
     Handler = new HttpClientHandler();
     Client  = new HttpClient(Handler);
 }
 public LuisRecognizer(LuisApplication application, LuisPredictionOptions predictionOptions = null, bool includeApiResults = false, HttpClientHandler clientHandler = null)
 #pragma warning disable CS0618 // Type or member is obsolete
 : this(application, telemetryClient: null, logPersonalInformation: false, predictionOptions: predictionOptions, includeApiResults: includeApiResults, clientHandler: clientHandler)
 #pragma warning restore CS0618 // Type or member is obsolete
 {
 }
Esempio n. 56
0
        public static IServiceCollection AddProjectServices(this IServiceCollection services)
        {
            // PartyMatchManagement Client
            _ = services
                .AddTransient <UserAgentDelegatingHandler>()
                .AddTransient <PartyMatchManagementAuthenticationHandler>()
                .AddHttpClient <IPartyMatchClient, PartyMatchClient>((serviceProvider, httpClient) =>
            {
                var options = serviceProvider.GetRequiredService <PartyMatchManagementOptions>();
                SetHttpClientConfig(httpClient, options);
            })
                .ConfigurePrimaryHttpMessageHandler(x => new DefaultHttpClientHandler())
                .AddHttpMessageHandler <PartyMatchManagementAuthenticationHandler>()
                .AddHttpMessageHandler <UserAgentDelegatingHandler>();

            //QuoteManagement Client
            _ = services
                .AddTransient <QuoteManagementAuthenticationHandler>()
                .AddHttpClient <IQuoteManagementClient, QuoteManagementClient>((serviceProvider, httpClient) =>
            {
                var options = serviceProvider.GetRequiredService <QuoteManagementOptions>();
                SetHttpClientConfig(httpClient, options);
            })
                .ConfigurePrimaryHttpMessageHandler(x => new DefaultHttpClientHandler())
                .AddHttpMessageHandler <QuoteManagementAuthenticationHandler>()
                .AddHttpMessageHandler <UserAgentDelegatingHandler>();

            //CartManagement Client
            _ = services
                .AddTransient <CartManagementAuthenticationHandler>()
                .AddHttpClient <ICartManagementClient, CartManagementClient>((serviceProvider, httpClient) =>
            {
                var options = serviceProvider.GetRequiredService <CartManagementOptions>();
                SetHttpClientConfig(httpClient, options);
            })
                .ConfigurePrimaryHttpMessageHandler(x => new DefaultHttpClientHandler())
                .AddHttpMessageHandler <CartManagementAuthenticationHandler>()
                .AddHttpMessageHandler <UserAgentDelegatingHandler>();

            //PartyManagement Client
            _ = services
                .AddTransient <PartyManagementBearerTokenAuthenticationHandler>()
                .AddHttpClient()
                .AddHttpClient <IPartyManagementClient, PartyManagementClient>((serviceProvider, httpClient) =>
            {
                var options = serviceProvider.GetRequiredService <PartyManagementOptions>();
                SetHttpClientConfig(httpClient, options);
            })
#if DEBUG
                .ConfigurePrimaryHttpMessageHandler(() =>
            {
                var handler = new HttpClientHandler
                {
#pragma warning disable SCS0004 // Certificate Validation has been disabled
                    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
#pragma warning restore SCS0004 // Certificate Validation has been disabled
                };
                return(handler);
            })
#else
                .ConfigurePrimaryHttpMessageHandler(x => new DefaultHttpClientHandler())
#endif
                .AddHttpMessageHandler <PartyManagementBearerTokenAuthenticationHandler>()
                .AddHttpMessageHandler <UserAgentDelegatingHandler>();

            services.AddSingleton <IServiceBusSender, ServiceBusSender>();
            services.AddSingleton <IValidator <Nomination>, NominationValidator>();

            return(services);
        }
        public static async Task <HttpClient> BuildHttpClient(string gridMaster, string apiVersion, Cookie cookie, TimeSpan?timeout = null)
        {
            if (!String.IsNullOrEmpty(gridMaster))
            {
                if (!String.IsNullOrEmpty(apiVersion))
                {
                    if (cookie != null)
                    {
                        if (!cookie.Expired)
                        {
                            if (await CommandHelpers.CheckConnection(gridMaster))
                            {
                                HttpClientHandler Handler = new HttpClientHandler()
                                {
                                    CookieContainer = new CookieContainer()
                                };

                                if (!apiVersion.StartsWith("v"))
                                {
                                    apiVersion = $"v{apiVersion}";
                                }

                                Uri Address = new Uri("https://" + gridMaster + "/wapi/" + apiVersion + "/");

                                Handler.CookieContainer.Add(Address, cookie);

                                Handler.ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

                                HttpClient Client = new HttpClient(Handler)
                                {
                                    BaseAddress = Address
                                };

                                //The actual default timeout is 100 seconds
                                if (timeout != null)
                                {
                                    Client.Timeout = (TimeSpan)timeout;
                                }

                                return(Client);
                            }
                            else
                            {
                                throw new WebException("The grid master could not be contacted.");
                            }
                        }
                        else
                        {
                            throw new ArgumentException($"The provided cookie is expired, it expired on {cookie.Expires.ToUniversalTime().ToString()} UTC");
                        }
                    }
                    else
                    {
                        throw new ArgumentNullException("cookie", "Cookie cannot be null");
                    }
                }
                else
                {
                    throw new ArgumentNullException("apiVersion", "The api version parameter cannot be null or empty.");
                }
            }
            else
            {
                throw new ArgumentNullException("gridMaster", "The value for the grid master cannot be null or empty.");
            }
        }
        public static async Task <HttpClient> BuildHttpClient(string gridMaster, string apiVersion, string username, SecureString password, TimeSpan?timeout = null)
        {
            if (!String.IsNullOrEmpty(gridMaster))
            {
                if (!String.IsNullOrEmpty(apiVersion))
                {
                    if (!String.IsNullOrEmpty(username))
                    {
                        if (password != null)
                        {
                            if (await CommandHelpers.CheckConnection(gridMaster))
                            {
                                HttpClientHandler Handler = new HttpClientHandler();
                                Handler.ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

                                if (!apiVersion.StartsWith("v"))
                                {
                                    apiVersion = $"v{apiVersion}";
                                }

                                HttpClient Client = new HttpClient(Handler)
                                {
                                    BaseAddress = new Uri("https://" + gridMaster + "/wapi/" + apiVersion + "/")
                                };

                                //The actual default is 100 seconds
                                if (timeout != null)
                                {
                                    Client.Timeout = (TimeSpan)timeout;
                                }

                                Client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic",
                                                                                                                                   Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + SecureStringHelper.ToReadableString(password))));

                                return(Client);
                            }
                            else
                            {
                                throw new WebException("The grid master could not be contacted.");
                            }
                        }
                        else
                        {
                            throw new ArgumentNullException("password", "The provided password cannot be null.");
                        }
                    }
                    else
                    {
                        throw new ArgumentNullException("username", "The username used to connect to the grid master cannot be null or empty.");
                    }
                }
                else
                {
                    throw new ArgumentNullException("apiVersion", "The api version parameter cannot be null or empty.");
                }
            }
            else
            {
                throw new ArgumentNullException("gridMaster", "The value for the grid master cannot be null or empty.");
            }
        }
        public static async Task <HttpClient> BuildHttpClient(string gridMaster, string apiVersion, TimeSpan?timeout = null)
        {
            if (!String.IsNullOrEmpty(gridMaster))
            {
                if (!String.IsNullOrEmpty(apiVersion))
                {
                    if (await CommandHelpers.CheckConnection(gridMaster))
                    {
                        if (InfobloxSessionData.UseSessionData)
                        {
                            if (InfobloxSessionData.Cookie != null && !InfobloxSessionData.Cookie.Expired)
                            {
                                HttpClientHandler Handler = new HttpClientHandler()
                                {
                                    CookieContainer = new CookieContainer()
                                };

                                if (!apiVersion.StartsWith("v"))
                                {
                                    apiVersion = $"v{apiVersion}";
                                }

                                Uri Address = new Uri("https://" + gridMaster + "/wapi/" + apiVersion + "/");

                                Handler.CookieContainer.Add(Address, InfobloxSessionData.Cookie);

                                Handler.ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

                                HttpClient Client = new HttpClient(Handler)
                                {
                                    BaseAddress = Address
                                };

                                //The actual default is 100 seconds
                                if (timeout != null)
                                {
                                    Client.Timeout = (TimeSpan)timeout;
                                }

                                return(Client);
                            }
                            else
                            {
                                throw new Exception("There is not a valid cookie to utilize, you must specify a credential.");
                            }
                        }
                        else
                        {
                            throw new Exception("There is not a valid cookie to utilize, you must specify a credential.");
                        }
                    }
                    else
                    {
                        throw new WebException("The grid master could not be contacted.");
                    }
                }
                else
                {
                    throw new ArgumentNullException("apiVersion", "The api version parameter cannot be null or empty.");
                }
            }
            else
            {
                throw new ArgumentNullException("gridMaster", "The value for the grid master cannot be null or empty.");
            }
        }
 public void Default_CredentialCacheDefaultCredentials_Same()
 {
     using (var handler = new HttpClientHandler())
     {
         Assert.Same(CredentialCache.DefaultCredentials, handler.DefaultProxyCredentials);
     }
 }