public static void RegisterTypes(this IUnityContainer container, ISdkConfiguration userConfig)
        {
            Guard.Argument(container, nameof(container)).NotNull();
            Guard.Argument(userConfig, nameof(userConfig)).NotNull();

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            RegisterBaseClasses(container, userConfig);

            RegisterRabbitMqTypes(container, userConfig, _environment);

            RegisterTicketSenders(container);

            RegisterMarketDescriptionCache(container, userConfig);

            RegisterSdkStatisticsWriter(container, userConfig);

            RegisterMtsAuthService(container, userConfig);

            RegisterClientApi(container, userConfig);

            RegisterReportManager(container, userConfig);

            RegisterCustomBet(container);
        }
        private static void RegisterReportManager(IUnityContainer container, ISdkConfiguration userConfig)
        {
            container.RegisterType <HttpDataFetcher, HttpDataFetcher>("ReportManager",
                                                                      new ContainerControlledLifetimeManager(),
                                                                      new InjectionConstructor(
                                                                          new ResolvedParameter <HttpClient>(),
                                                                          string.Empty,
                                                                          RestConnectionFailureLimit,
                                                                          RestConnectionFailureTimeoutInSec));

            container.RegisterType <LogHttpDataFetcher, LogHttpDataFetcher>("ReportManager",
                                                                            new ContainerControlledLifetimeManager(),
                                                                            new InjectionConstructor(
                                                                                new ResolvedParameter <HttpClient>(),
                                                                                string.Empty,
                                                                                new ResolvedParameter <ISequenceGenerator>(),
                                                                                RestConnectionFailureLimit,
                                                                                RestConnectionFailureTimeoutInSec));

            var logFetcher = container.Resolve <LogHttpDataFetcher>("ReportManager");

            container.RegisterInstance <IDataFetcher>("ReportManager", logFetcher, new ContainerControlledLifetimeManager());

            container.RegisterType <IReportManager, ReportManager>(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    new ResolvedParameter <IDataFetcher>("ReportManager"),
                    userConfig.MtsClientApiHost + "/ReportingCcf/external/api/report/export/history/ccf/changes/client/api",
                    new ResolvedParameter <IMtsAuthService>(),
                    userConfig
                    ));
        }
        private void InitReportManager(ISdkConfiguration config = null)
        {
            var newConfig = config ?? MtsSdk.CreateConfigurationBuilder()
                            .SetUsername("username")
                            .SetPassword("password")
                            .SetHost("mtsgate-ci.betradar.com")
                            .SetVirtualHost("/vhost")
                            .SetLimitId(111)
                            .SetBookmakerId(333)
                            .SetAccessToken("erErk34kfErr")
                            .SetCurrency("EUR")
                            .SetNode(10)
                            .SetMtsClientApiHost("https://mts-api-ci.betradar.com/edge/proxy")
                            .SetKeycloakHost("https://mts-auth-ci.betradar.com")
                            .SetKeycloakUsername("keycloackUsername")
                            .SetKeycloakPassword("keycloackPassword")
                            .SetKeycloakSecret("53d342-4a7c-dgdbd23-9e1b-93822f2")
                            .Build();

            _mtsAuthService = new MtsAuthServiceHelper(config);

            var uri = new Uri(newConfig.KeycloakHost + "/ReportingCcf/external/api/report/export/history/ccf/changes/client/api");

            _mockDataFetcher = new Mock <DataFetcherHelper>();
            _mockDataFetcher.Setup(p => p.GetDataAsync(It.IsAny <Uri>())).Returns(new DataFetcherHelper(BuilderFactoryHelper.UriReplacements).GetDataAsync(uri));

            _reportManager = new ReportManager(_mockDataFetcher.Object, uri.OriginalString, _mtsAuthService, null, newConfig);
        }
        private static void RegisterMtsAuthService(IUnityContainer container, ISdkConfiguration userConfig)
        {
            container.RegisterType <HttpDataFetcher, HttpDataFetcher>("MtsAuthService",
                                                                      new ContainerControlledLifetimeManager(),
                                                                      new InjectionConstructor(
                                                                          new ResolvedParameter <HttpClient>(),
                                                                          string.Empty,
                                                                          RestConnectionFailureLimit,
                                                                          RestConnectionFailureTimeoutInSec));

            var logDataFetcher = container.Resolve <HttpDataFetcher>("MtsAuthService");
            var logDataPoster  = container.Resolve <HttpDataFetcher>("MtsAuthService");

            container.RegisterInstance <IDataFetcher>("MtsAuthService", logDataFetcher, new ContainerControlledLifetimeManager());
            container.RegisterInstance <IDataPoster>("MtsAuthService", logDataPoster, new ContainerControlledLifetimeManager());

            container.RegisterType <IDeserializer <AccessTokenDTO>, Entities.Internal.JsonDeserializer <AccessTokenDTO> >(new ContainerControlledLifetimeManager());
            container.RegisterType <ISingleTypeMapperFactory <AccessTokenDTO, KeycloakAuthorization>, KeycloakAuthorizationMapperFactory>(new ContainerControlledLifetimeManager());
            container.RegisterType <IDataProvider <KeycloakAuthorization>,
                                    DataProvider <AccessTokenDTO, KeycloakAuthorization> >(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    userConfig.KeycloakHost + "/auth/realms/mts/protocol/openid-connect/token",
                    new ResolvedParameter <IDataFetcher>("MtsAuthService"),
                    new ResolvedParameter <IDataPoster>("MtsAuthService"),
                    new ResolvedParameter <IDeserializer <AccessTokenDTO> >(),
                    new ResolvedParameter <ISingleTypeMapperFactory <AccessTokenDTO, KeycloakAuthorization> >()));

            container.RegisterType <IMtsAuthService, MtsAuthService>(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    new ResolvedParameter <IDataProvider <KeycloakAuthorization> >(),
                    userConfig
                    ));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SdkConfiguration"/> class
        /// </summary>
        public SdkConfigurationInternal(ISdkConfiguration config, IDataFetcher dataFetcher)
            : base(config.Username, config.Password, config.Host, config.VirtualHost, config.UseSsl, config.SslServerName, config.NodeId, config.BookmakerId, config.LimitId, config.Currency, config.Channel, config.AccessToken, config.UfEnvironment, config.ProvideAdditionalMarketSpecifiers, config.Port, config.ExclusiveConsumer)
        {
            Guard.Argument(config, nameof(config)).NotNull();
            ApiHost = null;

            switch (config.UfEnvironment)
            {
            case Entities.Enums.UfEnvironment.Integration:
                ApiHost = SdkInfo.ApiHostIntegration;
                return;

            case Entities.Enums.UfEnvironment.Production:
                ApiHost = SdkInfo.ApiHostProduction;
                return;
            }

            if (dataFetcher == null)
            {
                ApiHost = SdkInfo.ApiHostIntegration;
            }
            else
            {
                try
                {
                    var result = dataFetcher.GetDataAsync(new Uri($"{SdkInfo.ApiHostProduction}/v1/users/whoami.xml")).Result;
                    ApiHost = SdkInfo.ApiHostProduction;
                    result.Close();
                }
                catch (Exception)
                {
                    ApiHost = SdkInfo.ApiHostIntegration;
                }
            }
        }
Example #6
0
 private static void CheckAllSettings(
     ISdkConfiguration config,
     string username       = "******",
     string password       = "******",
     string host           = "host",
     int port              = 5671,
     string virtualHost    = "/username",
     bool useSsl           = true,
     string sslServerName  = null,
     int nodeId            = 1,
     int bookmakerId       = 0,
     int limitId           = 0,
     string currency       = null,
     SenderChannel?channel = null,
     string accessToken    = "",
     bool provideAdditionalMarketSpecifiers = true,
     bool statisticsEnabled                = false,
     int statisticsTimeout                 = 3600,
     int statisticsRecordLimit             = 1000000,
     bool exclusiveConsumer                = true,
     string keycloakHost                   = null,
     string keycloakUsername               = null,
     string keycloakPassword               = null,
     string keycloakSecret                 = null,
     string mtsClientApiHost               = null,
     int ticketResponseTimeoutLive         = SdkInfo.TicketResponseTimeoutLiveDefault,
     int ticketResponseTimeoutPrematch     = SdkInfo.TicketResponseTimeoutPrematchDefault,
     int ticketCancellationResponseTimeout = SdkInfo.TicketCancellationResponseTimeoutDefault,
     int ticketCashoutResponseTimeout      = SdkInfo.TicketCashoutResponseTimeoutDefault,
     int ticketNonSrResponseTimeout        = SdkInfo.TicketNonSrResponseTimeoutDefault)
 {
     Assert.AreEqual(username, config.Username);
     Assert.AreEqual(password, config.Password);
     Assert.AreEqual(host, config.Host);
     Assert.AreEqual(port, config.Port);
     Assert.AreEqual(virtualHost, config.VirtualHost);
     Assert.AreEqual(useSsl, config.UseSsl);
     Assert.AreEqual(sslServerName, config.SslServerName);
     Assert.AreEqual(nodeId, config.NodeId);
     Assert.AreEqual(bookmakerId, config.BookmakerId);
     Assert.AreEqual(limitId, config.LimitId);
     Assert.AreEqual(currency, config.Currency);
     Assert.AreEqual(channel, config.Channel);
     Assert.AreEqual(accessToken, config.AccessToken);
     Assert.AreEqual(provideAdditionalMarketSpecifiers, config.ProvideAdditionalMarketSpecifiers);
     Assert.AreEqual(statisticsEnabled, config.StatisticsEnabled);
     Assert.AreEqual(statisticsTimeout, config.StatisticsTimeout);
     Assert.AreEqual(statisticsRecordLimit, config.StatisticsRecordLimit);
     Assert.AreEqual(exclusiveConsumer, config.ExclusiveConsumer);
     Assert.AreEqual(keycloakHost, config.KeycloakHost);
     Assert.AreEqual(keycloakUsername, config.KeycloakUsername);
     Assert.AreEqual(keycloakPassword, config.KeycloakPassword);
     Assert.AreEqual(keycloakSecret, config.KeycloakSecret);
     Assert.AreEqual(mtsClientApiHost, config.MtsClientApiHost);
     Assert.AreEqual(ticketResponseTimeoutLive, config.TicketResponseTimeoutLive);
     Assert.AreEqual(ticketResponseTimeoutPrematch, config.TicketResponseTimeoutPrematch);
     Assert.AreEqual(ticketCancellationResponseTimeout, config.TicketCancellationResponseTimeout);
     Assert.AreEqual(ticketCashoutResponseTimeout, config.TicketCashoutResponseTimeout);
     Assert.AreEqual(ticketNonSrResponseTimeout, config.TicketNonSrSettleResponseTimeout);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="TicketCancelBuilder"/> class
        /// </summary>
        /// <param name="config">A <see cref="ISdkConfiguration"/> providing configuration for the associated sdk instance</param>
        internal TicketCancelBuilder(ISdkConfiguration config)
        {
            Guard.Argument(config, nameof(config)).NotNull();

            _bookmakerId = config.BookmakerId;
            _percent     = null;
            _betCancels  = null;
        }
        private static void RegisterClientApi(IUnityContainer container, ISdkConfiguration userConfig)
        {
            container.RegisterType <HttpDataFetcher, HttpDataFetcher>("MtsClientApi",
                                                                      new ContainerControlledLifetimeManager(),
                                                                      new InjectionConstructor(
                                                                          new ResolvedParameter <HttpClient>(),
                                                                          string.Empty,
                                                                          RestConnectionFailureLimit,
                                                                          RestConnectionFailureTimeoutInSec));

            container.RegisterType <LogHttpDataFetcher, LogHttpDataFetcher>("MtsClientApi",
                                                                            new ContainerControlledLifetimeManager(),
                                                                            new InjectionConstructor(
                                                                                new ResolvedParameter <HttpClient>(),
                                                                                string.Empty,
                                                                                new ResolvedParameter <ISequenceGenerator>(),
                                                                                RestConnectionFailureLimit,
                                                                                RestConnectionFailureTimeoutInSec));

            var logFetcher = container.Resolve <LogHttpDataFetcher>("MtsClientApi");

            container.RegisterInstance <IDataFetcher>("MtsClientApi", logFetcher, new ContainerControlledLifetimeManager());
            container.RegisterInstance <IDataPoster>("MtsClientApi", logFetcher, new ContainerControlledLifetimeManager());

            container.RegisterType <IDeserializer <MaxStakeResponseDTO>, Entities.Internal.JsonDeserializer <MaxStakeResponseDTO> >(new ContainerControlledLifetimeManager());
            container.RegisterType <ISingleTypeMapperFactory <MaxStakeResponseDTO, MaxStakeImpl>, MaxStakeMapperFactory>(new ContainerControlledLifetimeManager());
            container.RegisterType <IDataProvider <MaxStakeImpl>,
                                    DataProvider <MaxStakeResponseDTO, MaxStakeImpl> >(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    userConfig.MtsClientApiHost + "/ClientApi/api/maxStake/v1",
                    new ResolvedParameter <IDataFetcher>("MtsClientApi"),
                    new ResolvedParameter <IDataPoster>("MtsClientApi"),
                    new ResolvedParameter <IDeserializer <MaxStakeResponseDTO> >(),
                    new ResolvedParameter <ISingleTypeMapperFactory <MaxStakeResponseDTO, MaxStakeImpl> >()));

            container.RegisterType <IDeserializer <CcfResponseDTO>, Entities.Internal.JsonDeserializer <CcfResponseDTO> >(new ContainerControlledLifetimeManager());
            container.RegisterType <ISingleTypeMapperFactory <CcfResponseDTO, CcfImpl>, CcfMapperFactory>(new ContainerControlledLifetimeManager());
            container.RegisterType <IDataProvider <CcfImpl>,
                                    DataProvider <CcfResponseDTO, CcfImpl> >(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    userConfig.MtsClientApiHost + "/ClientApi/api/ccf/v1?sourceId={0}",
                    new ResolvedParameter <IDataFetcher>("MtsClientApi"),
                    new ResolvedParameter <IDataPoster>("MtsClientApi"),
                    new ResolvedParameter <IDeserializer <CcfResponseDTO> >(),
                    new ResolvedParameter <ISingleTypeMapperFactory <CcfResponseDTO, CcfImpl> >()));

            container.RegisterType <IMtsClientApi, MtsClientApi>(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    new ResolvedParameter <IDataProvider <MaxStakeImpl> >(),
                    new ResolvedParameter <IDataProvider <CcfImpl> >(),
                    new ResolvedParameter <IMtsAuthService>(),
                    new ResolvedParameter <IMetricsRoot>()
                    ));
        }
Example #9
0
        /// <summary>
        /// Constructs a new instance of the <see cref="MtsSdk"/> class
        /// </summary>
        /// <param name="config">A <see cref="ISdkConfiguration"/> instance representing feed configuration</param>
        /// <param name="loggerFactory">A <see cref="ILoggerFactory"/> used to create <see cref="ILogger"/> used within sdk</param>
        /// <param name="metricsRoot">A <see cref="IMetricsRoot"/> used to provide metrics within sdk</param>
        public MtsSdk(ISdkConfiguration config, ILoggerFactory loggerFactory = null, IMetricsRoot metricsRoot = null)
        {
            Guard.Argument(config, nameof(config)).NotNull();

            LogInit();

            _isDisposed = false;
            _isOpened   = 0;

            _unityContainer = new UnityContainer();
            _unityContainer.RegisterTypes(config, loggerFactory, metricsRoot);
            _config = _unityContainer.Resolve <ISdkConfigurationInternal>();

            _executionLog   = SdkLoggerFactory.GetLoggerForExecution(typeof(MtsSdk));
            _interactionLog = SdkLoggerFactory.GetLoggerForExecution(typeof(MtsSdk));

            LogInit();

            _metricsRoot          = _unityContainer.Resolve <IMetricsRoot>();
            _metricsLogger        = SdkLoggerFactory.GetLoggerForStats(typeof(MtsSdk));
            _metricsTaskScheduler = new AppMetricsTaskScheduler(
                TimeSpan.FromSeconds(_config.StatisticsTimeout),
                async() => { await LogMetricsAsync(); });


            _connectionValidator = _unityContainer.Resolve <ConnectionValidator>();

            BuilderFactory          = _unityContainer.Resolve <IBuilderFactory>();
            _ticketPublisherFactory = _unityContainer.Resolve <ITicketSenderFactory>();

            _entitiesMapper = _unityContainer.Resolve <EntitiesMapper>();

            _rabbitMqMessageReceiverForTickets           = _unityContainer.Resolve <IRabbitMqMessageReceiver>("TicketResponseMessageReceiver");
            _rabbitMqMessageReceiverForTicketCancels     = _unityContainer.Resolve <IRabbitMqMessageReceiver>("TicketCancelResponseMessageReceiver");
            _rabbitMqMessageReceiverForTicketCashouts    = _unityContainer.Resolve <IRabbitMqMessageReceiver>("TicketCashoutResponseMessageReceiver");
            _rabbitMqMessageReceiverForTicketNonSrSettle = _unityContainer.Resolve <IRabbitMqMessageReceiver>("TicketNonSrSettleResponseMessageReceiver");

            ClientApi        = _unityContainer.Resolve <IMtsClientApi>();
            CustomBetManager = _unityContainer.Resolve <ICustomBetManager>();
            ConnectionStatus = _unityContainer.Resolve <IConnectionStatus>();
            ReportManager    = _unityContainer.Resolve <IReportManager>();

            _autoResetEventsForBlockingRequests        = new ConcurrentDictionary <string, AutoResetEvent>();
            _responsesFromBlockingRequests             = new ConcurrentDictionary <string, ISdkTicket>();
            _ticketsForNonBlockingRequests             = new MemoryCache("TicketsForNonBlockingRequests");
            _lockForTicketsForNonBlockingRequestsCache = new object();

            foreach (var t in Enum.GetValues(typeof(SdkTicketType)))
            {
                var publisher = _ticketPublisherFactory.GetTicketSender((SdkTicketType)t);
                if (publisher != null)
                {
                    publisher.TicketSendFailed += PublisherOnTicketSendFailed;
                }
            }
        }
Example #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SelectionBuilder"/> class
        /// </summary>
        public SelectionBuilder(IMarketDescriptionProvider marketDescriptionProvider, ISdkConfiguration config, bool isCustomBet)
        {
            Guard.Argument(marketDescriptionProvider, nameof(marketDescriptionProvider)).NotNull();
            Guard.Argument(config, nameof(config)).NotNull();

            _marketDescriptionProvider = marketDescriptionProvider;
            _isBanker    = false;
            _config      = config;
            _isCustomBet = isCustomBet;
        }
Example #11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SenderBuilder"/> class
        /// </summary>
        /// <param name="config">The <see cref="ISdkConfiguration"/> providing default builder values</param>
        internal SenderBuilder(ISdkConfiguration config)
        {
            Guard.Argument(config, nameof(config)).NotNull();

            _bookmakerId = config.BookmakerId;
            _limitId     = config.LimitId;
            _currency    = config.Currency;
            if (config.Channel != null)
            {
                _channel = (SenderChannel)config.Channel;
            }
        }
        public static void RegisterTypes(this IUnityContainer container, ISdkConfiguration userConfig, ILoggerFactory loggerFactory, IMetricsRoot metricsRoot)
        {
            Guard.Argument(container, nameof(container)).NotNull();
            Guard.Argument(userConfig, nameof(userConfig)).NotNull();

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            if (loggerFactory != null)
            {
                var _ = new SdkLoggerFactory(loggerFactory);
            }
            _log = SdkLoggerFactory.GetLogger(typeof(SdkUnityBootstrapper));

            if (metricsRoot == null)
            {
                _metricsRoot = new MetricsBuilder()
                               .Configuration.Configure(
                    options =>
                {
                    options.DefaultContextLabel = "UF SDK .NET Core";
                    options.Enabled             = true;
                    options.ReportingEnabled    = true;
                })
                               .OutputMetrics.AsPlainText()
                               .Build();
            }
            else
            {
                _metricsRoot = metricsRoot;
            }
            container.RegisterInstance(_metricsRoot, new ContainerControlledLifetimeManager());

            RegisterBaseClasses(container, userConfig);

            RegisterRabbitMqTypes(container, userConfig, _environment);

            RegisterTicketSenders(container);

            RegisterMarketDescriptionCache(container, userConfig);

            RegisterSdkStatisticsWriter(container);

            RegisterMtsAuthService(container, userConfig);

            RegisterClientApi(container, userConfig);

            RegisterReportManager(container, userConfig);

            RegisterCustomBet(container);
        }
Example #13
0
        public ReportManager(IDataFetcher ccfChangeHistoryFetcher,
                             string ccfChangeHistoryUri,
                             IMtsAuthService mtsAuthService,
                             ISdkConfiguration config)
        {
            Guard.Argument(ccfChangeHistoryFetcher, nameof(ccfChangeHistoryFetcher)).NotNull();
            Guard.Argument(ccfChangeHistoryUri, nameof(ccfChangeHistoryUri)).NotNull().NotEmpty();
            Guard.Argument(config, nameof(config)).NotNull();

            _ccfChangeHistoryFetcher = ccfChangeHistoryFetcher;
            _ccfChangeHistoryUri     = ccfChangeHistoryUri;
            _mtsAuthService          = mtsAuthService;
            _config = config;
        }
Example #14
0
        public MtsAuthService(IDataProvider <KeycloakAuthorization> authorizationDataProvider,
                              ISdkConfiguration config)
        {
            Guard.Argument(authorizationDataProvider, nameof(authorizationDataProvider)).NotNull();
            Guard.Argument(config, nameof(config)).NotNull();

            _authorizationDataProvider = authorizationDataProvider;
            _keycloackUsername         = config.KeycloakUsername;
            _keycloackPassword         = config.KeycloakPassword;
            _keycloackSecret           = config.KeycloakSecret;

            if (string.IsNullOrEmpty(_keycloackSecret))
            {
                ExecutionLog.Debug("No keycloack secret set.");
            }
        }
Example #15
0
        /// <summary>
        /// Constructs a new instance of the <see cref="MtsSdk"/> class
        /// </summary>
        /// <param name="config">A <see cref="ISdkConfiguration"/> instance representing feed configuration</param>
        public MtsSdk(ISdkConfiguration config)
        {
            Guard.Argument(config, nameof(config)).NotNull();

            LogInit();

            _isDisposed = false;
            _isOpened   = 0;

            _unityContainer = new UnityContainer();
            SdkUnityBootstrapper.RegisterTypes(_unityContainer, config);

            _config = _unityContainer.Resolve <ISdkConfigurationInternal>();
            _connectionValidator = _unityContainer.Resolve <ConnectionValidator>();

            BuilderFactory          = _unityContainer.Resolve <IBuilderFactory>();
            _ticketPublisherFactory = _unityContainer.Resolve <ITicketSenderFactory>();

            _entitiesMapper = _unityContainer.Resolve <EntitiesMapper>();

            _rabbitMqMessageReceiverForTickets           = _unityContainer.Resolve <IRabbitMqMessageReceiver>("TicketResponseMessageReceiver");
            _rabbitMqMessageReceiverForTicketCancels     = _unityContainer.Resolve <IRabbitMqMessageReceiver>("TicketCancelResponseMessageReceiver");
            _rabbitMqMessageReceiverForTicketCashouts    = _unityContainer.Resolve <IRabbitMqMessageReceiver>("TicketCashoutResponseMessageReceiver");
            _rabbitMqMessageReceiverForTicketNonSrSettle = _unityContainer.Resolve <IRabbitMqMessageReceiver>("TicketNonSrSettleResponseMessageReceiver");

            ClientApi        = _unityContainer.Resolve <IMtsClientApi>();
            CustomBetManager = _unityContainer.Resolve <ICustomBetManager>();
            ConnectionStatus = _unityContainer.Resolve <IConnectionStatus>();
            ReportManager    = _unityContainer.Resolve <IReportManager>();

            _autoResetEventsForBlockingRequests        = new ConcurrentDictionary <string, AutoResetEvent>();
            _responsesFromBlockingRequests             = new ConcurrentDictionary <string, ISdkTicket>();
            _ticketsForNonBlockingRequests             = new MemoryCache("TicketsForNonBlockingRequests");
            _lockForTicketsForNonBlockingRequestsCache = new object();

            foreach (var t in Enum.GetValues(typeof(SdkTicketType)))
            {
                var publisher = _ticketPublisherFactory.GetTicketSender((SdkTicketType)t);
                if (publisher != null)
                {
                    publisher.TicketSendFailed += PublisherOnTicketSendFailed;
                }
            }
        }
        private static void RegisterSdkStatisticsWriter(IUnityContainer container, ISdkConfiguration config)
        {
            var messageReceivers = container.ResolveAll <IRabbitMqMessageReceiver>();
            var statusProviders  = new List <IHealthStatusProvider>();

            messageReceivers.ForEach(f => statusProviders.Add((IHealthStatusProvider)f));

            container.RegisterType <MetricsReporter, MetricsReporter>(new ContainerControlledLifetimeManager(),
                                                                      new InjectionConstructor(MetricsReportPrintMode.Normal, 2, true));

            var metricReporter = container.Resolve <MetricsReporter>();

            Metric.Config.WithAllCounters().WithReporting(rep => rep.WithReport(metricReporter, TimeSpan.FromSeconds(config.StatisticsTimeout)));

            container.RegisterInstance(metricReporter, new ContainerControlledLifetimeManager());

            foreach (var sp in statusProviders)
            {
                sp.RegisterHealthCheck();
            }
        }
        public MtsAuthServiceHelper(ISdkConfiguration config = null)
        {
            var newConfig = config ?? MtsSdk.CreateConfigurationBuilder()
                            .SetUsername("username")
                            .SetPassword("password")
                            .SetHost("mtsgate-ci.betradar.com")
                            .SetVirtualHost("/vhost")
                            .SetLimitId(111)
                            .SetBookmakerId(333)
                            .SetAccessToken("erErk34kfErr")
                            .SetCurrency("EUR")
                            .SetNode(10)
                            .SetMtsClientApiHost("https://mts-api-ci.betradar.com/edge/proxy")
                            .SetKeycloakHost("https://mts-auth-ci.betradar.com")
                            .SetKeycloakUsername("keycloackUsername")
                            .SetKeycloakPassword("keycloackPassword")
                            .SetKeycloakSecret("53d342-4a7c-dgdbd23-9e1b-93822f2")
                            .Build();

            var uri = new Uri(newConfig.KeycloakHost + "/auth/realms/mts/protocol/openid-connect/token");

            var mockDataFetcher = new Mock <DataFetcherHelper>();

            mockDataFetcher.Setup(p => p.GetDataAsync(It.IsAny <Uri>())).Returns(new DataFetcherHelper(BuilderFactoryHelper.UriReplacements).GetDataAsync(uri));
            mockDataFetcher.Setup(p => p.PostDataAsync(It.IsAny <Uri>(), It.IsAny <HttpContent>())).Returns(new DataFetcherHelper(BuilderFactoryHelper.UriReplacements).PostDataAsync(uri, null));

            var deserializer = new SDK.Entities.Internal.JsonDeserializer <AccessTokenDTO>();
            var mapper       = new KeycloakAuthorizationMapperFactory();

            var dataProvider = new DataProvider <AccessTokenDTO, KeycloakAuthorization>(
                uri.AbsoluteUri,
                mockDataFetcher.Object,
                mockDataFetcher.Object,
                deserializer,
                mapper);

            _mtsAuthService = new MtsAuthService(dataProvider, newConfig);
        }
        internal TicketCancelAckBuilder(ISdkConfiguration config)
        {
            Guard.Argument(config, nameof(config)).NotNull();

            _bookmakerId = config.BookmakerId;
        }
        private static void RegisterRabbitMqTypes(IUnityContainer container, ISdkConfiguration config, string environment)
        {
            container.RegisterType <IRabbitMqChannelSettings, RabbitMqChannelSettings>(new ContainerControlledLifetimeManager());
            container.RegisterInstance <IRabbitMqChannelSettings>("TicketChannelSettings", new RabbitMqChannelSettings(true, config.ExclusiveConsumer, publishQueueTimeoutInMs1: config.TicketResponseTimeoutLive, publishQueueTimeoutInMs2: config.TicketResponseTimeoutPrematch));
            container.RegisterInstance <IRabbitMqChannelSettings>("TicketCancelChannelSettings", new RabbitMqChannelSettings(true, config.ExclusiveConsumer, publishQueueTimeoutInMs1: config.TicketCancellationResponseTimeout, publishQueueTimeoutInMs2: config.TicketCancellationResponseTimeout));
            container.RegisterInstance <IRabbitMqChannelSettings>("TicketCashoutChannelSettings", new RabbitMqChannelSettings(true, config.ExclusiveConsumer, publishQueueTimeoutInMs1: config.TicketCashoutResponseTimeout, publishQueueTimeoutInMs2: config.TicketCashoutResponseTimeout));
            container.RegisterInstance <IRabbitMqChannelSettings>("TicketNonSrSettleChannelSettings", new RabbitMqChannelSettings(true, config.ExclusiveConsumer, publishQueueTimeoutInMs1: config.TicketNonSrSettleResponseTimeout, publishQueueTimeoutInMs2: config.TicketNonSrSettleResponseTimeout));

            var rootExchangeName = config.VirtualHost.Replace("/", string.Empty);

            container.RegisterType <IMtsChannelSettings, MtsChannelSettings>(new ContainerControlledLifetimeManager());
            var mtsTicketChannelSettings              = MtsChannelSettings.GetTicketChannelSettings(rootExchangeName, config.Username, config.NodeId, environment);
            var mtsTicketCancelChannelSettings        = MtsChannelSettings.GetTicketCancelChannelSettings(rootExchangeName, config.Username, config.NodeId, environment);
            var mtsTicketAckChannelSettings           = MtsChannelSettings.GetTicketAckChannelSettings(rootExchangeName, config.Username, config.NodeId, environment);
            var mtsTicketCancelAckChannelSettings     = MtsChannelSettings.GetTicketCancelAckChannelSettings(rootExchangeName, config.Username, config.NodeId, environment);
            var mtsTicketReofferCancelChannelSettings = MtsChannelSettings.GetTicketReofferCancelChannelSettings(rootExchangeName, config.Username, config.NodeId, environment);
            var mtsTicketCashoutChannelSettings       = MtsChannelSettings.GetTicketCashoutChannelSettings(rootExchangeName, config.Username, config.NodeId, environment);
            var mtsTicketNonSrSettleChannelSettings   = MtsChannelSettings.GetTicketNonSrSettleChannelSettings(rootExchangeName, config.Username, config.NodeId, environment);

            var mtsTicketResponseChannelSettings            = MtsChannelSettings.GetTicketResponseChannelSettings(rootExchangeName, config.Username, config.NodeId, environment);
            var mtsTicketCancelResponseChannelSettings      = MtsChannelSettings.GetTicketCancelResponseChannelSettings(rootExchangeName, config.Username, config.NodeId, environment);
            var mtsTicketCashoutResponseChannelSettings     = MtsChannelSettings.GetTicketCashoutResponseChannelSettings(rootExchangeName, config.Username, config.NodeId, environment);
            var mtsTicketNonSrSettleResponseChannelSettings = MtsChannelSettings.GetTicketNonSrSettleResponseChannelSettings(rootExchangeName, config.Username, config.NodeId, environment);

            container.RegisterInstance("TicketChannelSettings", mtsTicketChannelSettings);
            container.RegisterInstance("TicketCancelChannelSettings", mtsTicketCancelChannelSettings);
            container.RegisterInstance("TicketAckChannelSettings", mtsTicketAckChannelSettings);
            container.RegisterInstance("TicketCancelAckChannelSettings", mtsTicketCancelAckChannelSettings);
            container.RegisterInstance("TicketReofferCancelChannelSettings", mtsTicketReofferCancelChannelSettings);
            container.RegisterInstance("TicketCashoutChannelSettings", mtsTicketCashoutChannelSettings);
            container.RegisterInstance("TicketNonSrSettleChannelSettings", mtsTicketNonSrSettleChannelSettings);

            container.RegisterInstance("TicketResponseChannelSettings", mtsTicketResponseChannelSettings);
            container.RegisterInstance("TicketCancelResponseChannelSettings", mtsTicketCancelResponseChannelSettings);
            container.RegisterInstance("TicketCashoutResponseChannelSettings", mtsTicketCashoutResponseChannelSettings);
            container.RegisterInstance("TicketNonSrSettleResponseChannelSettings", mtsTicketNonSrSettleResponseChannelSettings);

            container.RegisterType <IRabbitMqConsumerChannel, RabbitMqConsumerChannel>(new HierarchicalLifetimeManager());
            var ticketResponseConsumerChannel = new RabbitMqConsumerChannel(container.Resolve <IChannelFactory>(),
                                                                            container.Resolve <IMtsChannelSettings>("TicketResponseChannelSettings"),
                                                                            container.Resolve <IRabbitMqChannelSettings>("TicketChannelSettings"));
            var ticketCancelResponseConsumerChannel = new RabbitMqConsumerChannel(container.Resolve <IChannelFactory>(),
                                                                                  container.Resolve <IMtsChannelSettings>("TicketCancelResponseChannelSettings"),
                                                                                  container.Resolve <IRabbitMqChannelSettings>("TicketCancelChannelSettings"));
            var ticketCashoutResponseConsumerChannel = new RabbitMqConsumerChannel(container.Resolve <IChannelFactory>(),
                                                                                   container.Resolve <IMtsChannelSettings>("TicketCashoutResponseChannelSettings"),
                                                                                   container.Resolve <IRabbitMqChannelSettings>("TicketCashoutChannelSettings"));
            var ticketNonSrSettleResponseConsumerChannel = new RabbitMqConsumerChannel(container.Resolve <IChannelFactory>(),
                                                                                       container.Resolve <IMtsChannelSettings>("TicketNonSrSettleResponseChannelSettings"),
                                                                                       container.Resolve <IRabbitMqChannelSettings>("TicketNonSrSettleChannelSettings"));

            container.RegisterInstance <IRabbitMqConsumerChannel>("TicketConsumerChannel", ticketResponseConsumerChannel);
            container.RegisterInstance <IRabbitMqConsumerChannel>("TicketCancelConsumerChannel", ticketCancelResponseConsumerChannel);
            container.RegisterInstance <IRabbitMqConsumerChannel>("TicketCashoutConsumerChannel", ticketCashoutResponseConsumerChannel);
            container.RegisterInstance <IRabbitMqConsumerChannel>("TicketNonSrSettleConsumerChannel", ticketNonSrSettleResponseConsumerChannel);

            container.RegisterType <IRabbitMqMessageReceiver, RabbitMqMessageReceiver>(new HierarchicalLifetimeManager());
            container.RegisterInstance <IRabbitMqMessageReceiver>("TicketResponseMessageReceiver", new RabbitMqMessageReceiver(ticketResponseConsumerChannel, TicketResponseType.Ticket));
            container.RegisterInstance <IRabbitMqMessageReceiver>("TicketCancelResponseMessageReceiver", new RabbitMqMessageReceiver(ticketCancelResponseConsumerChannel, TicketResponseType.TicketCancel));
            container.RegisterInstance <IRabbitMqMessageReceiver>("TicketCashoutResponseMessageReceiver", new RabbitMqMessageReceiver(ticketCashoutResponseConsumerChannel, TicketResponseType.TicketCashout));
            container.RegisterInstance <IRabbitMqMessageReceiver>("TicketNonSrSettleResponseMessageReceiver", new RabbitMqMessageReceiver(ticketNonSrSettleResponseConsumerChannel, TicketResponseType.TicketNonSrSettle));

            container.RegisterType <IRabbitMqPublisherChannel, RabbitMqPublisherChannel>(new HierarchicalLifetimeManager());
            var ticketPublisherChannel = new RabbitMqPublisherChannel(container.Resolve <IChannelFactory>(),
                                                                      mtsTicketChannelSettings,
                                                                      container.Resolve <IRabbitMqChannelSettings>("TicketChannelSettings"),
                                                                      container.Resolve <IConnectionStatus>());
            var ticketAckPublisherChannel = new RabbitMqPublisherChannel(container.Resolve <IChannelFactory>(),
                                                                         mtsTicketAckChannelSettings,
                                                                         container.Resolve <IRabbitMqChannelSettings>("TicketChannelSettings"),
                                                                         container.Resolve <IConnectionStatus>());
            var ticketCancelPublisherChannel = new RabbitMqPublisherChannel(container.Resolve <IChannelFactory>(),
                                                                            mtsTicketCancelChannelSettings,
                                                                            container.Resolve <IRabbitMqChannelSettings>("TicketCancelChannelSettings"),
                                                                            container.Resolve <IConnectionStatus>());
            var ticketCancelAckPublisherChannel = new RabbitMqPublisherChannel(container.Resolve <IChannelFactory>(),
                                                                               mtsTicketCancelAckChannelSettings,
                                                                               container.Resolve <IRabbitMqChannelSettings>("TicketCancelChannelSettings"),
                                                                               container.Resolve <IConnectionStatus>());
            var ticketReofferCancelPublisherChannel = new RabbitMqPublisherChannel(container.Resolve <IChannelFactory>(),
                                                                                   mtsTicketReofferCancelChannelSettings,
                                                                                   container.Resolve <IRabbitMqChannelSettings>("TicketCancelChannelSettings"),
                                                                                   container.Resolve <IConnectionStatus>());
            var ticketCashoutPublisherChannel = new RabbitMqPublisherChannel(container.Resolve <IChannelFactory>(),
                                                                             mtsTicketCashoutChannelSettings,
                                                                             container.Resolve <IRabbitMqChannelSettings>("TicketCashoutChannelSettings"),
                                                                             container.Resolve <IConnectionStatus>());
            var ticketNonSrSettlePublisherChannel = new RabbitMqPublisherChannel(container.Resolve <IChannelFactory>(),
                                                                                 mtsTicketNonSrSettleChannelSettings,
                                                                                 container.Resolve <IRabbitMqChannelSettings>("TicketNonSrSettleChannelSettings"),
                                                                                 container.Resolve <IConnectionStatus>());

            container.RegisterInstance <IRabbitMqPublisherChannel>("TicketPublisherChannel", ticketPublisherChannel);
            container.RegisterInstance <IRabbitMqPublisherChannel>("TicketAckPublisherChannel", ticketAckPublisherChannel);
            container.RegisterInstance <IRabbitMqPublisherChannel>("TicketCancelPublisherChannel", ticketCancelPublisherChannel);
            container.RegisterInstance <IRabbitMqPublisherChannel>("TicketCancelAckPublisherChannel", ticketCancelAckPublisherChannel);
            container.RegisterInstance <IRabbitMqPublisherChannel>("TicketReofferCancelPublisherChannel", ticketReofferCancelPublisherChannel);
            container.RegisterInstance <IRabbitMqPublisherChannel>("TicketCashoutPublisherChannel", ticketCashoutPublisherChannel);
            container.RegisterInstance <IRabbitMqPublisherChannel>("TicketNonSrSettlePublisherChannel", ticketNonSrSettlePublisherChannel);
        }
        private static void RegisterMarketDescriptionCache(IUnityContainer container, ISdkConfiguration config)
        {
            var configInternal = container.Resolve <ISdkConfigurationInternal>();

            // Invariant market description provider
            container.RegisterType <IDeserializer <market_descriptions>, Deserializer <market_descriptions> >(new ContainerControlledLifetimeManager());
            container.RegisterType <ISingleTypeMapperFactory <market_descriptions, IEnumerable <MarketDescriptionDTO> >, MarketDescriptionsMapperFactory>(new ContainerControlledLifetimeManager());
            container.RegisterType <IDataProvider <IEnumerable <MarketDescriptionDTO> >,
                                    DataProvider <market_descriptions, IEnumerable <MarketDescriptionDTO> > >(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    configInternal.ApiHost + "/v1/descriptions/{0}/markets.xml?include_mappings=true",
                    new ResolvedParameter <IDataFetcher>("Base"),
                    new ResolvedParameter <IDataPoster>("Base"),
                    new ResolvedParameter <IDeserializer <market_descriptions> >(),
                    new ResolvedParameter <ISingleTypeMapperFactory <market_descriptions, IEnumerable <MarketDescriptionDTO> > >()));

            // Cache for invariant markets
            container.RegisterInstance(
                "InvariantMarketDescriptionCache_Cache",
                new MemoryCache("invariantMarketsDescriptionsCache"),
                new ContainerControlledLifetimeManager());

            // Timer for invariant markets
            container.RegisterType <ITimer, SdkTimer>(
                "InvariantMarketCacheTimer",
                new HierarchicalLifetimeManager(),
                new InjectionConstructor(
                    TimeSpan.FromSeconds(5),
                    TimeSpan.FromHours(6)));

            // Invariant market cache
            container.RegisterType <IMarketDescriptionCache, MarketDescriptionCache>(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    new ResolvedParameter <MemoryCache>("InvariantMarketDescriptionCache_Cache"),
                    new ResolvedParameter <IDataProvider <IEnumerable <MarketDescriptionDTO> > >(),
                    new List <CultureInfo> {
                DefaultCulture
            },
                    config.AccessToken ?? string.Empty,
                    TimeSpan.FromHours(4),
                    new CacheItemPolicy {
                SlidingExpiration = TimeSpan.FromDays(1)
            }));

            container.RegisterType <IMarketDescriptionProvider, MarketDescriptionProvider>(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    new ResolvedParameter <IMarketDescriptionCache>(),
                    new List <CultureInfo> {
                DefaultCulture
            }));

            container.RegisterType <IBuilderFactory, BuilderFactory>(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    new ResolvedParameter <ISdkConfigurationInternal>(),
                    new ResolvedParameter <IMarketDescriptionProvider>()));
        }
        private static void RegisterBaseClasses(IUnityContainer container, ISdkConfiguration config)
        {
            container.RegisterInstance(config, new ContainerControlledLifetimeManager());

            //register common types
            container.RegisterType <HttpClient, HttpClient>(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor());

            var seed  = (int)DateTime.Now.Ticks;
            var rand  = new Random(seed);
            var value = rand.Next();

            Log.Info($"Initializing sequence generator with MinValue={value}, MaxValue={long.MaxValue}");
            container.RegisterType <ISequenceGenerator, IncrementalSequenceGenerator>(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    (long)value,
                    long.MaxValue));

            container.RegisterType <HttpDataFetcher, HttpDataFetcher>("Base",
                                                                      new ContainerControlledLifetimeManager(),
                                                                      new InjectionConstructor(
                                                                          new ResolvedParameter <HttpClient>(),
                                                                          config.AccessToken ?? string.Empty,
                                                                          RestConnectionFailureLimit,
                                                                          RestConnectionFailureTimeoutInSec));

            container.RegisterType <LogHttpDataFetcher, LogHttpDataFetcher>("Base",
                                                                            new ContainerControlledLifetimeManager(),
                                                                            new InjectionConstructor(
                                                                                new ResolvedParameter <HttpClient>(),
                                                                                config.AccessToken ?? string.Empty,
                                                                                new ResolvedParameter <ISequenceGenerator>(),
                                                                                RestConnectionFailureLimit,
                                                                                RestConnectionFailureTimeoutInSec));

            var logFetcher = container.Resolve <LogHttpDataFetcher>("Base");

            container.RegisterInstance <IDataFetcher>("Base", logFetcher, new ContainerControlledLifetimeManager());
            container.RegisterInstance <IDataPoster>("Base", logFetcher, new ContainerControlledLifetimeManager());

            container.RegisterType <ISdkConfigurationInternal, SdkConfigurationInternal>(new ContainerControlledLifetimeManager());
            var configInternal = new SdkConfigurationInternal(config, logFetcher);

            container.RegisterInstance(configInternal);

            if (configInternal.Host.Contains("mtsgate-t1"))
            {
                _environment = "PROD";
            }
            else if (configInternal.Host.Contains("mtsgate-ci"))
            {
                _environment = "CI";
            }
            else
            {
                _environment = "CUSTOM";
            }

            container.RegisterType <IRabbitServer>(new ContainerControlledLifetimeManager());
            var rabbitServer = new RabbitServer(configInternal);

            container.RegisterInstance <IRabbitServer>(rabbitServer);

            container.RegisterType <ConnectionValidator, ConnectionValidator>(new ContainerControlledLifetimeManager());

            container.RegisterType <IConnectionFactory, ConfiguredConnectionFactory>(new ContainerControlledLifetimeManager());

            container.RegisterType <IChannelFactory, ChannelFactory>(new ContainerControlledLifetimeManager());

            container.RegisterInstance <ISequenceGenerator>(new IncrementalSequenceGenerator(), new ContainerControlledLifetimeManager());

            container.RegisterInstance <IConnectionStatus>(new ConnectionStatus(), new ContainerControlledLifetimeManager());
        }