public IBinaryConnection Create(BinaryConnectionConfig config, IMessageValidator validator)
        {
            IBinaryConnection connection = null;

            if (config is TcpClientConfig)
            {
                connection = new TcpClientConnection(validator)
                {
                    Logger = _logger
                }
            }
            ;

            if (config is TcpListenerConfig)
            {
                connection = new TcpListenerConnection(validator)
                {
                    Logger = _logger
                }
            }
            ;

            connection?.Initialize(config);

            return(connection);
        }
Beispiel #2
0
 public HomeController(IMessageEncryptor encryptor, IMessageRepository repository,
                       IMessageValidator validator, IMessageMapper mapper)
 {
     this.encryptor  = encryptor;
     this.repository = repository;
     this.validator  = validator;
     this.mapper     = mapper;
 }
 public MessageProcessor(IMessageValidator validator, IMessageMapper mapper, IIdDeDuplicator idDeDuplicator,
                         MessageProcessorOptions options)
 {
     this.mapper         = mapper;
     this.idDeDuplicator = idDeDuplicator;
     this.options        = options;
     this.validator      = validator;
 }
Beispiel #4
0
        public ItemOutValidator(IMessageValidator <ItemAsset> itemValidator)
        {
            this.itemValidator = itemValidator ?? throw new ArgumentNullException(nameof(itemValidator));

            // Define the validation rules.

            this.RuleFor(message => message.Assets)
            .Cascade(CascadeMode.StopOnFirstFailure)
            .NotNull().WithErrorCode(ErrorCode.ValueIsRequired)
            .Must(item => item.Count <= ItemOutValidator.MaxitemItemCount).WithErrorCode(ErrorCode.SetCountIsInvalid)
            .SetCollectionValidator((FluentValidation.IValidator <ItemAsset>)itemValidator);
        }
Beispiel #5
0
 /// <summary>
 /// Creates a message handler
 /// </summary>
 /// <param name="channel"> name of a channel from that a message is received and processed</param>
 /// <param name="messageValidator">validator checking each message received whether it is out of order based on its sequence number</param>
 /// <param name="messageLoader">provides capability to directly get messages stored in Redis server</param>
 /// <param name="messageHandler">a handler responsible for processing a message received</param>
 /// <param name="log">logger tracing internal activity of this subscriber</param>
 public MessageProcessor(
     string channel,
     IMessageValidator messageValidator,
     IMessageLoader messageLoader,
     IMessageHandler messageHandler,
     ILogger <MessageProcessor> log = default)
 {
     Channel           = channel;
     _messageValidator = messageValidator;
     _messageLoader    = messageLoader;
     _messageHandler   = messageHandler;
     _log = log ?? NullLogger <MessageProcessor> .Instance;
 }
        /// <summary>
        ///     The class initialize.
        /// </summary>
        protected static void ClassInitialize()
        {
            //EffortProviderConfiguration.RegisterProvider();
            var containerBuilder   = new DependencyContainerBuilder(new HostUnityContainer());
            var container          = containerBuilder.BuildUnityContainer();
            var dependencyResolver = container.Resolve(typeof(IDependencyResolver), string.Empty) as IDependencyResolver;

            //DbInitializer dbInitializer = dependencyResolver.Resolve(typeof(DbInitializer)) as DbInitializer;

            //Database.SetInitializer(dbInitializer);

            MessageValidator = dependencyResolver.Resolve <IMessageValidator>();
        }
Beispiel #7
0
 /// <summary>
 /// Creates a QbManager. The main program which handles all the WebConnector interations.
 /// </summary>
 /// <param name="authenticator">An authenticator.</param>
 /// <param name="messageValidator">A message validator.</param>
 /// <param name="webConnectorHandler">A WebConnectorHandler.</param>
 /// <param name="stepRequest">A list of step requests.</param>
 /// <param name="stepResponse">A list of step responses.</param>
 /// <param name="logger">Logger.</param>
 public QbManager(
     IAuthenticator authenticator,
     IMessageValidator messageValidator,
     IWebConnectorHandler webConnectorHandler,
     IEnumerable <IStepQueryRequest> stepRequest,
     IEnumerable <IStepQueryResponse> stepResponse,
     ILogger <QbManager> logger
     )
 {
     this.authenticator       = authenticator;
     this.messageValidator    = messageValidator;
     this.webConnectorHandler = webConnectorHandler;
     this.stepRequest         = stepRequest;
     this.stepResponse        = stepResponse;
     this.logger = logger;
 }
Beispiel #8
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="OrderFulfillmentMessageValidator" /> class.
        /// </summary>
        ///
        /// <param name="headerValidator">The validator to use for validaiton of the order header.</param>
        /// <param name="itemOutValidator">The validator to use for valdiation of the item items assocaited with the order.</param>
        ///
        public OrderFulfillmentMessageValidator(IMessageValidator <OrderHeader> headerValidator,
                                                IMessageValidator <LineItem> itemOutValidator)
        {
            // Initialize the class.

            this.headerValidator  = headerValidator ?? throw new ArgumentNullException(nameof(headerValidator));
            this.itemOutValidator = itemOutValidator ?? throw new ArgumentNullException(nameof(itemOutValidator));

            // Define the validation rules.

            this.RuleFor(message => message.OrderRequestHeader)
            .Cascade(CascadeMode.StopOnFirstFailure)
            .NotEmpty().WithErrorCode(ErrorCode.ValueIsRequired)
            .SetValidator((FluentValidation.IValidator <OrderHeader>) this.headerValidator);

            this.RuleFor(message => message.LineItems)
            .Cascade(CascadeMode.StopOnFirstFailure)
            .NotNull().WithErrorCode(ErrorCode.ValueIsRequired)
            .SetCollectionValidator((FluentValidation.IValidator <LineItem>)itemOutValidator);
        }
        /// <summary>
        /// The on action executing.
        /// </summary>
        /// <param name="actionContext">
        /// The action context.
        /// </param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            this.MessageValidator   = (IMessageValidator)actionContext.Request.GetDependencyScope().GetService(typeof(IMessageValidator));
            this.Logger             = (ILogger)actionContext.Request.GetDependencyScope().GetService(typeof(ILogger));
            this.DependencyResolver =
                (IDependencyResolver)actionContext.Request.GetDependencyScope().GetService(typeof(IDependencyResolver));

            this.Logger.Debug(() => "ValidateFilterAttribute.OnActionExecuting");

            var validationInstance = actionContext.ActionArguments.Values.FirstOrDefault();

            if (validationInstance == null)
            {
                var errors = new List <ExceptionMessage>();
                errors.Add(new ExceptionMessage(BaseErrorCodes.CommandValidation, "Command should not be null."));
                throw this.DependencyResolver.Resolve <ValidationException>()
                      .GetException(errors, isTopAsRoot: true);
            }

            var validationNotification = this.MessageValidator.Validate(validationInstance);

            if (!actionContext.ModelState.IsValid || !validationNotification.IsValid)
            {
                throw this.DependencyResolver.Resolve <ValidationException>()
                      .GetException(
                          this.BuildNestedMessages(validationNotification.Errors),
                          "Validation failed",
                          BaseErrorCodes.CommandValidation);

                //ObjectContent<List<ValidationResult>> content = new ObjectContent<List<ValidationResult>>(validationNotification.Errors, new JsonMediaTypeFormatter());
                //var resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
                //{
                //    Content = content,
                //    ReasonPhrase = "Validation failed",
                //    RequestMessage = actionContext.Request
                //};
                //actionContext.Response = resp;
            }
        }
Beispiel #10
0
 /// <summary>
 /// Create a new instance of the
 /// </summary>
 /// <param name="validator"></param>
 public TcpClientConnection(IMessageValidator validator)
 {
     _validator = validator;
 }
Beispiel #11
0
 public SendingControl()
 {
     _validator = new MessageValidator();
 }
Beispiel #12
0
        /// <summary>
        /// Добавляет еще одного обработчика сообщений.
        /// </summary>
        /// <param name="label">
        /// Метка сообщения, которое может быть обработано.
        /// </param>
        /// <param name="consumer">
        /// Обработчик сообщения.
        /// </param>
        /// <param name="validator">
        /// Механизм проверки входящего сообщения.
        /// </param>
        /// <typeparam name="T">
        /// Тип входящего сообщения.
        /// </typeparam>
        public void RegisterConsumer <T>(MessageLabel label, IConsumerOf <T> consumer, IMessageValidator validator) where T : class
        {
            ConsumingAction consumingAction = delivery =>
            {
                IConsumingContext <T> context = delivery.BuildConsumingContext <T>(label);

                if (validator != null)
                {
                    validator.Validate(context.Message).ThrowIfBroken();
                }
                else
                {
                    this.validatorRegistry.Validate(context.Message);
                }

                var sw = Stopwatch.StartNew();

                consumer.Handle(context);

                this.MetricsCollector?.Histogram("contour.rmq.consuming.duration", sw.ElapsedMilliseconds, 1D, new[] { "endpoint:" + this.busContext.Endpoint.Address, "label:" + label.ToString() });
            };

            this.consumers[label] = consumingAction;
        }
Beispiel #13
0
 /// <summary>
 /// The register validator.
 /// </summary>
 /// <param name="validator">
 /// The validator.
 /// </param>
 public void RegisterValidator(IMessageValidator validator)
 {
     this.ValidatorRegistry.Register(validator);
 }
 /// <summary>
 /// Create listener connection
 /// </summary>
 /// <param name="validator">Validator for this listener</param>
 public TcpListenerConnection(IMessageValidator validator)
 {
     Validator = validator;
 }
Beispiel #15
0
 /// <summary>
 /// Constructor taking the object to use as interface to an outbound
 /// message queue
 /// </summary>
 /// <param name="queue">The outbound message queue</param>
 /// <param name="validator">The object that knows how to validate
 /// incoming messages</param>
 public OutputQueueFecsAdapter(FecsBecsOutputWrapper queue, IMessageValidator validator)
 {
     _outQueue  = queue;
     _validator = validator;
 }
Beispiel #16
0
        /// <summary>
        /// Регистрирует механизм проверки входящего сообщения.
        /// </summary>
        /// <param name="validator">Механизм проверки входящего сообщения.</param>
        /// <returns>Конфигуратор получателя с установленным механизмом проверки входящих сообщений.</returns>
        public IReceiverConfigurator WhenVerifiedBy(IMessageValidator validator)
        {
            this.Validator = validator;

            return(this);
        }
Beispiel #17
0
 public MimeMessageConverter(IOptions <AppConfig> config, IMessageValidator messageValidator, ILogger <MimeMessageConverter> logger)
 {
     this.config           = config;
     this.messageValidator = messageValidator;
     this.logger           = logger;
 }
Beispiel #18
0
        /// <summary>
        /// Добавляет еще одного обработчика сообщений.
        /// </summary>
        /// <param name="label">
        /// Метка сообщения, которое может быть обработано.
        /// </param>
        /// <param name="consumer">
        /// Обработчик сообщения.
        /// </param>
        /// <param name="validator">
        /// Механизм проверки входящего сообщения.
        /// </param>
        /// <typeparam name="T">
        /// Тип входящего сообщения.
        /// </typeparam>
        public void RegisterConsumer <T>(MessageLabel label, IConsumerOf <T> consumer, IMessageValidator validator) where T : class
        {
            ConsumingAction consumingAction = delivery =>
            {
                IConsumingContext <T> context = delivery.BuildConsumingContext <T>(label);

                if (validator != null)
                {
                    validator.Validate(context.Message).ThrowIfBroken();
                }
                else
                {
                    this.validatorRegistry.Validate(context.Message);
                }

                consumer.Handle(context);
            };

            this.consumers[label] = consumingAction;
        }
Beispiel #19
0
        /// <summary>
        /// Добавляет еще одного обработчика сообщений.
        /// </summary>
        /// <param name="label">
        /// Метка сообщения, которое может быть обработано.
        /// </param>
        /// <param name="consumer">
        /// Обработчик сообщения.
        /// </param>
        /// <param name="validator">
        /// Механизм проверки входящего сообщения.
        /// </param>
        /// <typeparam name="T">
        /// Тип входящего сообщения.
        /// </typeparam>
        public void RegisterConsumer <T>(MessageLabel label, IConsumerOf <T> consumer, IMessageValidator validator) where T : class
        {
            ConsumingAction consumingAction = delivery =>
            {
                IConsumingContext <T> context = delivery.BuildConsumingContext <T>(label);

                if (validator != null)
                {
                    validator.Validate(context.Message).ThrowIfBroken();
                }
                else
                {
                    this.validatorRegistry.Validate(context.Message);
                }

                this.logger.Trace(
                    m => m($"{typeof(T)}: получил сообщение " +
                           $"[{JsonConvert.SerializeObject(context.Message.Payload)}] на обработку"));

                consumer.Handle(context);
            };

            this.consumers[label] = consumingAction;
        }
Beispiel #20
0
 public MessageStore(IMessageValidator messageValidator, ApplicationDatabase applicationDatabase)
 {
     _messageValidator    = messageValidator;
     _applicationDatabase = applicationDatabase;
 }
 /// <summary>
 /// Create connection instance
 /// </summary>
 public SerialBinaryConnection(IMessageValidator validator)
 {
     _validator = validator;
 }
        /// <summary>
        /// Creates and starts a listener on the server. There has to be one listener for each clients that shall connect.
        /// </summary>
        /// <param name="ipAdress">The ip adress.</param>
        /// <param name="port">The port.</param>
        /// <param name="id">The identifier. This identifier has to be matched be the client that connects to this listener. The listener will be determined, when the first message is received</param>
        /// <param name="messageValidator">The message validator to be used</param>
        protected ConnectionBuffer <TMessage> CreateAndStartServer(IPAddress ipAdress, int port, int id, IMessageValidator messageValidator)
        {
            var server = new ConnectionBuffer <TMessage>
            {
                Id         = id,
                Connection = _binaryConnectionFactory.Create(CreateServerConfig(ipAdress, port), messageValidator)
            };

            server.Connection.Received += (sender, message) => server.Received.Add((TMessage)message);
            server.Connection.NotifyConnectionState += (sender, message) => server.LastStateChangeEvents.Add(message);

            // Server should be disconnected
            Assert.AreEqual(server.Connection.CurrentState, BinaryConnectionState.Disconnected,
                            $"server is not in the state '{BinaryConnectionState.Disconnected:G}'. CurrentState: {server.Connection.CurrentState:G}");

            server.Connection.Start();

            // Server should be listening
            Assert.AreEqual(BinaryConnectionState.AttemptingConnection, server.Connection.CurrentState,
                            $"server is not in the state '{BinaryConnectionState.AttemptingConnection:G}'. CurrentState: {server.Connection.CurrentState:G}");

            _serverConnections.Add(server);

            return(server);
        }
        /// <summary>
        /// Конфигурирует клиента шины сообщений.
        /// </summary>
        /// <param name="endpointName">
        /// Имя точки подключения к шине.
        /// </param>
        /// <param name="cfg">
        /// Конфигуратор клиента шины.
        /// </param>
        /// <returns>
        /// Конфигуратор клиента шины, после применения к нему всех настроек.
        /// </returns>
        public IBusConfigurator Configure(string endpointName, IBusConfigurator cfg)
        {
            if (cfg == null)
            {
                throw new ArgumentNullException("cfg", "Файл конфигурации не может быть null");
            }

            var endpointConfig = this.GetEndPointByName(endpointName);

            IConnectionStringProvider connectionStringProvider = null;

            if (!string.IsNullOrEmpty(endpointConfig.ConnectionStringProvider))
            {
                connectionStringProvider = this.GetConnectionStringProvider(endpointConfig.ConnectionStringProvider);
            }

            cfg.SetEndpoint(endpointConfig.Name);
            cfg.SetConnectionString(endpointConfig.ConnectionString);
            cfg.SetExcludedIncomingHeaders(endpointConfig.ExcludedHeaders);

            if (endpointConfig.ReuseConnection.HasValue)
            {
                cfg.ReuseConnection(endpointConfig.ReuseConnection.Value);
            }

            if (!string.IsNullOrWhiteSpace(endpointConfig.LifecycleHandler))
            {
                cfg.HandleLifecycleWith(this.ResolveLifecycleHandler(endpointConfig.LifecycleHandler));
            }

            if (endpointConfig.ParallelismLevel.HasValue)
            {
                cfg.UseParallelismLevel(endpointConfig.ParallelismLevel.Value);
            }

            if (endpointConfig.FaultQueueTtl.HasValue)
            {
                cfg.UseFaultQueueTtl(endpointConfig.FaultQueueTtl.Value);
            }

            if (endpointConfig.FaultQueueLimit.HasValue)
            {
                cfg.UseFaultQueueLimit(endpointConfig.FaultQueueLimit.Value);
            }

            if (endpointConfig.Dynamic != null)
            {
                if (endpointConfig.Dynamic.Outgoing.HasValue)
                {
                    if (endpointConfig.Dynamic.Outgoing.Value)
                    {
                        cfg.Route(MessageLabel.Any)
                        .ConfiguredWith(
                            builder => new LambdaRouteResolver(
                                (endpoint, label) =>
                        {
                            builder.Topology.Declare(Exchange.Named(label.Name).Durable.Fanout);
                            return(new RabbitRoute(label.Name));
                        }));
                    }
                }
            }

            if (endpointConfig.Qos != null)
            {
                if (endpointConfig.Qos.PrefetchCount.HasValue)
                {
                    cfg.SetDefaultQoS(endpointConfig.Qos.PrefetchCount.Value);
                }
            }

            foreach (ValidatorElement validator in endpointConfig.Validators)
            {
                if (validator.Group)
                {
                    MessageValidatorGroup v = this.ResolveValidatorGroup(validator.Name);
                    cfg.RegisterValidators(v);
                }
                else
                {
                    IMessageValidator v = this.ResolveValidator(validator.Name);
                    cfg.RegisterValidator(v);
                }
            }

            foreach (OutgoingElement outgoingElement in endpointConfig.Outgoing)
            {
                var configurator = cfg.Route(outgoingElement.Label).WithAlias(outgoingElement.Key);

                if (outgoingElement.Confirm)
                {
                    configurator.WithConfirmation();
                }

                if (outgoingElement.Persist)
                {
                    configurator.Persistently();
                }

                if (outgoingElement.Ttl.HasValue)
                {
                    configurator.WithTtl(outgoingElement.Ttl.Value);
                }

                if (outgoingElement.CallbackEndpoint.Default)
                {
                    configurator.WithDefaultCallbackEndpoint();
                }

                if (outgoingElement.Timeout.HasValue)
                {
                    configurator.WithRequestTimeout(outgoingElement.Timeout);
                }

                if (outgoingElement.Delayed || outgoingElement.Delay.HasValue || endpointConfig.Delayed)
                {
                    configurator.WithDelay(outgoingElement.Delay ?? TimeSpan.Zero);
                }

                // Connection string
                var connectionString = endpointConfig.ConnectionString;
                if (!string.IsNullOrEmpty(outgoingElement.ConnectionString))
                {
                    connectionString = outgoingElement.ConnectionString;
                }

                connectionString = connectionStringProvider?.GetConnectionString(outgoingElement.Label.ToMessageLabel()) ?? connectionString;


                configurator.WithConnectionString(connectionString);

                // Reuse connection
                if (outgoingElement.ReuseConnection.HasValue)
                {
                    configurator.ReuseConnection(outgoingElement.ReuseConnection.Value);
                }
            }

            foreach (IncomingElement incomingElement in endpointConfig.Incoming)
            {
                var configurator = cfg.On(incomingElement.Label).WithAlias(incomingElement.Key);

                uint   size  = 0;
                ushort count = 50;

                // This should be the default values provided by RabbitMQ configurator (BusConsumerConfigurationEx);
                var qos = configurator.GetQoS();
                if (qos.HasValue)
                {
                    size  = qos.Value.PrefetchSize;
                    count = qos.Value.PrefetchCount;
                }

                // Prefetch size
                if (endpointConfig.Qos.PrefetchSize.HasValue)
                {
                    size = endpointConfig.Qos.PrefetchSize.Value;
                }

                if (incomingElement.Qos.PrefetchSize.HasValue)
                {
                    size = incomingElement.Qos.PrefetchSize.Value;
                }

                // Prefetch count
                if (endpointConfig.Qos.PrefetchCount.HasValue)
                {
                    count = endpointConfig.Qos.PrefetchCount.Value;
                }

                if (incomingElement.Qos.PrefetchCount.HasValue)
                {
                    count = incomingElement.Qos.PrefetchCount.Value;
                }

                configurator.WithQoS(new QoSParams(count, size));

                // Parallelism level
                if (endpointConfig.ParallelismLevel.HasValue)
                {
                    configurator.WithParallelismLevel(endpointConfig.ParallelismLevel.Value);
                }

                if (incomingElement.ParallelismLevel.HasValue)
                {
                    configurator.WithParallelismLevel(incomingElement.ParallelismLevel.Value);
                }

                // Accept
                if (incomingElement.RequiresAccept)
                {
                    configurator.RequiresAccept();
                }

                if (incomingElement.Delayed)
                {
                    configurator.Delayed();
                }

                // Connection string
                var connectionString = endpointConfig.ConnectionString;
                if (!string.IsNullOrEmpty(incomingElement.ConnectionString))
                {
                    connectionString = incomingElement.ConnectionString;
                }
                connectionString = connectionStringProvider?.GetConnectionString(incomingElement.Label.ToMessageLabel()) ?? connectionString;


                configurator.WithConnectionString(connectionString);

                // Reuse connection
                if (incomingElement.ReuseConnection.HasValue)
                {
                    configurator.ReuseConnection(incomingElement.ReuseConnection.Value);
                }

                Type messageType = typeof(ExpandoObject);
                if (!string.IsNullOrWhiteSpace(incomingElement.Type))
                {
                    messageType = ResolveType(incomingElement.Type);
                }

                var consumerFactory = this.BuildConsumerFactory(incomingElement, messageType, endpointName);

                object consumer = BuildConsumer(consumerFactory, messageType, incomingElement.Lifestyle);

                RegisterConsumer(configurator, messageType, consumer);

                if (!string.IsNullOrWhiteSpace(incomingElement.Validate))
                {
                    IMessageValidator validator = this.ResolveValidator(incomingElement.Validate, messageType);

                    configurator.WhenVerifiedBy(validator);
                }
            }

            var collectorType = endpointConfig.Metrics?.Collector;

            if (!string.IsNullOrEmpty(collectorType))
            {
                try
                {
                    var metricsCollector = (IMetricsCollector)this.dependencyResolver.Resolve(collectorType, typeof(IMetricsCollector));
                    cfg.CollectMetrics(metricsCollector);
                }
                catch (Exception e)
                {
                    Log.Warn(m => m("Could not load metric collector '{0}'", collectorType), e);
                }
            }
            else
            {
                Log.Trace(m => m("Metric collector is not specified"));
            }

            foreach (var configurator in this.childConfigurators)
            {
                configurator.Configure(endpointName, cfg);
            }

            return(cfg);
        }
        /// <summary>
        /// Creates and starts a client.
        /// </summary>
        /// <param name="ipAdress">The ip adress.</param>
        /// <param name="port">The port.</param>
        /// <param name="connectRetryWaitMs">The connect retry wait ms.</param>
        /// <param name="id">The identifier. This identifier has to be matched be the listener this client will connect to. The listener will be determined, when the first msg is send.</param>
        /// <returns></returns>
        protected int CreateAndStartClient(IPAddress ipAdress, int port, int connectRetryWaitMs, int id, IMessageValidator messageValidator)
        {
            var client = new ConnectionBuffer <TMessage>
            {
                Id         = id,
                Connection = _binaryConnectionFactory.Create(CreateClientConfig(ipAdress, port, connectRetryWaitMs), messageValidator)
            };

            client.Connection.Received +=
                (sender, message) => client.Received.Add((TMessage)message);
            client.Connection.NotifyConnectionState += (sender, message) => client.LastStateChangeEvents.Add(message);

            var clientIdx = _clients.Count;

            _clients.Add(client);
            _overallClients.Add(client);

            Console.WriteLine("CreateAndStartClient Added Client idx: {0}.", clientIdx);

            // Client should be disconnected
            Assert.AreEqual(_clients[clientIdx].Connection.CurrentState, BinaryConnectionState.Disconnected,
                            $"Client is not in the state '{BinaryConnectionState.Disconnected:G}'. CurrentState: {_clients[clientIdx].Connection.CurrentState:G}");

            _clients[clientIdx].Connection.Start();

            // In some tests the client shall be connected at this point and in some tests it shall not be connected,
            // so check the connection-state somewhere else...

            return(clientIdx);
        }
Beispiel #25
0
 public MessagesService(IOperationResult operationResult, IMessageValidator messageValidator, IMessagesBusinessLogic messagesBussinessLogic) : base(operationResult)
 {
     _messageValidator       = messageValidator;
     _messagesBussinessLogic = messagesBussinessLogic;
 }
        /// <summary>
        /// The register.
        /// </summary>
        /// <param name="validator">
        /// The validator.
        /// </param>
        public void Register(IMessageValidator validator)
        {
            IList <Type> supportedTypes = Reflection.GetGenericTypeParameterOf(typeof(IMessageValidatorOf <>), validator);

            supportedTypes.ForEach(t => this._validators[t] = validator);
        }
        /// <summary>
        /// Конфигурирует клиента шины сообщений.
        /// </summary>
        /// <param name="endpointName">
        /// Имя точки подключения к шине.
        /// </param>
        /// <param name="cfg">
        /// Конфигуратор клиента шины.
        /// </param>
        /// <returns>
        /// Конфигуратор клиента шины, после применения к нему всех настроек.
        /// </returns>
        public IBusConfigurator Configure(string endpointName, IBusConfigurator cfg)
        {
            if (cfg == null)
            {
                throw new ArgumentNullException("cfg", "Файл конфигурации не может быть null");
            }

            EndpointElement endpointConfig = this.GetEndPointByName(endpointName);

            cfg.SetEndpoint(endpointConfig.Name);

            cfg.SetConnectionString(endpointConfig.ConnectionString);

            if (!string.IsNullOrWhiteSpace(endpointConfig.LifecycleHandler))
            {
                cfg.HandleLifecycleWith(this.ResolveLifecycleHandler(endpointConfig.LifecycleHandler));
            }

            if (endpointConfig.Caching != null && endpointConfig.Caching.Enabled)
            {
                cfg.EnableCaching();
            }

            if (endpointConfig.ParallelismLevel.HasValue)
            {
                cfg.UseParallelismLevel(endpointConfig.ParallelismLevel.Value);
            }

            if (endpointConfig.Dynamic != null)
            {
                if (endpointConfig.Dynamic.Outgoing.HasValue)
                {
                    if (endpointConfig.Dynamic.Outgoing.Value)
                    {
                        cfg.Route(MessageLabel.Any)
                        .ConfiguredWith(builder => new LambdaRouteResolver(
                                            (endpoint, label) =>
                        {
                            builder.Topology.Declare(
                                Exchange.Named(label.Name)
                                .Durable.Fanout);
                            return(new RabbitRoute(label.Name));
                        }));
                    }
                }
            }

            if (endpointConfig.Qos != null)
            {
                if (endpointConfig.Qos.PrefetchCount.HasValue)
                {
                    cfg.SetDefaultQoS(endpointConfig.Qos.PrefetchCount.Value);
                }
            }

            foreach (ValidatorElement validator in endpointConfig.Validators)
            {
                if (validator.Group)
                {
                    MessageValidatorGroup v = this.ResolveValidatorGroup(validator.Name);
                    cfg.RegisterValidators(v);
                }
                else
                {
                    IMessageValidator v = this.ResolveValidator(validator.Name);
                    cfg.RegisterValidator(v);
                }
            }

            foreach (OutgoingElement message in endpointConfig.Outgoing)
            {
                ISenderConfigurator senderCfg = cfg.Route(message.Label).
                                                WithAlias(message.Key);

                if (message.Confirm)
                {
                    senderCfg.WithConfirmation();
                }

                if (message.Persist)
                {
                    senderCfg.Persistently();
                }

                if (message.Ttl.HasValue)
                {
                    senderCfg.WithTtl(message.Ttl.Value);
                }

                if (message.CallbackEndpoint.Default)
                {
                    senderCfg.WithDefaultCallbackEndpoint();
                }

                if (message.Timeout.HasValue)
                {
                    senderCfg.WithRequestTimeout(message.Timeout);
                }
            }

            foreach (IncomingElement message in endpointConfig.Incoming)
            {
                IReceiverConfigurator receiver = cfg.On(message.Label).
                                                 WithAlias(message.Key);

                if (message.RequiresAccept)
                {
                    receiver.RequiresAccept();
                }

                Type messageType = typeof(ExpandoObject);
                if (!string.IsNullOrWhiteSpace(message.Type))
                {
                    messageType = ResolveType(message.Type);
                }

                var consumerFactory = this.BuildConsumerFactory(message.React, messageType);

                object consumer = BuildConsumer(consumerFactory, messageType, message.Lifestyle);

                RegisterConsumer(receiver, messageType, consumer);

                if (!string.IsNullOrWhiteSpace(message.Validate))
                {
                    IMessageValidator validator = this.ResolveValidator(message.Validate, messageType);

                    receiver.WhenVerifiedBy(validator);
                }
            }

            return(cfg);
        }
        /// <summary>
        /// Регистрирует механизм проверки входящего сообщения.
        /// </summary>
        /// <param name="validator">Механизм проверки входящего сообщения.</param>
        /// <returns>Конфигуратор получателя с установленным механизмом проверки входящих сообщений.</returns>
        public IReceiverConfigurator WhenVerifiedBy(IMessageValidator validator)
        {
            this.configuration.WhenVerifiedBy(validator);

            return(this);
        }