/// <summary> /// Get client configurators /// </summary> /// <param name="clientConfigurations"></param> /// <returns></returns> public static List <ClientConfigurator> ToClientConfigurators(this List <ClientConfiguration> clientConfigurations) { return(clientConfigurations?.Select(config => { // create builder ClientConfigurator builder = new ClientConfigurator(); // set name if (!string.IsNullOrWhiteSpace(config.Name)) { builder.SetName(config.Name); } // add hosts config.Hosts?.ForEach(host => builder.AddHost(host)); // set client options if (config.Options != null) { builder.SetClientOptions(config.Options); } ; // get services config.Services?.Distinct().ToList().ForEach(svc => { builder.AddService(svc); }); // return return builder; }).ToList()); }
public void ShouldNotValidateSerializer() { // Given var configurator = new ClientConfigurator(); // When, Then Assert.Throws <ArgumentNullException>(() => configurator.WithSerializer(null)); }
public void ShouldNotValidateBaseUrl(string baseUrl) { // Given var configurator = new ClientConfigurator(); // When, Then Assert.Throws <ArgumentNullException>(() => configurator.WithBaseUrl(baseUrl)); }
public EmbeddedConfigurator(AppDomainSetup setup) { domain = AppDomain.CreateDomain("EmbeddedOrleans", null, setup ?? AppDomain.CurrentDomain.SetupInformation); client = new ClientConfigurator(); cluster = (ClusterConfigurator)domain.CreateInstanceAndUnwrap( GetType().Assembly.FullName, typeof(ClusterConfigurator).FullName, false, BindingFlags.NonPublic | BindingFlags.Instance, null, new object[0], null, null); }
/// <summary> /// Setup custom client /// </summary> /// <param name="collection"></param> /// <param name="cfg"></param> /// <returns></returns> public static IServiceCollection AddGrpcClient(this IServiceCollection collection, Action <ClientConfigurator> cfg) { // apply configuration ClientConfigurator configurator = new ClientConfigurator(); collection.AddGrpcClient(configurator, cfg); // return return(collection); }
public void ShouldSetBasUrl() { // Given const string baseUrl = "http://localhost"; var configurator = new ClientConfigurator(); // When configurator.WithBaseUrl(baseUrl); // Then Assert.Equal(baseUrl, configurator.BaseUrl); }
public void ShouldSetTimeout() { // Given var timeout = TimeSpan.FromMinutes(1); var configurator = new ClientConfigurator(); // When configurator.WithTimeout(timeout); // Then Assert.Equal(timeout, configurator.ClientSettings.Timeout); }
public void ShouldSetSerializer() { // Given var serializer = new JilJsonSerializer(Options.Default); var configurator = new ClientConfigurator(); // When configurator.WithSerializer(serializer); // Then Assert.Equal(serializer, configurator.ClientSettings.JsonSerializer); }
protected FavouriteExchangesClient(ClientConfigurator clientConfigurator) { ApiConfiguration = clientConfigurator.ApiConfiguration; Top12ExchangeIds = ApiConfiguration.FavouriteExchanges?.Count > 0 ? ApiConfiguration.FavouriteExchanges !.AsReadOnly() : new List <string> { "bitstamp", "bittrex", "poloniex", "kraken", "bitfinex", "coinbasepro", "itbi", "gemini", "binance", "bfly", "cflr", "huobiglobal" }.AsReadOnly(); Top12ExchangeIdsAsCsv = string.Join(",", Top12ExchangeIds); }
static void Main(string[] args) { logger.Debug("Bot started"); matchRequestService = new MatchRequestService(ClientConfigurator.CreateWebClient(ConfigurationManager.AppSettings["authToken"])); userFavouriteService = new UserFavouriteService(); stadiumService = new StadiumService(); webClient = ClientConfigurator.CreateWebClient(ConfigurationManager.AppSettings["authToken"]); markupCreator = new MarkupCreator(); botClient = new TelegramBotClient(ConfigurationManager.AppSettings["botToken"]); //event handlers botClient.OnMessage += Bot_OnMessage; botClient.OnCallbackQuery += BotClient_OnCallbackQuery; botClient.StartReceiving(); Thread.Sleep(int.MaxValue); }
protected FlurlBasedClient(Func <IClientConfigurator, IClientConfigurator> configurationBuilder) { if (configurationBuilder == null) { throw new ArgumentNullException(nameof(configurationBuilder)); } var clientConfigurator = new ClientConfigurator(); configurationBuilder(clientConfigurator); _baseUrl = clientConfigurator.BaseUrl; _clientSettings = clientConfigurator.ClientSettings; _exceptionsTypesByStatusCodes = new Dictionary <HttpStatusCode, Type> { { HttpStatusCode.NotFound, typeof(NotFoundException) }, { HttpStatusCode.Unauthorized, typeof(UnauthorizedException) }, { HttpStatusCode.BadRequest, typeof(BadRequestException) } }; }
private static void AddClients(this IServiceCollection services, CoinGeckoApiConfiguration configuration) { var configurator = new ClientConfigurator(configuration); var maxRetryCount = configuration.MaxRetryCount ?? 10; var delays = Backoff.DecorrelatedJitterBackoffV2( medianFirstRetryDelay: TimeSpan.FromMilliseconds(configuration.InitialRetryDelayInMilliseconds ?? 100), retryCount: maxRetryCount, fastFirst: false).ToList(); services.AddHttpClient <IPingClient, PingClient>("Trakx.CoinGecko.ApiClient.PingClient", x => configurator.AddHeaders(x)) .AddPolicyHandler((s, request) => Policy <HttpResponseMessage> .Handle <ApiException>() .OrTransientHttpStatusCode() .WaitAndRetryAsync( retryCount: maxRetryCount, sleepDurationProvider: (retryCount, response, context) => GetServerWaitDuration(response, delays[retryCount - 1]), onRetryAsync: (result, timeSpan, retryCount, context) => LogFailure(Log.Logger.ForContext <PingClient>(), result, timeSpan, retryCount, context)) .WithPolicyKey("Trakx.CoinGecko.ApiClient.PingClient")) .AddHttpMessageHandler <CachedHttpClientHandler>(); services.AddHttpClient <ISimpleClient, SimpleClient>("Trakx.CoinGecko.ApiClient.SimpleClient", x => configurator.AddHeaders(x)) .AddPolicyHandler((s, request) => Policy <HttpResponseMessage> .Handle <ApiException>() .OrTransientHttpStatusCode() .WaitAndRetryAsync( retryCount: maxRetryCount, sleepDurationProvider: (retryCount, response, context) => GetServerWaitDuration(response, delays[retryCount - 1]), onRetryAsync: (result, timeSpan, retryCount, context) => LogFailure(Log.Logger.ForContext <SimpleClient>(), result, timeSpan, retryCount, context)) .WithPolicyKey("Trakx.CoinGecko.ApiClient.SimpleClient")) .AddHttpMessageHandler <CachedHttpClientHandler>(); services.AddHttpClient <ICoinsClient, CoinsClient>("Trakx.CoinGecko.ApiClient.CoinsClient", x => configurator.AddHeaders(x)) .AddPolicyHandler((s, request) => Policy <HttpResponseMessage> .Handle <ApiException>() .OrTransientHttpStatusCode() .WaitAndRetryAsync( retryCount: maxRetryCount, sleepDurationProvider: (retryCount, response, context) => GetServerWaitDuration(response, delays[retryCount - 1]), onRetryAsync: (result, timeSpan, retryCount, context) => LogFailure(Log.Logger.ForContext <CoinsClient>(), result, timeSpan, retryCount, context)) .WithPolicyKey("Trakx.CoinGecko.ApiClient.CoinsClient")) .AddHttpMessageHandler <CachedHttpClientHandler>(); services.AddHttpClient <IContractClient, ContractClient>("Trakx.CoinGecko.ApiClient.ContractClient", x => configurator.AddHeaders(x)) .AddPolicyHandler((s, request) => Policy <HttpResponseMessage> .Handle <ApiException>() .OrTransientHttpStatusCode() .WaitAndRetryAsync( retryCount: maxRetryCount, sleepDurationProvider: (retryCount, response, context) => GetServerWaitDuration(response, delays[retryCount - 1]), onRetryAsync: (result, timeSpan, retryCount, context) => LogFailure(Log.Logger.ForContext <ContractClient>(), result, timeSpan, retryCount, context)) .WithPolicyKey("Trakx.CoinGecko.ApiClient.ContractClient")) .AddHttpMessageHandler <CachedHttpClientHandler>(); services.AddHttpClient <IExchangesClient, ExchangesClient>("Trakx.CoinGecko.ApiClient.ExchangesClient", x => configurator.AddHeaders(x)) .AddPolicyHandler((s, request) => Policy <HttpResponseMessage> .Handle <ApiException>() .OrTransientHttpStatusCode() .WaitAndRetryAsync( retryCount: maxRetryCount, sleepDurationProvider: (retryCount, response, context) => GetServerWaitDuration(response, delays[retryCount - 1]), onRetryAsync: (result, timeSpan, retryCount, context) => LogFailure(Log.Logger.ForContext <ExchangesClient>(), result, timeSpan, retryCount, context)) .WithPolicyKey("Trakx.CoinGecko.ApiClient.ExchangesClient")) .AddHttpMessageHandler <CachedHttpClientHandler>(); services.AddHttpClient <IFinanceClient, FinanceClient>("Trakx.CoinGecko.ApiClient.FinanceClient", x => configurator.AddHeaders(x)) .AddPolicyHandler((s, request) => Policy <HttpResponseMessage> .Handle <ApiException>() .OrTransientHttpStatusCode() .WaitAndRetryAsync( retryCount: maxRetryCount, sleepDurationProvider: (retryCount, response, context) => GetServerWaitDuration(response, delays[retryCount - 1]), onRetryAsync: (result, timeSpan, retryCount, context) => LogFailure(Log.Logger.ForContext <FinanceClient>(), result, timeSpan, retryCount, context)) .WithPolicyKey("Trakx.CoinGecko.ApiClient.FinanceClient")) .AddHttpMessageHandler <CachedHttpClientHandler>(); services.AddHttpClient <IIndexesClient, IndexesClient>("Trakx.CoinGecko.ApiClient.IndexesClient", x => configurator.AddHeaders(x)) .AddPolicyHandler((s, request) => Policy <HttpResponseMessage> .Handle <ApiException>() .OrTransientHttpStatusCode() .WaitAndRetryAsync( retryCount: maxRetryCount, sleepDurationProvider: (retryCount, response, context) => GetServerWaitDuration(response, delays[retryCount - 1]), onRetryAsync: (result, timeSpan, retryCount, context) => LogFailure(Log.Logger.ForContext <IndexesClient>(), result, timeSpan, retryCount, context)) .WithPolicyKey("Trakx.CoinGecko.ApiClient.IndexesClient")) .AddHttpMessageHandler <CachedHttpClientHandler>(); services.AddHttpClient <IDerivativesClient, DerivativesClient>("Trakx.CoinGecko.ApiClient.DerivativesClient", x => configurator.AddHeaders(x)) .AddPolicyHandler((s, request) => Policy <HttpResponseMessage> .Handle <ApiException>() .OrTransientHttpStatusCode() .WaitAndRetryAsync( retryCount: maxRetryCount, sleepDurationProvider: (retryCount, response, context) => GetServerWaitDuration(response, delays[retryCount - 1]), onRetryAsync: (result, timeSpan, retryCount, context) => LogFailure(Log.Logger.ForContext <DerivativesClient>(), result, timeSpan, retryCount, context)) .WithPolicyKey("Trakx.CoinGecko.ApiClient.DerivativesClient")) .AddHttpMessageHandler <CachedHttpClientHandler>(); services.AddHttpClient <IStatus_updatesClient, Status_updatesClient>("Trakx.CoinGecko.ApiClient.Status_updatesClient", x => configurator.AddHeaders(x)) .AddPolicyHandler((s, request) => Policy <HttpResponseMessage> .Handle <ApiException>() .OrTransientHttpStatusCode() .WaitAndRetryAsync( retryCount: maxRetryCount, sleepDurationProvider: (retryCount, response, context) => GetServerWaitDuration(response, delays[retryCount - 1]), onRetryAsync: (result, timeSpan, retryCount, context) => LogFailure(Log.Logger.ForContext <Status_updatesClient>(), result, timeSpan, retryCount, context)) .WithPolicyKey("Trakx.CoinGecko.ApiClient.Status_updatesClient")) .AddHttpMessageHandler <CachedHttpClientHandler>(); services.AddHttpClient <IEventsClient, EventsClient>("Trakx.CoinGecko.ApiClient.EventsClient", x => configurator.AddHeaders(x)) .AddPolicyHandler((s, request) => Policy <HttpResponseMessage> .Handle <ApiException>() .OrTransientHttpStatusCode() .WaitAndRetryAsync( retryCount: maxRetryCount, sleepDurationProvider: (retryCount, response, context) => GetServerWaitDuration(response, delays[retryCount - 1]), onRetryAsync: (result, timeSpan, retryCount, context) => LogFailure(Log.Logger.ForContext <EventsClient>(), result, timeSpan, retryCount, context)) .WithPolicyKey("Trakx.CoinGecko.ApiClient.EventsClient")) .AddHttpMessageHandler <CachedHttpClientHandler>(); services.AddHttpClient <IExchange_ratesClient, Exchange_ratesClient>("Trakx.CoinGecko.ApiClient.Exchange_ratesClient", x => configurator.AddHeaders(x)) .AddPolicyHandler((s, request) => Policy <HttpResponseMessage> .Handle <ApiException>() .OrTransientHttpStatusCode() .WaitAndRetryAsync( retryCount: maxRetryCount, sleepDurationProvider: (retryCount, response, context) => GetServerWaitDuration(response, delays[retryCount - 1]), onRetryAsync: (result, timeSpan, retryCount, context) => LogFailure(Log.Logger.ForContext <Exchange_ratesClient>(), result, timeSpan, retryCount, context)) .WithPolicyKey("Trakx.CoinGecko.ApiClient.Exchange_ratesClient")) .AddHttpMessageHandler <CachedHttpClientHandler>(); services.AddHttpClient <ITrendingClient, TrendingClient>("Trakx.CoinGecko.ApiClient.TrendingClient", x => configurator.AddHeaders(x)) .AddPolicyHandler((s, request) => Policy <HttpResponseMessage> .Handle <ApiException>() .OrTransientHttpStatusCode() .WaitAndRetryAsync( retryCount: maxRetryCount, sleepDurationProvider: (retryCount, response, context) => GetServerWaitDuration(response, delays[retryCount - 1]), onRetryAsync: (result, timeSpan, retryCount, context) => LogFailure(Log.Logger.ForContext <TrendingClient>(), result, timeSpan, retryCount, context)) .WithPolicyKey("Trakx.CoinGecko.ApiClient.TrendingClient")) .AddHttpMessageHandler <CachedHttpClientHandler>(); services.AddHttpClient <IGlobalClient, GlobalClient>("Trakx.CoinGecko.ApiClient.GlobalClient", x => configurator.AddHeaders(x)) .AddPolicyHandler((s, request) => Policy <HttpResponseMessage> .Handle <ApiException>() .OrTransientHttpStatusCode() .WaitAndRetryAsync( retryCount: maxRetryCount, sleepDurationProvider: (retryCount, response, context) => GetServerWaitDuration(response, delays[retryCount - 1]), onRetryAsync: (result, timeSpan, retryCount, context) => LogFailure(Log.Logger.ForContext <GlobalClient>(), result, timeSpan, retryCount, context)) .WithPolicyKey("Trakx.CoinGecko.ApiClient.GlobalClient")) .AddHttpMessageHandler <CachedHttpClientHandler>(); }
private static void Main(string[] args) { if (args.Length < 3) { Console.WriteLine("Required arguments not found!"); Console.WriteLine("URI AppKey ScanRate"); Console.WriteLine("Example:"); Console.WriteLine("SteamSensorClient.exe wss://localhost:443/Thingworx/WS xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx 1000"); return; } // Set the required configuration information var config = new ClientConfigurator { // Set the size of the threadpools MaxMsgHandlerThreadCount = 8, MaxApiTaskerThreadCount = 8, DisableCertValidation = true, OfflineMsgStoreDir = ".", // The uri for connecting to Thingworx Uri = args[0], // Reconnect every 15 seconds if a disconnect occurs or if initial connection cannot be made ReconnectInterval = 15 }; // Set the security using an Application Key var appKey = args[1]; var claims = SecurityClaims.fromAppKey(appKey); config.Claims = claims; // Set the name of the client config.Name = "SteamSensorGateway"; // Get the scan rate (milliseconds) that is specific to this example // The example will execute the processScanRequest of the VirtualThing // based on this scan rate var scanRate = int.Parse(args[2]); // Create the client passing in the configuration from above var client = new SteamSensorClient(config); try { // Create think var sensor1 = new SteamThing("ThingTemperature_dntichy", "Senzor id: ...dorob ID ak viac senzorov", "SN000", client); client.bindThing(sensor1); LoggerFactory.Log(Logger, TraceEventType.Critical, "CONNECTNG TO PLATFORM:\n " + "Uri: {0} \n " + "AppKey: {1} \n " + "Think: [name: {2}, identifier: {3}] \n " + "AllowSelfSignedCertificates: {4} \n " + "DisableCertValidation: {5}", config.Uri, appKey, sensor1.getName(), sensor1.getIdentifier(), config.AllowSelfSignedCertificates, config.DisableCertValidation); // Start the client ThreadPool.QueueUserWorkItem(client.StartClient); } catch (Exception eStart) { Console.WriteLine("Initial Start Failed : " + eStart.Message); } // Wait for the SteamSensorClient to connect, then process its associated things. // As long as the client has not been shutdown, continue while (!client.isShutdown()) { // Only process the Virtual Things if the client is connected if (client.isConnected()) { ThreadPool.QueueUserWorkItem(client.RunClient); } // Suspend processing at the scan rate interval Thread.Sleep(scanRate); } }
public SteamSensorClient(ClientConfigurator config) : base(config) { }
protected AuthorisedClient(ClientConfigurator configurator) : base(configurator) { CredentialProvider = configurator.GetCredentialProvider(GetType()); BaseUrl = configurator.ApiConfiguration.BaseUrl; }
static void Main(string[] args) { /*if(args.Length < 3) * { * Console.WriteLine("Required arguments not found!"); * Console.WriteLine("URI AppKey ScanRate"); * Console.WriteLine("Example:"); * Console.WriteLine("SteamSensorClient.exe wss://localhost:443/Thingworx/WS xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx 1000"); * return; * }*/ // Set the required configuration information var config = new ClientConfigurator(); // Set the size of the threadpools config.MaxMsgHandlerThreadCount = 8; config.MaxApiTaskerThreadCount = 8; /***** WARNING: For Development purposes only. Do not use these settings in a production environment. *****/ config.AllowSelfSignedCertificates = true; config.DisableCertValidation = true; /***** WARNING *****/ // The uri for connecting to Thingworx config.Uri = ConfigurationManager.AppSettings["config.Uri"].ToString(); // Reconnect every 15 seconds if a disconnect occurs or if initial connection cannot be made config.ReconnectInterval = 15; // Set the security using an Application Key var appKey = ConfigurationManager.AppSettings["appKey"].ToString(); var claims = SecurityClaims.fromAppKey(appKey); config.Claims = claims; // Set the name of the client config.Name = "TakePhotoGateway"; config.MaxMessageSize = 1048576; // Get the scan rate (milliseconds) that is specific to this example // The example will execute the processScanRequest of the VirtualThing // based on this scan rate int scanRate = 1000; // Create the client passing in the configuration from above SteamSensorClient client = new SteamSensorClient(config); // prepare the camera IP FindCameraIp(); try { // Create two Virtual Things SteamThing sensor1 = new SteamThing("AlexaAgentTR", "desc", null, client); // SteamThing sensor2 = new SteamThing("SteamSensor2", "2nd Floor Steam Sensor", "SN0002", client); // Bind the Virtual Things client.bindThing(sensor1); // client.bindThing(sensor2); // Start the client ThreadPool.QueueUserWorkItem(client.startClient); } catch (Exception eStart) { Console.WriteLine("Initial Start Failed : " + eStart.Message); } // Wait for the SteamSensorClient to connect, then process its associated things. // As long as the client has not been shutdown, continue while (!client.isShutdown()) { // Only process the Virtual Things if the client is connected if (client.isConnected()) { ThreadPool.QueueUserWorkItem(client.runClient); } // Suspend processing at the scan rate interval Thread.Sleep(scanRate); } }
/// <summary> /// Add grpc client /// </summary> /// <typeparam name="TService"></typeparam> /// <param name="collection"></param> /// <param name="configurator"></param> /// <param name="setup"></param> /// <returns></returns> internal static IServiceCollection AddGrpcClient(this IServiceCollection collection, ClientConfigurator configurator, Action <ClientConfigurator> setup = null) { // apply configuration setup?.Invoke(configurator); // add client manager collection.AddSingleton(provider => new GrpcClientManager(configurator.ClientConfiguration, provider)); // add services configurator.RegisteredServices.ForEach(svcType => { // get build method var methodBuild = typeof(GrpcClientFactoryUtil). GetMethod(nameof(GrpcClientFactoryUtil.Create), BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(svcType); // add client collection.AddSingleton(svcType, provider => { var invoker = provider.GetServices <GrpcClientManager>().First(m => m.Name == configurator.ClientConfiguration.Name).GetInvoker(); return(methodBuild.Invoke(null, new object[] { invoker, configurator.ClientConfiguration })); }); }); // return return(collection); }
public EmbeddedConfigurator() { client = new ClientConfigurator(); cluster = new ClusterConfigurator(); }