예제 #1
0
        public ISensorReading GetSensorReading(IClientOptions options)
        {
            var currentSensor = GetSensorByGpio(options.GpioPin);
            var client        = _sensorReadingClientFactory.Create(options, currentSensor.Type);

            return(client.ReadSensor());
        }
예제 #2
0
        private static IMqttClientOptions UnwrapOptions(IClientOptions wrappedOptions, IWillMessage willMessage)
        {
            var optionsBuilder = new MqttClientOptionsBuilder();

            if (wrappedOptions.ConnectionType == ConnectionType.Tcp)
            {
                optionsBuilder.WithTcpServer(wrappedOptions.Uri.Host);
            }
            else
            {
                optionsBuilder.WithWebSocketServer(wrappedOptions.Uri.AbsoluteUri);
            }

            return(optionsBuilder
                   .WithWillMessage(WrapWillMessage(willMessage))
                   .WithCleanSession(wrappedOptions.CleanSession)
                   .WithClientId(wrappedOptions.ClientId ?? Guid.NewGuid().ToString().Replace("-", string.Empty))
                   .WithTls(wrappedOptions.AllowUntrustedCertificates, wrappedOptions.IgnoreCertificateChainErrors,
                            wrappedOptions.IgnoreCertificateChainErrors, UnwrapCertificates(wrappedOptions.Certificates))
                   .WithProtocolVersion(UnwrapProtocolVersion(wrappedOptions.ProtocolVersion))
                   .WithCommunicationTimeout(wrappedOptions.DefaultCommunicationTimeout == default(TimeSpan)
                    ? TimeSpan.FromSeconds(10)
                    : wrappedOptions.DefaultCommunicationTimeout)
                   .WithKeepAlivePeriod(wrappedOptions.KeepAlivePeriod == default(TimeSpan)
                    ? TimeSpan.FromSeconds(5)
                    : wrappedOptions.KeepAlivePeriod)
                   .WithCredentials(wrappedOptions.UserName, wrappedOptions.Password)
                   .Build());
        }
예제 #3
0
파일: Watcher.cs 프로젝트: korch/Messaging
        public Watcher(IClientOptions options)
        {
            _options = options;
            _watcher = new FileSystemWatcher();

            SetupDefaultNotifiedFilters();
        }
예제 #4
0
 public OrderRenewSubscriptionPayedEventHandler(IOrderRepository orderRepository,
                                                ISubscriptionRepository subscriptionRepository,
                                                IRepository <SubscriptionCycle, Guid> subscriptionCycleRepository,
                                                IRepository <SubscriptionCycleOrder, Guid> subscriptionCycleOrderRepository,
                                                IPlanPriceRepository planPriceRepository,
                                                ISubscriptionDomainService subscriptionDomainService,
                                                ISubscriptionCycleDomainService subscriptionCycleDomainService,
                                                IOrderDomainService orderDomainService,
                                                IRepository <Notification, Guid> noticationRepository,
                                                IMapper mapper,
                                                IClientOptions clientOptions,
                                                IHttpClientFactory httpClientFactory,
                                                IBackgroundJobManager backgroundJobManager,
                                                IRepository <Invoice, Guid> invoiceRepository,
                                                IInvoiceDomainService invoiceDomainService,
                                                INotificationDomainService notificationDomainService)
 {
     _orderRepository                  = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
     _subscriptionRepository           = subscriptionRepository ?? throw new ArgumentNullException(nameof(subscriptionRepository));
     _subscriptionCycleRepository      = subscriptionCycleRepository ?? throw new ArgumentNullException(nameof(subscriptionCycleRepository));
     _subscriptionCycleOrderRepository = subscriptionCycleOrderRepository ?? throw new ArgumentNullException(nameof(subscriptionCycleOrderRepository));
     _planPriceRepository              = planPriceRepository ?? throw new ArgumentNullException(nameof(planPriceRepository));
     _subscriptionDomainService        = subscriptionDomainService ?? throw new ArgumentNullException(nameof(subscriptionDomainService));
     _subscriptionCycleDomainService   = subscriptionCycleDomainService ?? throw new ArgumentNullException(nameof(subscriptionCycleDomainService));
     _orderDomainService               = orderDomainService ?? throw new ArgumentNullException(nameof(orderDomainService));
     _notificationDomainService        = notificationDomainService ?? throw new ArgumentNullException(nameof(notificationDomainService));
     _noticationRepository             = noticationRepository ?? throw new ArgumentNullException(nameof(noticationRepository));
     _clientOptions        = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions));
     _httpClient           = httpClientFactory?.CreateClient() ?? throw new ArgumentNullException(nameof(httpClientFactory));
     _backgroundJobManager = backgroundJobManager ?? throw new ArgumentNullException(nameof(backgroundJobManager));
     _invoiceRepository    = invoiceRepository ?? throw new ArgumentNullException(nameof(invoiceRepository));
     _invoiceDomainService = invoiceDomainService ?? throw new ArgumentNullException(nameof(invoiceDomainService));
     _eventBus             = EventBus.Default;
     _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
 }
예제 #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ApiClient"/> class.
        /// </summary>
        protected ApiRest(HttpClient httpClient, IClientOptions options, ILogger <ApiRest> logger, IMemoryCache cache)
        {
            _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
            _logger     = logger ?? throw new ArgumentNullException(nameof(logger));
            _cache      = new CacheManager(cache, logger);
            _policy     = new PolicyManager(options, logger);

            Options = options as ClientOptions;
        }
예제 #6
0
        public WebSocketClient(IClientOptions options = null)
        {
            Options = options ?? new ClientOptions();

            if (Options.ClientType == TwitchLib.Communication.Enums.ClientType.Chat)
            {
                throw new Exception("Use TCP");
            }
        }
예제 #7
0
        public void ShouldRefreshComponentsWithOptions(Boolean regularClientOptions)
        {
            IClientOptions clientOptions = regularClientOptions ? RegularClientOptions : ModeratorClientOptions;

            Sut.Refresh(clientOptions);

            MockedTwitchClientManager.Verify(x => x.TryInitializeTwitchClient(Sut, clientOptions, It.IsAny <LoginCredentials>()), Times.Once());
            MockedTwitchClientManager.Verify(x => x.TryJoinInitialChannels(It.IsAny <IReadOnlyList <JoinedChannel> >()), Times.Once());
        }
예제 #8
0
 public TcpClient(IClientOptions options = null)
 {
     Options     = options ?? new ClientOptions();
     _throttlers =
         new Throttlers(this, Options.ThrottlingPeriod, Options.WhisperThrottlingPeriod)
     {
         TokenSource = _tokenSource
     };
     InitializeClient();
 }
예제 #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PolicyManager"/> class.
        /// </summary>
        /// <param name="options">Options for application configuration.</param>
        /// <param name="logger">Logger for application caching.</param>
        public PolicyManager(IClientOptions options, ILogger logger)
        {
            _logger  = logger ?? throw new ArgumentNullException(nameof(logger));
            _options = options ?? throw new ArgumentNullException(nameof(options));

            // Initialize policies
            InvokePolicy   = CreateInvokePolicy();
            InvokeDownload = CreateDownloadPolicy();
            InvokeUpload   = CreateUploadPolicy();
            InvokeClient   = Policy.NoOpAsync <HttpResponseMessage>(); //CreateRetryPolicy(); //Policy.NoOpAsync<HttpResponseMessage>()
        }
예제 #10
0
        public ISensorReadingClient Create(IClientOptions options, SensorType sensorType)
        {
            if (sensorType == SensorType.Humidity_Temperature)
            {
                return(new HumidityTemperatureClient((SensorReadingByGpioOptions)options));
            }

            if (sensorType == SensorType.Humidity_Temperature_Altitude_Pressure)
            {
                return(new HumidityTemperatureAltitudePressureClient(
                           (SensorReadingByGpioI2COptions)options));
            }

            return(null);
        }
예제 #11
0
        public ITwitchClient CreateClient(IClientOptions options)
        {
            var client = new TwitchClient(
                ClientFactory(options),
                ClientProtocol,
                Logger);

            if (TryInitializeTwitchClient(options))
            {
                return(client);
            }

            // TODO replace
            throw new ApplicationException("Could not initialize client.");
        }
예제 #12
0
        CreateObservableMQTTClient(
            IClientOptions options,
            IWillMessage willMessage = null,
            params ITopicFilter[] topicFilters)
        {
            ClientOptions = options;
            WillMessage   = willMessage;

            _wrappedClient = new MQTTClient(this, topicFilters);

            var observable = Observable.Create <IMQTTMessage>(
                obs =>
            {
                var disposableConnect = _wrappedClient.ObservableConnect
                                        .Subscribe(_ =>
                {
                },
                                                   obs.OnError,
                                                   obs.OnCompleted);

                var disposableMessage = _wrappedClient.ObservableMessage
                                        .Subscribe(
                    obs.OnNext,
                    obs.OnError,
                    obs.OnCompleted);

                var disposableDisconnect = _wrappedClient.ObservableDisconnect
                                           .Where(disconnect => disconnect == true)
                                           .Select(x => Observable.FromAsync(() => _wrappedClient.DisconnectAsync()).Timeout(TimeSpan.FromSeconds(5)))
                                           .Concat()
                                           .Subscribe(d =>
                {
                    Debug.WriteLine("Disconnected");
                    obs.OnCompleted();
                },
                                                      obs.OnError,
                                                      obs.OnCompleted);

                return(new CompositeDisposable(
                           disposableMessage,
                           disposableConnect,
                           disposableDisconnect));
            })
                             .FinallyAsync(async() => { await _wrappedClient?.DisconnectAsync(); })
                             .Publish().RefCount();

            return(observable, _wrappedClient);
        }
예제 #13
0
파일: Bot.cs 프로젝트: EvanQuan/Chubberino
        public LoginCredentials Start(
            IClientOptions clientOptions = null,
            LoginCredentials credentials = null)
        {
            IReadOnlyList <JoinedChannel> previouslyJoinedChannels = TwitchClientManager.Client?.JoinedChannels;

            LoginCredentials = TwitchClientManager.TryInitializeTwitchClient(this, clientOptions, credentials);
            if (LoginCredentials is not null && TwitchClientManager.TryJoinInitialChannels(previouslyJoinedChannels))
            {
                Commands.Configure(LoginCredentials);

                return(LoginCredentials);
            }

            return(null);
        }
예제 #14
0
        public Boolean TryInitializeTwitchClient(IClientOptions clientOptions = null)
        {
            // We need to get all the channel that the old client was connected to,
            // so we can rejoin those channels on the new client.
            //var previouslyJoinedChannels = Client == null
            //    ? Array.Empty<JoinedChannel>()
            //    : Client.JoinedChannels.ToArray();

            if (clientOptions is not null)
            {
                CurrentClientOptions = clientOptions;
            }

            // Try to get new credentials if not provided
            return(CredentialsManager.LoginCredentials.HasValue || CredentialsManager.TryUpdateLoginCredentials(null, out _));
        }
예제 #15
0
파일: Bot.cs 프로젝트: EvanQuan/Chubberino
        public void Refresh(IClientOptions clientOptions = null)
        {
            // TODO: Is this needed if the whole program will restart after?
            LoginCredentials = Start(clientOptions, LoginCredentials);

            Boolean successful = LoginCredentials != null;

            if (successful)
            {
                Writer.WriteLine("Refresh successful");
            }
            else
            {
                Writer.WriteLine("Failed to refresh");
                State = BotState.ShouldStop;
            }
        }
예제 #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Storage"/> class.
        /// </summary>
        protected Storage(HttpClient client, IClientOptions options, ILoggerFactory logger, IMemoryCache cache)
        {
            try
            {
                // Initialize components
                _client = new ApiClient(client, options, logger.CreateLogger <ApiClient>(), cache);
                _logger = logger.CreateLogger <Storage>();
            }
            catch (Exception ex)
            {
                //Log exception error
                _logger.LogError(ex, ex.Message);

                //Continue error
                throw;
            }
        }
        public static Client CreateClient(this IClientOptions options, bool logState = true)
        {
            var client = new Client(options.GatewayUrl, options.ApplicationId, options.UserId, options.DeviceId, null, options.ClientRoles.ToArray(), options.Region)
            {
                UserAlias   = options.UserAlias,
                DeviceAlias = options.DeviceAlias,
                Tag         = options.ClientTag
            };

            if (logState)
            {
                client.OnStateChange += (c) =>
                {
                    Console.Error.WriteLine($"Client '{client.Id}' state is {client.State.ToString().ToLower()}.");
                };
            }

            return(client);
        }
예제 #18
0
 public JobAppService(ISubscriptionRepository subscriptionRepository,
                      ISubscriptionCycleRepository subscriptionCycleRepository,
                      IRepository <SubscriptionCycleOrder, Guid> subscriptionCycleOrderRepository,
                      IRepository <Notification, Guid> notificationRepository,
                      INotificationDomainService notificationDomainService,
                      IPlanPriceRepository planPriceRepository,
                      IOrderRepository orderRepository,
                      IRepository <Invoice, Guid> invoiceRepository,
                      IRepository <InvoicePaymentProvider, Guid> invoicePaymentProviderRepository,
                      IOrderDomainService orderDomainService,
                      ISubscriptionDomainService subscriptionDomainService,
                      ISubscriptionCycleDomainService subscriptionCycleDomainService,
                      ISubscriptionCycleOrderDomainService subscriptionCycleOrderDomainService,
                      IInvoiceDomainService invoiceDomainService,
                      IObjectMapper mapper,
                      IPaypalService paypalService,
                      IMobbexService mobbexService,
                      IClientOptions clientOptions,
                      IHttpClientFactory httpClientFactory)
 {
     _subscriptionRepository           = subscriptionRepository ?? throw new ArgumentNullException(nameof(subscriptionRepository));
     _subscriptionCycleRepository      = subscriptionCycleRepository ?? throw new ArgumentNullException(nameof(subscriptionCycleRepository));
     _subscriptionCycleOrderRepository = subscriptionCycleOrderRepository ?? throw new ArgumentNullException(nameof(subscriptionCycleOrderRepository));
     _noticationRepository             = notificationRepository ?? throw new ArgumentNullException(nameof(notificationRepository));
     _notificationDomainService        = notificationDomainService ?? throw new ArgumentNullException(nameof(notificationDomainService));
     _planPriceRepository = planPriceRepository ?? throw new ArgumentNullException(nameof(planPriceRepository));
     _orderRepository     = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
     _invoiceRepository   = invoiceRepository ?? throw new ArgumentNullException(nameof(invoiceRepository));
     _invoicePaymentProviderRepository = invoicePaymentProviderRepository ?? throw new ArgumentNullException(nameof(invoicePaymentProviderRepository));
     _orderDomainService                  = orderDomainService ?? throw new ArgumentNullException(nameof(orderDomainService));
     _subscriptionDomainService           = subscriptionDomainService ?? throw new ArgumentNullException(nameof(subscriptionDomainService));
     _subscriptionCycleDomainService      = subscriptionCycleDomainService ?? throw new ArgumentNullException(nameof(subscriptionCycleDomainService));
     _subscriptionCycleOrderDomainService = subscriptionCycleOrderDomainService ?? throw new ArgumentNullException(nameof(subscriptionCycleOrderDomainService));
     _invoiceDomainService                = invoiceDomainService ?? throw new ArgumentNullException(nameof(invoiceDomainService));
     _mapper        = mapper ?? throw new ArgumentNullException(nameof(mapper));
     _paypalService = paypalService ?? throw new ArgumentNullException(nameof(paypalService));
     _mobbexService = mobbexService ?? throw new ArgumentNullException(nameof(mobbexService));
     _clientOptions = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions));
     _httpClient    = httpClientFactory?.CreateClient() ?? throw new ArgumentNullException(nameof(httpClientFactory));
 }
예제 #19
0
        public void ConfigureClient()
        {
            // arrange
            // act
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddOperationClientOptions("foo")
            .AddHttpOperationPipeline(builder => builder.UseHttpDefaultPipeline())
            .AddOperationFormatter(s => new JsonOperationFormatter(s))
            .AddResultParser(s => new DummyResultParser())
            .AddValueSerializer(() => new DummyValueSerializer());

            // assert
            IServiceProvider services      = serviceCollection.BuildServiceProvider();
            IClientOptions   clientOptions = services.GetRequiredService <IClientOptions>();

            Assert.IsType <JsonOperationFormatter>(
                clientOptions.GetOperationFormatter("foo"));
            Assert.IsType <DummyResultParser>(
                clientOptions.GetResultParsers("foo").Get(typeof(string)));
            Assert.IsType <DummyValueSerializer>(
                clientOptions.GetValueSerializers("foo").Get("Dummy"));
        }
예제 #20
0
        public WebSocketClient(IClientOptions options = null)
        {
            Options = options ?? new ClientOptions();

            switch (Options.ClientType)
            {
            case ClientType.Chat:
                Url = Options.UseSsl ? "wss://irc-ws.chat.twitch.tv:443" : "ws://irc-ws.chat.twitch.tv:80";
                break;

            case ClientType.PubSub:
                Url = Options.UseSsl ? "wss://pubsub-edge.twitch.tv:443" : "ws://pubsub-edge.twitch.tv:80";
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            _throttlers = new Throttlers(this, Options.ThrottlingPeriod, Options.WhisperThrottlingPeriod)
            {
                TokenSource = _tokenSource
            };
        }
예제 #21
0
        public LoginCredentials TryInitializeTwitchClient(
            IBot bot,
            IClientOptions clientOptions = null,
            LoginCredentials credentials = null)
        {
            // We need to get all the channel that the old client was connected to,
            // so we can rejoin those channels on the new client.
            //var previouslyJoinedChannels = Client == null
            //    ? Array.Empty<JoinedChannel>()
            //    : Client.JoinedChannels.ToArray();

            if (clientOptions is not null)
            {
                CurrentClientOptions = clientOptions;
            }

            if (!CredentialsManager.TryUpdateLoginCredentials(credentials, out credentials))
            {
                Writer.WriteLine("Failed to update login credentials");
                return(null);
            }

            ConnectionCredentials = credentials.ConnectionCredentials;
            bot.LoginCredentials  = credentials;
            Name  = Name.From(credentials.ConnectionCredentials.TwitchUsername);
            IsBot = credentials.IsBot;

            if (PrimaryChannelName is null)
            {
                PrimaryChannelName = CredentialsManager.ApplicationCredentials.InitialTwitchPrimaryChannelName;
            }

            RefreshTwitchClient(bot);

            return(credentials);
        }
예제 #22
0
 public MultipleMessageSender(IMessageCreator messageCreator, IClientOptions options)
 {
     _messageCreator = messageCreator;
     _options        = options;
 }
        /// <summary>
        /// Adds the Backblaze client agent services to the collection.
        /// </summary>
        /// <param name="services">The service collection.</param>
        /// <param name="options">The agent options.</param>
        public static IBackblazeAgentBuilder AddBackblazeAgent(this IServiceCollection services, IClientOptions options)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            options.Validate();
            services.AddSingleton(options);

            services.AddTransient <UserAgentHandler>();
            services.AddTransient <HttpErrorHandler>();
            services.AddHttpClient <IApiClient, ApiClient>(client =>
            {
                client.Timeout = TimeSpan.FromSeconds(options.Timeout);
            })
            .AddHttpMessageHandler <UserAgentHandler>()
            .AddHttpMessageHandler <HttpErrorHandler>()
            .SetHandlerLifetime(TimeSpan.FromSeconds(options.HandlerLifetime));

            services.AddSingleton <IStorageClient, StorageService>();

            return(new BackblazeAgentBuilder(services));
        }
예제 #24
0
 public static async Task Register(this Client client, IClientOptions options)
 {
     await client.Register(Token.GenerateClientRegisterToken(client, new ChannelClaim[0], options.SharedSecret, options.Region)).AsTask().ConfigureAwait(false);
 }
예제 #25
0
 public InvoiceWebhookController(IInvoiceWebhookAppService invoiceWebhookAppService, IClientOptions clientOptions)
 {
     _invoiceWebhookAppService = invoiceWebhookAppService ?? throw new ArgumentNullException(nameof(invoiceWebhookAppService));
     _clientOptions            = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions));
 }
예제 #26
0
 public ProcessingManager(IClientOptions options, IMessageSenderFactory messageSenderFactory, IMessageCreator messageCreator)
 {
     _options = options;
     _messageSenderFactory = messageSenderFactory;
     _messageCreator       = messageCreator;
 }
예제 #27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ApiClient"/> class.
 /// </summary>
 public ApiClient(HttpClient httpClient, IClientOptions options, ILogger <ApiRest> logger, IMemoryCache cache)
     : base(httpClient, options, logger, cache)
 {
 }
예제 #28
0
 public FDGTClient(IClientOptions options = null) : base(options)
 {
     Url = "wss://irc.fdgt.dev:443";
 }
예제 #29
0
        public IMessageSender GetMessageSender(MessageType type, IMessageCreator messageCreator, IClientOptions options)
        {
            switch (type)
            {
            case MessageType.Single:
                return(new SingleMessageSender(messageCreator, options));

            case MessageType.Multiple:
                return(new MultipleMessageSender(messageCreator, options));

            default:
                return(new SingleMessageSender(messageCreator, options));
            }
        }
예제 #30
0
 /// <summary>
 /// Initializes an instance of the <see cref="HttpErrorHandler"/> class.
 /// </summary>
 /// <param name="options"></param>
 /// <param name="logger">Logger for transient error handler.</param>
 public HttpErrorHandler(IClientOptions options, ILogger <StorageService> logger)
 {
     _policy = PolicyManager.CreateRetryPolicy(options.RetryCount, logger);
 }