Esempio n. 1
0
        static List <int> SendMessages(int messageCount)
        {
            var transport = new MsmqTransport(QueueName, new ConsoleLoggerFactory(true));

            MsmqUtil.EnsureQueueExists(MsmqUtil.GetPath(QueueName));

            var sendIds = new List <int>();

            Enumerable.Range(0, messageCount)
            .Select(id => new SomeMessage {
                Id = id
            })
            .ToList()
            .ForEach(msg =>
            {
                using (var scope = new RebusTransactionScope())
                {
                    transport.Send(QueueName, TransportMessageHelpers.FromString(JsonConvert.SerializeObject(msg)), scope.TransactionContext).Wait();

                    scope.Complete();

                    sendIds.Add(msg.Id);
                }
            });

            return(sendIds);
        }
Esempio n. 2
0
    public void SendOperationsEnlistInTheSameTransactionContext(bool commitTransaction)
    {
        var receivedMessages = new ConcurrentQueue <string>();
        var bus = _activator.Bus.Advanced.SyncBus;

        _activator.AddHandlerWithBusTemporarilyStopped <string>(async msg => receivedMessages.Enqueue(msg));

        using (var context = new RebusTransactionScope())
        {
            bus.SendLocal("hej med dig min ven");
            bus.SendLocal("her er endnu en besked");

            if (commitTransaction)
            {
                context.Complete();
            }
        }

        Thread.Sleep(500);

        if (commitTransaction)
        {
            Assert.That(receivedMessages, Contains.Item("hej med dig min ven"));
            Assert.That(receivedMessages, Contains.Item("her er endnu en besked"));
        }
        else
        {
            Assert.That(receivedMessages.Count, Is.EqualTo(0));
        }
    }
        void Send(string destinationAddress, string message)
        {
            Console.WriteLine("Sending to {0}", destinationAddress);

            using (var scope = new RebusTransactionScope())
            {
                _transport.Send(destinationAddress, NewMessage(message), scope.TransactionContext).Wait();
                scope.Complete();
            }
        }
 public void Commit(Enlistment enlistment)
 {
     try
     {
         _scope.Complete();
         enlistment.Done();
     }
     catch
     {
         _scope.Dispose();
         throw;
     }
 }
        string Receive()
        {
            using (var scope = new RebusTransactionScope())
            {
                var transportMessage = _transport.Receive(scope.TransactionContext, _cancellationToken).Result;

                scope.Complete();

                if (transportMessage == null)
                {
                    return(null);
                }

                return(Encoding.UTF8.GetString(transportMessage.Body));
            }
        }
        public async Task TriggerEvent([FromBody] EventContract eventContract)
        {
            Logger.LogInformation($"Storing event with id {eventContract.Id.ToString()} in outbox for publishing.");

            if (eventContract.Event.Length > EventContract.MaxEventLength)
            {
                eventContract.Event = eventContract.Event.Substring(0, EventContract.MaxEventLength);
            }

            using (var rebusTransactionScope = new RebusTransactionScope())
            {
                await Bus.Advanced.Topics.Publish(EventContract.Topic, eventContract);

                rebusTransactionScope.Complete();
            }

            Logger.LogInformation($"Event with id {eventContract.Id.ToString()} successfully stored in outbox.");
        }
    static void RunTest(InMemNetwork network, string destinationAddress, bool complete)
    {
        using (var activator = new BuiltinHandlerActivator())
        {
            var bus = Configure.With(activator)
                      .Transport(t => t.UseInMemoryTransport(network, "test-queue"))
                      .Routing(t => t.TypeBased().Map <string>(destinationAddress))
                      .Start();

            using (var scope = new RebusTransactionScope())
            {
                bus.Advanced.SyncBus.Send("HEJ MED DIG");

                if (complete)
                {
                    scope.Complete();
                }
            }
        }
    }
Esempio n. 8
0
        public async Task OnlyReceivesPublishedEventWhenRebusTransactionScopeIsCompleted()
        {
            // manually register the subscriber transport as a subscriber
            await _subscriptionStorage.RegisterSubscriber(typeof(TestEvent).GetSimpleAssemblyQualifiedName(), "subscriber");

            var bus = Configure.With(new BuiltinHandlerActivator())
                      .Subscriptions(config => config.StoreInMySql(MySqlTestHelper.ConnectionString, "Subscriptions"))
                      .Transport(configurer => configurer.UseMySql(new MySqlTransportOptions(MySqlTestHelper.ConnectionString), "Test"))
                      .Start();

            // this event should be published and received successfully by the subscriber
            using (var scope = new RebusTransactionScope())
            {
                bus.Advanced.SyncBus.Publish(new TestEvent("completed"));
                scope.Complete();
            }

            // this event is published, but the scope is not completed - therefore, it should NOT be received
            using (var scope = new RebusTransactionScope())
            {
                bus.Advanced.SyncBus.Publish(new TestEvent("not completed"));
                // this scope is intentionally not completed!
                //scope.Complete();
            }

            var messages = _subscriberTransport.GetMessages().ToList();

            Assert.That(messages.Count, Is.EqualTo(1),
                        "Expected one single event to have been received, because only one of the scopes were completed");

            var transportMessage = messages.First();

            Assert.That(transportMessage.Headers.GetValue(Headers.Type), Is.EqualTo(typeof(TestEvent).GetSimpleAssemblyQualifiedName()),
                        "Expected the type header to say 'TestEvent' (by the type's simple assembly-qualified name)");

            var json      = Encoding.UTF8.GetString(transportMessage.Body);
            var testEvent = JsonConvert.DeserializeObject <TestEvent>(json);

            Assert.That(testEvent.Label, Is.EqualTo("completed"),
                        "Expected the received event to be the one with the label saying 'completed'");
        }
Esempio n. 9
0
        public void DoesNotBlockOnCompletingTransactionContext()
        {
            var bus        = _activator.Bus.Advanced.SyncBus;
            var gotMessage = new ManualResetEvent(false);

            _activator.AddHandlerWithBusTemporarilyStopped <string>(async str => gotMessage.Set());

            using (var aspNet = new AspNetSimulatorSynchronizationContext())
            {
                aspNet.Post(s =>
                {
                    using (var scope = new RebusTransactionScope())
                    {
                        try
                        {
                            // enlist some other async thing
                            scope.TransactionContext.OnCommitted(async _ =>
                            {
                                Console.WriteLine("waiting....");
                                await Task.Delay(100);
                                Console.WriteLine("waiting....");
                                await Task.Delay(100);
                                Console.WriteLine("waiting....");
                                await Task.Delay(100);
                            });

                            // enlist an operation in the context
                            bus.SendLocal("HEJ MED DIG MIN VEN");

                            scope.Complete();
                        }
                        finally
                        {
                            AmbientTransactionContext.SetCurrent(null);
                        }
                    }
                }, null);

                gotMessage.WaitOrDie(TimeSpan.FromSeconds(3));
            }
        }
        public void OnlyReceivesPublishedEventWhenRebusTransactionScopeIsCompleted()
        {
            var network         = new InMemNetwork();
            var subscriberStore = new InMemorySubscriberStore();

            network.CreateQueue("subscriber");
            subscriberStore.AddSubscriber(typeof(TestEvent).GetSimpleAssemblyQualifiedName(), "subscriber");

            var bus = Configure.With(new BuiltinHandlerActivator())
                      .Subscriptions(config => config.StoreInMemory(subscriberStore))
                      .Transport(configurer => configurer.UseInMemoryTransport(network, "Test"))
                      .Start();

            using (var scope = new RebusTransactionScope())
            {
                bus.Advanced.SyncBus.Publish(new TestEvent("completed"));
                scope.Complete();
            }

            using (new RebusTransactionScope())
            {
                bus.Advanced.SyncBus.Publish(new TestEvent("not completed"));
                // this scope is intentionally not completed!
            }

            var messages = network.GetMessages("subscriber").ToList();

            Assert.That(messages.Count, Is.EqualTo(1));

            var transportMessage = messages.First();

            Assert.That(transportMessage.Headers.GetValue(Headers.Type), Is.EqualTo(typeof(TestEvent).GetSimpleAssemblyQualifiedName()));

            var json      = Encoding.UTF8.GetString(transportMessage.Body);
            var testEvent = JsonConvert.DeserializeObject <TestEvent>(json);

            Assert.That(testEvent.Label, Is.EqualTo("completed"));
        }
Esempio n. 11
0
        public static MqttClient Setup(this MqttClient mqttClient, IServiceProvider serviceProvider)
        {
            var logger        = serviceProvider.GetRequiredService <ILogger <MqttClient> >();
            var configuration = serviceProvider.GetRequiredService <IConfiguration>();

            if (!mqttClient.Connect(configuration))
            {
                const string errorMsg = "MqttClient could not connect!";
                logger.LogError(errorMsg);
                throw new Exception(errorMsg);
            }

            mqttClient.ConnectionClosed += (sender, args) =>
            {
                logger.LogInformation("Connection closed");

                while (!mqttClient.TryConnect(configuration, logger))
                {
                    Thread.Sleep(TimeSpan.FromSeconds(5));
                }
            };

            mqttClient.MqttMsgSubscribed += (sender, args) =>
            {
                logger.LogInformation("Subscribed");
            };

            mqttClient.MqttMsgPublished += (sender, args) =>
            {
                logger.LogInformation("Published");
            };

            mqttClient.MqttMsgPublishReceived += (sender, args) =>
            {
                logger.LogInformation("Publish Received");
            };

            mqttClient.MqttMsgPublishReceived += (sender, args) =>
            {
                var payload = Encoding.UTF8.GetString(args.Message);
                logger.LogInformation("### RECEIVED APPLICATION MESSAGE ###");
                logger.LogInformation($"+ Topic = {args.Topic}");
                logger.LogInformation($"+ Payload = {payload}");
                logger.LogInformation($"+ QoS = {args.QosLevel}");
                logger.LogInformation($"+ Retain = {args.Retain}");

                var eventContract = JsonConvert.DeserializeObject <EventContract>(payload);

                using (var rebusTransactionScope = new RebusTransactionScope())
                {
                    var bus = serviceProvider.GetRequiredService <IBus>();
                    bus.Advanced.Topics.Publish(EventContract.Topic, eventContract);
                    rebusTransactionScope.Complete();
                }
            };

            if (MqttTopics.Length > 0)
            {
                mqttClient.Subscribe(MqttTopics, new[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });
            }

            return(mqttClient);
        }