public AsyncReturn(string frontendAddr, string backendAddr, MessageProcessor msgProc) : base(new Socket(SocketType.XREP), new Socket(SocketType.PULL)) { messageProcessor = msgProc; _frontend.Bind(frontendAddr); _backend.Bind(backendAddr); }
public TcpGateway(NetMQContext ctx, string endpoint, MessageProcessor processor) { _ctx = ctx; _endpoint = endpoint; _processor = processor; _socket = connect(); }
static void Main(string[] args) { using (SalesDB context = new SalesDB()) { EnsureMember(context.GetMemberRepository()); Rebate rebate = EnsureRebate(context.GetRebateRepository()); EnsureProduct(rebate, context.GetProductRepository()); } Console.WriteLine("Subscribing to events..."); var queue = new MsmqMessageQueueOutbound<Subscription>( ".", typeof(OrderShipped).FullName); queue.Send(new Subscription { Target = Environment.MachineName, QueueName = typeof(OrderShippedSubscriber).FullName }); Console.WriteLine("Starting order shipped subscriber..."); MessageProcessor<OrderShipped> processor = new MessageProcessor<OrderShipped>( typeof(OrderShippedSubscriber).FullName, () => new OrderShippedSubscriber()); processor.Start(); Console.ReadKey(); processor.Stop(); }
public void HistogramItemDispathesCount_ForOneThread_IsEqualToMessagesCount() { var messageProcessor = new MessageProcessor(1,10); messageProcessor.Start(); Assert.AreEqual(1,messageProcessor.Histogram.ElementAt(0).Dispatches); Assert.AreEqual(10,messageProcessor.Histogram.ElementAt(0).DispatchesCount); }
private static IEventStore CreateEventStore() { IEventPublisher publisher = new MessageProcessor(); IEventPersistente persistente = new MemoryEventPersistente(); IEventStore store = new EventStore(publisher, persistente); return store; }
public void SetUp() { Configure.Transactions.Enable() .Advanced( settings => settings.DefaultTimeout(TimeSpan.FromSeconds(10)) .IsolationLevel(IsolationLevel.ReadCommitted) .EnableDistributedTransactions()); sessionFactoryMock = new Mock<ISessionFactory>(); activeMqMessageMapperMock = new Mock<IActiveMqMessageMapper>(); purger = new Mock<IActiveMqPurger>(); transactionScopeFactoryMock = new Mock<ITransactionScopeFactory>(); testee = new MessageProcessor( activeMqMessageMapperMock.Object, sessionFactoryMock.Object, purger.Object, transactionScopeFactoryMock.Object); transactionScopeFactoryMock .Setup(f => f.CreateNewTransactionScope(It.IsAny<TransactionSettings>(), It.IsAny<ISession>())) .Returns(new Mock<ITransactionScope>().Object); order = string.Empty; }
static void Main(string[] args) { FulfillmentDB.Initialize(); FulfillmentDB context = new FulfillmentDB(); var product = EnsureProduct(context); EnsureWarehouse(context, product); Console.WriteLine("Starting order processor..."); SubscriberRegistry<OrderShipped> subscrptionRegistry = new SubscriberRegistry<OrderShipped>(); MessageProcessor<PlaceOrder> orderProcessor = new MessageProcessor<PlaceOrder>( typeof(PlaceOrder).FullName, () => new PlaceOrderHandler(subscrptionRegistry)); orderProcessor.Start(); MessageProcessor<Subscription> subscriptionProcessor = new MessageProcessor<Subscription>( typeof(OrderShipped).FullName, () => new SubscriptionHandler<OrderShipped>( subscrptionRegistry)); subscriptionProcessor.Start(); Console.ReadKey(); orderProcessor.Stop(); subscriptionProcessor.Stop(); }
public AsyncReturn(Context context, string frontendAddr, string backendAddr, MessageProcessor msgProc) : base(context.Socket(SocketType.XREP), context.Socket(SocketType.PULL)) { _messageProcessor = msgProc; _frontend.Bind(frontendAddr); _backend.Bind(backendAddr); }
public ServiceBusListener(MessagingFactory messagingFactory, string entityPath, ServiceBusTriggerExecutor triggerExecutor, ServiceBusConfiguration config) { _messagingFactory = messagingFactory; _entityPath = entityPath; _triggerExecutor = triggerExecutor; _cancellationTokenSource = new CancellationTokenSource(); _messageProcessor = config.MessagingProvider.CreateMessageProcessor(entityPath); }
public async Task CompleteProcessingMessageAsync_DefaultOnMessageOptions() { MessageProcessor processor = new MessageProcessor(new OnMessageOptions()); BrokeredMessage message = new BrokeredMessage(); FunctionResult result = new FunctionResult(true); await processor.CompleteProcessingMessageAsync(message, result, CancellationToken.None); }
/// <inheritdoc /> public override IAsyncResult BeginProcessRequest(IAMFContext context, IMessage request, AsyncCallback callback, object asyncState) { CommandMessage commandMessage = (CommandMessage)request; MessageProcessor processor = new MessageProcessor(context, commandMessage, this, callback, asyncState); processor.BeginTask(); return processor; }
public void fii () { var processor = new MessageProcessor(); processor.Register<CartUserChanged>(e=> Console.WriteLine(e.CartId + " event handled.")); Cart cart = new Cart(); cart.ChangeUser(new User()); processor.Publish(cart.AppliedEvents); }
public void ProcessMessage_extracts_command_with_message() { const string rawMessage = "EHLO client.example.com"; var msgProcessor = new MessageProcessor(); var msg = msgProcessor.ProcessMessage(rawMessage); Assert.AreEqual(SmtpCommand.EHLO, msg.SMTPCommand); Assert.AreEqual("client.example.com", msg.MessageText); }
public void ProcessMessage_Returns_Message_When_Message_Too_Short_For_Command() { const string rawMessage = "ab"; var msgProcessor = new MessageProcessor(); var msg = msgProcessor.ProcessMessage(rawMessage); Assert.AreEqual(SmtpCommand.Unknown, msg.SMTPCommand); Assert.AreEqual(rawMessage, msg.MessageText); }
public void ProcessMessage_returns_message_when_no_command_given() { const string rawMessage = "From: [email protected]\r\nTo: [email protected]\r\n"; var msgProcessor = new MessageProcessor(); var msg = msgProcessor.ProcessMessage(rawMessage); Assert.AreEqual(SmtpCommand.Unknown, msg.SMTPCommand); Assert.AreEqual(rawMessage, msg.MessageText); }
public void ProcessMessage_Returns_No_Message_When_Command_Only() { const string rawMessage = "EHLO"; var msgProcessor = new MessageProcessor(); var msg = msgProcessor.ProcessMessage(rawMessage); Assert.AreEqual(SmtpCommand.EHLO, msg.SMTPCommand); Assert.AreEqual(string.Empty, msg.MessageText); }
public Server(int port) { Version = 1; Methods = new Methods(); Subscriptions = new Subscriptions(); Publications = new Publications(); new PublicationMethods(this).AttachMethods(); var messageMethods = new MessageMethods(this).GetMethods(); var messageProcessor = new MessageProcessor(messageMethods); _messageQueue = new ResultQueue<KeyValuePair<IWebSocketConnection, string>>(messageProcessor); _connector = new Connector(this, "127.0.0.1", port); }
public static void Main() { using (IUnityContainer container = new UnityContainer()) { container.RegisterInstance(typeof(ISpy), new NullSpy()); using (ProcessorConfiguration config = new ProcessorConfiguration()) { config.DefaultHandlerLifetime = HandlerLifetime.Transient; config.RegisterCommandHandler<TestCommand>(async command => { await Task.FromResult(0); }); config.RegisterCommandHandler<TestCommand2>(async command => { await Task.FromResult(0); }); //// config.RegisterContainer(container); //// config.Services.Replace(typeof(ICommandValidator), new NullValidator()); //// config.EnableDefaultTracing(); //// PerformanceTracer traceWriter = new PerformanceTracer(); ////config.Services.Replace(typeof(ITraceWriter), traceWriter); //// traceWorker.MinimumLevel = Tracing.TraceLevel.DefaultCommandValidator; ////config.Filters.Add(new CustomExceptionFilterAttribute()); //// long initialMemory = GC.GetTotalMemory(false); //// config.EnableGlobalExceptionHandler(); const int MaxIterations = 100000; config.EnableRedisMessageQueuing("localhost"); using (MessageProcessor processor = new MessageProcessor(config)) { processor.ProcessAsync(new TestCommand()); SingleProcessing(processor); ParallelProcessing(MaxIterations, processor); //// SequentialTaskProcessing(maxIterations, processor); //// SequentialTaskProcessingV2(maxIterations, processor); //// SequentialTaskProcessingV3(maxIterations, processor); RunCommandBroker(config.CommandBroker); } } //// Console.ReadLine(); } }
/// <inheritdoc /> public IAsyncResult BeginProcessRequest(IAMFContext context, IMessage request, AsyncCallback callback, object asyncState) { if (context == null) throw new ArgumentNullException("context"); if (request == null) throw new ArgumentNullException("request"); IService service = UncheckedGetServiceForMessage(context.Serializer, request); MessageProcessor processor = new MessageProcessor(context, request, service, callback, asyncState); processor.BeginTask(); return processor; }
private static void ParallelProcessing(int maxIterations, MessageProcessor processor) { Stopwatch stopwatch = Stopwatch.StartNew(); Parallel.For( 0, maxIterations, async i => { PlaceOrder command = new PlaceOrder(1); await processor.ProcessAsync(command); }); stopwatch.Stop(); System.Console.WriteLine("Parallel for, " + maxIterations + " iterations : " + stopwatch.ElapsedMilliseconds + " ms"); }
public void Initialize(MessageProcessor messageHandler) { //ViewModel require Settings and ManualPictureCombiner this.SettingManager = new SettingManager(); SettingManager.ReadSettings(Settings); MessageDispatcher = new MessageDispatcher(); MessageDispatcher.MessageHandler += messageHandler; photoModifier = new PhotoModifier(Settings); fileWriter = new FileWriter(Settings, MessageDispatcher); ManualPictureCombiner = new ManualPictureCombiner(photoModifier, fileWriter, MessageDispatcher); FolderScanner = new FolderScanner(MessageDispatcher); FolderScanner.InitVisitors(Settings); FolderScanner.NewPhotoGoupHandler = HandlePictureGroup; }
public static void Main(string[] args) { // -- Start database connection databaseManager = new DatabaseManager(); // -- Run web server webServer = new WebServer(); // -- Set up debugging NetworkManager.isUnity = false; // -- Set up network messenger networkMessenger = NetworkMessenger.GetInstance(); // -- Set up client manager clientManager = new ClientManager(4); // -- Set up message processor messageProcessor = new MessageProcessorServer(); // -- Set up game manager gameManager = new GameManager(); // -- Open local socket for sending and receiving networkMessenger.OpenClient(11999); // -- Start listening networkMessenger.Listen(IPAddress.Any, messageProcessor); // -- Build server world BuildServerWorld(); // -- Start ping Ping(); // -- Start update Update(); // -- Start tick Tick(); // -- Wait for exit command CommandLoop(); // -- Close all networkMessenger.Close(); }
/// <summary> /// <see cref="ChatworkLoggerProvider"/> クラスの新しいインスタンスを初期化します。 /// </summary> /// <param name="optionsMonitor">ロガーの設定。</param> /// <exception cref="ArgumentNullException"><see cref="ChatworkLoggerOptions.ApiToken"/> or <see cref="ChatworkLoggerOptions.RoomId"/> is <c>null</c>.</exception> public ChatworkLoggerProvider(IOptionsMonitor <ChatworkLoggerOptions> optionsMonitor) { var options = optionsMonitor?.CurrentValue ?? throw new ArgumentNullException(nameof(optionsMonitor)); if (options.ApiToken == null) { throw new ArgumentNullException(nameof(options.ApiToken)); } if (options.RoomId == null) { throw new ArgumentNullException(nameof(options.RoomId)); } _formatter = new ChatworkLogMessageFormatter(options.LogMessageFormatter, headerText: options.HeaderText); _chatworkApi = new ChatworkMessageApi(apiToken: options.ApiToken, roomId: options.RoomId, options.HttpClient ?? _defaultHttpClient); _processor = new MessageProcessor <LogMessage>(consumer: WriteMessages, queueSize: options.BackgroundQueueSize); }
public async Task SendMessageAsync_Should_Invoke_MessageProcessor() { using CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(DefaultTimeOut * 3)); _ = StartServer(cts.Token, 9987); TestRequestMessage message = new TestRequestMessage() { Message = "Test123" }; WSNetworkConnector wsNetworkConnector = await StartClient(cts.Token, 9987); await wsNetworkConnector.SendMessageAsync(message, cts.Token); IMessage messageInMessageProcessor = await MessageProcessor.GetMessageAsync(cts.Token); Assert.AreEqual(message.Id, messageInMessageProcessor?.Id); cts.Cancel(); }
public async Task SendMessageAsync_Should_Invoke_MessageProcessor() { using CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(DefaultTimeOut * 3)); _ = StartServer(cts.Token, 9987); AuthenticateRequest message = new AuthenticateRequest() { CredentialTypeCode = "Name", Password = "******", Username = "******" }; WSNetworkConnector wsNetworkConnector = await StartClient(cts.Token, 9987); await wsNetworkConnector.SendMessageAsync(message, cts.Token); IMessage messageInMessageProcessor = await MessageProcessor.GetMessageAsync(cts.Token); Assert.AreEqual(message.Id, messageInMessageProcessor?.Id); cts.Cancel(); }
private void ShowOldMessages() { List <Message> messages = MessageProcessor.GetAllMessages(); var result = new StringBuilder(); if (messages.Any()) { result.AppendLine("All messages:"); messages.ForEach(x => result.AppendLine(x.ToString())); } else { result.AppendLine("There is not any message"); } TbRecentMessages.Text = result.ToString(); }
public MessageProcessorTests() { delivererMock = new Mock <IMailDeliverer>(); delivererMock .Setup(d => d.DeliverAsync(It.Is <EmailMessage>(m => m.Subject == DELIVER_FAILURE))) .ThrowsAsync(new Exception()); storageMock = new Mock <IMailStorage>(); storageMock .Setup(s => s.SetProcessedAsync(It.Is <EmailMessage>(m => m.Subject == SET_PROCESSED_FAILURE))) .ThrowsAsync(new Exception()); storageMock .Setup(s => s.SetErrorAsync(It.Is <EmailMessage>(m => m.Subject == SET_ERROR_FAILURE), It.IsAny <string>())) .ThrowsAsync(new Exception()); storageMock .Setup(s => s.SetSentAsync(It.Is <EmailMessage>(m => m.Subject == SET_SENT_FAILURE))) .ThrowsAsync(new Exception()); cacheMock = new Mock <IDistributedCache>(); var internalCache = new MemoryDistributedCache(Options.Create <MemoryDistributedCacheOptions>(new MemoryDistributedCacheOptions())); cacheMock .Setup(c => c.GetAsync(It.Is <string>(m => m == CACHE_GET_EXCEPTION.ToString()), It.IsAny <CancellationToken>())) .ThrowsAsync(new Exception()); cacheMock .Setup(c => c.GetAsync(It.Is <string>(m => m != CACHE_GET_EXCEPTION.ToString()), It.IsAny <CancellationToken>())) .Returns(async(string key, CancellationToken c) => await internalCache.GetAsync(key, c)); cacheMock .Setup(c => c.SetAsync(It.Is <string>(m => m == CACHE_SET_EXCEPTION.ToString()), It.IsAny <byte[]>(), It.IsAny <DistributedCacheEntryOptions>(), It.IsAny <CancellationToken>())) .ThrowsAsync(new Exception()); cacheMock .Setup(c => c.SetAsync(It.Is <string>(m => m != CACHE_SET_EXCEPTION.ToString()), It.IsAny <byte[]>(), It.IsAny <DistributedCacheEntryOptions>(), It.IsAny <CancellationToken>())) .Returns(async(string key, byte[] value, DistributedCacheEntryOptions o, CancellationToken c) => await internalCache.SetAsync(key, value, o, c)); var logger = new NullLogger <MessageProcessor>(); messageProcessor = new MessageProcessor(delivererMock.Object, storageMock.Object, cacheMock.Object, logger); }
public ActionResult EncryptMessage(MessageModel model) { if (ModelState.IsValid) { string Message = model.OriginalMessage; int i = 0; foreach (char c in Message) { var sModel = SymbolProcessor.GetRow(c); Message = $"{Message.Substring(0,i)}{sModel.newSymbol}{Message.Substring(i+1)}"; i++; } MessageProcessor.CreateMessage(model.OriginalMessage, Message); return(RedirectToAction("Index")); } return(View("Index")); }
protected override void OnStart(string[] args) { try { LocalLog.Info("Starting MessageProcessor."); processor = new MessageProcessor(); processor.Start(); LocalLog.Info("MessageProcessor started."); } catch (Exception ex) { LocalLog.Error(ex.ToString()); } }
public void MessageProcessorWillDetermineFlatNumberFromEmailSubjectWhenNoAssociatedFlatFoundTest() { var flatsRepoMock = new Mock <IFlatsRepository>(); flatsRepoMock .Setup(fr => fr.FindFlatNumberBySender(It.IsAny <string>())) .Returns <string>(null); var messageProcessor = new MessageProcessor(flatsRepoMock.Object); var result = messageProcessor.Process(new DateTime(2018, 1, 9, 19, 13, 00), "*****@*****.**", "Квартира 159", "Доброго дня!\r\nТепло-40,450"); flatsRepoMock.VerifyAll(); Assert.AreEqual("159", result.FlatNumber); Assert.AreEqual(40.45, result.MeterReading); }
public async Task WhenProcessingInvalidCommandThenAbortProcesssing() { // Arrange InvalidCommand command = new InvalidCommand(); var handler = this.SetupHandler <InvalidCommand>(); MessageProcessor processor = this.CreatTestableProcessor(); // Act var result = await processor.ProcessAsync(command); // Assert Assert.NotNull(result); Assert.NotEqual(0, result.ModelState.Count); handler.Verify(h => h.Handle(It.IsAny <InvalidCommand>()), Times.Never()); }
public void testModifyURL19() { String myip = getAddress(); string myhostname = Environment.MachineName.ToLower(); //String url = "http://localhost:8080/something"; String exp = "http://" + myhostname + ":80/something"; String result = ""; //client test string url = "http://" + myip + "/something"; result = MessageProcessor.ModifyURL(url, true); Assert.AreEqual(exp, result, result); //NO PORT DEFINED }
public void MessageProcessorWillDetermineFlatNumberFromEmailBodyWhenNoAssociatedFlatFoundTest() { var flatsRepoMock = new Mock <IFlatsRepository>(); flatsRepoMock .Setup(fr => fr.FindFlatNumberBySender(It.IsAny <string>())) .Returns <string>(null); var messageProcessor = new MessageProcessor(flatsRepoMock.Object); var result = messageProcessor.Process(new DateTime(2018, 1, 2, 16, 17, 00), "*****@*****.**", "Опалення Прізвище І.П.", "Показник 14,5 квартира 280 Прізвище І.П."); flatsRepoMock.VerifyAll(); Assert.AreEqual("280", result.FlatNumber); Assert.AreEqual(14.5, result.MeterReading); }
internal void RegisterHandleAny_ThenStoresInReceiver() { // Arrange var receiver = new List <object>(); var processor = new MessageProcessor(); processor.RegisterHandler <object>(receiver.Add); // Act processor.Endpoint.SendAsync(1).Wait(); processor.GracefulStop().Wait(); // Assert Assert.Contains(1, receiver); Assert.DoesNotContain(1, processor.UnhandledMessages); Assert.Equal(1, processor.CountProcessed); }
internal void GivenMessage_WithExplodingHandler_PropagatesException() { // Arrange var processor = new MessageProcessor(); processor.RegisterHandler <string>(ThisWillBlowUp); // Act processor.Endpoint.SendAsync("BOOM!").Wait(); processor.GracefulStop().Wait(); // Assert Assert.Single(processor.Exceptions); Assert.Contains("BOOM!", processor.UnhandledMessages); Assert.Equal(0, processor.CountInput); Assert.Equal(1, processor.CountProcessed); }
public void TestInitialize() { _testHandler1Called = 0; _testHandler2Called = 0; _testHandler3Called = 0; _testFaultHandler1Called = 0; _testFaultHandler2Called = 0; _testFaultHandler3Called = 0; _transportMessageFaultHandler = 0; _typeMapping = new Dictionary <Type, HashSet <Type> >() { { typeof(TestMessage), new HashSet <Type>() { typeof(TestHandler), typeof(TestHandler2) } }, { typeof(TestHandler), new HashSet <Type>() { typeof(TestHandler), typeof(TestHandler2) } }, }; _faultHandlers = new Dictionary <Type, HashSet <Type> >() { { typeof(TestMessage), new HashSet <Type>() { typeof(TestFaultHandler1), typeof(TestFaultHandler2) } }, { typeof(TestHandler), new HashSet <Type>() { typeof(TestFaultHandler1), typeof(TestFaultHandler2) } }, }; _objectBuilder = new Mock <IObjectBuilder>(MockBehavior.Strict); _objectBuilder.Setup(x => x.GetNestedBuilder()).Returns(_objectBuilder.Object); _objectBuilder.Setup(x => x.Dispose()); _objectBuilder.Setup(x => x.RegisterInstance <ILog>(It.IsAny <ILog>())); _objectBuilder.Setup(x => x.GetValue(It.IsAny <Type>())).Returns <Type>(x => Activator.CreateInstance(x)); _processor = new MessageProcessor(_objectBuilder.Object, _typeMapping, _faultHandlers); _message = new TransportMessage() { MessageType = typeof(TestMessage), Message = new TestMessage(), MessageParsingSucceeded = true, }; }
public async Task When_Api_Returns_DevAlreadyUsed_Should_Return_Null() { var simulatedDevice = new SimulatedDevice(TestDeviceInfo.CreateOTAADevice(1, gatewayID: null)); var joinRequest = simulatedDevice.CreateJoinRequest(); // Create Rxpk var rxpk = joinRequest.SerializeUplink(simulatedDevice.LoRaDevice.AppKey).Rxpk[0]; var payloadDecoder = new Mock <ILoRaPayloadDecoder>(); var devNonce = ConversionHelper.ByteArrayToString(joinRequest.DevNonce); var devAddr = string.Empty; var devEUI = simulatedDevice.LoRaDevice.DeviceID; var appEUI = simulatedDevice.LoRaDevice.AppEUI; var loRaDeviceClient = new Mock <ILoRaDeviceClient>(MockBehavior.Strict); // Lora device api will be search by devices with matching deveui, var loRaDeviceApi = new Mock <LoRaDeviceAPIServiceBase>(MockBehavior.Strict); loRaDeviceApi.Setup(x => x.SearchAndLockForJoinAsync(this.ServerConfiguration.GatewayID, devEUI, appEUI, devNonce)) .ReturnsAsync(new SearchDevicesResult() { IsDevNonceAlreadyUsed = true }); var loRaDeviceFactory = new TestLoRaDeviceFactory(loRaDeviceClient.Object); var memoryCache = new MemoryCache(new MemoryCacheOptions()); var deviceRegistry = new LoRaDeviceRegistry(this.ServerConfiguration, memoryCache, loRaDeviceApi.Object, loRaDeviceFactory); // Send to message processor var messageProcessor = new MessageProcessor( this.ServerConfiguration, deviceRegistry, this.FrameCounterUpdateStrategyFactory.Object, payloadDecoder.Object); var downlinkMessage = await messageProcessor.ProcessMessageAsync(rxpk); Assert.Null(downlinkMessage); loRaDeviceApi.VerifyAll(); loRaDeviceClient.VerifyAll(); }
public void ParseThereWasAConflict() { var lines = @"""System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" was chosen because it was primary and ""System.IO.Compression, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" was not. References which depend on ""System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" [C:\Program Files (x86)\System.IO.Compression.dll]. C:\Program Files (x86)\System.IO.Compression.dll Project file item includes which caused reference ""C:\Program Files (x86)\System.IO.Compression.dll"". System.IO.Compression References which depend on ""System.IO.Compression, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" []. C:\A\\A.dll Project file item includes which caused reference ""C:\A\\A.dll"". C:\A\bin\Debug\C.dll C:\A\\B.dll Project file item includes which caused reference ""C:\A\\B.dll"". C:\A\\B\D.dll C:\A\\C.dll".GetLines(); var parameter = new Parameter() { Name = "There was a conflict" }; var stringCache = new StringCache(); foreach (var line in lines) { MessageProcessor.HandleThereWasAConflict(parameter, line, stringCache); } Assert.True(parameter.Children.Count == 3); var text = StringWriter.GetString(parameter); Assert.Equal(@"There was a conflict ""System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" was chosen because it was primary and ""System.IO.Compression, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" was not. References which depend on ""System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" [C:\Program Files (x86)\System.IO.Compression.dll]. C:\Program Files (x86)\System.IO.Compression.dll Project file item includes which caused reference ""C:\Program Files (x86)\System.IO.Compression.dll"". System.IO.Compression References which depend on ""System.IO.Compression, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" []. C:\A\\A.dll Project file item includes which caused reference ""C:\A\\A.dll"". C:\A\bin\Debug\C.dll C:\A\\B.dll Project file item includes which caused reference ""C:\A\\B.dll"". C:\A\\B\D.dll C:\A\\C.dll ", text); }
public void Fire() { config = MessageProcessor.GetConfig; if (config == null) { return; } if (HasPersistenceFiles()) { Logger.info("Stored files are present, attempting to restablish communications"); System.Console.WriteLine("Stored files are present, attempting to restablish communications"); //grab the first one AddDataRequestMsg rr = MessageProcessor.ReadItemsFromDisk(); if (rr != null) { bool online = MessageProcessor.ProcessSingleMessage(rr); if (!online) { Logger.warn("Still offline, we'll try again later"); System.Console.WriteLine("Still offline, we'll try again later"); MessageProcessor.WriteToDisk(rr); } else { Logger.info("We're online, add all items to the cache."); System.Console.WriteLine("We're online, add all items to the cache."); while (HasPersistenceFiles()) { rr = MessageProcessor.ReadItemsFromDisk(); if (rr != null) { //use standard built in functions to enqueue the data MessageProcessor.ProcessMessage(rr); } //throttling if (MessageProcessor.GetQueueSize() > 100) { Thread.Sleep(5000); } } } } } }
public async Task CompleteProcessingMessageAsync_Failure_AbandonsMessage() { OnMessageOptions options = new OnMessageOptions { AutoComplete = false }; MessageProcessor processor = new MessageProcessor(options); BrokeredMessage message = new BrokeredMessage(); FunctionResult result = new FunctionResult(false); var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => { await processor.CompleteProcessingMessageAsync(message, result, CancellationToken.None); }); // this verifies that we initiated the abandon Assert.True(ex.ToString().Contains("Microsoft.ServiceBus.Messaging.BrokeredMessage.BeginAbandon")); }
public EventSubscriber(IMessageQueueClient messageQueueClient, IHandlerProvider handlerProvider, ICommandBus commandBus, IMessagePublisher messagePublisher, string subscriptionName, string topic, string consumerId) { _MessageQueueClient = messageQueueClient; _handlerProvider = handlerProvider; _topic = topic; _consumerId = consumerId; _subscriptionName = subscriptionName; _messagePublisher = messagePublisher; _commandBus = commandBus; _messageProcessor = new MessageProcessor(new DefaultProcessingMessageScheduler <IMessageContext>()); _logger = IoCFactory.Resolve <ILoggerFactory>().Create(this.GetType()); }
static void TestMockQScenario1() { var q = new MockQ(); var exchangeName = "Test"; var publisher = q.GetMessagePublisher(exchangeName); var handlerRegistration = q.GetHandlerRegister(exchangeName); var are = new AutoResetEvent(false); var msgProcessor = new MessageProducer(publisher); Task.Factory.StartNew(msgProcessor.Run); Thread.Sleep(10000); var messageHandler = new MessageProcessor(handlerRegistration, are); are.WaitOne(); Console.WriteLine("Back to main thread"); Console.ReadKey(); }
static void Main() { // 3600 No transaction // 2800 Msmq transaction // 2000 Transaction scope / DTC Console.WriteLine("64bit: {0}", Environment.Is64BitProcess); var reader = new MessageProcessor(@".\private$\msmqnative", 4, MessageProcessor.MessageProcessorKind.TransactionScope //MessageProcessor.MessageProcessorKind.MsmqTransaction //MessageProcessor.MessageProcessorKind.NoTransaction ); reader.Open(); var p = new Program(); p.Init(); p.Loop(); }
public CommandConsumer(IMessageQueueClient messageQueueClient, IMessagePublisher messagePublisher, IHandlerProvider handlerProvider, string commandQueueName, string consumerId, ConsumerConfig consumerConfig = null) { _consumerConfig = consumerConfig ?? ConsumerConfig.DefaultConfig; _commandQueueName = commandQueueName; _handlerProvider = handlerProvider; _messagePublisher = messagePublisher; _consumerId = consumerId; _cancellationTokenSource = new CancellationTokenSource(); _messageQueueClient = messageQueueClient; _messageProcessor = new MessageProcessor(new DefaultProcessingMessageScheduler <IMessageContext>(), _consumerConfig.MailboxProcessBatchCount); _logger = IoCFactory.IsInit() ? IoCFactory.Resolve <ILoggerFactory>().Create(GetType().Name) : null; }
public async Task CompleteProcessingMessageAsync_Failure_AbandonsMessage() { OnMessageOptions options = new OnMessageOptions { AutoComplete = false }; MessageProcessor processor = new MessageProcessor(options); BrokeredMessage message = new BrokeredMessage(); FunctionResult result = new FunctionResult(false); var ex = await Assert.ThrowsAsync <InvalidOperationException>(async() => { await processor.CompleteProcessingMessageAsync(message, result, CancellationToken.None); }); // this verifies that we initiated the abandon Assert.True(ex.ToString().Contains("Microsoft.ServiceBus.Messaging.BrokeredMessage.BeginAbandon")); }
public void testModifyURL20() { String myip = getAddress(); string myhostname = Environment.MachineName.ToLower(); String exp = "https://" + myhostname + ":443/something"; String result = ""; //NO PORT DEFINED string url = "https://localhost/something"; exp = "https://" + myhostname + ":443/something"; //String expResult = ""; result = MessageProcessor.ModifyURL(url, false); Assert.AreEqual(exp, result, result); }
public CommandBus(IMessageQueueClient messageQueueClient, ILinearCommandManager linearCommandManager, string consumerId, string replyTopicName, string replySubscriptionName, ConsumerConfig consumerConfig = null) : base(messageQueueClient) { _consumerConfig = consumerConfig ?? ConsumerConfig.DefaultConfig; _consumerId = consumerId; _commandStateQueues = new ConcurrentDictionary <string, MessageState>(); _linearCommandManager = linearCommandManager; _replyTopicName = Configuration.Instance.FormatAppName(replyTopicName); _replySubscriptionName = Configuration.Instance.FormatAppName(replySubscriptionName); // _commandQueueNames = commandQueueNames; _messageProcessor = new MessageProcessor(new DefaultProcessingMessageScheduler <IMessageContext>(), _consumerConfig.MailboxProcessBatchCount); }
public async Task ProcessAsyncCallsPutAsyncAndReturnsOkResultWhenDataExists() { // Arrange var putHttpClientService = A.Fake <IHttpClientService>(); A.CallTo(() => putHttpClientService.PutAsync(A <RelatedCareersSegmentModel> .Ignored)).Returns(HttpStatusCode.OK); var putMessageProcessor = new MessageProcessor(putHttpClientService, mappingService); // Act var result = await putMessageProcessor .ProcessAsync(BaseMessage, SequenceNumber, MessageContentType.JobProfile, MessageAction.Published) .ConfigureAwait(false); // Assert A.CallTo(() => putHttpClientService.PutAsync(A <RelatedCareersSegmentModel> .Ignored)).MustHaveHappenedOnceExactly(); Assert.Equal(HttpStatusCode.OK, result); }
public void WhenUsingServiceWithoutProxyThenReturnsService() { // Arrange SimpleService service = new SimpleService(); this.dependencyResolver.Setup(d => d.GetService(typeof(ISimpleService))).Returns(service); this.configuration.ServiceProxyCreationEnabled = false; MessageProcessor processor = this.CreatTestableProcessor(); // Act var serviceDirect = processor.Use <ISimpleService>(); // Assert Assert.NotNull(serviceDirect); Assert.IsType(service.GetType(), serviceDirect); Assert.True(serviceDirect.GetType() == service.GetType()); }
public FixInitiatorDropCopy(FixSessionItem config) { _config = config; _bConectadoBolsa = false; _socketInitiator = null; _finalizarSinalizado = false; _intCanal = _config.Operador; _running = false; #if _CQUEUE _queueToDB = new ConcurrentQueue <TODropCopyDB>(); #else _queueToDB = new Queue <TODropCopyDB>(); #endif //_db = new DbDropCopy(); _rulesMsg = new MessageProcessor(); }
static void tcpClient_DataReceived(object sender, Tcp.DataReceivedEventArgs e) { try { bool compression = false; if (e.CustomHeader[0] == 1) { compression = true; } bool encryption = false; if (e.CustomHeader[1] == 1) { encryption = true; } byte[] packetBytes = e.ByteData; if (compression) { packetBytes = packetModifiers.DecompressPacket(packetBytes); } if (encryption) { packetBytes = packetModifiers.DecompressPacket(packetBytes); } if (e.CustomHeader[2] == 1) { // This was a packet list, process it int position = 0; while (position < packetBytes.Length) { int segmentSize = ByteEncoder.ByteArrayToInt(packetBytes, position); position += 4; MessageProcessor.HandleData(ByteEncoder.ByteArrayToString(packetBytes, position, segmentSize)); position += segmentSize; } } else { MessageProcessor.HandleData(ByteEncoder.ByteArrayToString(packetBytes)); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Packet:"); System.Diagnostics.Debug.WriteLine(ex.ToString()); System.Diagnostics.Debug.WriteLine(ex.StackTrace); } }
static void Main(string[] args) { AppDomain.CurrentDomain.SetData("DataDirectory", Application.StartupPath); CourseDBContext context = new CourseDBContext(); ObjectMessageQueue.InitializeQueue(ObjectMessageQueue.DB_REQUEST); ObjectMessageQueue queue = new ObjectMessageQueue(); while (true) { try { Object obj = queue.receiveObject(ObjectMessageQueue.DB_REQUEST); GenericRequest gen_req = obj as GenericRequest; if (gen_req == null) { Console.WriteLine("Error processing request, it is not a request object!"); queue.sendObject(null, ObjectMessageQueue.DB_RESPONSE); } else { Console.WriteLine("Fetching data..."); MessageProcessor parser = new MessageProcessor(context, gen_req); try { Object result = typeof(MessageProcessor).GetMethod(gen_req.Method.ToString()).Invoke(parser, null); Console.WriteLine("It worked!"); queue.sendResponse(result, ObjectMessageQueue.DB_RESPONSE); } catch (SqlException) { Console.WriteLine("An error occurred."); } } } catch (Exception e) { Console.WriteLine(e.ToString()); continue; } } }
public async Task ProcessAsyncCallsPatchAsyncWhenPatchUniformModelContentTypeSent() { // Arrange var fakeMapper = A.Fake <IMapper>(); var postMessageProcessor = new MessageProcessor(fakeMapper, httpClientService, mappingService); A.CallTo(() => fakeMapper.Map <PatchUniformModel>(A <PatchUniformServiceBusModel> .Ignored)).Returns(A.Fake <PatchUniformModel>()); A.CallTo(() => httpClientService.PatchAsync(A <PatchUniformModel> .Ignored, A <string> .Ignored)).Returns(HttpStatusCode.OK); // Act var result = await postMessageProcessor .ProcessAsync("{}", SequenceNumber, MessageContentType.Uniform, MessageActionType.Published) .ConfigureAwait(false); // assert A.CallTo(() => fakeMapper.Map <PatchUniformModel>(A <PatchUniformServiceBusModel> .Ignored)).MustHaveHappenedOnceExactly(); A.CallTo(() => httpClientService.PatchAsync(A <PatchUniformModel> .Ignored, A <string> .Ignored)).MustHaveHappenedOnceExactly(); Assert.Equal(HttpStatusCode.OK, result); }
public void Processor_Calls_Run_On_A_Message() { // Arrange bool runCalled = false; var message = new Message(() => runCalled = true); MessageQueue messageQueue = new MessageQueue(); messageQueue.Add(message); var processor = new MessageProcessor(messageQueue); // Act Task.Factory.StartNew(processor.Start); while (processor.QueueCount > 0) { Thread.Sleep(100); } processor.Stop(); // Assert Assert.IsTrue(runCalled); }
public async Task PlaceOrder_WithMessageQueuing_EventsArePublished() { IUnityContainer container = new UnityContainer(); Mock<ISpy> spy = new Mock<ISpy>(); container.RegisterInstance(typeof(ISpy), spy.Object); using (ProcessorConfiguration config = new ProcessorConfiguration()) { config.EnableInMemoryMessageQueuing(); config.RegisterContainer(container); using (MessageProcessor processor = new MessageProcessor(config)) { PlaceOrder command = new PlaceOrder(1); await processor.ProcessAsync(command); CancellationTokenSource cts = new CancellationTokenSource(5); await config.CommandBroker.StartAsync(cts.Token); // commands assertions spy.Verify(s => s.Spy("PlaceOrder"), Times.Once()); spy.Verify(s => s.Spy("MakePayment"), Times.Once()); spy.Verify(s => s.Spy("MakeReservation"), Times.Once()); spy.Verify(s => s.Spy("AddSeatsToWaitList"), Times.Never()); // events assertions spy.Verify(s => s.Spy("OrderConfirmed"), Times.Exactly(2)); spy.Verify(s => s.Spy("OrderCreated"), Times.Once()); spy.Verify(s => s.Spy("PaymentAccepted"), Times.Once()); spy.Verify(s => s.Spy("SeatsReserved"), Times.Once()); spy.Verify(s => s.Spy("SeatsNotReserved"), Times.Never()); // ctor assertions spy.Verify(s => s.Spy("OrderProcessManager ctor"), Times.Exactly(3)); spy.Verify(s => s.Spy("Order ctor"), Times.Exactly(2)); spy.Verify(s => s.Spy("Payment ctor"), Times.Once()); spy.Verify(s => s.Spy("Payment ctor"), Times.Once()); spy.Verify(s => s.Spy("Payment ctor"), Times.Once()); spy.Verify(s => s.Spy("Reservation ctor"), Times.Exactly(2)); } } }
public async Task CompleteProcessingMessageAsync_Success_CompletesMessage_WhenAutoCompleteFalse() { OnMessageOptions options = new OnMessageOptions { AutoComplete = false }; MessageProcessor processor = new MessageProcessor(options); BrokeredMessage message = new BrokeredMessage(); FunctionResult result = new FunctionResult(true); var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => { await processor.CompleteProcessingMessageAsync(message, result, CancellationToken.None); }); // The service bus APIs aren't unit testable, so in this test suite // we rely on exception stacks to verify APIs are called as expected. // this verifies that we initiated the completion Assert.True(ex.ToString().Contains("Microsoft.ServiceBus.Messaging.BrokeredMessage.BeginComplete")); }
public void should_not_run_expired_messages() { // Arrange bool runCalled = false; int timeToLive = 100; var message = new Message(() => runCalled = true, timeToLive); MessageQueue messageQueue = new MessageQueue(); var processor = new MessageProcessor(messageQueue); // Act Task.Factory.StartNew(processor.Start); Thread.Sleep(150); messageQueue.Add(message); while (processor.QueueCount > 0) { Thread.Sleep(100); } processor.Stop(); // Assert Assert.IsFalse(runCalled); }
private void ReadThread(object state) { var schema = new MessageSchema(); schema.Register(ClientMessageIds.LoginRequest, LoginRequest.GetRootAsLoginRequest); schema.Register(ClientMessageIds.InputRequest, InputRequest.GetRootAsInputRequest); var processor = new MessageProcessor(schema); processor.Attach((int)ClientMessageIds.LoginRequest, OnLoginRequest); processor.Attach((int)ClientMessageIds.InputRequest, OnInputRequest); var buffer = new byte[this.tcpClient.ReceiveBufferSize]; while (this.networkStream.CanRead) { int readSize; try { readSize = this.networkStream.Read(buffer, 0, buffer.Length); } catch (IOException) { readSize = 0; } if (readSize == 0) { logger.Info("Disconnected"); break; } var bytes = new byte[readSize]; Array.Copy(buffer, bytes, readSize); logger.Info("Received {0} bytes", readSize); processor.Enqueue(bytes); processor.Process(); } }
public Streamer(string frontendAddr, string backendAddr, MessageProcessor msgProc) : base(new Socket(SocketType.PUB), new Socket(SocketType.SUB)) { _frontend.Bind(frontendAddr); _backend.Connect(backendAddr); }
public ErrorHandlingMessageProcessor(MessageProcessor processor) { _processor = processor; _errorResolver = new ErrorResolver(); }