public void SetUp() { // mock logger var mockLogger = Substitute.For <ILogger>(); mockLogger.IsDebugEnabled.Returns(true); mockLogger.IsInfoEnabled.Returns(true); mockLogger.IsWarnEnabled.Returns(true); mockLogger.IsErrorEnabled.Returns(true); // mock trust manager var trustManager = Substitute.For <ISSLTrustManager>(); var openKitConfig = Substitute.For <IOpenKitConfiguration>(); openKitConfig.EndpointUrl.Returns(BaseUrl); openKitConfig.DefaultServerId.Returns(ServerId); openKitConfig.ApplicationId.Returns(ApplicationId); openKitConfig.TrustManager.Returns(trustManager); var threadSuspender = Substitute.For <IInterruptibleThreadSuspender>(); // HTTPClient spy var httpConfiguration = HttpClientConfiguration.From(openKitConfig); spyClient = Substitute.ForPartsOf <StubHttpClient>(mockLogger, httpConfiguration, threadSuspender); mockAdditionalParameters = Substitute.For <IAdditionalQueryParameters>(); }
public UDSDto GetUDSSource(Data.Entity.UDS.UDSRepository udsRepository, string odataFilter) { string controllerName = Utils.GetWebAPIControllerName(udsRepository.Name); IBaseAddress webApiAddress = DocSuiteContext.Current.CurrentTenant.WebApiClientConfig.Addresses.FirstOrDefault(x => x.AddressName.Eq(UDS_ADDRESS_NAME)); WebApiControllerEndpoint udsEndpoint = new WebApiControllerEndpoint { AddressName = UDS_ADDRESS_NAME, ControllerName = controllerName, EndpointName = "UDSModel" }; HttpClientConfiguration customHttpConfiguration = new HttpClientConfiguration(); customHttpConfiguration.Addresses.Add(webApiAddress); customHttpConfiguration.EndPoints.Add(udsEndpoint); odataFilter = string.Concat("?", odataFilter, "&applySecurity='0'"); string jsonSource = WebAPIImpersonatorFacade.ImpersonateRawRequest <UDSModel, string>(WebAPIHelper, odataFilter, customHttpConfiguration); if (string.IsNullOrEmpty(jsonSource)) { return(null); } return(ReadUDSJson(jsonSource, udsRepository)); }
public void Usage2() { using (var services = TestHelper.CreateServiceProvider(registerServices)) { var sut = services.GetRequiredService <IHttpClientGenerator>(); var cfg1 = new HttpClientConfiguration() { BaseAddress = "https://www.wikipedia.org/" }; var cfg2 = new HttpClientConfiguration() { BaseAddress = "https://www.wikipedia.org/" }; var client1 = sut.CreateHttpClient(cfg1); var client2 = sut.CreateHttpClient(cfg2); Assert.NotSame(client1, client2); cfg2.BaseAddress = "https://localhost"; var client3 = sut.CreateHttpClient(cfg2); Assert.NotSame(client2, client3); client1.Dispose(); client2.Dispose(); client3.Dispose(); } }
public OpenKitInitializer(IOpenKitBuilder builder) { logger = builder.Logger; privacyConfiguration = PrivacyConfiguration.From(builder); openKitConfiguration = OpenKitConfiguration.From(builder); timingProvider = new DefaultTimingProvider(); threadIdProvider = new DefaultThreadIdProvider(); sessionIdProvider = new DefaultSessionIdProvider(); beaconCache = new BeaconCache(logger); beaconCacheEvictor = new BeaconCacheEvictor(logger, beaconCache, BeaconCacheConfiguration.From(builder), timingProvider); var httpClientConfig = HttpClientConfiguration.From(openKitConfiguration); // shared thread suspender between BeaconSender and HttpClient. HttpClient will be woken up when // BeaconSender shuts down var beaconSenderThreadSuspender = new InterruptibleThreadSuspender(); beaconSender = new BeaconSender( logger, httpClientConfig, new DefaultHttpClientProvider(logger, beaconSenderThreadSuspender), timingProvider, beaconSenderThreadSuspender); var watchdogThreadSuspender = new InterruptibleThreadSuspender(); sessionWatchdog = new SessionWatchdog( logger, new SessionWatchdogContext(timingProvider, watchdogThreadSuspender)); }
private async Task RunHttpsAvailabilityTest(HttpClientConfiguration configuration, string hostname, int basePort) { try { var clientConfiguration = new HttpClientConfiguration( useHttps: true, configuration.SecurityRole, configuration.Timeout, configuration.VerificationMode, configuration.SupplyClientCertificate ); HttpMessageHandler messageHandler = null; HttpClient httpsClient = null; await ValidateReachability(hostname, basePort, fallbackOnProtocolError : false, clientFactory : _ => { messageHandler = _httpMessageHandlerFactory(clientConfiguration); httpsClient = CreateHttpClient(messageHandler, configuration.Timeout); return(httpsClient, isHttps : true, isNewCreated : true); // the return value is ignored as this async task is not awaited }, cancellationToken : CancellationToken.None); lock (HttpClientLock) { Log.Info(msg => msg($"DelayDebug : ValidateReachability created new Https HttpClient (isEqual={LastHttpClient.Equals(httpsClient)})")); // we expect this not to be equal ever LastHttpClient = httpsClient; LastHttpClientKey = new HttpClientConfiguration( useHttps: true, configuration.SecurityRole, configuration.Timeout, configuration.VerificationMode, configuration.SupplyClientCertificate); _httpMessageHandler = messageHandler; } }
public static IUnityContainer GetConfiguredContainer() { var container = new UnityContainer(); var httpConfiguration = new HttpClientConfiguration(new Uri("http://localhost:18511/api/"), new MediaTypeWithQualityHeaderValue("application/json")); //container.RegisterInstance(typeof(IHttpClientConfiguration), httpConfiguration); container.RegisterType( typeof(ICartClientProxy <Customer>), typeof(CartClientProxy <Customer>), ServiceName.Customer.ToString(), new InjectionConstructor( new InjectionParameter(typeof(IHttpClientConfiguration), httpConfiguration), new InjectionParameter(typeof(ServiceName), ServiceName.Customer) )); container.RegisterType(typeof(ICartClientService <>), typeof(CartClientService <>)); container.RegisterType <ICustomerViewModel, CustomerViewModel>( new InjectionConstructor( new InjectionParameter( typeof(ICartClientService <Customer>), container.Resolve( typeof(ICartClientService <Customer>) , new DependencyOverride( typeof(ICartClientProxy <Customer>), container.Resolve(typeof(ICartClientProxy <Customer>), ServiceName.Customer.ToString())))))); return(container); }
public bool HasViewableRight(Guid idDocumentUnit, string username, string domain) { string odataFilter = $"/DocumentUnitService.HasViewableDocument(idDocumentUnit={idDocumentUnit},username='******',domain='{domain}')"; IBaseAddress webApiAddress = DocSuiteContext.Current.CurrentTenant.WebApiClientConfig.Addresses.Single(x => x.AddressName.Eq(WebApiHttpClient.ODATA_ADDRESS_NAME)); TenantEntityConfiguration documentUnitEndpoint = DocSuiteContext.Current.CurrentTenant.Entities.Single(x => x.Key.Eq(ODATA_DOCUMENTUNIT_ENDPOINT_NAME)).Value; HttpClientConfiguration customHttpConfiguration = new HttpClientConfiguration(); customHttpConfiguration.Addresses.Add(webApiAddress); WebApiControllerEndpoint endpoint = new WebApiControllerEndpoint { AddressName = webApiAddress.AddressName, ControllerName = documentUnitEndpoint.ODATAControllerName, EndpointName = ODATA_DOCUMENTUNIT_ENDPOINT_NAME }; customHttpConfiguration.EndPoints.Add(endpoint); ODataModel <bool> result = WebAPIImpersonatorFacade.ImpersonateRawRequest <DocumentUnitEntities.DocumentUnit, ODataModel <bool> >(WebAPIHelper, odataFilter, customHttpConfiguration); if (result != null) { return(result.Value); } else { FileLogger.Warn(LogName.FileLog, string.Concat("HasViewableRight -> Document unit con id ", idDocumentUnit, " non trovata.")); return(false); } }
public async Task CorrelationId_IsUsedInRequestHeader(string correlationId) { using (var httpTest = new HttpTest()) { // Arrange var baseUri = "http://localhost"; httpTest.RespondWithJson("{}"); var headers = new Dictionary <string, string> { { "X-Correlation-Id", correlationId } }; HttpClientConfiguration.ConfigureHttpClients(() => headers); // Act await baseUri .GetAsync(); // Assert httpTest.CallLog.Single().Request.Headers.Single() .Key.Should().Be("X-Correlation-Id"); httpTest.CallLog.Single().Request.Headers.Single() .Value.Single().Should().Be(correlationId); } }
public void GetHashCodeTest() { var configuration = new HttpClientConfiguration(); var value = configuration.GetHashCode(); var configuration2 = new HttpClientConfiguration(); configuration2.GetHashCode().Should().Be(value); configuration2 = new HttpClientConfiguration(); configuration2.AllowAutoRedirect = !configuration.AllowAutoRedirect; configuration2.GetHashCode().Should().NotBe(value); configuration2 = new HttpClientConfiguration(); configuration2.SslProtocol = "Tls12"; configuration2.GetHashCode().Should().NotBe(value); configuration2 = new HttpClientConfiguration(); configuration2.Certificates = "test"; configuration2.GetHashCode().Should().NotBe(value); configuration2 = new HttpClientConfiguration(); configuration2.ClientCertificateOption = System.Net.Http.ClientCertificateOption.Automatic; configuration2.GetHashCode().Should().NotBe(value); }
private (HttpClient httpClient, bool isHttps, bool isNewCreated) GetHttpClient(ServiceDiscoveryConfig serviceConfig, DiscoveryConfig defaultConfig, bool tryHttps, string hostname, int basePort) { var forceHttps = serviceConfig.UseHttpsOverride ?? (ServiceInterfaceRequiresHttps || defaultConfig.UseHttpsOverride); var useHttps = tryHttps || forceHttps; string securityRole = serviceConfig.SecurityRole; var verificationMode = serviceConfig.ServerCertificateVerification ?? defaultConfig.ServerCertificateVerification; var supplyClientCertificate = (serviceConfig.ClientCertificateVerification ?? defaultConfig.ClientCertificateVerification) == ClientCertificateVerificationMode.VerifyIdenticalRootCertificate; var httpKey = new HttpClientConfiguration(useHttps, securityRole, serviceConfig.RequestTimeout, verificationMode, supplyClientCertificate); lock (HttpClientLock) { if (LastHttpClient != null && LastHttpClientKey.Equals(httpKey)) { return(httpClient : LastHttpClient, isHttps : useHttps, isNewCreated : false); } // In case we're trying HTTPs and the previous request on this instance was HTTP (or if this is the first request) if (Not(forceHttps) && httpKey.UseHttps && Not(LastHttpClientKey?.UseHttps ?? false)) { var now = DateTime.Now; if (now - _lastHttpsTestTime > _httpsTestInterval) { _lastHttpsTestTime = now; RunHttpsAvailabilityTest(httpKey, hostname, basePort); } httpKey = new HttpClientConfiguration( useHttps: false, securityRole: null, timeout: httpKey.Timeout, verificationMode: httpKey.VerificationMode, supplyClientCertificate: httpKey.SupplyClientCertificate); } var isNewCreated = false; if (!(LastHttpClientKey?.Equals(httpKey) ?? false)) { isNewCreated = true; var equalState = (LastHttpClientKey?.Equals(httpKey))?.ToString() ?? "FirstTime"; Log.Info(msg => msg("GetHttpClient created new HttpClient", unencryptedTags: new Tags { { "debug.delay.newHttpClient", equalState }, { "debug.delay.method", "GetHttpClient" } })); // we expect this not to be equal ever var messageHandler = _httpMessageHandlerFactory(httpKey); var httpClient = CreateHttpClient(messageHandler, httpKey.Timeout); LastHttpClient = httpClient; LastHttpClientKey = httpKey; _httpMessageHandler = messageHandler; } return(httpClient : LastHttpClient, isHttps : httpKey.UseHttps, isNewCreated : isNewCreated); } }
public void SslProtocolInternalTest(string sslProtocol, SslProtocols expected) { var configuration = new HttpClientConfiguration(); configuration.SslProtocol = sslProtocol; configuration.SslProtocolInternal.Should().Be(expected); }
public void Setup() { var config = new HttpClientConfiguration { BaseUrl = WebApiSetupFixture.BaseAddress }; _client = new HttpClient(config); _repo = InMemoryTodoRepo.Instance; }
public void Usage1() { using (var services = TestHelper.CreateServiceProvider(registerServices)) { var sut = services.GetRequiredService <IHttpClientGenerator>(); var cfg1 = new HttpClientConfiguration(); var cfg2 = new HttpClientConfiguration(); var client1 = sut.CreateHttpClient(cfg1); var client2 = sut.CreateHttpClient(cfg2); Assert.NotSame(client1, client2); } }
public HttpClient(HttpClientConfiguration config) { var serializers = config.Advanced.Serializers.Concat(ContentSerializers.Defaults).ToList(); var defaultContentType = config.Advanced.ContentType == ContentType.Unknown ? ContentType.ApplicationJson : config.Advanced.ContentType; _urlBuilder = new UrlBuilder(config.BaseUrl); _requestWrapper = new WebRequestWrapper(serializers, defaultContentType); _responseTransformer = new ResponseTransformer(serializers); }
public void ConfigurationIsLoadedCorrectly() { // arrange const string agentString = "Kuroyukihime"; ApplicationConfigurationHelper.AdjustKeys(ConfigurationKeys.UserAgent, agentString); // act var sut = new HttpClientConfiguration(); // assert sut.UserAgent.Should().Be(agentString); }
static void Main(string[] args) { var config = new HttpClientConfiguration { BaseUrl = "http://localhost:1337/", Advanced = { Serializers = new List <IContentSerializer> { new Serializer <NewtonSoft>(ContentType.ApplicationJson), new Serializer <DefaultXml>(ContentType.ApplicationXml) } } }; var tomorrow = new Todo { Description = "Sleep in" }; var xmlSerializer = new Serializer <DefaultXml>(ContentType.ApplicationXml); var todoXml = xmlSerializer.Serialize(tomorrow); var xmlBack = xmlSerializer.Deserialize <Todo>(todoXml); // Create a custom serializer var custom = SerializeSettings .For(ContentType.ApplicationJson) .Serialize(NewtonSoft.Serialize) .Deserialize(DefaultJson.Deserialize); var customJson = custom.Serialize(tomorrow); var customObj = custom.Deserialize <Todo>(customJson); // Configure JsonNet however you want var newtonSoftSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; //Register the change NewtonSoft.UpdateSettings(new NewtonsoftSettings { Settings = newtonSoftSettings }); // Go crazy, oh baby! var serializer = new Serializer <NewtonSoft>(ContentType.ApplicationJson); var tomorrowJson = serializer.Serialize(tomorrow); var tommorowObj = serializer.Deserialize <Todo>(tomorrowJson); var client = new HttpClient(config); var created = client.PostAsync <Todo>("api/todos", tomorrow).Result; }
public void SetConnectionTimeout_ConfiguresConnectionLeaseTimeout( Uri uri, int timeout) { // Arrange // Act HttpClientConfiguration.SetConnectionTimeout(uri, timeout); // Assert var sp = ServicePointManager.FindServicePoint(uri); sp.ConnectionLeaseTimeout.Should().Be(timeout * 1000); }
private (HttpClient httpClient, bool isHttps) GetHttpClient(ServiceDiscoveryConfig serviceConfig, DiscoveryConfig defaultConfig, bool tryHttps, string hostname, int basePort) { var forceHttps = serviceConfig.UseHttpsOverride ?? (ServiceInterfaceRequiresHttps || defaultConfig.UseHttpsOverride); var useHttps = tryHttps || forceHttps; string securityRole = serviceConfig.SecurityRole; var verificationMode = serviceConfig.ServerCertificateVerification ?? defaultConfig.ServerCertificateVerification; var supplyClientCertificate = (serviceConfig.ClientCertificateVerification ?? defaultConfig.ClientCertificateVerification) == ClientCertificateVerificationMode.VerifyIdenticalRootCertificate; var httpKey = new HttpClientConfiguration(useHttps, securityRole, serviceConfig.RequestTimeout, verificationMode, supplyClientCertificate); lock (HttpClientLock) { if (LastHttpClient != null && LastHttpClientKey.Equals(httpKey)) { return(httpClient : LastHttpClient, isHttps : useHttps); } // In case we're trying HTTPs and the previous request on this instance was HTTP (or if this is the first request) if (Not(forceHttps) && httpKey.UseHttps && Not(LastHttpClientKey?.UseHttps ?? false)) { var now = DateTime.Now; if (now - _lastHttpsTestTime > _httpsTestInterval) { _lastHttpsTestTime = now; RunHttpsAvailabilityTest(httpKey, hostname, basePort); } httpKey = new HttpClientConfiguration( useHttps: false, securityRole: null, timeout: httpKey.Timeout, verificationMode: httpKey.VerificationMode, supplyClientCertificate: httpKey.SupplyClientCertificate); } if (!(LastHttpClientKey?.Equals(httpKey) ?? false)) { var messageHandler = _httpMessageHandlerFactory(httpKey); var httpClient = CreateHttpClient(messageHandler, httpKey.Timeout); LastHttpClient = httpClient; LastHttpClientKey = httpKey; _httpMessageHandler = messageHandler; } return(httpClient : LastHttpClient, isHttps : httpKey.UseHttps); } }
public void CreateWithSslCertificateTest() { var factory = CreateHttpClientFactory(); HttpClientConfiguration configuration = new HttpClientConfiguration { Certificates = "certName", SslProtocol = "Tls11|Tls12" }; var client = factory.Create(configuration); configuration.SslProtocolInternal.Should().Be(SslProtocols.Tls11 | SslProtocols.Tls12); client.Should().NotBeNull(); // todo: veryfication of settings }
public FunTranslationClient(IHttpClientFactory clientFactory, IOptions <HttpClientOptions> options) { _client = clientFactory.CreateClient(_httpClientName); HttpClientConfiguration httpClientConfiguration = options?.Value?.ClientConfigurations ?.FirstOrDefault(cc => cc.Name == _httpClientConfigurationName); if (httpClientConfiguration == null) { throw new InvalidOperationException($"Cannot create {nameof(FunTranslationClient)} without {nameof(HttpClientConfiguration)}"); } _client.BaseAddress = new Uri(httpClientConfiguration.BaseAddress); _client.Timeout = httpClientConfiguration.Timeout; _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); }
private static async Task run3(string urlOfSampleServer, IHttpClientGenerator httpClientGenerator) { System.Console.Out.WriteLine( $"Calling '{urlOfSampleServer}' using a dynamic configuration" ); int loop = 0; var configuration = new HttpClientConfiguration() { Name = "dynamicHttpSampleServer", Discriminator = "anonymous", BaseAddress = urlOfSampleServer, }; configuration.PrimaryHandlerConfigurations.Add((builder) => { System.Console.Out.WriteLine($"This is called only once in the loop {loop} for PrimaryHandlerConfigurations."); // enable windows-auth builder.EnsurePrimaryHandler().UseDefaultCredentials = true; // you can call // builder.AdditionalHandlers.Add // you don't need to do it seperatly }); configuration.AdditionalHandlerConfigurations.Add((builder) => { System.Console.Out.WriteLine($"This is called only once in the loop {loop} for AdditionalHandlerConfigurations."); builder.AdditionalHandlers.Add( new WhateverDelegatingHandler("you") ); }); configuration.HttpClientConfigurations.Add((HttpClient, httpClientConfiguration) => { System.Console.Out.WriteLine($"This is called for each request - now in the loop {loop} for HttpClientConfigurations."); }); for (loop = 0; loop < 3; loop++) { using (var httpClient = httpClientGenerator.CreateHttpClient(configuration)) { var responce = await httpClient.GetAsync(""); var content = await responce.Content.ReadAsStringAsync(); System.Console.Out.WriteLine($"Responce: {responce.StatusCode} {content}"); } } }
private static async Task run2(IHttpClientGenerator httpClientGenerator) { System.Console.Out.WriteLine( $"Calling 'https://www.github.com' using a dynamic configuration" ); var configuration = new HttpClientConfiguration() { Name = "dynamic", Discriminator = "anonymous", BaseAddress = "https://www.github.com" }; // // To reuse the configuration set it to the Configurations. // httpClientGenerator.Configurations[configuration.Name] = configuration; // after the configuration is shared don't modify it - unless you know it better. // // You may / You can do this - You *don't* have to. // // The fields // configuration.BaseAddress // configuration.Name // configuration.Discriminator // are part of the HashCode / Equals. // // To reuse the socket in a valid way set the values. // configuration.Name: the name as e.g "DynamicForMyAPI" // configuration.Discriminator: if you have 2 user you may set Discriminator = username // /* * The name is part of the logger * info: System.Net.Http.HttpClient.github.LogicalHandler[100] * Start processing HTTP request GET https://www.github.com/ * * info: System.Net.Http.HttpClient.dynamic.LogicalHandler[100] * Start processing HTTP request GET https://www.github.com/ */ using (var httpClient = httpClientGenerator.CreateHttpClient(configuration)) { var responce = await httpClient.GetAsync(""); System.Console.Out.WriteLine($"StatusCode: {responce.StatusCode}"); } }
public void CacheTest() { var factory = CreateHttpClientFactory(); HttpClientConfiguration configuration = new HttpClientConfiguration { Certificates = "certName", SslProtocol = "Tls12" }; var client1 = factory.Create(configuration); var client2 = factory.Create(configuration); client1.Should().Be(client2); configuration.SslProtocol = "Tls11"; var client3 = factory.Create(configuration); client3.Should().NotBe(client1); }
public async Task CorrelationId_IsNotSpecifiedInRequest_Header() { using (var httpTest = new HttpTest()) { // Arrange var baseUri = "http://localhost"; httpTest.RespondWithJson("{}"); var headers = new Dictionary <string, string>(); HttpClientConfiguration.ConfigureHttpClients(() => headers); // Act await baseUri .GetAsync(); // Assert httpTest.CallLog.Single().Request.Headers.Should().NotContain( x => x.Key.Equals("X-Correlation-Id", StringComparison.OrdinalIgnoreCase)); } }
public DomainUserModel domainUserModel() { string odataFilter = $"/DomainUserService.GetCurrentRights()"; IBaseAddress webApiAddress = DocSuiteContext.Current.CurrentTenant.WebApiClientConfig.Addresses.Single(x => x.AddressName.Eq(WebApiHttpClient.ODATA_ADDRESS_NAME)); TenantEntityConfiguration domainuserEndpoint = DocSuiteContext.Current.CurrentTenant.Entities.Single(x => x.Key.Eq(ODATA_DOMAINUSER_ENDPOINT_NAME)).Value; HttpClientConfiguration customHttpConfiguration = new HttpClientConfiguration(); customHttpConfiguration.Addresses.Add(webApiAddress); WebApiControllerEndpoint endpoint = new WebApiControllerEndpoint { AddressName = webApiAddress.AddressName, ControllerName = domainuserEndpoint.ODATAControllerName, EndpointName = ODATA_DOMAINUSER_ENDPOINT_NAME }; customHttpConfiguration.EndPoints.Add(endpoint); DomainUserModel result = WebAPIImpersonatorFacade.ImpersonateRawRequest <DomainUser, DomainUserModel>(WebAPIHelper, odataFilter, customHttpConfiguration); return(result); }
public bool HasProcedureDistributionInsertRight(int idCategory) { string odataFilter = $"/FascicleService.HasProcedureDistributionInsertRight(idCategory={idCategory})"; IBaseAddress webApiAddress = DocSuiteContext.Current.CurrentTenant.WebApiClientConfig.Addresses.Single(x => x.AddressName.Eq(WebApiHttpClient.ODATA_ADDRESS_NAME)); TenantEntityConfiguration fascicleEndpoint = DocSuiteContext.Current.CurrentTenant.Entities.Single(x => x.Key.Eq(ODATA_FASCICLE_ENDPOINT_NAME)).Value; HttpClientConfiguration customHttpConfiguration = new HttpClientConfiguration(); customHttpConfiguration.Addresses.Add(webApiAddress); WebApiControllerEndpoint endpoint = new WebApiControllerEndpoint { AddressName = webApiAddress.AddressName, ControllerName = fascicleEndpoint.ODATAControllerName, EndpointName = ODATA_FASCICLE_ENDPOINT_NAME }; customHttpConfiguration.EndPoints.Add(endpoint); ODataModel <bool> result = WebAPIImpersonatorFacade.ImpersonateRawRequest <Fascicle, ODataModel <bool> >(WebAPIHelper, odataFilter, customHttpConfiguration); return(result.Value); }
public bool HasCollaborationViewableRight(int idCollaboration) { string odataFilter = $"/CollaborationService.HasViewableRight(idCollaboration={idCollaboration})"; IBaseAddress webApiAddress = DocSuiteContext.Current.CurrentTenant.WebApiClientConfig.Addresses.Single(x => x.AddressName.Eq(WebApiHttpClient.ODATA_ADDRESS_NAME)); TenantEntityConfiguration collaborationEndpoint = DocSuiteContext.Current.CurrentTenant.Entities.Single(x => x.Key.Eq(ODATA_COLLABORATION_ENDPOINT_NAME)).Value; HttpClientConfiguration customHttpConfiguration = new HttpClientConfiguration(); customHttpConfiguration.Addresses.Add(webApiAddress); WebApiControllerEndpoint endpoint = new WebApiControllerEndpoint { AddressName = webApiAddress.AddressName, ControllerName = collaborationEndpoint.ODATAControllerName, EndpointName = ODATA_COLLABORATION_ENDPOINT_NAME }; customHttpConfiguration.EndPoints.Add(endpoint); ODataModel <bool> result = WebAPIImpersonatorFacade.ImpersonateRawRequest <Collaboration, ODataModel <bool> >(WebAPIHelper, odataFilter, customHttpConfiguration); return(result.Value); }
public bool HasFascicleDocumentViewableRight(Guid idFascicle, string username, string domain) { string odataFilter = string.Concat("/FascicleService.HasViewableDocument(idFascicle=", idFascicle, ",username='******',domain='", domain, "')"); IBaseAddress webApiAddress = DocSuiteContext.Current.CurrentTenant.WebApiClientConfig.Addresses.Single(x => x.AddressName.Eq(WebApiHttpClient.ODATA_ADDRESS_NAME)); TenantEntityConfiguration fascicleEndpoint = DocSuiteContext.Current.CurrentTenant.Entities.Single(x => x.Key.Eq(ODATA_FASCICLE_ENDPOINT_NAME)).Value; HttpClientConfiguration customHttpConfiguration = new HttpClientConfiguration(); customHttpConfiguration.Addresses.Add(webApiAddress); WebApiControllerEndpoint endpoint = new WebApiControllerEndpoint { AddressName = webApiAddress.AddressName, ControllerName = fascicleEndpoint.ODATAControllerName, EndpointName = ODATA_FASCICLE_ENDPOINT_NAME }; customHttpConfiguration.EndPoints.Add(endpoint); ODataModel <bool> result = WebAPIHelper.GetRawRequest <Fascicle, ODataModel <bool> >(customHttpConfiguration, customHttpConfiguration, odataFilter); return(result.Value); }
private async Task RunHttpsAvailabilityTest(HttpClientConfiguration configuration, string hostname, int basePort) { try { var clientConfiguration = new HttpClientConfiguration( useHttps: true, configuration.SecurityRole, configuration.Timeout, configuration.VerificationMode, configuration.SupplyClientCertificate ); HttpMessageHandler messageHandler = null; HttpClient httpsClient = null; await ValidateReachability(hostname, basePort, fallbackOnProtocolError : false, clientFactory : _ => { messageHandler = _httpMessageHandlerFactory(clientConfiguration); httpsClient = CreateHttpClient(messageHandler, configuration.Timeout); return(httpsClient, isHttps : true); // the return value is ignored as this async task is not awaited }, cancellationToken : CancellationToken.None); lock (HttpClientLock) { LastHttpClient = httpsClient; LastHttpClientKey = new HttpClientConfiguration( useHttps: true, configuration.SecurityRole, configuration.Timeout, configuration.VerificationMode, configuration.SupplyClientCertificate); _httpMessageHandler = messageHandler; } } catch (HttpRequestException ex) { Log.Info(_ => _($"HTTPS for service {ServiceName} is not available.")); Log.Debug(_ => _($"HTTPS for service {ServiceName} is not available.", ex)); } }
public void FlurlHttpGlobalSettings_AreConfigured() { // Arrange var headers = new Dictionary <string, string>(); var testObject = new { Property = "value" }; // Initial Assert FlurlHttp.GlobalSettings.BeforeCall.Should().BeNull(); var initialSerializedTestObject = FlurlHttp.GlobalSettings .JsonSerializer.Serialize(testObject); initialSerializedTestObject.Should().Be("{\"Property\":\"value\"}"); // Act HttpClientConfiguration.ConfigureHttpClients(() => headers); // Final Assert FlurlHttp.GlobalSettings.BeforeCall.Should().NotBeNull(); var serializedTestObject = FlurlHttp.GlobalSettings .JsonSerializer.Serialize(testObject); serializedTestObject.Should().Be("{\"property\":\"value\"}"); }