Esempio n. 1
0
        private async Task <IDictionary <string, Card> > GetCardInventoryAsync(string authToken)
        {
            var cards = new Dictionary <string, Card>(StringComparer.OrdinalIgnoreCase);

            using (var httpClient = HttpClientProvider.GetHttpClient(authToken))
            {
                string endpoint = this.configuration[Constants.CardsServiceEndpoint];
                Uri    uri      = new Uri(FormattableString.Invariant($"{endpoint}/api/cards"));
                string result   = await httpClient.GetStringAsync(uri);

                if (string.IsNullOrWhiteSpace(result))
                {
                    return(null);
                }

                CardInventory cardInventory = JsonConvert.DeserializeObject <CardInventory>(result);
                if (cardInventory?.Cards != null)
                {
                    foreach (var card in cardInventory.Cards)
                    {
                        cards[card.CardId] = card;
                    }
                }
            }

            return(cards);
        }
Esempio n. 2
0
        /// <summary>
        /// 获取公共的键值对配置
        /// </summary>
        public async static Task <string> GetRedisConfig()
        {
            foreach (var url in oauthUrls)
            {
                using (var client = HttpClientProvider.CreateHttpClient(url))
                {
                    try
                    {
                        if (!await PrepareAccessToken(client))
                        {
                            continue;
                        }
                        var resp = await client.GetAsync("/api/Config/GetRedisConfig");

                        if (resp.IsSuccessStatusCode)
                        {
                            var result = await resp.Content.ReadAsStringAsync();

                            if (!string.IsNullOrWhiteSpace(result))
                            {
                                return(result);
                            }
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            return(null);
        }
        public FullListUsersWindow(HttpClientProvider httpClientProvider)
        {
            InitializeComponent();
            this.httpClientProvider = httpClientProvider;

            ReloadDataGridUsersItemsSource();
        }
Esempio n. 4
0
 /// <summary>
 /// Sends a DELETE request and deserialises the JSON response.
 /// </summary>
 /// <typeparam name="T">The class to use to deserialise the JSON response.</typeparam>
 /// <param name="resource">The resource.</param>
 /// <param name="parameters">The parameters.</param>
 /// <returns></returns>
 public async Task <T> DeleteAsync <T>(string resource, HttpParams parameters = null)
 {
     using (var client = HttpClientProvider.Create())
     {
         return(await SendAsync <T>(client, HttpMethod.Delete, ApiUrl, resource, parameters));
     }
 }
Esempio n. 5
0
        /// <summary>
        /// 获取公共的键值对配置
        /// </summary>
        public async static Task <Dictionary <string, string> > GetKeyValues()
        {
            foreach (var url in oauthUrls)
            {
                using (var client = HttpClientProvider.CreateHttpClient(url))
                {
                    try
                    {
                        if (!await PrepareAccessToken(client))
                        {
                            continue;
                        }
                        var resp = await client.GetAsync("/api/Config/GetKeyValues");

                        if (resp.IsSuccessStatusCode)
                        {
                            var result = await resp.Content.ReadAsAsync <Dictionary <string, string> >();

                            if (result != null && result.Count > 0)
                            {
                                return(result);
                            }
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            return(new Dictionary <string, string>());
        }
Esempio n. 6
0
 /// <summary>
 /// Sends a POST request.
 /// </summary>
 /// <param name="resource">The resource.</param>
 /// <param name="parameters">The parameters.</param>
 /// <param name="content">The payload for the content of the HTTP request.</param>
 /// <returns></returns>
 public async Task <HttpResponseMessage> PostAsync(string resource, HttpParams parameters = null, object content = null)
 {
     using (var client = HttpClientProvider.Create())
     {
         return(await SendAsync(client, HttpMethod.Post, ApiUrl, resource, parameters, content));
     }
 }
Esempio n. 7
0
 /// <summary>
 /// Sends a PUT request and deserialises the JSON response.
 /// </summary>
 /// <typeparam name="T">The class to use to deserialise the JSON response.</typeparam>
 /// <param name="resource">The resource.</param>
 /// <param name="parameters">The parameters.</param>
 /// <param name="content">The content.</param>
 /// <returns></returns>
 public async Task <T> PutAsync <T>(string resource, HttpParams parameters = null, object content = null)
 {
     using (var client = HttpClientProvider.Create())
     {
         return(await SendAsync <T>(client, HttpMethod.Put, ApiUrl, resource, parameters, content));
     }
 }
        public void TestSetup()
        {
            log = new ConsoleLog();

            settings = new NativeTransportSettings();
            provider = new HttpClientProvider(settings, log);
        }
        public void Should_cache_handler_between_multiple_instances()
        {
            var handler1 = provider.Obtain(connectionTimeout);
            var handler2 = new HttpClientProvider(settings, log).Obtain(connectionTimeout);

            handler2.Should().BeSameAs(handler1);
        }
        private async void Login()
        {
            bool isServerLocal = false;

            if (LocalWork.IsChecked.HasValue && LocalWork.IsChecked.Value)
            {
                isServerLocal = true;
            }

            HttpClientProvider.SetHttpClientUri(isServerLocal);

            var commandQueryDispatcher = new CommandQueryDispatcher();
            var login = new Login(LoginTextBox.Text, PasswordTextBox.Password);

            var response = await commandQueryDispatcher.SendAsync(login, "api/user-management/users/login", HttpOperationType.POST);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                await SetUpCurrentUser(commandQueryDispatcher, LoginTextBox.Text);

                var projectsWindow = new MainWindow();
                projectsWindow.Top  = this.Top;
                projectsWindow.Left = this.Left;
                projectsWindow.Show();
                Close();
            }
            else
            {
                ResponseExtensions.ToMessageBox(response.ResponseContent);
            }
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            var username     = "";
            var password     = "";
            var url          = "";
            var httpProvider = new HttpClientProvider(url, username, password);

            var categoryService = new CategoryService(httpProvider);
            var categories      = categoryService.Get().Result;

            foreach (var category in categories.Data)
            {
                Console.WriteLine("Category {0}# {1}", category.Id, category.Title);
            }


            var contactService = new ContactService(httpProvider);
            var contacts       = contactService.Get().Result;

            foreach (var contact in contacts.Data)
            {
                Console.WriteLine(contact.Id);
            }

            var emailService = new EmailService(httpProvider);
            var emails       = emailService.Get().Result;

            foreach (var email in emails.Data)
            {
                Console.WriteLine(email.Name);
            }

            Console.Read();
        }
Esempio n. 12
0
        public SettingsWindow(HttpClientProvider httpClientProvider)
        {
            InitializeComponent();

            this.httpClientProvider = httpClientProvider;
            clientConfiguration     = LoadClientConfiguration();
        }
Esempio n. 13
0
        public BoardControl(HttpClientProvider httpClientProvider)
        {
            this.httpClientProvider = httpClientProvider;
            InitializeComponent();

            AddColumn += (sender, args) => LoadBoard(thisBoard?.Name);
        }
        public object CreateFor(Type type, Uri host)
        {
            var client     = HttpClientProvider.GetClient(this.HttpClientSettings, this.HttpClientSettings.DelegatingHandlers.Select(i => i()).ToArray());
            var proxyClass = new HttpClientWrapper(type, client, host, this.HttpClientSettings);

            return(proxyClass.GetTransparentProxy());
        }
Esempio n. 15
0
        public static async Task <List <Movie> > GetMoviesAsync()
        {
            var httpClientProvider = new HttpClientProvider <List <Movie> >();
            var movies             = await httpClientProvider.GetAsync(Config.MoviesUrl);

            return(movies);
        }
Esempio n. 16
0
        public async Task LogoutFromAppAsync()
        {
            using (var _clientProvider = new HttpClientProvider())
            {
                var uniquePartOfUri = "logout";

                await AddAuthCookieAsync(_clientProvider.clientHandler);

                await GetCsrfToken(_clientProvider);

                await PostAsync($"{_uri}{uniquePartOfUri}", null, _clientProvider);

                if (localSettings.Values.ContainsKey(DefaultCookieName))
                {
                    var cookieObj = await DecryptCookieValueAsync(localSettings.Values[DefaultCookieName].ToString());

                    if (cookieObj != null)
                    {
                        var authCookie = new Cookie(DefaultCookieName, cookieObj.ToString());
                        authCookie.Expires = DateTime.Now.Subtract(TimeSpan.FromDays(1));
                        localSettings.Values.Remove(DefaultCookieName);
                    }
                }
            }
        }
Esempio n. 17
0
        public async Task LoggedInUserIdAndUserType()
        {
            using (var _clientProvider = new HttpClientProvider())
            {
                var uniquePartOfUri = "currentUserIdAndRole";

                await AddAuthCookieAsync(_clientProvider.clientHandler);

                try
                {
                    var user = await GetAsync <User>($"{_uri}{uniquePartOfUri}", _clientProvider);

                    IdOfLoggedInUser = user.Id;

                    UserTypeOfLoggedInUser = user.UserType;

                    AlreadyFetchedLoggedInUser = true;

                    IsLoggedIn = true;
                }
                catch
                {
                }
            }
        }
        public async Task <BulkResponse> ExecuteAsync(RescheduleBulkExecuteContext context, BulkRequest bodyObject)
        {
            using (var client = HttpClientProvider.GetHttpClient(configuration))
            {
                NameValueCollection queryParameters = HttpUtility.ParseQueryString(string.Empty);
                SetQueryParamIfNotNull(queryParameters, "bulkId", context.BulkId);

                string queryString = queryParameters.ToString();
                string endpoint    = path + "?" + queryString;

                string      requestJson = JsonConvert.SerializeObject(bodyObject, Settings);
                HttpContent content     = new StringContent(requestJson, Encoding.UTF8, "application/json");

                var response = await client.PutAsync(endpoint, content);

                string contents = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    return(JsonConvert.DeserializeObject <BulkResponse>(contents, Settings));
                }
                else
                {
                    throw new InfobipApiException(
                              response.StatusCode,
                              JsonConvert.DeserializeObject <ApiErrorResponse>(contents, Settings)
                              );
                }
            }
        }
Esempio n. 19
0
        private async Task <Deck> GetDeckAsync(string deckId, string authToken)
        {
            using (var httpClient = HttpClientProvider.GetHttpClient(authToken))
            {
                string decksServiceEndpoint  = this.configuration["DecksServiceEndpoint"];
                string decksServiceUrl       = FormattableString.Invariant($"{decksServiceEndpoint}/api/decks/{deckId}");
                HttpResponseMessage response = await httpClient.GetAsync(decksServiceUrl);

                if (!response.IsSuccessStatusCode)
                {
                    return(null);
                }

                string deckJson = await response.Content.ReadAsStringAsync();

                if (string.IsNullOrWhiteSpace(deckJson))
                {
                    return(null);
                }

                try
                {
                    Deck deck = JsonConvert.DeserializeObject <Deck>(deckJson);
                    return(deck);
                }
                catch (Exception ex)
                {
                    return(null);
                }
            }
        }
Esempio n. 20
0
        public async Task <Campaign> ExecuteAsync(string campaignKey, Destinations bodyObject)
        {
            using (var client = HttpClientProvider.GetHttpClient(configuration))
            {
                string endpoint = path;
                endpoint = endpoint.Replace("{campaignKey}", HttpUtility.UrlEncode(campaignKey));

                string      requestJson = JsonConvert.SerializeObject(bodyObject, Settings);
                HttpContent content     = new StringContent(requestJson, Encoding.UTF8, "application/json");

                var response = await client.PutAsync(endpoint, content);

                string contents = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    return(JsonConvert.DeserializeObject <Campaign>(contents, Settings));
                }
                else
                {
                    throw new InfobipApiException(
                              response.StatusCode,
                              JsonConvert.DeserializeObject <ApiErrorResponse>(contents, Settings)
                              );
                }
            }
        }
Esempio n. 21
0
        public async Task <OMNIReportsResponse> ExecuteAsync(GetOMNIReportsExecuteContext context)
        {
            using (var client = HttpClientProvider.GetHttpClient(configuration))
            {
                NameValueCollection queryParameters = HttpUtility.ParseQueryString(string.Empty);
                SetQueryParamIfNotNull(queryParameters, "bulkId", context.BulkId);
                SetQueryParamIfNotNull(queryParameters, "messageId", context.MessageId);
                SetQueryParamIfNotNull(queryParameters, "limit", context.Limit);
                SetQueryParamIfNotNull(queryParameters, "channel", context.Channel);

                string queryString = queryParameters.ToString();
                string endpoint    = path + "?" + queryString;

                var response = await client.GetAsync(endpoint);

                string contents = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    return(JsonConvert.DeserializeObject <OMNIReportsResponse>(contents, Settings));
                }
                else
                {
                    throw new InfobipApiException(
                              response.StatusCode,
                              JsonConvert.DeserializeObject <ApiErrorResponse>(contents, Settings)
                              );
                }
            }
        }
Esempio n. 22
0
        public async Task <PreviewResponse> ExecuteAsync(PreviewRequest bodyObject)
        {
            using (var client = HttpClientProvider.GetHttpClient(configuration))
            {
                string endpoint = path;

                string      requestJson = JsonConvert.SerializeObject(bodyObject, Settings);
                HttpContent content     = new StringContent(requestJson, Encoding.UTF8, "application/json");

                var response = await client.PostAsync(endpoint, content);

                string contents = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    return(JsonConvert.DeserializeObject <PreviewResponse>(contents, Settings));
                }
                else
                {
                    throw new InfobipApiException(
                              response.StatusCode,
                              JsonConvert.DeserializeObject <ApiErrorResponse>(contents, Settings)
                              );
                }
            }
        }
        public void SetupHttpClient_Returns_HttpClient()
        {
            var        provider = new HttpClientProvider();
            HttpClient client   = provider.SetupHttpClient();

            Assert.That(client, Is.Not.Null);
        }
Esempio n. 24
0
        async System.Threading.Tasks.Task <Document> DownloadAndOpenFileAsync(StackFrame frame, int line, SourceLink sourceLink)
        {
            var pm = IdeApp.Workbench.ProgressMonitors.GetStatusProgressMonitor(
                GettextCatalog.GetString("Downloading {0}", sourceLink.Uri),
                Stock.StatusDownload,
                true
                );

            Document doc = null;

            try {
                var downloadLocation = sourceLink.GetDownloadLocation(symbolCachePath);
                Directory.CreateDirectory(Path.GetDirectoryName(downloadLocation));
                DocumentRegistry.SkipNextChange(downloadLocation);
                var client = HttpClientProvider.CreateHttpClient(sourceLink.Uri);
                using (var stream = await client.GetStreamAsync(sourceLink.Uri).ConfigureAwait(false))
                    using (var fs = new FileStream(downloadLocation, FileMode.Create)) {
                        await stream.CopyToAsync(fs).ConfigureAwait(false);
                    }
                frame.UpdateSourceFile(downloadLocation);
                doc = await Runtime.RunInMainThread(() => IdeApp.Workbench.OpenDocument(downloadLocation, null, line, 1, OpenDocumentOptions.Debugger));
            } catch (Exception ex) {
                LoggingService.LogInternalError("Error downloading SourceLink file", ex);
            } finally {
                pm.Dispose();
            }
            return(doc);
        }
Esempio n. 25
0
        public async Task <MOLogsResponse> ExecuteAsync(GetReceivedSmsLogsExecuteContext context)
        {
            using (var client = HttpClientProvider.GetHttpClient(configuration))
            {
                NameValueCollection queryParameters = HttpUtility.ParseQueryString(string.Empty);
                SetQueryParamIfNotNull(queryParameters, "to", context.To);
                SetQueryParamIfNotNull(queryParameters, "receivedSince", context.ReceivedSince);
                SetQueryParamIfNotNull(queryParameters, "receivedUntil", context.ReceivedUntil);
                SetQueryParamIfNotNull(queryParameters, "limit", context.Limit);
                SetQueryParamIfNotNull(queryParameters, "keyword", context.Keyword);

                string queryString = queryParameters.ToString();
                string endpoint    = path + "?" + queryString;

                var response = await client.GetAsync(endpoint);

                string contents = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    return(JsonConvert.DeserializeObject <MOLogsResponse>(contents, Settings));
                }
                else
                {
                    throw new InfobipApiException(
                              response.StatusCode,
                              JsonConvert.DeserializeObject <ApiErrorResponse>(contents, Settings)
                              );
                }
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Requests an access and refresh token from the code provided by the mercado libre callback.
        /// </summary>
        /// <param name="code">The code.</param>
        /// <param name="redirectUri">The redirect URI.</param>
        /// <returns>
        /// Return True when the operation is successful.
        /// </returns>
        public async Task <bool> AuthorizeAsync(string code, string redirectUri)
        {
            if (Credentials == null)
            {
                throw new ApplicationException("Credentials property not initalised.");
            }

            var success = false;

            var parameters = new HttpParams().Add("grant_type", "authorization_code")
                             .Add("client_id", Credentials.ClientId)
                             .Add("client_secret", Credentials.ClientSecret)
                             .Add("code", code)
                             .Add("redirect_uri", redirectUri);

            using (var client = HttpClientProvider.Create(false))
            {
                var tokens = await SendAsync <TokenResponse>(client, HttpMethod.Post, ApiUrl, "/oauth/token", parameters);

                if (tokens != null)
                {
                    Credentials.SetTokens(tokens);

                    success = true;
                }
            }

            return(success);
        }
        public async Task <NumberContextLogsResponse> ExecuteAsync(GetNumberContextLogsExecuteContext context)
        {
            using (var client = HttpClientProvider.GetHttpClient(configuration))
            {
                NameValueCollection queryParameters = new NameValueCollection();
                SetQueryParamIfNotNull(queryParameters, "to", context.To);
                SetQueryParamIfNotNull(queryParameters, "bulkId", context.BulkId);
                SetQueryParamIfNotNull(queryParameters, "messageId", context.MessageId);
                SetQueryParamIfNotNull(queryParameters, "generalStatus", context.GeneralStatus);
                SetQueryParamIfNotNull(queryParameters, "sentSince", context.SentSince);
                SetQueryParamIfNotNull(queryParameters, "sentUntil", context.SentUntil);
                SetQueryParamIfNotNull(queryParameters, "limit", context.Limit);
                SetQueryParamIfNotNull(queryParameters, "mcc", context.Mcc);
                SetQueryParamIfNotNull(queryParameters, "mnc", context.Mnc);

                string queryString = queryParameters.ToQueryString();
                string endpoint    = path + "?" + queryString;

                var response = await client.GetAsync(endpoint);

                string contents = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    return(JsonConvert.DeserializeObject <NumberContextLogsResponse>(contents, Settings));
                }
                else
                {
                    throw new InfobipApiException(
                              response.StatusCode,
                              JsonConvert.DeserializeObject <ApiErrorResponse>(contents, Settings)
                              );
                }
            }
        }
Esempio n. 28
0
        protected override SmartSubtransportStream Action(string url, GitSmartSubtransportAction action)
        {
            string postContentType = null;
            string serviceUri;

            switch (action)
            {
            case GitSmartSubtransportAction.UploadPackList:
                serviceUri = url + "/info/refs?service=git-upload-pack";
                break;

            case GitSmartSubtransportAction.UploadPack:
                serviceUri      = url + "/git-upload-pack";
                postContentType = "application/x-git-upload-pack-request";
                break;

            case GitSmartSubtransportAction.ReceivePackList:
                serviceUri = url + "/info/refs?service=git-receive-pack";
                break;

            case GitSmartSubtransportAction.ReceivePack:
                serviceUri      = url + "/git-receive-pack";
                postContentType = "application/x-git-receive-pack-request";
                break;

            default:
                throw new InvalidOperationException();
            }

            // Grab the credentials from the user.
            var httpClient = HttpClientProvider.CreateHttpClient(serviceUri);

            httpClient.Timeout = TimeSpan.FromMinutes(1.0);

            var res = httpClient.GetAsync(serviceUri).Result;

            if (res.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                var cred = (UsernamePasswordCredentials)GitCredentials.TryGet(url, "", SupportedCredentialTypes.UsernamePassword, GitCredentialsType.Tfs);

                httpClient = new HttpClient(new HttpClientHandler {
                    Credentials = new System.Net.NetworkCredential(cred.Username, cred.Password)
                })
                {
                    Timeout = TimeSpan.FromMinutes(1.0),
                };
                res = httpClient.GetAsync(serviceUri).Result;
                if (res.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    GitCredentials.StoreCredentials(GitCredentialsType.Tfs);
                }
            }

            return(new TfsSmartSubtransportStream(this)
            {
                HttpClient = httpClient,
                ServiceUri = new Uri(serviceUri),
                PostContentType = postContentType,
            });
        }
        public async Task <ScenariosResponse> ExecuteAsync(GetScenariosExecuteContext context)
        {
            using (var client = HttpClientProvider.GetHttpClient(configuration))
            {
                NameValueCollection queryParameters = new NameValueCollection();
                SetQueryParamIfNotNull(queryParameters, "isDefault", context.IsDefault);
                SetQueryParamIfNotNull(queryParameters, "limit", context.Limit);
                SetQueryParamIfNotNull(queryParameters, "page", context.Page);

                string queryString = queryParameters.ToQueryString();
                string endpoint    = path + "?" + queryString;

                var response = await client.GetAsync(endpoint);

                string contents = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    return(JsonConvert.DeserializeObject <ScenariosResponse>(contents, Settings));
                }
                else
                {
                    throw new InfobipApiException(
                              response.StatusCode,
                              JsonConvert.DeserializeObject <ApiErrorResponse>(contents, Settings)
                              );
                }
            }
        }
Esempio n. 30
0
        public static async Task<List<Movie>> GetMoviesAsync()
        {
            var httpClientProvider = new HttpClientProvider<List<Movie>>();
            var movies = await httpClientProvider.GetAsync(Config.MoviesUrl);

            return movies;
        }
        public void HttpClientProvider_ConstructedWithNullWebCfgReader_ShouldThrow()
        {
            // Arrange
            HttpClientProvider client = new HttpClientProvider(null);

            // Act
            var returnedValue = client.GetHttpClientInstance();
        }
Esempio n. 32
0
        public void CanAuthenticateDocFlock()
        {
            //   var handler = new NativeMessageHandler();

            var context         = new HttpContext();
            context.HostAddress = new Uri("http://api-shs-dev.docflock.com/");

            //context.HostAddress = new Uri("http://shs-dev.docflock.com/");

            var credentials     = new DocFlockCredentials("*****@*****.**", "Password");
            var client          = new HttpClientProvider(context, new CancellationToken());
            var authProvider    = new DocFlockAuthProvider(client);
            var response        = authProvider.AuthenticateAsync(credentials).Result;

               Assert.IsTrue(response.Principal.Identity.IsAuthenticated);
        }