private void ResolveAction(MessageExchange message) { switch (message.Action) { case ActionType.NewContact: message.CreateNewContact(_eventAggregator); break; case ActionType.GetAllContacts: _eventAggregator.GetEvent <GetAllContactsMessage>().Publish(); break; case ActionType.EditContact: message.EditContact(_eventAggregator); break; case ActionType.DeleteContact: message.DeleteContact(_eventAggregator); break; case ActionType.SearchContactByName: _eventAggregator.GetEvent <SearchContactsByNameMessage>().Publish(message.Content); break; case ActionType.SearchContactByTelephone: _eventAggregator.GetEvent <SearchContactsByTelephoneMessage>().Publish(message.Content); break; default: break; } }
/// <summary> /// The result. /// </summary> /// <param name="exchange"> /// The exchange. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public static Task <MessageExchange> Result(MessageExchange exchange) { var completionSource = new TaskCompletionSource <MessageExchange>(); completionSource.SetResult(exchange); return(completionSource.Task); }
public Task <MessageExchange> Send(MessageExchange exchange) { if (this.disposed) { throw new ObjectDisposedException(typeof(FaultTolerantProducer).Name); } var errors = new List <Exception>(); for (var count = 0; count < this.attempts; count++) { this.logger.Trace($"Attempt to send #{count}"); try { var producer = this.selector.Next(); return(this.TrySend(exchange, producer)); } catch (Exception ex) { this.logger.Warn($"Attempt #{count} to send a message has failed", ex); errors.Add(ex); } } throw new FailoverException($"Failed to send a message after {this.attempts} attempts", new AggregateException(errors)) { Attempts = this.attempts }; }
public void should_reset_retry_delay_on_producer_success() { const int RetryDelay = 5; const int Attempts = 3; const int ResetDelay = 0; var tcs = new TaskCompletionSource<bool>(); tcs.SetResult(true); var producerMock = new Mock<IProducer>(); producerMock .Setup(p => p.Publish(It.IsAny<IMessage>())) .Returns(tcs.Task); var hash = producerMock.Object.GetHashCode(); var selector = new Mock<IProducerSelector>(); selector.Setup(s => s.Next()).Returns(() => producerMock.Object); var producer = new FaultTolerantProducer(selector.Object, Attempts, RetryDelay, ResetDelay); var message = new Message<DummyRequest>(MessageLabel.Any, new DummyRequest(1)); var exchange = new MessageExchange(message); Assert.DoesNotThrow(() => producer.Send(exchange)); var delays = producer.Delays.ToList(); delays.Should().HaveCount(1); delays.Should().Contain(kv => kv.Key == hash); delays.First().Value.Should().Be(0); }
public void should_increase_retry_delay_no_greater_then_max_delay_on_producer_failure() { const int RetryDelay = 5; const int Attempts = 3; const int ResetDelay = 10; var producerMock = new Mock<IProducer>(); producerMock .Setup(p => p.Publish(It.IsAny<IMessage>())) .Throws(new Exception("Publish error")); var hash = producerMock.Object.GetHashCode(); var selector = new Mock<IProducerSelector>(); selector.Setup(s => s.Next()).Returns(() => producerMock.Object); var producer = new FaultTolerantProducer(selector.Object, Attempts, RetryDelay, ResetDelay); var message = new Message<DummyRequest>(MessageLabel.Any, new DummyRequest(1)); var exchange = new MessageExchange(message); Assert.Throws<FailoverException>(() => producer.Send(exchange)); var delays = producer.Delays.ToList(); delays.Should().HaveCount(1); delays.Should().Contain(kv => kv.Key == hash); delays.First().Value.Should().BeGreaterThan(0).And.BeLessOrEqualTo(RetryDelay); }
public void should_reset_retry_delay_after_inactivity_period() { const int RetryDelay = 1; const int Attempts = 1; const int InactivityResetDelay = 3; var tcs = new TaskCompletionSource<bool>(); tcs.SetResult(true); var producerMock = new Mock<IProducer>(); producerMock .Setup(p => p.Publish(It.IsAny<IMessage>())) .Returns(tcs.Task); var selector = new Mock<IProducerSelector>(); selector.Setup(s => s.Next()).Returns(() => producerMock.Object); var producer = new FaultTolerantProducer(selector.Object, Attempts, RetryDelay, InactivityResetDelay); var message = new Message<DummyRequest>(MessageLabel.Any, new DummyRequest(1)); var exchange = new MessageExchange(message); Assert.DoesNotThrow(() => producer.Send(exchange)); Thread.Sleep(TimeSpan.FromSeconds(InactivityResetDelay + 1)); var delays = producer.Delays; delays.Should().BeEmpty(); }
/// <summary> /// Выполняет отправку сообщения. /// </summary> /// <param name="exchange">Информация об отправке.</param> /// <returns>Задача ожидания отправки сообщения.</returns> protected override Task <MessageExchange> InternalSend(MessageExchange exchange) { var producer = this.producerSelector.Next <Producer>(); if (exchange.IsRequest) { return(producer.Request(exchange.Out, exchange.ExpectedResponseType) .ContinueWith( t => { if (t.IsFaulted) { exchange.Exception = t.Exception; } else { exchange.In = t.Result; } return exchange; })); } return(producer.Publish(exchange.Out) .ContinueWith( t => { if (t.IsFaulted) { exchange.Exception = t.Exception; } return exchange; })); }
private Task <MessageExchange> TrySend(MessageExchange exchange, IProducer producer) { if (exchange.IsRequest) { return(producer.Request(exchange.Out, exchange.ExpectedResponseType) .ContinueWith( t => { if (t.IsFaulted) { exchange.Exception = t.Exception; } else { exchange.In = t.Result; } return exchange; })); } return(producer.Publish(exchange.Out) .ContinueWith( t => { if (t.IsFaulted) { exchange.Exception = t.Exception; } return exchange; })); }
public Task <MessageExchange> Try(MessageExchange exchange) { var errors = new List <Exception>(); for (var count = 0; count < this.attempts; count++) { this.logger.Trace($"Attempt to send #{count}"); var producer = this.selector.Next(); try { return(this.TrySend(exchange, producer)); } catch (Exception ex) { this.logger.Warn( $"Attempt #{count} to send a message on producer at [{producer.BrokerUrl}] has failed, will try the next producer", ex); errors.Add(ex); } } throw new FailoverException($"Failed to send a message after {this.attempts} attempts", new AggregateException(errors)) { Attempts = this.attempts }; }
void LoadModule(System.Windows.Controls.Control addIn) { FormContainer doc = this.FindAddInContainer(addIn); if (doc == null) { doc = CreateAddInContainer(addIn); doc.Tag = addIn; //注册模块。 this.m_AddIns.Add(doc.ExplorerControl); //删除事件。 doc.FormClosed += (s, e) => { if (this.m_AddIns.Contains(doc.ExplorerControl)) { MessageExchange.Singleton.Unsubscribe(doc.ExplorerControl); MessageExchange.RemoveNotify(doc.ExplorerControl); this.m_AddIns.Remove(doc.ExplorerControl); } }; } else { AddInActivate(addIn); } }
private void barDocuments_DockTabClosing(object sender, DevComponents.DotNetBar.DockTabClosingEventArgs e) { if (!XContext.AllowClose) { if (e.DockContainerItem.Tag.GetType() == typeof(StartWF)) { e.Cancel = true; } return; } e.RemoveDockTab = true; if (((Bar)sender).Items.Count == 1) // Remove bar if last item is closed... { dotNetBarManager1.Bars.Remove((Bar)sender); } //删除事件订阅。 if (this.m_AddIns.Contains(e.DockContainerItem.Tag)) { MessageExchange.Singleton.Unsubscribe(e.DockContainerItem.Tag); MessageExchange.RemoveNotify(e.DockContainerItem.Tag); this.m_AddIns.Remove(e.DockContainerItem.Tag); } }
public void should_aggregate_attempt_errors() { const int Count = 5; var producers = Enumerable.Range(0, Count).Select(i => { var mock = new Mock <IProducer>(); mock .Setup(p => p.Publish(It.IsAny <IMessage>())) .Throws(new Exception("Publish error")); mock .Setup(p => p.BrokerUrl).Returns(() => $"fake.url.{DateTime.Now.Ticks}"); return(mock.Object); }); var selector = new RoundRobinSelector(new ConcurrentQueue <IProducer>(producers)); var producer = new FaultTolerantProducer(selector, Count, 0, 0); var message = new Message <DummyRequest>(MessageLabel.Any, new DummyRequest(1)); var exchange = new MessageExchange(message); try { producer.Send(exchange); Assert.Fail(); } catch (FailoverException fex) { fex.InnerException.Should().BeOfType <AggregateException>(); var errors = (AggregateException)fex.InnerException; errors.InnerExceptions.Count.Should().Be(Count); } }
/// <summary> /// Обрабатывает сообщение с помощью зарегистрированных фильтров. /// </summary> /// <param name="message">Обрабатываемое сообщение.</param> /// <returns>Задача обработки сообщения с помощью фильтров.</returns> private Task ProcessFilter(IMessage message) { var exchange = new MessageExchange(message, null); var invoker = this.GetMessageExchangeFilterInvoker(); return(invoker.Process(exchange)); }
static void Main(string[] args) { foreach (var arg in args) { MessageExchange.Write($"input {arg}"); } var id = args.Count() > 0 ? args[0] : "0"; for (int i = 0; i < 2; i++) { Thread.Sleep(1000); MessageExchange.Write($"id: {id}, hello from client {i}"); MessageExchange.Error($"id: {id}, error from client {i}"); } var exception1 = new Exception("test1") { Source = Environment.StackTrace }; var exception2 = new Exception("test2", exception1) { Source = Environment.StackTrace }; MessageExchange.Exception(exception2); throw exception2; Console.Out.Flush(); Console.Error.Flush(); }
private static TimeSpan?GetTtl(CacheConfiguration config, MessageExchange exchange) { if (config.Ttl != null) { return(config.Ttl.Value); } var expiresHeader = Headers.GetString(exchange.In.Headers, Headers.Expires); if (!string.IsNullOrEmpty(expiresHeader)) { var expiration = Expires.Parse(expiresHeader); if (expiration != null) { if (expiration.Period != null) { return(expiration.Period); } var now = DateTimeOffset.Now; if (expiration.Date != null && expiration.Date.Value > now) { return(expiration.Date.Value - now); } } } return(null); }
/// <summary> /// Выполняет отправку сообщения. /// </summary> /// <param name="exchange">Информация об отправке.</param> /// <returns>Задача ожидания отправки сообщения.</returns> protected override Task <MessageExchange> InternalSend(MessageExchange exchange) { var attempts = this.senderOptions.GetFailoverAttempts() ?? AttemptsDefault; var wrapper = new FaultTolerantProducer(this.producerSelector, attempts); return(wrapper.Try(exchange)); }
private static MessageExchange GetExchange(string routeName = null) { var outMessage = new Message <TestRequest>(MessageLabel.From(!string.IsNullOrEmpty(routeName) ? routeName : RouteName), GetRequest()); var exchange = new MessageExchange(outMessage, typeof(TestResponse)); return(exchange); }
/// <summary> /// The continue. /// </summary> /// <param name="exchange"> /// The exchange. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public Task<MessageExchange> Continue(MessageExchange exchange) { if (!this.filterEnumerator.MoveNext()) { return Filter.Result(exchange); } return this.filterEnumerator.Current.Process(exchange, this); }
/// <summary> /// The continue. /// </summary> /// <param name="exchange"> /// The exchange. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public Task <MessageExchange> Continue(MessageExchange exchange) { if (!this.filterEnumerator.MoveNext()) { return(Filter.Result(exchange)); } return(this.filterEnumerator.Current.Process(exchange, this)); }
public void TestDirittiConversazione() { //Creazione di una conversazione da parte di un operatore Message message1 = new Message(operator1, "Salve, come devo comportarmi se X ha fatto Y?"); MessageExchange conversazione1 = new MessageExchange(message1); //Controllo dei diritto di accesso alla conversazione Assert.True(conversazione1.IsThisUserInTheConversation(operator1)); Assert.False(conversazione1.IsThisUserInTheConversation(operator2)); }
public MessageExchange NewConversation(Message message) { try { MessageExchange conversation = new MessageExchange(message); messageExchanges.Add(conversation); return(conversation); } catch (ArgumentException) { return(null); } }
public void should_invoke_starting_with_recent() { var log = new List <string>(); var filters = new[] { new LoggingFilter("A", log), new LoggingFilter("B", log), new LoggingFilter("C", log) }; var exchange = new MessageExchange(new Message("msg".ToMessageLabel(), new object())); var invoker = new MessageExchangeFilterInvoker(filters); invoker.Process(exchange). Wait(1.Seconds()); log.Should(). BeEquivalentTo(new object[] { "C: before", "B: before", "A: before", "A: after", "B: after", "C: after" }); }
private static void AddConversationTestData(MessageExchangesContext context) { Message firstMessage = new Message(users[0], "Testo di prova 1 messaggio"); MessageExchange conv = new MessageExchange(firstMessage); //Message secondMessage = new Message(users[1], "Testo secondo"); //conv.AddMessage(secondMessage); context.MessageExchanges.Add(conv); context.SaveChanges(); }
private void SendServerMessage(ActionType actionType, object content) { var jsonContent = JsonConvert.SerializeObject(content); var message = new MessageExchange(actionType, jsonContent); var jsonMessage = JsonConvert.SerializeObject(message); Writer.Write(jsonMessage); _eventAggregator.GetEvent <AddConsoleMessage>().Publish("Waiting server response..\n\n"); var messageFromServer = Reader.ReadString(); _eventAggregator.GetEvent <AddConsoleMessage>().Publish(messageFromServer); }
public void TestNuovaConversazione() { //Creazione di una conversazione da parte di un consulente Message message1 = new Message(consultant1, "Messaggio di test"); Assert.Throws <ArgumentException>(() => { MessageExchange conversazione1 = new MessageExchange(message1); }); //Creazione di una conversazione da parte di un operatore Message message2 = new Message(operator1, "Salve, come devo comportarmi se X ha fatto Y?"); MessageExchange conversazione2 = new MessageExchange(message2); }
/// <summary> /// Sends message using request-reply pattern. /// <see cref="Headers.CorrelationId"/> header from <see cref="headers"/> parameter is used to correlate the request with the reply, /// new one is generated if none is supplied. /// </summary> /// <param name="payload">Message payload.</param> /// <param name="headers">Message headers.</param> /// <typeparam name="T">Type of response.</typeparam> /// <returns>Request processing task.</returns> public Task <T> Request <T>(object payload, IDictionary <string, object> headers) where T : class { var message = new Message(this.Configuration.Label, headers, payload); var exchange = new MessageExchange(message, typeof(T)); var invoker = this.GetMessageExchangeFilterInvoker(); return(invoker.Process(exchange) .ContinueWith( t => { t.Result.ThrowIfFailed(); return (T)t.Result.In.Payload; })); }
public void should_delay_sending_on_producer_failure() { const int RetryDelay = 5; const int Attempts = 3; const int ResetDelay = 0; var producerMock = new Mock <IProducer>(); producerMock .Setup(p => p.Publish(It.IsAny <IMessage>())) .Throws(new Exception("Publish error")); var selector = new Mock <IProducerSelector>(); selector.Setup(s => s.Next()).Returns(() => producerMock.Object); var producer = new FaultTolerantProducer(selector.Object, Attempts, RetryDelay, ResetDelay); var message = new Message <DummyRequest>(MessageLabel.Any, new DummyRequest(1)); var exchange = new MessageExchange(message); var action = new Action(() => { try { producer.Send(exchange); } catch { // ignored } }); var overall = 0; Enumerable .Range(0, Attempts - 1) .Aggregate( 0, (prev, cur) => { var time = Math.Min(2 * (prev + 1), RetryDelay); overall += time; return(time); }); action.ExecutionTimeOf(a => a()).ShouldNotExceed(TimeSpan.FromSeconds(overall + 1)); }
private static MessageExchange TryCacheResponse(MessageExchange processedExchange, CacheConfiguration config) { if (!processedExchange.IsCompleteRequest) { return(processedExchange); } var ttl = GetTtl(config, processedExchange); if (ttl != null) { config.Cache.Set(processedExchange.Out, processedExchange.In.Payload, ttl.Value); } return(processedExchange); }
/// <summary> /// Creates a test isolation server. /// </summary> /// <param name="ipcPortName">The IPC port name.</param> /// <param name="linkId">The unique id of the client/server pair.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="ipcPortName"/> is null.</exception> public TestIsolationServer(string ipcPortName, Guid linkId) { if (ipcPortName == null) { throw new ArgumentNullException("ipcPortName"); } serverChannel = new BinaryIpcServerChannel(ipcPortName); clientChannel = new BinaryIpcClientChannel(ipcPortName + ".ServerCallback"); activeTasks = new Dictionary <Guid, IsolatedTaskState>(); MessageConsumer messageConsumer = new MessageConsumer() .Handle <IsolatedTaskFinishedMessage>(HandleIsolatedTaskFinished); messageExchange = new MessageExchange(messageConsumer); serverChannel.RegisterService(GetMessageExchangeLinkServiceName(linkId), messageExchange); }
/// <summary> /// The process. /// </summary> /// <param name="exchange"> /// The exchange. /// </param> /// <param name="invoker"> /// The invoker. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public Task <MessageExchange> Process(MessageExchange exchange, MessageExchangeFilterInvoker invoker) { this._log.Add(this._name + ": before"); if (this._stop) { return(Filter.Result(exchange)); } return(invoker.Continue(exchange). ContinueWith( t => { this._log.Add(this._name + ": after"); return t.Result; })); }
/// <summary> /// The continue. /// </summary> /// <param name="exchange"> /// The exchange. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public Task <MessageExchange> Continue(MessageExchange exchange) { if (!this.filterEnumerator.MoveNext()) { return(Filter.Result(exchange)); } var currentFilter = this.filterEnumerator.Current; var currentFilterType = currentFilter.GetType(); if (this.filterDecorators.ContainsKey(currentFilterType)) { return(this.filterDecorators[currentFilterType].Process(currentFilter, exchange, this)); } return(currentFilter.Process(exchange, this)); }
/// <summary> /// Если в кеше, есть ответное сообщение на входящее сообщение, тогда возвращает объект из кеша. /// </summary> /// <param name="exchange">Конвейер обработки сообщений.</param> /// <param name="invoker">Фильтры вызывающий конвейер.</param> /// <returns>Задача обработки сообщений.</returns> public Task<MessageExchange> Process(MessageExchange exchange, MessageExchangeFilterInvoker invoker) { if (!exchange.IsIncompleteRequest) { return invoker.Continue(exchange); } string hash = this.hasher.CalculateHashOf(exchange.Out).ToString(); Maybe<object> cached = this.cacheProvider.Find<object>(hash); if (cached.HasValue) { exchange.In = new Message(MessageLabel.Empty, cached.Value); return Filter.Result(exchange); } return invoker.Continue(exchange) .ContinueWith( t => { MessageExchange resultExchange = t.Result; if (!resultExchange.IsCompleteRequest) { return resultExchange; } string expiresHeader = Headers.GetString(resultExchange.In.Headers, Headers.Expires); if (!string.IsNullOrEmpty(expiresHeader)) { Expires expiration = Expires.Parse(expiresHeader); if (expiration.Period.HasValue) { this.cacheProvider.Put(hash, resultExchange.In.Payload, expiration.Period.Value); } else { this.cacheProvider.Put(hash, resultExchange.In.Payload, expiration.Date.Value); } } return resultExchange; }); }
/// <summary> /// The process. /// </summary> /// <param name="exchange"> /// The exchange. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public virtual Task<MessageExchange> Process(MessageExchange exchange) { return this.Continue(exchange); }
/// <summary> /// The process. /// </summary> /// <param name="exchange"> /// The exchange. /// </param> /// <param name="invoker"> /// The invoker. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public Task<MessageExchange> Process(MessageExchange exchange, MessageExchangeFilterInvoker invoker) { return this._sendingAction(exchange).ContinueWith(_ => invoker.Continue(exchange).Result); }
/// <summary> /// The process. /// </summary> /// <param name="exchange"> /// The exchange. /// </param> /// <param name="invoker"> /// The invoker. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public Task<MessageExchange> Process(MessageExchange exchange, MessageExchangeFilterInvoker invoker) { this._log.Add(this._name + ": before"); if (this._stop) { return Filter.Result(exchange); } return invoker.Continue(exchange). ContinueWith( t => { this._log.Add(this._name + ": after"); return t.Result; }); }
public void should_invoke_starting_with_recent() { var log = new List<string>(); var filters = new[] { new LoggingFilter("A", log), new LoggingFilter("B", log), new LoggingFilter("C", log) }; var exchange = new MessageExchange(new Message("msg".ToMessageLabel(), new object())); var invoker = new MessageExchangeFilterInvoker(filters); invoker.Process(exchange). Wait(1.Seconds()); log.Should(). BeEquivalentTo(new object[] { "C: before", "B: before", "A: before", "A: after", "B: after", "C: after" }); }
/// <summary> /// The result. /// </summary> /// <param name="exchange"> /// The exchange. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public static Task<MessageExchange> Result(MessageExchange exchange) { var completionSource = new TaskCompletionSource<MessageExchange>(); completionSource.SetResult(exchange); return completionSource.Task; }
/// <summary> /// Выполняет отправку сообщения. /// </summary> /// <param name="exchange">Информация об отправке.</param> /// <returns>Задача ожидания отправки сообщения.</returns> protected override Task<MessageExchange> InternalSend(MessageExchange exchange) { this.EnsureProducerIsReady(); if (exchange.IsRequest) { return this.producer.Request(exchange.Out, exchange.ExpectedResponseType) .ContinueWith( t => { if (t.IsFaulted) { exchange.Exception = t.Exception; } else { exchange.In = t.Result; } return exchange; }); } return this.producer.Publish(exchange.Out) .ContinueWith( t => { if (t.IsFaulted) { exchange.Exception = t.Exception; } return exchange; }); }