public void Instance_ProgramTakesTwoInstances_ThoseAreTheSameInstance() { HttpClientSingleton client1 = HttpClientSingleton.Instance; HttpClientSingleton client2 = HttpClientSingleton.Instance; Assert.AreSame(client1, client2); }
public override async Task <BaseResponse> Execute(object query) { if (!(query is OrganizationRequest temp) || string.IsNullOrEmpty(temp.Query)) { throw new InvalidQueryException(query); } return(await HttpClientSingleton.GetInstance().SendResponseAsync <OrganizationResponse>(HttpMethod.Post, new Uri(Url), query)); }
private static LoginToken GetLoginToken(String url, HttpContent authContent) { try { HttpClient c = HttpClientSingleton.GetClient(); var uri = new Uri(MakeUrl(url, LOGIN_URI_SUFFIX)); _log.Debug($"Login URL: {uri}"); var response = c.PostAsync(uri, authContent).Result; if (response.StatusCode != HttpStatusCode.OK) { if (_log.IsDebugEnabled) { _log.Debug($"Response code [{response.StatusCode}]: " + $"{response.Content.ReadAsStringAsync().Result}"); } throw new InvalidOperationException(response.ReasonPhrase); } else { _log.Debug("Successful login."); } using (JsonReader r = new JsonTextReader(new StreamReader (response.Content.ReadAsStreamAsync().Result))) { var results = JsonSerializer.Create().Deserialize(r, typeof(Dictionary <String, String>)) as Dictionary <String, String>; return(new LoginToken { TokenType = results["token_type"], ExpireTime = DateTime.Now.AddSeconds(Convert.ToDouble(results["expires_in"])), Token = results["access_token"], ReauthContent = authContent }); } } catch (HttpRequestException hex) { // Next operation will try to log in again due to expired token. _log.Warn("Unable to obtain login token due to a communication problem. " + "Login will retry on next operation.", hex); return(GetNullToken(authContent)); } catch (Exception ex) { _log.Warn("Unable to obtain login token due to an unexpected exception. " + "Login will retry on the next operation.", ex); return(GetNullToken(authContent)); } }
public void TestInitializedAccessGivesResult() { HttpClientSingleton.Initialize(true, TimeSpan.FromSeconds(600)); var h = HttpClientSingleton.GetClient(); bool result = h != null; HttpClientSingleton.Clear(); Assert.True(result); }
public void TestUninitializedAccessThrowsError() { try { var h = HttpClientSingleton.GetClient(); } catch (InvalidOperationException) { HttpClientSingleton.Clear(); Assert.Pass(); return; } HttpClientSingleton.Clear(); Assert.Fail(); }
public void TestDoubleInitializeThrowsError() { HttpClientSingleton.Initialize(true, TimeSpan.FromSeconds(600)); try { HttpClientSingleton.Initialize(true, TimeSpan.FromSeconds(600)); } catch (InvalidOperationException) { HttpClientSingleton.Clear(); Assert.Pass(); return; } HttpClientSingleton.Clear(); Assert.Fail(); }
/// <summary> /// Implementation IDadataApiClient /// </summary> /// <param name="options">Authentication options (Token required!)</param> /// <exception cref="InvalidTokenException">Throw if one from tokens is invalid</exception> public ApiClient(ApiClientOptions options) { if (string.IsNullOrEmpty(options.Token)) { throw new InvalidTokenException(); } Options = options; if (Options.LimitQueries != null && Options.LimitQueries <= 0) { throw new InvalidLimitQueriesException(Options.LimitQueries); } _limitQueries = Options.LimitQueries ?? (int)DefaultOptions.QueriesLimit; //Initialization of HttpClientSingleton HttpClientSingleton.GetInstance(options); //Reset count of messages per second (timer) ResetCountMessagesTimer = new Timer(ResetCounter, null, TimeSpan.Zero, TimeSpan.FromSeconds(1)); }
protected override void OnStart(string[] args) { // Update the service state to Start Pending. ServiceStatus serviceStatus = new ServiceStatus(); serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING; serviceStatus.dwWaitHint = 100000; SetServiceStatus(this.ServiceHandle, ref serviceStatus); eventLog1.WriteEntry("In OnStart."); Thread.Sleep(10 * 1000); HttpClientSingleton.InitialiseInstance(); // Build enrollment job EnrollmentJob enrollmentJob = new EnrollmentJob(); enrollmentJob.RegisterListener(this); mNetworking.ExecuteAsync(enrollmentJob); // Update the service state to Running. serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING; SetServiceStatus(this.ServiceHandle, ref serviceStatus); }
public CxRestContext Build() { if (_url == null) { throw new InvalidOperationException("Endpoint URL was not specified."); } if (_user == null) { throw new InvalidOperationException("Username was not specified."); } if (_pass == null) { throw new InvalidOperationException("Password was not specified."); } var timeoutSpan = new TimeSpan(0, 0, _timeout); HttpClientSingleton.Initialize(_validate, timeoutSpan); CxRestContext retVal = new CxRestContext() { SastToken = GetLoginToken(_url, _user, _pass, SAST_SCOPE), MNOToken = GetLoginToken(_url, _user, _pass, $"{MNO_SCOPE} {SAST_SCOPE}"), Url = _url, MnoUrl = String.IsNullOrEmpty(_mnoUrl) ? _url : _mnoUrl, ValidateSSL = _validate, Timeout = timeoutSpan }; retVal.Json = new CxClientFactory("application/json", retVal); retVal.Xml = new CxClientFactory("application/xml", retVal); return(retVal); }
public async Task IronOrderSubmit(string query) { HttpClientSingleton.SetHeaders(ironfe.KEY_ID, ironfe.APCA_API_KEY_ID, ironfe.SECRET, ironfe.APCA_API_SECRET_KEY); var test = QueryBuilderJSON.Build(query); var res = await _localClient.GetAsync(test, Token); }