예제 #1
0
 public Startup(IConfiguration configuration)
 {
     _configuration         = configuration;
     _apiClientOptions      = _configuration.GetSection("ApiClient").Get <ApiClientOptions>();
     _identityClientOptions = _configuration.GetSection("IdentityClient").Get <IdentityClientOptions>();
     _openIdConnectOptions  = _configuration.GetSection("OpenIdConnect").Get <OpenIdConnectOptions>();
 }
예제 #2
0
        private ApiClientOptions Configure()
        {
            var directoryInfo = Directory.GetParent(Environment.CurrentDirectory).Parent?.Parent?.Parent;
            ApiClientOptions options;

            var path = Path.Combine(directoryInfo?.FullName ?? "./", "appsettings.json");

            if (File.Exists(path))
            {
                options = JsonConvert.DeserializeObject <ApiClientOptions>(File.ReadAllText(path));
            }
            else
            {
                options = new ApiClientOptions();
                var variables = Environment.GetEnvironmentVariables();

                if (variables.Contains("TOKEN"))
                {
                    options.Token = Environment.GetEnvironmentVariable("TOKEN");
                }

                if (variables.Contains("SECRET"))
                {
                    options.Secret = Environment.GetEnvironmentVariable("SECRET");
                }
//                Console.WriteLine(JsonConvert.SerializeObject(options));
            }

            return(options);
        }
        public static HttpClient GetInstance(ApiClientOptions options)
        {
            lock (MLock)
            {
                if (Instance == null)
                {
                    Instance = new HttpClient(new HttpClientHandler
                    {
                        AutomaticDecompression = DecompressionMethods.GZip
                    });

                    Instance.DefaultRequestHeaders.Accept.Add(
                        MediaTypeWithQualityHeaderValue.Parse("application/json"));

                    if (options != null)
                    {
                        if (options.Token != null)
                        {
                            Instance.DefaultRequestHeaders.Authorization =
                                new AuthenticationHeaderValue("Token", options.Token);
                        }
                        if (options.Secret != null)
                        {
                            Instance.DefaultRequestHeaders.Add("X-Secret", options.Secret);
                        }
                    }
                }

                return(Instance);
            }
        }
        private HttpRequestMessage GenerateRequestMessage(ApiClientOptions options)
        {
            var requestUri = (_currentSettings.BaseUrl ?? "") + (options.EndPointAddress ?? "");

            if (options.Method == HttpMethod.Get || options.Method == HttpMethod.Delete)
            {
                var queryString = GetQueryString(options.ParametersObject);
                if (!string.IsNullOrEmpty(queryString))
                {
                    requestUri += "?" + queryString;
                }
            }

            var requestMessage = new HttpRequestMessage
            {
                Method     = options.Method,
                RequestUri = new Uri(requestUri)
            };

            if (options.Method != HttpMethod.Get && options.Method != HttpMethod.Delete)
            {
                requestMessage.Content = GetHttpContent(options);
            }

            return(requestMessage);
        }
예제 #5
0
 // Demonstrates using the provided ApiClientOptions
 public SampleApiClient(HttpClient client, ApiClientOptions <SampleApiClient> options, ILogger <SampleApiClient> logger) : base(client, options, logger)
 {
     _logger.LogDebug("SampleApiClient constructed");
     // We can customise the HttpClient here
     _client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue()
     {
         NoCache = true
     };
 }
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.MainMenuView);

            System.Threading.ThreadPool.SetMinThreads(30, 30);

            //Arrange
            var authenticationOptions = new AuthenticationOptions()
            {
                BaseUri = new Uri("http://www.glueware.nl/klootzakken/kz/")
            };
            var authenticationService = new AuthenticationService(authenticationOptions);
            var apiClientOptions      = new ApiClientOptions()
            {
                BaseUri = new Uri("http://www.glueware.nl/klootzakken/kzapi/")
            };
            var apiClient          = new DefaultApiClient(authenticationService, apiClientOptions);
            var lobbyStatusService = new LobbyStatusService(apiClient);
            var lobbyActionService = new LobbyActionService(apiClient);

            //Act
            string randomString = Guid.NewGuid().ToString("n").Substring(0, 8);

            var isCreateGameSucces = await lobbyActionService.CreateLobbyAsync(randomString);

            var lobbies = await lobbyStatusService.GetLobbiesAsync();

            var createdLobby  = lobbies.Find(l => l.Name.Equals(randomString));
            var joinedToLobby = await lobbyActionService.JoinLobbyAsync(createdLobby.Id);

            var myLobbyies = await lobbyStatusService.GetMyLobbiesAsync();

            var justJoinedMyLobby = myLobbyies.Find(l => l.Name.Equals(randomString));
            var gameIsStarted     = await lobbyActionService.StartGameForLobbyAsync(createdLobby.Id);

            //Assert
            myGames = new List <string>
            {
                "GetLobbiesAsync() - " + randomString.Equals(createdLobby.Name).ToString(),
                "GetMyLobbiesAsync() - " + randomString.Equals(justJoinedMyLobby.Name).ToString(),
                "CreateLobbyAsync() - " + isCreateGameSucces.ToString(),
                "JoinLobbyAsync() - " + joinedToLobby.ToString(),
                "StartGameForLobbyAsync() - " + gameIsStarted.ToString()
            };
            myGamesListView         = FindViewById <ListView>(Resource.Id.myGamesListView);
            myGamesListView.Adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleListItem1, myGames);

            Button createGame = FindViewById <Button>(Resource.Id.btnCreateGame);

            createGame.Click += delegate
            {
                StartActivity(typeof(MainActivity));
            };
        }
예제 #7
0
        private static ITellerApiClient GetTellerApiClient(string apiBaseUrl, string clientId, string clientSecret, string identityProvider)
        {
            var apiClientOptions = new ApiClientOptions
            {
                ApiBaseUrl  = apiBaseUrl,
                TokenHeader = AccessTokenGenerator.GetReferenceTokenHeader(identityProvider, clientId, clientSecret)
            };

            return(new TellerApiClient(apiClientOptions, BackfillManager.Logger));
        }
예제 #8
0
        public static IServiceCollection AddApiClient(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure <ApiClientOptions>(configuration);

            ApiClientOptions options = new ApiClientOptions();

            configuration.Bind(options);

            AddApiClientCore(services, options);

            return(services);
        }
예제 #9
0
        public static IServiceCollection AddApiClient(this IServiceCollection services, Action <ApiClientOptions> action)
        {
            services.Configure(action);

            ApiClientOptions options = new ApiClientOptions();

            action(options);

            AddApiClientCore(services, options);

            return(services);
        }
예제 #10
0
        public ClientTests(CustomWebApplicationFactory factory)
        {
            var options = new ApiClientOptions()
            {
                GetApiKeyAsync = sp => Task.FromResult(_key)
            };

            var client = factory.WithPopulatedSeedData().CreateDefaultClient(
                new RedirectHandler(),
                new AuthorizationMessageHandler(factory.Services, Options.Create(options)));

            _client = RestService.For <IApiClient>(client);
        }
        private IApiClient SetUpApiClient()
        {
            var authenticationOptions = new AuthenticationOptions()
            {
                BaseUri = new Uri("http://www.glueware.nl/klootzakken/kz/")
            };
            var authenticationService = new AuthenticationService(authenticationOptions);
            var apiClientOptions      = new ApiClientOptions()
            {
                BaseUri = new Uri("http://www.glueware.nl/klootzakken/kzapi/")
            };

            return(new DefaultApiClient(authenticationService, apiClientOptions));
        }
예제 #12
0
        private HttpClientHandler GetClientHandler(ApiClientOptions apiClientOptions)
        {
            var clientHandler = new HttpClientHandler();

            if (apiClientOptions.CookieCollection != null)
            {
                var cookieContainer = new CookieContainer();
                cookieContainer.Add(apiClientOptions.CookieCollection);

                clientHandler.CookieContainer = cookieContainer;
            }

            return(clientHandler);
        }
예제 #13
0
        private HttpContent GetHttpContent(ApiClientOptions options)
        {
            switch (options.RequestType)
            {
            case ApiClientRequestType.Xml:
            case ApiClientRequestType.Json:
                return(new ObjectContent(options.ParametersObject.GetType(), options.ParametersObject, GetMediaTypeFormatter(options.RequestType)));

            case ApiClientRequestType.FormUrlEncoded:
                return(new FormUrlEncodedContent(GetPropertiesCollection(options.ParametersObject)));

            default:
                return(new StringContent(options.ParametersObject.ToString(), Encoding.UTF8, options.RequestType.ToMediaType()));
            }
        }
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.MainMenuView);

            var authenticationOptions = new AuthenticationOptions()
            {
                BaseUri = new Uri("http://10.0.2.2:5000/")
            };
            var authenticationService = new AuthenticationService(authenticationOptions);
            var apiClientOptions      = new ApiClientOptions()
            {
                BaseUri = new Uri("http://10.0.2.2:5000/")
            };
            var apiClient          = new DefaultApiClient(authenticationService, apiClientOptions);
            var lobbyStatusService = new LobbyStatusService(apiClient);
            var lobbyActionService = new LobbyActionService(apiClient);

            bool             isCreatingLobbySucces = false;
            List <LobbyView> lobbyViews            = null;

            try
            {
                isCreatingLobbySucces = await lobbyActionService.CreateLobbyAsync("dani2Lobby");

                lobbyViews = await lobbyStatusService.GetLobbiesAsync();
            }
            catch (Exception e)
            {
                Console.Write(e);
            }

            myGamesListView = FindViewById <ListView>(Resource.Id.myGamesListView);
            myGames         = new List <string>
            {
                isCreatingLobbySucces.ToString()
            };
            myGamesListView.Adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleListItem1, myGames);

            Button createGame = FindViewById <Button>(Resource.Id.btnCreateGame);

            createGame.Click += delegate
            {
                StartActivity(typeof(MainActivity)); //TODO: make a new activity for creating new game
            };
        }
예제 #15
0
        public ApiClient(ApiClientOptions options)
        {
            Iterations    = 0;
            MaxIterations = 3;
            Timeout       = 10;

            ApiCalls = new Dictionary <string, ApiCall>();

            if (options.MaxIterations != null)
            {
                MaxIterations = (int)options.MaxIterations;
            }
            if (options.Timeout != null)
            {
                Timeout = (int)options.Timeout;
            }
        }
예제 #16
0
        /// <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));
        }
예제 #17
0
        private async Task <string> InvokeBaseService(ApiClientOptions options)
        {
            using (HttpClient client = _clientFactory.CreateClient(options.HttlClientName))
            {
                HttpResponseMessage response    = null;
                HttpContent         httpContent = null;

                if (options.ContentType == ApiClientRequestContentTypes.Json)
                {
                    DefaultContractResolver contractResolver = new DefaultContractResolver
                    {
                        NamingStrategy = new CamelCaseNamingStrategy()
                    };

                    var requestObject = JsonConvert.SerializeObject(options.RequestContent, new JsonSerializerSettings
                    {
                        ContractResolver = contractResolver,
                        Formatting       = Formatting.Indented
                    });

                    httpContent = new StringContent(requestObject, Encoding.UTF8, "application/json");
                }
                else
                {
                    throw new NotImplementedException("HttpClientApi only accept Json as contentType");
                }

                if (options.RequestType == ApiClientRequestTypes.Get)
                {
                    response = await client.GetAsync(options.Uri);
                }
                if (options.RequestType == ApiClientRequestTypes.Post)
                {
                    response = await client.PostAsync(options.Uri, httpContent);
                }

                response.EnsureSuccessStatusCode();
                return(await response.Content.ReadAsStringAsync());
            }
        }
예제 #18
0
        public ApiClientResult <T> SendRequest <T>(ApiClientOptions apiClientOptions) where T : class
        {
            var httpClientHandler = GetClientHandler(apiClientOptions);

            using (var client = new HttpClient(httpClientHandler))
            {
                InitializeHttpClient(client, _currentSettings, apiClientOptions);

                var request = GenerateRequestMessage(apiClientOptions);

                var httpResponseMessage = client.SendAsync(request).WaitAndGetResult();

                var apiClientResult = ProcessResponseMessage <T>(httpResponseMessage, apiClientOptions);

                if (httpClientHandler.CookieContainer != null)
                {
                    var currentUri = new Uri(_currentSettings.BaseUrl + apiClientOptions.EndPointAddress);
                    apiClientResult.Cookies = httpClientHandler.CookieContainer.GetCookies(currentUri);
                }

                return(apiClientResult);
            }
        }
예제 #19
0
        private void InitializeHttpClient(HttpClient client, IApiClientSettings settings, ApiClientOptions options)
        {
            client.DefaultRequestHeaders.Accept.Clear();

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(options.RequestType.ToMediaType()));

            if (!string.IsNullOrEmpty(settings.AuthorizationToken))
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(settings.AuthorizationToken)));
            }
        }
예제 #20
0
 public ApiClientResult <T> Delete <T>(ApiClientOptions apiClientOptions) where T : class
 {
     apiClientOptions.Method = HttpMethod.Delete;
     return(_apiClientHelper.SendRequest <T>(apiClientOptions));
 }
예제 #21
0
 public ItemServiceApiClient(IOptions <ApiClientOptions> options)
 {
     _options = options.Value;
 }
예제 #22
0
 public ApiClientResult Put(ApiClientOptions apiClientOptions)
 {
     apiClientOptions.Method = HttpMethod.Put;
     return(_apiClientHelper.SendRequest(apiClientOptions));
 }
예제 #23
0
 public async Task InvokeService(ApiClientOptions options)
 {
     await InvokeBaseService(options);
 }
예제 #24
0
        private static void AddApiClientCore(IServiceCollection services, ApiClientOptions options)
        {
            //添加默认HttpClient
            services.AddHttpClient(ApiClient.NO_BASEURL_HTTPCLIENT_NAME, httpClient =>
            {
                httpClient.DefaultRequestHeaders.Add("User-Agent", typeof(ApiClient).FullName);
            })
#if DEBUG
            .ConfigurePrimaryHttpMessageHandler(() =>
            {
                HttpClientHandler handler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
                    {
                        if (cert !.Issuer.Equals("CN=localhost", GlobalSettings.Comparison))
                        {
                            return(true);
                        }
                        return(errors == System.Net.Security.SslPolicyErrors.None);
                    }
                };
                return(handler);
            })
#endif
            ;

            //添加各站点的HttpClient
            foreach (var endpoint in options.Endpoints)
            {
                services.AddHttpClient(endpoint.GetHttpClientName(), httpClient =>
                {
                    httpClient.BaseAddress = endpoint.Url;
                    httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
                    httpClient.DefaultRequestHeaders.Add("User-Agent", typeof(ApiClient).FullName);
                })

                //TODO: 调查这个
                //.AddTransientHttpErrorPolicy(p =>
                //{
                //    //TODO: Move this to options
                //    return p.WaitAndRetryAsync(3, _ => TimeSpan.FromMilliseconds(1000));
                //})
#if DEBUG
                .ConfigurePrimaryHttpMessageHandler(() =>
                {
                    HttpClientHandler handler = new HttpClientHandler
                    {
                        ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
                        {
                            if (cert !.Issuer.Equals("CN=localhost", GlobalSettings.Comparison))
                            {
                                return(true);
                            }
                            return(errors == System.Net.Security.SslPolicyErrors.None);
                        }
                    };
                    return(handler);
                })
#endif
                ;
            }

            services.AddSingleton <IApiClient, ApiClient>();

            //HttpClientHandler会随着HttpClient Dispose 而Dispose
            services.AddTransient <TokenAutoRefreshedHttpClientHandler>();
        }
 public TestSubSocketClient(BaseClientOptions options, ApiClientOptions apiOptions) : base(options, apiOptions)
 {
 }
예제 #26
0
 /// <summary>
 /// ctor
 /// </summary>
 /// <param name="options">Client options</param>
 /// <param name="apiOptions">Api client options</param>
 protected BaseApiClient(BaseClientOptions options, ApiClientOptions apiOptions)
 {
     Options         = apiOptions;
     _apiCredentials = apiOptions.ApiCredentials?.Copy() ?? options.ApiCredentials?.Copy();
     BaseAddress     = apiOptions.BaseAddress;
 }
예제 #27
0
        private ApiClientResult <T> ProcessResponseMessage <T>(HttpResponseMessage httpResponseMessage, ApiClientOptions options) where T : class
        {
            var apiClientResult = new ApiClientResult <T>();

            apiClientResult.Fill(httpResponseMessage);

            T responseContent;

            if (!httpResponseMessage.IsSuccessStatusCode)
            {
                responseContent = default(T);
            }
            else
            {
                if (typeof(T) == typeof(String))
                {
                    responseContent = apiClientResult.RawResponseContent as T;
                }
                else if (options.ResponseType == ApiClientResponseType.Xml)
                {
                    var message    = apiClientResult.RawResponseContent;
                    var serializer = new XmlSerializer(typeof(T));

                    using (var reader = new StringReader(message))
                    {
                        responseContent = serializer.Deserialize(reader) as T;
                    }
                }
                else
                {
                    responseContent = httpResponseMessage.Content.ReadAsAsync <T>().WaitAndGetResult();
                }
            }

            apiClientResult.ResponseContent = responseContent;

            return(apiClientResult);
        }
예제 #28
0
 public ApiClientResult Delete(ApiClientOptions apiClientOptions)
 {
     apiClientOptions.Method = HttpMethod.Delete;
     return(_apiClientHelper.SendRequest(apiClientOptions));
 }
 /// <summary>
 /// ctor
 /// </summary>
 /// <param name="options">The base client options</param>
 /// <param name="apiOptions">The Api client options</param>
 public SocketApiClient(BaseClientOptions options, ApiClientOptions apiOptions) : base(options, apiOptions)
 {
 }
예제 #30
0
        public async Task <TResponse> InvokeService <TResponse>(ApiClientOptions options) where TResponse : class
        {
            var result = await InvokeBaseService(options);

            return(JsonConvert.DeserializeObject <TResponse>(result));
        }