Ejemplo n.º 1
0
 public EventBus(IBusContext context, ITextSerializer serializer)
 {
     if (context == null) throw new ArgumentNullException(nameof(context));
     if (serializer == null) throw new ArgumentNullException(nameof(serializer));
     _context = context;
     _serializer = serializer;
 }
Ejemplo n.º 2
0
		public Closed(
			BusConfiguration configuration,
			IConnectionManager connectionManager,
			IBusContext context)
			: base(configuration, connectionManager, context)
		{
			base.Logger.Info("ctor Completed");
		}
Ejemplo n.º 3
0
        public static void TryEnqueue(this IBusContext ctx, CacheMessage message)
        {
            if (message == null)
            {
                return;
            }

            ctx.Enqueue(ContextName, message);
        }
        public EventReplayService(IBusContext <IConnection> context, IServiceCollection services, int timeout)
        {
            _queues   = new Stack <string>();
            _services = services;
            _context  = context;
            _timeout  = timeout;

            _channel = _context.Connection.CreateModel();
        }
    public Task Start(IBusContext context)
    {
        ErrorsNotifications errors = busNotifications.Errors;

        errors.MessageHasBeenSentToSecondLevelRetries  += (sender, retry) => LogToConsole(retry);
        errors.MessageHasFailedAFirstLevelRetryAttempt += (sender, retry) => LogToConsole(retry);
        errors.MessageSentToErrorQueue += (sender, retry) => LogToConsole(retry);
        return(Task.FromResult(0));
    }
        public async Task InterfaceMessage()
        {
            IBusContext busContext = null;

            #region InterfacePublish
            await busContext.Publish <IMyEvent>(m => { m.SomeProperty = "Hello world"; });

            #endregion
        }
Ejemplo n.º 7
0
    // Shut down server before sending this message, after 30 seconds, the message will be moved to Transactional dead-letter messages queue.
    static async Task Expiration(IBusContext bus)
    {
        await bus.Send(new MessageThatExpires
        {
            RequestId = new Guid()
        });

        Console.WriteLine("message with expiration was sent");
    }
Ejemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RabbitChannel"/> class.
        /// </summary>
        /// <param name="connectionId">A connection identifier to which this channel belongs</param>
        /// <param name="model">A native transport channel</param>
        /// <param name="busContext">A bus context</param>
        public RabbitChannel(Guid connectionId, IModel model, IBusContext busContext)
        {
            this.ConnectionId = connectionId;
            this.Model        = model;
            this.busContext   = busContext;
            this.logger       = LogManager.GetLogger($"{this.GetType().FullName}({this.ConnectionId}, {this.GetHashCode()})");

            this.Model.ModelShutdown += this.OnModelShutdown;
        }
Ejemplo n.º 9
0
        public static void Send <T>(this IBusContext ctx, T message, bool onCallback = false, string contextName = null)
            where T : class, ISpecializedMessage
        {
            if (message == null)
            {
                return;
            }

            SendInternal(ctx, message, onCallback, contextName);
        }
Ejemplo n.º 10
0
        private static void SendInternal(this IBusContext ctx, CacheMessage message, bool onCallback = false)
        {
            if (onCallback)
            {
                message.Token = message.Token ?? message.RequestId.ToString();
                MessageLogger.Sended(message);
            }

            ctx.Enqueue(ContextName, message);
        }
 /// <summary>
 /// Initialize a message receiver with a context, queue name and topic filters
 /// </summary>
 public RabbitMqMessageReceiver(IBusContext <IConnection> context, string queueName, IEnumerable <string> topicFilters)
 {
     Context      = context;
     Model        = Context.Connection.CreateModel();
     QueueName    = queueName;
     TopicFilters = topicFilters;
     Consumer     = new EventingBasicConsumer(Model);
     Logger       = RabbitMqLoggerFactory.CreateInstance <RabbitMqMessageReceiver>();
     ConsumerTag  = Guid.NewGuid().ToString();
 }
Ejemplo n.º 12
0
    static async Task SendJsonMessage(IBusContext busContext)
    {
        MessageWithJson message = new MessageWithJson
        {
            SomeProperty = "Some content in a json message",
        };
        await busContext.Send("Samples.MultiSerializer.Receiver", message);

        Console.WriteLine("Json Message sent");
    }
Ejemplo n.º 13
0
    static async Task SendRequest(IBusContext bus)
    {
        Guid requestId = Guid.NewGuid();

        await bus.Send(new Request
        {
            RequestId = requestId
        });

        Console.WriteLine("Request sent id: " + requestId);
    }
Ejemplo n.º 14
0
    static async Task PublishEvent(IBusContext busContext)
    {
        Guid eventId = Guid.NewGuid();

        await busContext.Publish <IMyEvent>(m =>
        {
            m.EventId = eventId;
        });

        Console.WriteLine("Event published, id: " + eventId);
    }
Ejemplo n.º 15
0
        public async Task RequestImmediateDispatchUsingScope()
        {
            IBusContext busContext = null;

            #region RequestImmediateDispatchUsingScope
            using (new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled))
            {
                await busContext.SendLocal(new MyMessage());
            }
            #endregion
        }
 public BestelStatusController(
     IBusContext <IConnection> context,
     IBestellingDataMapper bestellingDataMapper,
     IEventPublisher eventPublisher,
     ILoggerFactory loggerFactory)
 {
     _bestellingDataMapper = bestellingDataMapper;
     _eventPublish         = eventPublisher;
     _commandSender        = context.CreateCommandSender();
     _logger = loggerFactory.CreateLogger <BestelStatusController>();
 }
Ejemplo n.º 17
0
        public async Task RequestImmediateDispatch()
        {
            IBusContext busContext = null;

            #region RequestImmediateDispatch
            var options = new SendOptions();
            options.RequireImmediateDispatch();
            await busContext.Send(new MyMessage(), options);

            #endregion
        }
Ejemplo n.º 18
0
        public async Task Subscribe()
        {
            IBusContext busContext = null;

            #region ExplicitSubscribe
            await busContext.Subscribe <MyEvent>();

            await busContext.Unsubscribe <MyEvent>();

            #endregion
        }
Ejemplo n.º 19
0
    static async Task AsyncMain()
    {
        #region config
        BusConfiguration busConfiguration = new BusConfiguration();
        busConfiguration.EndpointName("Samples.Serialization.Xml");
        // this is optional since Xml is the default serializer
        busConfiguration.UseSerialization <XmlSerializer>();
        // register the mutator so the the message on the wire is written
        busConfiguration.RegisterComponents(components =>
        {
            components.ConfigureComponent <MessageBodyWriter>(DependencyLifecycle.InstancePerCall);
        });
        #endregion
        busConfiguration.UsePersistence <InMemoryPersistence>();
        busConfiguration.EnableInstallers();
        busConfiguration.SendFailedMessagesTo("error");

        IEndpointInstance endpoint = await Endpoint.Start(busConfiguration);

        try
        {
            IBusContext busContext = endpoint.CreateBusContext();
            #region message
            CreateOrder message = new CreateOrder
            {
                OrderId    = 9,
                Date       = DateTime.Now,
                CustomerId = 12,
                OrderItems = new List <OrderItem>
                {
                    new OrderItem
                    {
                        ItemId   = 6,
                        Quantity = 2
                    },
                    new OrderItem
                    {
                        ItemId   = 5,
                        Quantity = 4
                    },
                }
            };
            await busContext.SendLocal(message);

            #endregion
            Console.WriteLine("Order Sent");
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            await endpoint.Stop();
        }
    }
Ejemplo n.º 20
0
    static async Task SendMessageTooLargePayload(IBusContext bus)
    {
        #region SendMessageTooLargePayload

        AnotherMessageWithLargePayload message = new AnotherMessageWithLargePayload
        {
            LargeBlob = new byte[1024 * 1024 * 5] //5MB
        };
        await bus.Send("Samples.DataBus.Receiver", message);

        #endregion
    }
Ejemplo n.º 21
0
        async Task DisablePerMessage()
        {
            IBusContext busContext = null;

            #region DisableBestPracticeEnforcementPerMessage
            SendOptions options = new SendOptions();

            options.DoNotEnforceBestPractices();

            await busContext.Send(new MyEvent(), options);
            #endregion
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RabbitDelivery"/> class.
        /// </summary>
        /// <param name="busContext">
        /// The bus Context.
        /// </param>
        /// <param name="channel">
        /// Канал поставки сообщения.
        /// </param>
        /// <param name="args">
        /// Параметры поставки сообщения.
        /// </param>
        /// <param name="requiresAccept">
        /// Верно, если требуется подтверждение доставки.
        /// </param>
        public RabbitDelivery(IBusContext busContext, RabbitChannel channel, BasicDeliverEventArgs args, bool requiresAccept)
        {
            this.busContext = busContext;

            this.Channel        = channel;
            this.Label          = this.busContext.MessageLabelHandler.Resolve(args);
            this.Args           = args;
            this.requiresAccept = requiresAccept;

            this.headers = new Lazy <IDictionary <string, object> >(
                () => this.ExtractHeadersFrom(args));
        }
Ejemplo n.º 23
0
    static async Task SendCommand(IBusContext bus)
    {
        Guid commandId = Guid.NewGuid();

        await bus.Send(new MyCommand
        {
            CommandId       = commandId,
            EncryptedString = "Some sensitive information"
        });

        Console.WriteLine("Command sent id: " + commandId);
    }
Ejemplo n.º 24
0
        public async Task ConcreteMessage()
        {
            IBusContext busContext = null;

            #region InstancePublish
            MyEvent message = new MyEvent {
                SomeProperty = "Hello world"
            };
            await busContext.Publish(message);

            #endregion
        }
Ejemplo n.º 25
0
    static void Start(IBusContext busContext)
    {
        Console.WriteLine("Press '1' to publish IEvent");
        Console.WriteLine("Press '2' to publish EventMessage");
        Console.WriteLine("Press '3' to publish AnotherEventMessage");
        Console.WriteLine("Press 'Enter' to publish a message.To exit, Ctrl + C");
        #region PublishLoop
        while (true)
        {
            ConsoleKeyInfo key = Console.ReadKey();
            Console.WriteLine();

            Guid eventId = Guid.NewGuid();
            switch (key.Key)
            {
            case ConsoleKey.D1:
                busContext.Publish <IMyEvent>(m =>
                {
                    m.EventId  = eventId;
                    m.Time     = DateTime.Now.Second > 30 ? (DateTime?)DateTime.Now : null;
                    m.Duration = TimeSpan.FromSeconds(99999D);
                });
                Console.WriteLine("Published IMyEvent with Id {0}.", eventId);
                continue;

            case ConsoleKey.D2:
                EventMessage eventMessage = new EventMessage
                {
                    EventId  = eventId,
                    Time     = DateTime.Now.Second > 30 ? (DateTime?)DateTime.Now : null,
                    Duration = TimeSpan.FromSeconds(99999D)
                };
                busContext.Publish(eventMessage);
                Console.WriteLine("Published EventMessage with Id {0}.", eventId);
                continue;

            case ConsoleKey.D3:
                AnotherEventMessage anotherEventMessage = new AnotherEventMessage
                {
                    EventId  = eventId,
                    Time     = DateTime.Now.Second > 30 ? (DateTime?)DateTime.Now : null,
                    Duration = TimeSpan.FromSeconds(99999D)
                };
                busContext.Publish(anotherEventMessage);
                Console.WriteLine("Published AnotherEventMessage with Id {0}.", eventId);
                continue;

            default:
                return;
            }
        }
        #endregion
    }
Ejemplo n.º 26
0
        public static void AddRabbitMQBusContext(this IServiceCollection services,
                                                 Action <RabbitMQBusContextBuilder> busContextConfiguration)
        {
            services.AddTransient <IEventPublisher, EventPublisher <IConnection> >();

            var builder = new RabbitMQBusContextBuilder();

            busContextConfiguration(builder);
            IBusContext <IConnection> context = builder.CreateContext();

            services.AddSingleton(context);
        }
Ejemplo n.º 27
0
        public Disconnected(
            BusConfiguration configuration,
            IConnectionManager connectionManager,
            IBusContext context)
            : base(configuration, connectionManager, context)
        {
            base.Logger.Info("ctor Starting");

            new Task(this.TryRestablishingConnection).Start();

            base.Logger.Info("ctor Completed");
        }
Ejemplo n.º 28
0
    static async Task Data(IBusContext bus)
    {
        Guid requestId = Guid.NewGuid();

        await bus.Send(new LargeMessage
        {
            RequestId    = requestId,
            LargeDataBus = new byte[1024 * 1024 * 5]
        });

        Console.WriteLine("Request sent id: " + requestId);
    }
Ejemplo n.º 29
0
 public EventBus(IBusContext context, ITextSerializer serializer)
 {
     if (context == null)
     {
         throw new ArgumentNullException(nameof(context));
     }
     if (serializer == null)
     {
         throw new ArgumentNullException(nameof(serializer));
     }
     _context    = context;
     _serializer = serializer;
 }
Ejemplo n.º 30
0
        protected override Task OnStop(IBusContext context)
        {
            using (var waitHandle = new ManualResetEvent(false))
            {
                sweepTimer.Dispose(waitHandle);

                // TODO: Use async synchronization primitive
                waitHandle.WaitOne();
            }

            subscription.Unsubscribe();
            return(Task.FromResult(0));
        }
Ejemplo n.º 31
0
        private static void SendInternal <T>(this IBusContext ctx, T message, bool onCallback = false, string contextName = null)
            where T : class, ISpecializedMessage
        {
            contextName = contextName ?? message.ContextName;

            if (onCallback)
            {
                message.Token = message.Token ?? message.RequestId.ToString();
                MessageLogger.Sended(message);
            }

            ctx.Enqueue(contextName, message);
        }
Ejemplo n.º 32
0
        public async Task Start(Guid taskId, IBusContext busContext)
        {
            TaskDefinition taskDefinition;

            if (!scheduledTasks.TryGetValue(taskId, out taskDefinition))
            {
                logger.InfoFormat("Could not find any scheduled task with id {0}. The DefaultScheduler does not persist tasks between restarts.", taskId);
                return;
            }

            await DeferTask(taskDefinition, busContext).ConfigureAwait(false);
            await ExecuteTask(taskDefinition, busContext).ConfigureAwait(false);
        }
        protected override Task OnStop(IBusContext context)
        {
            using (var waitHandle = new ManualResetEvent(false))
            {
                timer.Dispose(waitHandle);

                // TODO: Use async synchronization primitive
                waitHandle.WaitOne();
            }

            publication.Active = false;
            return Publish();
        }
        protected override Task OnStart(IBusContext context)
        {
            publication = new HandledMessageDeclaration
            {
                EndpointName = settings.EndpointName().ToString(),
                UserDiscriminator = settings.EndpointInstanceName().UserDiscriminator,
                TransportDiscriminator = settings.EndpointInstanceName().TransportDiscriminator,
                HandledMessageTypes = hanledMessageTypes.Select(m => m.AssemblyQualifiedName).ToArray(),
                Active = true,
            };

            timer = new Timer(state =>
            {
                Publish().ConfigureAwait(false).GetAwaiter().GetResult();
            }, null, heartbeatPeriod, heartbeatPeriod);

            return Publish();
        }
Ejemplo n.º 35
0
 Task SomeCustomMethod(IBusContext busContext)
 {
     return Task.FromResult(0);
 }
        protected override async Task OnStart(IBusContext context)
        {
            var routingTable = settings.Get<UnicastRoutingTable>();
            var endpointInstances = settings.Get<EndpointInstances>();

            routingTable.AddDynamic((list, bag) => FindDestination(list));
            endpointInstances.AddDynamic(FindInstances);
           
            subscription = await dataBackplane.GetAllAndSubscribeToChanges("NServiceBus.HandledMessages",
                async e =>
                {
                    var deserializedData = JsonConvert.DeserializeObject<HandledMessageDeclaration>(e.Data);
                    var endpointName = new EndpointName(deserializedData.EndpointName);
                    var instanceName = new EndpointInstanceName(endpointName, deserializedData.UserDiscriminator, deserializedData.TransportDiscriminator);

                    var types =
                        deserializedData.HandledMessageTypes.Select(x => Type.GetType(x, false))
                            .Where(x => x != null)
                            .ToArray();

                    EndpointInstanceInfo instanceInfo;
                    if (!instanceInformation.TryGetValue(instanceName, out instanceInfo))
                    {
                        var newInstanceInformation = new Dictionary<EndpointInstanceName, EndpointInstanceInfo>(instanceInformation);
                        instanceInfo = new EndpointInstanceInfo();
                        newInstanceInformation[instanceName] = instanceInfo;
                        instanceInformation = newInstanceInformation;
                    }
                    if (deserializedData.Active)
                    {
                        instanceInfo.Activate(deserializedData.Timestamp);
                        Logger.InfoFormat("Instance {0} active (heartbeat).", instanceName);
                    }
                    else
                    {
                        instanceInfo.Deactivate();
                        Logger.InfoFormat("Instance {0} deactivated.", instanceName);
                    }
                    await UpdateCaches(endpointName, instanceName, types);
                }, 
                async e =>
                {

                    var deserializedData = JsonConvert.DeserializeObject<HandledMessageDeclaration>(e.Data);
                    var endpointName = new EndpointName(deserializedData.EndpointName);
                    var instanceName = new EndpointInstanceName(endpointName, deserializedData.UserDiscriminator,
                        deserializedData.TransportDiscriminator);

                    Logger.InfoFormat("Instance {0} removed from routing tables.", instanceName);

                    await UpdateCaches(endpointName, instanceName, new Type[0]);

                    instanceInformation.Remove(instanceName);
                });
            sweepTimer = new Timer(state =>
            {
                foreach (var info in instanceInformation)
                {
                    if (!info.Value.Sweep(DateTime.UtcNow, heartbeatTimeout))
                    {
                        Logger.InfoFormat("Instance {0} deactivated (heartbeat timeout).", info.Key);
                    }
                }
            }, null, sweepPeriod, sweepPeriod);
        }
        protected override Task OnStop(IBusContext context)
        {
            using (var waitHandle = new ManualResetEvent(false))
            {
                sweepTimer.Dispose(waitHandle);

                // TODO: Use async synchronization primitive
                waitHandle.WaitOne();
            }

            subscription.Unsubscribe();
            return Task.FromResult(0);
        }
 protected override Task OnStop(IBusContext context)
 {
     return client.Stop();
 }