public void DoesNotCreateAuthenticationHeaderWhenUsernameIsNullOrEmpty( [Values("", " ", null)] string username ) { var wrapper = new HttpClientWrapper(username); Assert.IsNull(wrapper.AuthenticationHeaderValue); }
public void DoesNotCreateAuthenticationHeaderWhenPasswordIsNullOrEmpty( [Values("", " ", null)] string password ) { var wrapper = new HttpClientWrapper(password: password); Assert.IsNull(wrapper.AuthenticationHeaderValue); }
public void UsesGivenHttpClient() { var client = Substitute.For<HttpClient>(); var wrapper = new HttpClientWrapper(client); Assert.AreSame(wrapper.Client, client); }
public void SetsTheUsernameAndPasswordProperties() { const string username = "******"; const string password = "******"; var client = Substitute.For<HttpClient>(); var wrapper = new HttpClientWrapper(username, password, client); Assert.AreEqual(username, wrapper.Username); Assert.AreEqual(password, wrapper.Password); }
public void SetsAuthenticationHeaderValueCorrectly() { const string username = "******"; const string password = "******"; var base64 = Base64Header(username, password); var wrapper = new HttpClientWrapper(username, password, Substitute.For<HttpClient>()); Assert.AreEqual("Basic", wrapper.AuthenticationHeaderValue.Scheme); Assert.AreEqual(base64, wrapper.AuthenticationHeaderValue.Parameter); }
/// <summary> /// Login to DLAP. Call Logout to close session. /// </summary> /// <param name="prefix"> /// Login prefix /// </param> /// <param name="username"> /// User name /// </param> /// <param name="password"> /// The password /// </param> /// <returns> /// XML results /// </returns> public Task <XElement> LoginAsync(string prefix, string username, string password) { _httpClientWrapper = new HttpClientWrapper(Timeout, new CookieContainer(), false); return(PostAsync( null, new XElement( "request", new XAttribute("cmd", "login"), new XAttribute("username", string.Concat(prefix, "/", username)), new XAttribute("password", password)))); }
public async Task Send_EmptyAcceptHeader_SetsAcceptHeaderToJson() { HttpRequestMessage actualRequest = null; var httpClientWrapper = new HttpClientWrapper ( new Config(new UnitTestHandler(request => actualRequest = request)) ); await httpClientWrapper.Send(HttpMethod.Post, new Uri(BaseUrl), requestHeaders : new Dictionary <string, string>(), content : new {}); Assert.That(actualRequest.Headers.Accept.First().MediaType, Is.EqualTo(Config.JsonMediaType)); }
/// <summary>获得指定角色的门户菜单</summary> public async Task <PortalMenu> GetPortalMenuAsyncInternal(HttpClientWrapper client, int roleId) { var key = CacheConst.RoleKey + roleId.ToString(); var result = this.MemcachedCacher?.TryGet <PortalMenu>(key, CacheConst.PermissionRegion); if (result == null) { var url = GetActionUrl(nameof(GetPortalMenu)) + nameof(roleId).GetFirstQueryString(roleId.ToString()); result = await client.GetAsync <PortalMenu>(url).ConfigureAwait(false); } return(result); }
/// <summary> /// Get a document from Storage for owner,instance and specific document id /// </summary> /// <param name="instanceOwnerId">owner id</param> /// <param name="instanceGuid">id of the instance</param> /// <param name="dataId">id of the data element/file</param> /// <returns></returns> public Stream GetData(int instanceOwnerId, Guid instanceGuid, Guid dataId) { string cmd = $@"instances/{instanceOwnerId}/{instanceGuid}/data/{dataId}"; HttpClientWrapper httpClientWrapper = new HttpClientWrapper(_logger); Task <HttpResponseMessage> response = httpClientWrapper.GetCommand(BaseAddress, cmd); Stream stream = response.Result.Content.ReadAsStreamAsync().Result; return(stream); }
public void TimeoutIsCorrectlySet() { // arrange var timeout = TimeSpan.FromMilliseconds(1000); var sut = new HttpClientWrapper(); // act sut.Timeout = timeout; // assert sut.Timeout.Should().Be(timeout); }
public ActionResult NavMenu() { HomeSummaryDTO summary = null; //Get a summary of the employes currently linked to the Employee using (HttpClientWrapper httpClient = new HttpClientWrapper(Session)) { Task <String> response = httpClient.GetStringAsync("api/SummaryAPI"); summary = Task.Factory.StartNew(() => JsonConvert.DeserializeObject <HomeSummaryDTO>(response.Result)).Result; } return(PartialView(summary)); }
public ActionResult Create(EmployeeDTO employeedto, List <string> selectedRoles, bool addedAnother = false) { ViewBag.AddedAnother = addedAnother; if (selectedRoles != null) { if (selectedRoles.Count() > 5) { ModelState.AddModelError("", "Maximimum of 5 roles can be added"); } else { employeedto.Roles = new List <RoleDTO>(); foreach (var selectedRole in selectedRoles) { employeedto.Roles.Add(new RoleDTO { Id = Guid.Parse(selectedRole), Name = "PLACEHOLDER" }); } } } if (ModelState.IsValid) { using (HttpClientWrapper httpClient = new HttpClientWrapper(Session)) { var responseMessage = httpClient.PostAsJsonAsync("/api/EmployeeAPI", employeedto).Result; if (responseMessage.IsSuccessStatusCode) { if (employeedto.AddAnother) { return(RedirectToAction("Create", new { businessLocationId = employeedto.BusinessLocationId, businessId = employeedto.BusinessId, addedAnother = true })); } else { return(RedirectToAction("Index", new { businesslocationid = employeedto.BusinessLocationId })); } } else { //If and error occurred add details to model error. var error = JsonConvert.DeserializeObject <System.Web.Http.HttpError>(responseMessage.Content.ReadAsStringAsync().Result); ModelState.AddModelError(String.Empty, error.Message); } } } //Get roles for business BusinessController bc = new BusinessController(); ViewBag.BusinessRoles = bc.GetBusinessRoles(employeedto.BusinessId, this.Session); return(PartialView(employeedto)); }
/// <summary> /// Raises the <see cref="E:System.Windows.Application.Startup" /> event. /// </summary> /// <param name="e">A <see cref="T:System.Windows.StartupEventArgs" /> that contains the event data.</param> protected override void OnStartup(StartupEventArgs e) { ITracer stringTracer = new StringTracer(string.Empty); ITracer consoleTracer = new ConsoleTracer(string.Empty); var smartDetectorLoader = new SmartDetectorLoader(consoleTracer); // *Temporary*: if package file path wasn't accepted, raise file selection window to allow package file selection. // This option should be removed before launching version for customers (bug for tracking: 1177247) string smartDetectorPackagePath = e.Args.Length != 1 ? this.GetSmartDetectorPackagePath() : Diagnostics.EnsureStringNotNullOrWhiteSpace(() => e.Args[0]); SmartDetectorPackage smartDetectorPackage; using (var fileStream = new FileStream(smartDetectorPackagePath, FileMode.Open)) { smartDetectorPackage = SmartDetectorPackage.CreateFromStream(fileStream, consoleTracer); } SmartDetectorManifest smartDetectorManifest = smartDetectorPackage.Manifest; ISmartDetector detector = smartDetectorLoader.LoadSmartDetector(smartDetectorPackage); // Authenticate the user to Active Directory var authenticationServices = new AuthenticationServices(); authenticationServices.AuthenticateUser(); ICredentialsFactory credentialsFactory = new ActiveDirectoryCredentialsFactory(authenticationServices); IAzureResourceManagerClient azureResourceManagerClient = new AzureResourceManagerClient(credentialsFactory, consoleTracer); // Create analysis service factory var queryRunInroProvider = new QueryRunInfoProvider(azureResourceManagerClient); var httpClientWrapper = new HttpClientWrapper(); IAnalysisServicesFactory analysisServicesFactory = new AnalysisServicesFactory(consoleTracer, httpClientWrapper, credentialsFactory, azureResourceManagerClient, queryRunInroProvider); // Create state repository factory IStateRepositoryFactory stateRepositoryFactory = new InMemoryStateRepositoryFactory(); var smartDetectorRunner = new SmartDetectorRunner(detector, analysisServicesFactory, queryRunInroProvider, smartDetectorManifest, stateRepositoryFactory, smartDetectorManifest.Id, stringTracer); // Create a Unity container with all the required models and view models registrations Container = new UnityContainer(); Container .RegisterInstance(stringTracer) .RegisterInstance(new AlertsRepository()) .RegisterInstance(authenticationServices) .RegisterInstance(azureResourceManagerClient) .RegisterInstance(detector) .RegisterInstance(smartDetectorManifest) .RegisterInstance(analysisServicesFactory) .RegisterInstance(smartDetectorRunner) .RegisterInstance(stateRepositoryFactory); }
private async Task PutAsync(string endpoint, object data) { try { using (HttpClientWrapper client = new HttpClientWrapper(MixItUpAPIEndpoint)) { string content = SerializerHelper.SerializeToString(data); HttpResponseMessage response = await client.PutAsync(endpoint, new StringContent(content, Encoding.UTF8, "application/json")); } } catch (Exception) { } }
private IEnumerable <EmployeeRequestDTO> GetEmployeeRequestList() { IEnumerable <EmployeeRequestDTO> er = new List <EmployeeRequestDTO>(); //Get a summary of the employes currently linked to the Employee using (HttpClientWrapper httpClient = new HttpClientWrapper(Session)) { Task <String> response = httpClient.GetStringAsync("api/EmployerAPI/GetEmployeeRequests"); er = Task.Factory.StartNew(() => JsonConvert.DeserializeObject <IEnumerable <EmployeeRequestDTO> >(response.Result)).Result; } return(er); }
public CoinMarketTask(IRepository <User> userRepository, Notifyer notifyer, HttpClientWrapper client, CurrencyService currencyService, ILogger <CoinMarketTask> logger, IRepository <Alert> alertRepository) { _userRepository = userRepository; _notifyer = notifyer; _client = client; _currencyService = currencyService; _logger = logger; _alertRepository = alertRepository; }
public async Task Spotify() { HttpClientWrapper hcw = new HttpClientWrapper(new HttpClient()); //hcw.SendAsync() FluentSpotifyApi.Client.SpotifyHttpClient c = new FluentSpotifyApi.Client.SpotifyHttpClient(hcw); //c.SendAsync() FluentSpotifyApi.Builder.Search.QueryFields query = new FluentSpotifyApi.Builder.Search.QueryFields(); }
// // GET: /Calendar/Edit public ActionResult EditSchedule(int id) { using (HttpClientWrapper httpClient = new HttpClientWrapper(this.Session)) { Task <String> response = httpClient.GetStringAsync("api/ScheduleAPI/" + id.ToString()); var scheduleDTO = Task.Factory.StartNew(() => JsonConvert.DeserializeObject <ScheduleDTO>(response.Result)).Result; LoadViewBag(); return(PartialView(scheduleDTO)); } }
protected async Task <T> PatchAsync <T>(string requestUri, HttpContent content) { using (HttpClientWrapper client = new HttpClientWrapper(await this.client.GetAuthorizationToken())) { HttpMethod method = new HttpMethod("PATCH"); HttpRequestMessage request = new HttpRequestMessage(method, requestUri) { Content = content }; return(await this.ProcessResponse <T>(await client.SendAsync(request))); } }
public ActionResult EditTimesheetEntry(Guid id) { TimesheetEntryDTO val = null; using (HttpClientWrapper httpClient = new HttpClientWrapper(Session)) { Task <String> response = httpClient.GetStringAsync("api/TimesheetAPI/TimesheetEntry/" + id.ToString()); val = Task.Factory.StartNew(() => JsonConvert.DeserializeObject <TimesheetEntryDTO>(response.Result)).Result; } return(PartialView("_TimesheetEntryEditPartial", val)); }
public async void SendAsync_WhenResponseIsSuccessButContentIsEmpty_ResultShouldBeAsExpected(HttpRequestMessage message) { var sut = new HttpClientWrapper(new HttpClient(new SuccessEmptyMessageHandler()), Substitute.For <ISerialization>(), null); var result = await sut.SendAsync <Foo>(message); result.Success.Should().BeTrue(); result.Response.Should().BeNull(); result.StatusCode.Should().Be(HttpStatusCode.OK); result.OriginalBody.Should().BeNullOrEmpty(); sut.Serializer.DidNotReceive().Deserialize(Arg.Any <string>(), typeof(Foo)); }
public void MaxResponseContentBufferIsCorrectlySet() { // arrange const long maxResponseBufferSize = 1245; var sut = new HttpClientWrapper(); // act sut.MaxResponseContentBufferSize = maxResponseBufferSize; // assert sut.MaxResponseContentBufferSize.Should().Be(maxResponseBufferSize); }
/// <summary>获得指定用户的权限集合</summary> public async Task <Dictionary <string, bool> > GetPermissionsAsyncInternal(HttpClientWrapper client, int userId) { var key = CacheConst.UserKey + userId.ToString(); var result = this.MemcachedCacher?.TryGet <Dictionary <string, bool> >(key, CacheConst.PermissionRegion); if (result == null) { var url = GetActionUrl(nameof(GetPermissions)) + nameof(userId).GetFirstQueryString(userId.ToString()); result = await client.GetAsync <Dictionary <string, bool> >(url).ConfigureAwait(false); } return(result); }
public async Task Send_ByDefault_SetsExpectJsonResponse() { HttpRequestMessage actualRequest = null; var httpClientWrapper = new HttpClientWrapper ( new Config(new UnitTestHandler(request => actualRequest = request)) ); await httpClientWrapper.Send(HttpMethod.Post, new Uri(BaseUrl), null, null); Assert.That(actualRequest.ExpectJsonResponse(), Is.True); }
public async Task Send_DoNotSetContentType_SetsContentTypeToJson() { HttpRequestMessage actualRequest = null; var httpClientWrapper = new HttpClientWrapper ( new Config(new UnitTestHandler(request => actualRequest = request)) ); await httpClientWrapper.Send(HttpMethod.Post, new Uri(BaseUrl), null, new { }); Assert.That(actualRequest.Content.Headers.ContentType.MediaType, Is.EqualTo(Config.JsonMediaType)); }
public void Timeout() { var client1 = new WebClientWrapper(); client1.Timeout = 1; var client2 = new HttpClientWrapper(); client2.Timeout = 1; var url = "http://releases.ubuntu.com/18.04.3/ubuntu-18.04.3-desktop-amd64.iso"; string directory = Path.Combine(TestOutputPath, "Canceled"); Directory.CreateDirectory(directory); string filePath = Path.Combine(directory, "canceled.iso"); bool expectedResponseSuccess = false; int expectedStatus = 408; string expectedContentType = null; long? expectedContentLength = null; bool? actualResponseSuccess = null; int? actualStatus = null; string actualContentType = null; long? actualContentLength = null; Uri actualRequestUri = null; var action = new Func <IWebClient, Task <IWebResponseMessage> >(async(target) => { IWebResponseMessage response = null; Exception exception = null; try { response = await target.GetAsync(url).ConfigureAwait(false); Assert.Fail("Should've thrown exception"); } catch (WebClientException ex) { exception = ex; actualResponseSuccess = ex.Response?.IsSuccessStatusCode; actualStatus = ex.Response.StatusCode; actualRequestUri = ex.Response.RequestUri; } Assert.AreEqual(expectedResponseSuccess, actualResponseSuccess, $"Failed for {target.GetType().Name}: IsSuccessStatusCode"); Assert.AreEqual(expectedStatus, actualStatus, $"Failed for {target.GetType().Name}: StatusCode"); Assert.AreEqual(expectedContentType, actualContentType, $"Failed for {target.GetType().Name}: ContentType"); Assert.AreEqual(expectedContentLength, actualContentLength, $"Failed for {target.GetType().Name}: ContentLength"); Assert.AreEqual(url, actualRequestUri.ToString(), $"Failed for {target.GetType().Name}: RequestUri"); if (exception != null) { throw exception; } return(response); }); CompareGetAsync(client1, client2, action); }
public void NotFound_ThrowOnException() { var client1 = new WebClientWrapper(); var client2 = new HttpClientWrapper(); var url = "https://beatsaver.com/cdn/5317/aaa14fb7dcaeda7a688db77617045a24d7baa151d.zip"; bool expectedResponseSuccess = false; int expectedStatus = 404; string expectedContentType = null; long? expectedContentLength = null; bool? actualResponseSuccess = null; string actualReasonPhrase = null; int? actualStatus = null; string actualContentType = null; long? actualContentLength = null; Uri actualRequestUri = null; var action = new Func <IWebClient, Task <IWebResponseMessage> >(async(target) => { target.ErrorHandling = ErrorHandling.ThrowOnException; IWebResponseMessage response = null; Exception exception = null; try { response = await target.GetAsync(url).ConfigureAwait(false); actualResponseSuccess = response.IsSuccessStatusCode; actualStatus = response.StatusCode; actualContentType = response.Content.ContentType; actualContentLength = response.Content.ContentLength; actualRequestUri = response.RequestUri; //Assert.Fail("Should've thrown exception"); } catch (WebClientException ex) { exception = ex; actualResponseSuccess = ex.Response?.IsSuccessStatusCode; actualReasonPhrase = ex.Response.ReasonPhrase; actualStatus = ex.Response.StatusCode; actualRequestUri = ex.Response.RequestUri; } Assert.AreEqual(expectedResponseSuccess, actualResponseSuccess, $"Failed for {target.GetType().Name}: IsSuccessStatusCode"); Assert.AreEqual(expectedStatus, actualStatus, $"Failed for {target.GetType().Name}: StatusCode"); Assert.AreEqual(expectedContentType, response?.Content?.ContentType, $"Failed for {target.GetType().Name}: ContentType"); Assert.AreEqual(expectedContentLength, response?.Content?.ContentLength, $"Failed for {target.GetType().Name}: ContentLength"); Assert.AreEqual(url, actualRequestUri.ToString(), $"Failed for {target.GetType().Name}: RequestUri"); if (exception != null) { throw exception; } return(response); }); CompareGetAsync(client1, client2, action); }
public ServiceAuthenticationHelper() { lock (LockClass) { if (HttpClient != null) { return; } var handlers = OutboundPipeFactory.CreateDelegatingHandlers(); var httpClient = HttpClientFactory.Create(handlers); HttpClient = new HttpClientWrapper(httpClient); } }
static void ConfigureServices(IServiceCollection serviceCollection) { // add services var httpClient = new HttpClientWrapper(new HttpClientHandler { UseCookies = false }); serviceCollection.AddSingleton <IHttpClient>(httpClient); serviceCollection.AddTransient <IWeatherFetcher, WeatherFetcher>(); // add app serviceCollection.AddTransient <App>(); }
private static async Task LogAnalyticsUsageInternal(string eventName, string eventDetails) { try { using (HttpClientWrapper client = new HttpClientWrapper()) { client.BaseAddress = new Uri("https://api.mixitupapp.com/analytics/"); HttpResponseMessage response = await client.GetAsync(string.Format("log?username={0}&eventName={1}&eventDetails={2}&appVersion={3}", ChannelSession.User.username, eventName, eventDetails, Assembly.GetEntryAssembly().GetName().Version.ToString())); } } catch (Exception ex) { Logger.Log(ex); } }
public async Task Send_PassingStringToContent_ThrowsArgumentException() { const string stringContentToTest = "This is a string"; var httpClientWrapper = new HttpClientWrapper ( new Config(new UnitTestHandler()) ); await httpClientWrapper.Send(HttpMethod.Post, new Uri(BaseUrl), null, new { }); Assert.ThrowsAsync <ArgumentException>(async() => await httpClientWrapper.Send(HttpMethod.Post, new Uri(BaseUrl), null, stringContentToTest)); }
private async Task DeleteAsync(string endpoint) { try { using (HttpClientWrapper client = new HttpClientWrapper(MixItUpAPIEndpoint)) { HttpResponseMessage response = await client.DeleteAsync(endpoint); await this.ProcessResponseIfError(response); } } catch (Exception ex) { Logger.Log(ex); } }
public ActionResult RoleDeleteConfirmed(Guid businessid, Guid id) { using (HttpClientWrapper httpClient = new HttpClientWrapper(Session)) { var responseMessage = httpClient.DeleteAsync("api/BusinessAPI/Business/" + businessid.ToString() + "/Role/" + id.ToString()).Result; responseMessage.EnsureSuccessStatusCode(); } //Invalidate dependant cache item CacheManager.Instance.Remove(CacheManager.CACHE_KEY_BUSINESS + businessid.ToString()); return(RedirectToAction("RoleIndex", new { businessid = businessid })); }
/// <summary> /// Adds a sink that sends log events using HTTP POST over the network. /// </summary> /// <param name="sinkConfiguration">The logger configuration.</param> /// <param name="authToken">The token for your logzio account.</param> /// <param name="type">Your log type - it helps classify the logs you send.</param> /// <param name="options">Logzio configuration options</param> /// <returns>Logger configuration, allowing configuration to continue.</returns> public static LoggerConfiguration LogzIo(this LoggerSinkConfiguration sinkConfiguration, string authToken, string type, LogzioOptions options = null) { if (sinkConfiguration == null) { throw new ArgumentNullException(nameof(sinkConfiguration)); } var client = new HttpClientWrapper(); var sink = new LogzioSink(client, authToken, type, options ?? new LogzioOptions()); var restrictedToMinimumLevel = options?.RestrictedToMinimumLevel ?? LogEventLevel.Verbose; return(sinkConfiguration.Sink(sink, restrictedToMinimumLevel)); }
public ActionResult Search(EmployerSearchDTO searchData) { if (ModelState.IsValid) { using (HttpClientWrapper httpClient = new HttpClientWrapper(Session)) { HttpResponseMessage response = httpClient.PostAsJsonAsync("api/EmployerAPI/SearchBusinesses", searchData).Result; searchData = JsonConvert.DeserializeObject <EmployerSearchDTO>(response.Content.ReadAsStringAsync().Result); } } return(PartialView(searchData)); }
public CenturyLinkCloudServiceFactory(string username, string password, Uri proxyUri) { var serializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), Converters = new List<JsonConverter> { new StringEnumConverter{CamelCaseText = true}} }; var authProviderClient = HttpClientFactory.Create(new JsonMediaTypeHandler()); var authProviderWrapper = new HttpClientWrapper(authProviderClient, serializerSettings); _authenticationProvider = new AuthenticationProvider(username, password, authProviderWrapper); var authHandler = new AuthenticationHandler(_authenticationProvider); var authorizedClient = HttpClientFactory.Create(authHandler, new JsonMediaTypeHandler()); authProviderClient.BaseAddress = authorizedClient.BaseAddress = proxyUri; _clientWrapper = new HttpClientWrapper(authorizedClient, serializerSettings); }
public void CreatesNewHttpClientWhenNotSupplied() { var wrapper = new HttpClientWrapper(); Assert.IsNotNull(wrapper.Client); }
public void Setup() { _innerHandler = new Mock<HttpClientHandler>(); _innerClient = new HttpClient(_innerHandler.Object) {BaseAddress = new Uri(BaseAddress)}; _serializerSettings = new JsonSerializerSettings{ContractResolver = new CamelCasePropertyNamesContractResolver()}; _testObject = new HttpClientWrapper(_innerClient, _serializerSettings); }