private void StartConsumer()
        {
            Task.Run(() =>
            {
                using (var channel = _modelFactory.CreateModel())
                {
                    var queueName = _queueNameFactory();

                    var routingConfig = new RoutingConfig(queueName);
                    var queueConfig   = new QueueConfig(queueName, routingConfig, _exchangeConfig, false, true, true, null);

                    if (_declareQueue)
                    {
                        channel.DeclareAndBindQueue(queueConfig);
                    }

                    var consumer = new EventingBasicConsumer(channel);

                    consumer.Received += (obj, evtArgs) =>
                    {
                        var correlationId = new Guid(evtArgs.BasicProperties.CorrelationId);

                        _msgsReceived.Add(correlationId, evtArgs);
                    };

                    channel.BasicConsume(queueName, true, consumer);

                    _stopConsumer.Wait();
                }
            });

            // Allow half a second for consumer to start
            Thread.Sleep(500);
        }
Exemple #2
0
        public virtual IList <TModel> GetAll()
        {
            try
            {
                connection.Open();

                using (var command = CreateSelectCommand(connection))
                {
                    command.Prepare();

                    using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                        var models = new List <TModel>();

                        while (reader.Read())
                        {
                            object[] vals = new object[reader.FieldCount];

                            reader.GetValues(vals);

                            models.Add(factory.CreateModel(vals));
                        }

                        return(models);
                    }
                }
            }
            finally
            {
                connection.Close();
            }
        }
Exemple #3
0
        public int LogToDatabase(Log log)
        {
            var dbLog = _logModelFactory.CreateModel(log);

            var result = _logRepository.InsertLog(dbLog);

            return(result);
        }
Exemple #4
0
        public void Publish <TMsg>(string to, TMsg msg)
        {
            using (var channel = _modelFactory.CreateModel())
            {
                channel.ExchangeDeclare("direct_exchange", ExchangeType.Direct);

                var jsonMsg  = JsonConvert.SerializeObject(msg);
                var bytesMsg = Encoding.UTF8.GetBytes(jsonMsg);

                var props = channel.CreateBasicProperties();
                props.DeliveryMode = 2;

                channel.BasicPublish(
                    exchange: "direct_exchange",
                    routingKey: to,
                    basicProperties: props,
                    body: bytesMsg);
            }
        }
Exemple #5
0
        private IPublisher <TMessage> CreatePublisher <TMessage>(IPublisherConfiguration <TMessage> configuration)
        {
            logger.DebugFormat("Creating publisher for {0} with configuration {1}",
                               typeof(TMessage).Name,
                               configuration);

            var model = modelFactory.CreateModel();

            return(publisherFactory.Create(model, configuration));
        }
Exemple #6
0
        public ISubscription Create <TMessage>(
            IBus bus,
            ISubscriptionConfiguration configuration,
            Action <TMessage, IDeliveryContext> callback)
        {
            logger.DebugFormat("Creating new handler subscription with configuration: {0}", configuration);

            var deliveryProcessor = new ActionDeliveryProcessor <TMessage>(
                bus,
                messageSerializers,
                callback);

            var messageType = typeof(TMessage).Name;

            var faultStrategy = configuration.BuildFaultStrategy(bus);

            var endpointNames = configuration.EndpointNames.Any()
                ? configuration.EndpointNames
                : new[] { messageType };

            // each subscription get its own model, where each endpoint
            // will be a consumer

            var modelReferenceTag = string.Join("|", endpointNames);
            var modelReference    = modelFactory.CreateModel(modelReferenceTag);

            // apply basic quality of service, this will set the prefetch count
            // which is shared across all consumers

            modelReference.Execute(
                m => m.BasicQos(
                    configuration.PrefetchSize,
                    configuration.PrefetchCount,
                    false));

            var deliveryStrategy = configuration.BuildDeliveryStrategy(
                deliveryProcessor);

            var deliveryQueues = BuildDeliveryQueues(
                endpointNames,
                modelReference,
                messageType,
                configuration,
                faultStrategy);

            var subscription = new Subscription(
                configuration.Name,
                modelReference,
                deliveryStrategy,
                deliveryQueues.ToArray());

            return(Create(subscription));
        }
        protected async Task Start(bool noAck, Action <object, BasicDeliverEventArgs> onReceived)
        {
            await Task.Run(() =>
            {
                while (_isRunning)
                {
                    _stopConsumerEvent = new ManualResetEventSlim(false);

                    try
                    {
                        _channel = _modelFactory.CreateModel();

                        var consumer = new EventingBasicConsumer(_channel);

                        consumer.Received += (obj, evtArgs) =>
                        {
                            try
                            {
                                onReceived(obj, evtArgs);
                            }
                            catch (Exception ex)
                            {
                                _onError(ex, $"Error processing message from {QueueName}");
                            }
                        };

                        consumer.Shutdown += (obj, evtArgs) =>
                        {
                            _onError(new Exception(evtArgs.ReplyText), $"{QueueName}: Consumer shutdown: {evtArgs.ReplyText}");
                            _stopConsumerEvent.Set();
                        };

                        consumer.ConsumerCancelled += (obj, evtArgs) =>
                        {
                            _onError(new Exception("Consumer cancelled"), $"{QueueName}: Consumer cancelled: {evtArgs.ConsumerTag}");
                            _stopConsumerEvent.Set();
                        };

                        _channel.BasicConsume(QueueName, noAck, consumer);

                        _stopConsumerEvent.Wait();
                    }
                    catch (Exception ex)
                    {
                        _onError(ex, $"Error while trying to consume from {QueueName}: {ex.Message}");
                    }

                    Task.Delay(250).Wait();
                }
            });
        }
        // ========================================
        // method
        // ========================================
        public override void Execute()
        {
            var model = _modelFactory.CreateModel();

            _createdEditor = _target.AddChild(model);
            _createdEditor.Figure.Bounds = _bounds;
            _createdEditor.Enable();

            var select = new SelectRequest();

            select.DeselectOthers = true;
            select.Value          = SelectKind.True;
            _createdEditor.PerformRequest(select);
        }
Exemple #9
0
        public void Init()
        {
            using (var channel = _modelFactory.CreateModel())
            {
                foreach (var e in _exchanges)
                {
                    channel.DeclareExchange(e);
                }

                foreach (var q in _queueConfigs)
                {
                    channel.DeclareAndBindQueue(q);
                }
            }
        }
Exemple #10
0
        // ========================================
        // method
        // ========================================
        public override void Execute()
        {
            /// modelの生成
            var model = _modelFactory.CreateModel();

            Contract.Requires(model != null);

            _createdEditor = _target.AddChild(model);
            SetUp(_createdEditor, model);

            var select = new SelectRequest();

            select.DeselectOthers = true;
            select.Value          = SelectKind.True;
            _createdEditor.PerformRequest(select);
        }
        public Task <bool> VerifyMessageReceived <T>(Func <T, bool> verify, Guid correlationId, int millisecondsTimeout) where T : class
        {
            var t = Task.Run(() =>
            {
                var resetEvent = new ManualResetEventSlim(false);

                var verified = false;

                using (var channel = _modelFactory.CreateModel())
                {
                    var queueName = _queueNameFactory();

                    var routingConfig = new RoutingConfig(queueName);
                    var queueConfig   = new QueueConfig(queueName, routingConfig, _exchange, false, true, true, null);

                    if (_declareQueue)
                    {
                        channel.DeclareAndBindQueue(queueConfig);
                    }

                    var consumer = new EventingBasicConsumer(channel);

                    consumer.Received += (obj, evtArgs) =>
                    {
                        if (correlationId == new Guid(evtArgs.BasicProperties.CorrelationId))
                        {
                            var msg = _serializerFactory.DeserializeTo <T>(evtArgs);

                            verified = verify(msg);

                            resetEvent.Set();
                        }
                    };

                    channel.BasicConsume(queueName, true, consumer);

                    resetEvent.Wait(millisecondsTimeout);
                }

                return(verified);
            });

            // Allow half a second for consumer to start
            Thread.Sleep(500);

            return(t);
        }
        // ========================================
        // method
        // ========================================
        public override void Execute()
        {
            var model = _modelFactory.CreateModel();

            _createdEditor = _target.AddChild(model);
            var freehand = _createdEditor.Figure as FreehandFigure;

            freehand.SetPoints(_points);
            freehand.BorderWidth = _width;
            freehand.Foreground  = _color;
            _createdEditor.Enable();

            //var select = new SelectRequest();
            //select.DeselectOthers = true;
            //select.Value = SelectKind.True;
            //_createdEditor.PerformRequest(select);
        }
        public void CreateModel(Block block, object content)
        {
            var model = modelFactory.CreateModel();

            model.Content    = content;
            model.BlockModel = block;
            model.Height     = 100;
            model.Width      = 70;

            //TODO: just for testing. customization can be added
            var keyStem = "Overture";

            PropertyAdvisor.SetSelectedExternalToolParameter(block.Parameters, keyStem);
            PropertyAdvisor.SetExternalToolParameter(block.Parameters, keyStem, string.Empty, string.Empty, string.Empty, string.Empty);
            PropertyAdvisor.SetExternalResultLocationParameter(block.Parameters, keyStem, string.Empty);

            AddModel(model);
        }
Exemple #14
0
        protected void PublishMessage <T>(T msg, string routingKey, Guid correlationId, string contentType, Func <BasicProperties, BasicProperties> addProps)
        {
            var payload = _serializerFactory.Serialize(msg, contentType);

            var props = new BasicProperties
            {
                ContentType   = contentType,
                CorrelationId = correlationId.ToString(),
                MessageId     = _messageIdFactory(),
                Headers       = _headerFactory(),
                Type          = msg.GetType().AssemblyQualifiedName,
                Expiration    = _messageTimeToLive.TotalMilliseconds.ToString(CultureInfo.InvariantCulture)
            };

            props = addProps(props);

            if (_channel == null || _channel.IsClosed)
            {
                _channel = _modelFactory.CreateModel();
            }

            _channel.BasicPublish(ExchangeName, routingKey, props, payload);
        }
 public void Show <TModel>()
 {
     CurrentModel = models.CreateModel <TModel>();
 }
Exemple #16
0
        public void Start(ICollection <Type> msgTypes, ICollection <string> contentTypes)
        {
            ValidateTypeFactoriesProvided(msgTypes);
            ValidateSerializersProvided(contentTypes);

            var msgsToTrack = contentTypes
                              .SelectMany(a => msgTypes.Select(b => new Tuple <string, Type>(a, b)))
                              .ToList();

            _isRunning = true;

            while (_isRunning)
            {
                foreach (var t in msgsToTrack)
                {
                    if (_publisherChannel == null || _publisherChannel.IsClosed)
                    {
                        _publisherChannel = _modelFactory.CreateModel();
                    }

                    if (_consumerChannel == null || _consumerChannel.IsClosed)
                    {
                        _consumerChannel = _modelFactory.CreateModel();
                    }

                    var serializer  = _serializerFactory.For(t.Item1);
                    var msg         = _typeFactory[t.Item2]();
                    var resetEvent  = new ManualResetEventSlim();
                    var wasReceived = false;

                    var correlationId = Guid.NewGuid();
                    var routingKey    = Guid.NewGuid().ToString();

                    var consumer             = new EventingBasicConsumer(_consumerChannel);
                    var roundTripTimer       = new Stopwatch();
                    var deserializationTimer = new Stopwatch();

                    consumer.Received += (obj, evtArgs) =>
                    {
                        if (correlationId == new Guid(evtArgs.BasicProperties.CorrelationId))
                        {
                            deserializationTimer.Start();

                            serializer.DeserializeObject(evtArgs.Body, t.Item2);

                            deserializationTimer.Stop();
                            roundTripTimer.Stop();

                            wasReceived = true;
                            resetEvent.Set();
                        }
                    };

                    var queueConfig = new QueueConfig($"WhiteRabbit.Hopper.{routingKey}", new RoutingConfig($"WhiteRabbit.Hopper.{routingKey}"), _exchange, false, true, true, null);

                    _consumerChannel.DeclareAndBindQueue(queueConfig);
                    _consumerChannel.BasicConsume($"WhiteRabbit.Hopper.{routingKey}", true, consumer);

                    var props = new BasicProperties
                    {
                        ContentType   = t.Item1,
                        CorrelationId = correlationId.ToString(),
                        MessageId     = Guid.NewGuid().ToString(),
                        Type          = t.Item2.AssemblyQualifiedName,
                        Expiration    = _messageTimeout.TotalMilliseconds.ToString(CultureInfo.InvariantCulture)
                    };

                    roundTripTimer.Start();
                    var serializationTimer = Stopwatch.StartNew();

                    var payload = serializer.Serialize(msg);

                    serializationTimer.Stop();

                    _publisherChannel.BasicPublish(_exchange.Name, $"WhiteRabbit.Hopper.{routingKey}", props, payload);

                    resetEvent.Wait(_messageTimeout);

                    if (wasReceived)
                    {
                        _logAction($"[MessageType={t.Item2.Name}] [ContentType={t.Item1}] [MessageText=Serialization completed in {serializationTimer.Elapsed}]");
                        _logAction($"[MessageType={t.Item2.Name}] [ContentType={t.Item1}] [MessageText=De-serialization completed in {deserializationTimer.Elapsed}]");
                        _logAction($"[MessageType={t.Item2.Name}] [ContentType={t.Item1}] [MessageText=Round trip completed in {roundTripTimer.Elapsed}]");
                    }
                    else
                    {
                        _logAction($"{t.Item2.Name} was not received within the timeout {_messageTimeout}");
                    }
                }

                Task.Delay(_delayBetweenRuns).Wait();
            }
        }