public AdminConversationsClientTest()
        {
            var auth = new Authentication(AppId, AppKey);
            var restClientFactory = new RestClientFactory(auth);

            adminConversationsClient = new AdminConversationsClient(restClientFactory);
        }
        protected override IRestResponse <AccessTokenResult> ExecuteRetrieveAccessToken(string authorizationCode,
                                                                                        Uri redirectUri)
        {
            if (string.IsNullOrEmpty(authorizationCode))
            {
                throw new ArgumentNullException("authorizationCode");
            }

            if (redirectUri == null ||
                string.IsNullOrEmpty(redirectUri.AbsoluteUri))
            {
                throw new ArgumentNullException("redirectUri");
            }

            var restRequest = new RestRequest("/oauth20_token.srf");

            restRequest.AddParameter("client_id", PublicApiKey);
            restRequest.AddParameter("redirect_uri", redirectUri);
            restRequest.AddParameter("client_secret", SecretApiKey);
            restRequest.AddParameter("code", authorizationCode);
            restRequest.AddParameter("grant_type", "authorization_code");

            var restClient = RestClientFactory.CreateRestClient("https://login.live.com/oauth20_token.srf");

            TraceSource.TraceVerbose("Retrieving Access Token endpoint: {0}",
                                     restClient.BuildUri(restRequest).AbsoluteUri);

            return(restClient.Execute <AccessTokenResult>(restRequest));
        }
Exemple #3
0
        public async Task PostPedidosAsync(Encomenda encomenda, PlataformaRepository plataformaRepository)
        {
            RestClientFactory restClientFactory = new RestClientFactory(this._config);

            try
            {
                IRestResponse response = await restClientFactory.RestAPI("newOrder", Method.POST, encomenda);

                if (response.IsSuccessful)
                {
                    await plataformaRepository.CommitPedidosAsync(encomenda.Pedido, encomenda.DocFiscalNFe.NfeNumero, GerarTrackingUrl(encomenda));

                    string retorno = $"OrderId: {encomenda.Pedido} - Incluido.";
                    Console.WriteLine(retorno);
                }
                else
                {
                    await GerarLog(encomenda, response.Content);
                }
            }
            catch (Exception e)
            {
                await GerarLog(encomenda, e.Message);
            }
        }
Exemple #4
0
        private string RetrieveAccessToken(string code, Uri redirectUri)
        {
            if (string.IsNullOrEmpty(code))
            {
                throw new ArgumentNullException("code");
            }

            if (redirectUri == null ||
                string.IsNullOrEmpty(redirectUri.AbsoluteUri))
            {
                throw new ArgumentNullException("redirectUri");
            }

            IRestResponse response;

            try
            {
                var restRequest = new RestRequest("oauth/access_token");
                restRequest.AddParameter("client_id", _clientId);
                restRequest.AddParameter("client_secret", _clientSecret);
                restRequest.AddParameter("code", code);
                restRequest.AddParameter("redirect_uri", redirectUri.AbsoluteUri);

                var restClient = RestClientFactory.CreateRestClient(BaseUrl);
                response = restClient.Execute(restRequest);
            }
            catch (Exception exception)
            {
                throw new AuthenticationException("Failed to retrieve an oauth access token from Facebook.", exception);
            }

            if (response == null ||
                response.StatusCode != HttpStatusCode.OK)
            {
                // {"error":{"message":"Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request","type":"OAuthException","code":100}}

                throw new AuthenticationException(
                          string.Format(
                              "Failed to obtain an Access Token from Facebook OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}. Error Content: {2}",
                              response == null ? "-- null response --" : response.StatusCode.ToString(),
                              response == null ? string.Empty : response.StatusDescription,
                              response == null ? string.Empty : response.Content));
            }

            var querystringParameters = HttpUtility.ParseQueryString(response.Content);
            var accessToken           = querystringParameters["access_token"];
            int expires;
            var expiresOn = int.TryParse(querystringParameters["expires"], out expires)
                                ? DateTime.UtcNow.AddSeconds(expires)
                                : DateTime.MinValue;

            if (string.IsNullOrEmpty(accessToken) ||
                expiresOn <= DateTime.UtcNow)
            {
                throw new AuthenticationException(
                          "Retrieved a Facebook Access Token but it doesn't contain both the access_token and expires_on parameters.");
            }

            return(accessToken);
        }
Exemple #5
0
        private IRestClient BuildClient(TransmissionSettings settings)
        {
            var protocol = settings.UseSsl ? "https" : "http";

            String url;

            if (!settings.UrlBase.IsNullOrWhiteSpace())
            {
                url = String.Format(@"{0}://{1}:{2}/{3}/transmission/rpc", protocol, settings.Host, settings.Port, settings.UrlBase.Trim('/'));
            }
            else
            {
                url = String.Format(@"{0}://{1}:{2}/transmission/rpc", protocol, settings.Host, settings.Port);
            }

            var restClient = RestClientFactory.BuildClient(url);

            restClient.FollowRedirects = false;

            if (!settings.Username.IsNullOrWhiteSpace())
            {
                restClient.Authenticator = new HttpBasicAuthenticator(settings.Username, settings.Password);
            }

            return(restClient);
        }
        public NotesClientTest()
        {
            var auth = new Authentication(AppId, AppKey);
            var restClientFactory = new RestClientFactory(auth);

            notesClient = new NotesClient(restClientFactory);
        }
        private T DoSend <T>(RSharp.Method method, object body)
        {
            _request.AddParameter(
                "application/json",
                Newtonsoft.Json.JsonConvert.SerializeObject(body),
                ParameterType.RequestBody);

            _request.Timeout = 100000; // ms

            var response = _restClient.Execute(_request, method);

            if (response.IsSuccessful)
            {
                return(Deserialize <T>(response));
            }

            if (response.StatusCode == 0 && response.ErrorMessage.Contains("Section=ResponseStatusLine"))
            {
                return(Deserialize <T>(response));
            }

            if (response.ErrorException != null)
            {
                throw RestClientFactory.CreateErrorException(_restClient, response);
            }

            throw RestClientFactory.CreateFailedException(_restClient, response);
        }
Exemple #8
0
        private IRestClient BuildClient(DelugeSettings settings)
        {
            var protocol = settings.UseSsl ? "https" : "http";

            var url = String.Format(@"{0}://{1}:{2}",
                                    protocol,
                                    settings.Host,
                                    settings.Port);

            var restClient = RestClientFactory.BuildClient(url);

            restClient.Timeout = 4000;

            if (_authPassword != settings.Password || _authCookieContainer == null)
            {
                _authPassword = settings.Password;
                AuthenticateClient(restClient);
            }
            else
            {
                restClient.CookieContainer = _authCookieContainer;
            }

            return(restClient);
        }
Exemple #9
0
        protected override IRestResponse <AccessTokenResult> ExecuteRetrieveAccessToken(string authorizationCode,
                                                                                        Uri redirectUri)
        {
            if (string.IsNullOrEmpty(authorizationCode))
            {
                throw new ArgumentNullException("authorizationCode");
            }

            if (redirectUri == null ||
                string.IsNullOrEmpty(redirectUri.AbsoluteUri))
            {
                throw new ArgumentNullException("redirectUri");
            }

            var restRequest = new RestRequest("v2.4/oauth/access_token");

            restRequest.AddParameter("client_id", PublicApiKey);
            restRequest.AddParameter("client_secret", SecretApiKey);
            restRequest.AddParameter("code", authorizationCode);
            restRequest.AddParameter("redirect_uri", redirectUri.AbsoluteUri.ToLowerInvariant());
            restRequest.AddHeader("Content-Type", "application/json");
            restRequest.AddParameter("format", "json");

            var restClient = RestClientFactory.CreateRestClient(BaseUrl);

            TraceSource.TraceVerbose("Retrieving Access Token endpoint: {0}",
                                     restClient.BuildUri(restRequest).AbsoluteUri);

            return(restClient.Execute <AccessTokenResult>(restRequest));
        }
        private T DoSend <T>(HttpMethod method)
        {
            try
            {
                _request.Method = method;
                var req = _request.ToRestClientRequest(_restClient.BaseAddress);
                //Logging.WriteToFileThreadSafe(DateTime.Now.ToString("o") + " " + req.ToString(), FILE_LOG);
                HttpResponseMessage response = _restClient.SendAsync(_request).Result;
                var resp = response.ToRestClientRequest();
                //Logging.WriteToFileThreadSafe(DateTime.Now.ToString("o") + " " + resp.ToString(), FILE_LOG);

                if (response.IsSuccessStatusCode)
                {
                    return(Deserialize <T>(response));
                }

                //var errorMessage = response.Content.ReadAsStringAsync().Result;
                //if (response.StatusCode == 0 && errorMessage.Contains("Section=ResponseStatusLine"))
                //{
                //    return Deserialize<T>(response);
                //}

                throw RestClientFactory.CreateFailedException(_restClient, req, resp, response);
            }
            catch (HttpRequestException ex)
            {
                //Logging.WriteToFileThreadSafe(DateTime.Now.ToString("o") + " ERROR: " + _request.ToRestClientRequest(_restClient.BaseAddress).ToString(), FILE_LOG);
                //Logging.WriteToFileThreadSafe(DateTime.Now.ToString("o") + " EXCEP: " + ex.Message, FILE_LOG);
                throw RestClientFactory.CreateFailedException(_restClient, _request, ex);
            }
        }
        public CompanyClientTest()
        {
            var auth = new Authentication(AppId, AppKey);
            var restClientFactory = new RestClientFactory(auth);

            companyClient = new CompanyClient(restClientFactory);
        }
Exemple #12
0
        public void SendNotification(string title, string message, PushalotSettings settings)
        {
            var client  = RestClientFactory.BuildClient(URL);
            var request = BuildRequest();

            request.AddParameter("Source", "Radarr");

            if (settings.Image)
            {
                request.AddParameter("Image", "https://raw.githubusercontent.com/Radarr/Radarr/develop/Logo/128.png");
            }

            request.AddParameter("Title", title);
            request.AddParameter("Body", message);
            request.AddParameter("AuthorizationToken", settings.AuthToken);

            if ((PushalotPriority)settings.Priority == PushalotPriority.Important)
            {
                request.AddParameter("IsImportant", true);
            }

            if ((PushalotPriority)settings.Priority == PushalotPriority.Silent)
            {
                request.AddParameter("IsSilent", true);
            }

            client.ExecuteAndValidate(request);
        }
Exemple #13
0
        private void SendNotification(string title, string message, RestRequest request, PushBulletSettings settings)
        {
            try
            {
                var client = RestClientFactory.BuildClient(URL);

                request.AddParameter("type", "note");
                request.AddParameter("title", title);
                request.AddParameter("body", message);

                if (settings.SenderId.IsNotNullOrWhiteSpace())
                {
                    request.AddParameter("source_device_iden", settings.SenderId);
                }

                client.Authenticator = new HttpBasicAuthenticator(settings.ApiKey, string.Empty);
                client.ExecuteAndValidate(request);
            }
            catch (RestException ex)
            {
                if (ex.Response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    _logger.Error(ex, "API Key is invalid: " + ex.Message);
                    throw;
                }

                throw new PushBulletException("Unable to send text message: {0}", ex, ex.Message);
            }
        }
        public EventsClientTest()
        {
            var auth = new Authentication(AppId, AppKey);
            var restClientFactory = new RestClientFactory(auth);

            eventsClient = new EventsClient(restClientFactory);
        }
Exemple #15
0
        public async Task Execute(IJobExecutionContext context)
        {
            _logger.Info("Start StaticJob.Execute()");
            try
            {
                IAppSettings       appSettings       = new AppSettings("appSettings.json");
                IJsonSerializer    jsonSerializer    = new JsonSerializer();
                IRestClientFactory restClientFactory = new RestClientFactory();
                var serverConnector = new ServerConnector(
                    null,
                    appSettings,
                    jsonSerializer,
                    restClientFactory);

                var stableCollector =
                    new StableDeviceCollector(
                        new CpuCollector(null),
                        new MemoryCollector(null),
                        new NetworkCollector(null),
                        new DriveCollector(null),
                        new OsCollector(null),
                        new SoftwareCollector(null));

                var stableDeviceInfo = stableCollector.Read();

                await serverConnector.Send(await stableDeviceInfo);
            }
            catch (Exception ex)
            {
                _logger.Error($"StaticJob.Execute(): {ex.Message}");
                _logger.Error($"Stack Trace: {ex.StackTrace}");
            }
        }
Exemple #16
0
        static RestSharpServiceFactory()
        {
            JamaOptions           jamaOptions       = JamaOptionsFactory.Create();
            JsonSerializerOptions serializerOptions = JsonSerializerOptionsFactory.Create();

            Client = RestClientFactory.Create(jamaOptions, serializerOptions);
        }
        private void Given_a_rest_client()
        {
            var httpClient = new HttpClient();

            httpClient.BaseAddress = new Uri("http://localhost:5000");
            restClient             = RestClientFactory.Create(httpClient);
        }
Exemple #18
0
        protected override IRestResponse <AccessTokenResult> ExecuteRetrieveAccessToken(string authorizationCode,
                                                                                        Uri redirectUri)
        {
            if (string.IsNullOrEmpty(authorizationCode))
            {
                throw new ArgumentNullException("authorizationCode");
            }

            if (redirectUri == null ||
                string.IsNullOrEmpty(redirectUri.AbsoluteUri))
            {
                throw new ArgumentNullException("redirectUri");
            }

            // Reference: https://launchpad.37signals.com/authorization/token?type=web_server&client_id=your-client-id&redirect_uri=your-redirect-uri&client_secret=your-client-secret&code=verification-code

            var restRequest = new RestRequest("/authorization/token", Method.POST);

            restRequest.AddParameter("type", "web_server");
            restRequest.AddParameter("client_id", PublicApiKey);
            restRequest.AddParameter("client_secret", SecretApiKey);
            restRequest.AddParameter("redirect_uri", redirectUri.AbsoluteUri);
            restRequest.AddParameter("code", authorizationCode);

            var restClient = RestClientFactory.CreateRestClient(BaseUri);

            TraceSource.TraceVerbose("Retrieving Access Token endpoint: {0}; Post Params: {1}",
                                     restClient.BuildUri(restRequest).AbsoluteUri,
                                     string.Join(", ", restRequest.Parameters));

            return(restClient.Execute <AccessTokenResult>(restRequest));
        }
Exemple #19
0
        public void GetCustomiazeClient_BaseUriRightFact()
        {
            var restClientFactory = new RestClientFactory(productInfo);

            using var restClient = restClientFactory.Create(_serviceEndpoint);
            Assert.Equal(Endpoint, restClient.BaseUri.AbsoluteUri);
        }
Exemple #20
0
        public void SendNotification(string title, string message, PushoverSettings settings)
        {
            var client  = RestClientFactory.BuildClient(URL);
            var request = new RestRequest(Method.POST);

            request.AddParameter("token", settings.ApiKey);
            request.AddParameter("user", settings.UserKey);
            request.AddParameter("device", string.Join(",", settings.Devices));
            request.AddParameter("title", title);
            request.AddParameter("message", message);
            request.AddParameter("priority", settings.Priority);

            if ((PushoverPriority)settings.Priority == PushoverPriority.Emergency)
            {
                request.AddParameter("retry", settings.Retry);
                request.AddParameter("expire", settings.Expire);
            }

            if (!settings.Sound.IsNullOrWhiteSpace())
            {
                request.AddParameter("sound", settings.Sound);
            }

            client.ExecuteAndValidate(request);
        }
Exemple #21
0
        private void SendNotification(string title, string message, RestRequest request, BoxcarSettings settings)
        {
            try
            {
                var client = RestClientFactory.BuildClient(URL);

                request.AddParameter("user_credentials", settings.Token);
                request.AddParameter("notification[title]", title);
                request.AddParameter("notification[long_message]", message);
                request.AddParameter("notification[source_name]", BuildInfo.AppName);
                request.AddParameter("notification[icon_url]", "https://raw.githubusercontent.com/Sonarr/Sonarr/7818f0c59b787312f0bcbc5c0eafc3c9dd7e5451/Logo/64.png");

                client.ExecuteAndValidate(request);
            }
            catch (RestException ex)
            {
                if (ex.Response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    _logger.Error(ex, "Access Token is invalid");
                    throw;
                }

                throw new BoxcarException("Unable to send text message: " + ex.Message, ex);
            }
        }
Exemple #22
0
        private IRestClient BuildClient(DelugeSettings settings)
        {
            var protocol = settings.UseSsl ? "https" : "http";

            string url;

            if (!settings.UrlBase.IsNullOrWhiteSpace())
            {
                url = string.Format(@"{0}://{1}:{2}/{3}", protocol, settings.Host, settings.Port, settings.UrlBase.Trim('/'));
            }
            else
            {
                url = string.Format(@"{0}://{1}:{2}", protocol, settings.Host, settings.Port);
            }

            var restClient = RestClientFactory.BuildClient(url);

            restClient.Timeout = 15000;

            if (_authPassword != settings.Password || _authCookieContainer == null)
            {
                _authPassword = settings.Password;
                AuthenticateClient(restClient);
            }
            else
            {
                restClient.CookieContainer = _authCookieContainer;
            }

            return(restClient);
        }
Exemple #23
0
        public void TestArgumentExceptionOnNullOrEmptyApiKey()
        {
            var unit = new RestClientFactory();

            try
            {
                unit.Create(null);
                Assert.Fail("Expected ArgumentException not thrown.");
            }
            catch (ArgumentException)
            {
                //expected
            }

            try
            {
                unit.Create(string.Empty);
                Assert.Fail("Expected ArgumentException not thrown.");
            }
            catch (ArgumentException)
            {
                //expected
            }

            unit.Create("not empty");
            //passes without exception
        }
Exemple #24
0
        /// <summary>
        /// Registers <see cref="IEmailJobClient"/> in Autofac container using <see cref="EmailJobRestClientSettings"/>.
        /// </summary>
        /// <param name="builder">Autofac container builder.</param>
        /// <param name="settings">EmailJob client settings.</param>
        /// <param name="builderConfigure">Optional <see cref="RestClientFactoryBuilder"/> configure handler.</param>
        public static void RegisterEmailJobClient(
            [NotNull] this ContainerBuilder builder,
            [NotNull] EmailJobRestClientSettings settings,
            [CanBeNull] Func <RestClientFactoryBuilder, RestClientFactoryBuilder> builderConfigure)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            if (string.IsNullOrWhiteSpace(settings.ServiceUrl))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(EmailJobRestClientSettings.ServiceUrl));
            }

            var clientBuilder = RestClientFactory.BuildForUrl(settings.ServiceUrl)
                                .WithAdditionalCallsWrapper(new ExceptionHandlerCallsWrapper());

            clientBuilder = builderConfigure?.Invoke(clientBuilder) ?? clientBuilder.WithoutRetries();

            builder.RegisterInstance(new EmailJobClient(clientBuilder.Create()))
            .As <IEmailJobClient>()
            .SingleInstance();
        }
        protected override IRestResponse <AccessTokenResult> ExecuteRetrieveAccessToken(string authorizationCode,
                                                                                        Uri redirectUri)
        {
            if (string.IsNullOrEmpty(authorizationCode))
            {
                throw new ArgumentNullException("authorizationCode");
            }

            if (redirectUri == null ||
                string.IsNullOrEmpty(redirectUri.AbsoluteUri))
            {
                throw new ArgumentNullException("redirectUri");
            }

            var restRequest = new RestRequest("/sharing/rest/oauth2/token", Method.POST);

            restRequest.AddParameter("client_id", PublicApiKey);
            restRequest.AddParameter("code", authorizationCode);
            restRequest.AddParameter("redirect_uri", redirectUri.AbsoluteUri);
            restRequest.AddParameter("grant_type", "authorization_code");

            var restClient = RestClientFactory.CreateRestClient("https://www.arcgis.com/");

            TraceSource.TraceVerbose("Retrieving Access Token endpoint: {0}",
                                     restClient.BuildUri(restRequest).AbsoluteUri);

            // ArcGIS Online returns the token as text/plain, but it's actually a JSON payload
            restClient.AddHandler("text/plain", new RestSharp.Deserializers.JsonDeserializer());

            var response = restClient.Execute <AccessTokenResult>(restRequest);

            return(response);
        }
Exemple #26
0
        private void SendNotification(string title, string message, RestRequest request, JoinSettings settings)
        {
            var client = RestClientFactory.BuildClient(URL);

            if (settings.DeviceNames.IsNotNullOrWhiteSpace())
            {
                request.AddParameter("deviceNames", settings.DeviceNames);
            }
            else if (settings.DeviceIds.IsNotNullOrWhiteSpace())
            {
                request.AddParameter("deviceIds", settings.DeviceIds);
            }
            else
            {
                request.AddParameter("deviceId", "group.all");
            }

            request.AddParameter("apikey", settings.ApiKey);
            request.AddParameter("title", title);
            request.AddParameter("text", message);
            request.AddParameter("icon", "https://cdn.rawgit.com/Readarr/Readarr/develop/Logo/256.png");                   // Use the Readarr logo.
            request.AddParameter("smallicon", "https://cdn.rawgit.com/Readarr/Readarr/develop/Logo/96-Outline-White.png"); // 96x96px with outline at 88x88px on a transparent background.
            request.AddParameter("priority", settings.Priority);

            var response = client.ExecuteAndValidate(request);
            var res      = Json.Deserialize <JoinResponseModel>(response.Content);

            if (res.success)
            {
                return;
            }

            if (res.userAuthError)
            {
                throw new JoinAuthException("Authentication failed.");
            }

            if (res.errorMessage != null)
            {
                // Unfortunately hard coding this string here is the only way to determine that there aren't any devices to send to.
                // There isn't an enum or flag contained in the response that can be used instead.
                if (res.errorMessage.Equals("No devices to send to"))
                {
                    throw new JoinInvalidDeviceException(res.errorMessage);
                }

                // Oddly enough, rather than give us an "Invalid API key", the Join API seems to assume the key is valid,
                // but fails when doing a device lookup associated with that key.
                // In our case we are using "deviceIds" rather than "deviceId" so when the singular form error shows up
                // we know the API key was the fault.
                else if (res.errorMessage.Equals("No device to send message to"))
                {
                    throw new JoinAuthException("Authentication failed.");
                }

                throw new JoinException(res.errorMessage);
            }

            throw new JoinException("Unknown error. Join message failed to send.");
        }
Exemple #27
0
        protected override IRestResponse <AccessTokenResult> ExecuteRetrieveAccessToken(string authorizationCode, Uri redirectUri)
        {
            if (string.IsNullOrEmpty(authorizationCode))
            {
                throw new ArgumentNullException("authorizationCode");
            }

            if (redirectUri == null ||
                string.IsNullOrEmpty(redirectUri.AbsoluteUri))
            {
                throw new ArgumentNullException("redirectUri");
            }

            var restRequest = new RestRequest("/oauth/access_token", Method.POST);

            restRequest.AddParameter("client_id", PublicApiKey);
            restRequest.AddParameter("client_secret", SecretApiKey);
            restRequest.AddParameter("redirect_uri", redirectUri.AbsoluteUri);
            restRequest.AddParameter("code", authorizationCode);
            restRequest.AddParameter("grant_type", "authorization_code");

            var restClient = RestClientFactory.CreateRestClient("https://api.instagram.com");

            return(restClient.Execute <AccessTokenResult>(restRequest));
        }
Exemple #28
0
        private T DoSend <T>(HttpMethod method, object body)
        {
            _request.Method = method;

            try
            {
                _request.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");
                var req = _request.ToRestClientRequest(_restClient.BaseAddress);
                //Logging.WriteToFileThreadSafe(DateTime.Now.ToString("o") + " " + req.ToString(), FILE_LOG);
                var response = _restClient.SendAsync(_request).Result;
                var resp     = response.ToRestClientRequest();
                //Logging.WriteToFileThreadSafe(DateTime.Now.ToString("o") + " " + resp.ToString(), FILE_LOG);

                if (response.IsSuccessStatusCode)
                {
                    return(Deserialize <T>(response));
                }

                var errorMessage = response.Content.ReadAsStringAsync().Result;
                if (response.StatusCode == 0 && errorMessage.Contains("Section=ResponseStatusLine"))
                {
                    return(Deserialize <T>(response));
                }

                throw RestClientFactory.CreateFailedException(_restClient, req, resp, response);
            }
            catch (HttpRequestException ex)
            {
                //Logging.WriteToFileThreadSafe(DateTime.Now.ToString("o") + " ERROR: " + _request.ToRestClientRequest(_restClient.BaseAddress).ToString(), FILE_LOG);
                //Logging.WriteToFileThreadSafe(DateTime.Now.ToString("o") + " EXCEP: " + ex.Message, FILE_LOG);
                throw RestClientFactory.CreateFailedException(_restClient, _request, ex);
            }
        }
Exemple #29
0
 private void Initialize()
 {
     ServicePointManager.UseNagleAlgorithm = false;
     if (!ClassFactory.TryGet("EnrichmentServiceRestClient", out _restClient))
     {
         _restClient = RestClientFactory.CreateRestClient();
     }
 }
Exemple #30
0
 public ServiceManager(RestClientFactory restClientFactory, ServiceHubContextFactory serviceHubContextFactory, IServiceEndpointManager endpointManager, IServiceProvider serviceProvider)
 {
     _restClientFactory        = restClientFactory;
     _serviceHubContextFactory = serviceHubContextFactory;
     _serviceProvider          = serviceProvider;
     _endpoint         = endpointManager.Endpoints.Single().Key;
     _endpointProvider = endpointManager.GetEndpointProvider(_endpoint);
 }
        public TwitterProvider(ProviderParams providerParams) : base("Twitter", "OAuth 1.0a")
        {
            providerParams.Validate();

            PublicApiKey = providerParams.PublicApiKey;
            SecretApiKey = providerParams.SecretApiKey;

            RestClientFactory = new RestClientFactory();
        }
 public void AsyncRequestShouldPerformSuccessfully()
 {
     var factory = new RestClientFactory("http://httpbin.org");
     string origin = null;
     factory.GetAsyncWithAction<TestSuccessResponse>(new TestRequestWithSpecifiedOKType(), response =>
     {
         origin = response.Origin;
     });
     factory.WaitForAsync();
     Assert.That(origin, Is.Not.Null);
     Assert.That(origin, Is.Not.Empty);
 }
 public void AttributeWithSpecifiedOkTypeShouldReturnNonEmptyValue()
 {
     var factory = new RestClientFactory("http://httpbin.org");
     var c = factory.Get<TestSuccessResponse>(new TestRequestWithSpecifiedOKType());
     Assert.That(c.Origin, Is.Not.Empty);
 }
 public void GettingValuesWithPropertyInjectedUrlSegmentsShouldSucceed()
 {
     var client = new RestClientFactory("http://imenzies.apiary.io");
     var response = client.Get<CustomerCustomeridRange200>(new CustomerCustomeridRangeRequest("10"));
     Assert.That(response.Range.TitleCount, Is.GreaterThan(0));
 }
 public void AttributeWithSpecifiedDefaultTypeShouldRecognizeAnonymousFunctionObject()
 {
     var factory = new RestClientFactory("http://httpbin.org");
     var c = factory.Get(new TestRequestWithSpecifiedDefaultType());
     Assert.That(c, Is.TypeOf<TestSuccessResponse>());
 }
 public void GettingValuesShouldSucceed()
 {
     var client = new RestClientFactory("http://imenzies.apiary.io/");
     var response = client.Get<CustomerCustomeridRange200>(new CustomerCustomeridRangeRequest(), urlSegments: new Dictionary<string, string>() { { "customerid", "0" } });
     Assert.That(response.Range.TitleCount, Is.GreaterThan(0));
 }
 public void UsersLoginShouldSucceed()
 {
     var client = new RestClientFactory("http://imenzies.apiary.io/");
     Assert.DoesNotThrow(
         () =>
             client.Get(new UsersLoginRequest()
             {
                 Username = "******",
                 Password = "******"
             }));
 }