public void Parse_ValidMessage_ParsesSyslogMessage(SampleMessage testCase) { var target = new RegexSyslogMessageParser(); var actualMessage = target.Parse(testCase.GetMessageBytes()); AssertEqual(testCase.ExpectedMessage, actualMessage); }
static Task <DedupeResult> SendMessage(IEndpointInstance endpoint, Guid guid) { var message = new SampleMessage(); var options = new SendOptions(); options.RouteToThisEndpoint(); return(endpoint.SendWithDedupe(guid, message, options)); }
protected void ReceiveMessage(NetworkMessage networkMessage) { SampleMessage message = networkMessage.ReadMessage <SampleMessage>(); this.value = message.value; Debug.Log("RECEIVE : " + message.value); }
public void SendMessage() { SampleMessage message = new SampleMessage() { value = this.value }; NetworkServer.SendToAll(SampleMessageType.SampleMessage, message); }
public ActionResult About() { var myExample = new SampleMessage(); var error = myExample.SendSample(); ViewBag.Response = "Your error is " + error; return(View()); }
public void TryParse_ValidMessage_ParsesSyslogMessage(SampleMessage testCase) { var target = new RegexSyslogMessageParser(); SyslogMessage actualMessage; Assert.True(target.TryParse(testCase.GetMessageBytes(), out actualMessage)); AssertEqual(testCase.ExpectedMessage, actualMessage); }
private void listBoxSample_SelectedIndexChanged(object sender, EventArgs e) { SampleMessage msg = this.listBoxSample.SelectedItem as SampleMessage; if (msg != null) { this.textBoxSend.Text = msg.GetMessage(); } }
public void ConstructorReturnsSampleMessage() { const string key = "some-key-1"; const string someProperty = "some-property-value"; var sut = new SampleMessage(key, someProperty); Assert.Equal(key, sut.Key); Assert.Equal(someProperty, sut.SomeProperty); }
public async Task Should_handle_a_string_null() { var repository = new InMemoryMessageDataRepository(); var dataId = new InMemoryMessageDataId().Uri; var obj = new SampleMessage { Value = await repository.PutString("Hello, World!") }; Serialize(obj); }
static async Task MainAsync(string[] args) { // This message source will open a HTTP port to receive POST requests. HttpMessageSource <SampleMessage> httpMessageSource = new HttpMessageSourceBuilder <SampleMessage>() .ListenInUrl(_messageSourceUrl) .UseHttpRequestParser(new HttpRequestJsonParser <SampleMessage>()) .Build(); // This message processor will process messages received and published by the message source. MessageProcessor <SampleMessage> messageProcessor = new SampleMessageProcessor(httpMessageSource); Console.WriteLine("Press any key to start message processing."); Console.ReadLine(); Console.WriteLine("Starting..."); // Will not block. await messageProcessor.StartAsync(); while (true) { // Enter raw text to send to the message source. Console.WriteLine($"Enter message to send to HTTP message source in {_messageSourceUrl}:"); string input = Console.ReadLine(); // Do nothing if input is empty. if (string.IsNullOrEmpty(input)) { continue; } // Stop if triggered. if (string.Equals(input, "stop", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("Stopping..."); // Wait til last message is finished. await messageProcessor.StopAsync(); break; } // Create message. var message = new SampleMessage() { Message = input }; Console.WriteLine("-------------------------------------------------------------------------------------------------------------"); Console.WriteLine($"Sending message to HTTP message source for processing: | Id=[{message.Id}] | Message=[{message.Message}] |"); Console.WriteLine("-------------------------------------------------------------------------------------------------------------"); // Send message to the HttpMessageSource. await _httpClient.PostAsync(_messageSourceUrl, new StringContent(JsonConvert.SerializeObject(message))); } }
public void SampleMessageFieldParams() { var defaultSerializer = new DefaultSerializer<SampleMessage>(this.messageRegistry, this.typeRegistry); var d = new MessageDispatcher<SampleApiClass>(this.messageRegistry, this.typeRegistry); using (var buf = new ThreadSafeWriteQueue(1024)) { var orig = new SampleMessage { MessageId = defaultSerializer.MessageId, A = 10 }; defaultSerializer.Serialize(buf, orig); var pos = buf.ReadMessage(); Assert.IsTrue(d.Dispatch(buf, pos, defaultSerializer.MessageId, new SampleApiClass())); } }
public void AddSampleMessage(SampleMessage message) { using (var session = this.Cluster.Connect(Settings.Default.CassandraMessageStoreKeyspace)) { var sampleMessagesTable = session.GetTable <SampleMessage>(); var batch = session.CreateBatch(); batch.Append(sampleMessagesTable.Insert(message)); batch.Execute(); } }
public async Task Should_handle_a_string_null() { var repository = new InMemoryMessageDataRepository(); var dataId = new InMemoryMessageDataId().Uri; var obj = new SampleMessage { Value = await repository.PutString(new string('*', MessageDataDefaults.Threshold + 100)) }; Serialize(obj); }
public async Task <IActionResult> Post([FromBody] SampleMessage message) { try { var result = await messaging.Send(message); return(StatusCode(result.Code, result.Value)); } catch (Exception) { return(StatusCode(500)); } }
public SampleMessage SaveSampleMessage(SampleMessage message) { var request = new RestRequest { Resource = "Api/Messages", RequestFormat = DataFormat.Json, Method = Method.POST }; request.AddBody(message); return(this.SendRequest <SampleMessage>(request)); }
public RestRequestAsyncHandle SaveSampleMessageAsync(SampleMessage message, Action <IRestResponse <SampleMessage>, RestRequestAsyncHandle> callback) { var request = new RestRequest { Resource = @"Api/Messages", RequestFormat = DataFormat.Json, Method = Method.POST }; request.AddBody(message); return(this.SendRequestAsync(request, callback)); }
static void Main(string[] args) { var config = ConfigHelper.GetAppSettingsConfig(); var publisher = new Publisher(config); var message = new SampleMessage { TimeCode = DateTime.UtcNow, Message = $"Hello I'm Producer" }; publisher.Publish(message); }
public void ShouldSerializeSpecialSymbols() { var memoryStrem = new MemoryStream(); //Special character with hexadecimal value 0x15 is inserted in Name. It is not empty. var sampleMessage = new SampleMessage { Name = "" }; new AdvancedXmlSerializer().Serialize(new IMessage[] { sampleMessage }, memoryStrem); memoryStrem.Seek(0, SeekOrigin.Begin); var res = new AdvancedXmlSerializer().Deserialize(memoryStrem)[0] as SampleMessage; res.Name.Should(Be.Not.Empty); }
public void ShouldSerializeValueTypeArrays() { var message = new SampleMessage { Bytes = new byte[] { 1, 2, 3 } }; var bytesEncoded = Convert.ToBase64String(message.Bytes); var serialized = _serializer.Serialize(message); serialized.InnerText.Should(Is.StringContaining(bytesEncoded)); var deserialized = (SampleMessage)_deserializer.Deserialize(serialized); deserialized.Bytes.Should(Is.EquivalentTo(message.Bytes)); }
public void UpdateSampleMessage(Guid id, SampleMessage message) { using (var session = this.Cluster.Connect(Settings.Default.CassandraMessageStoreKeyspace)) { var sampleMessagesTable = session.GetTable <SampleMessage>(); sampleMessagesTable .Where(item => item.Id == id) .Select(item => new SampleMessage { Data = message.Data }) .Update() .Execute(); } }
/// <summary> /// Push msmq message /// </summary> /// <param name="msmqProviderFactory"></param> private static void MsmqPushMessage(IMsmqProviderFactory msmqProviderFactory) { using (var messageQueue = msmqProviderFactory.Create <SampleMessage>(Serializer.Json, "message_queue_sample_console")) { for (int i = 0; i < 5; i++) { var sampleMessage = new SampleMessage { SampleMessageId = i, Name = "Sample Message", Created = DateTime.UtcNow }; messageQueue.PushAsync(new QueueMessage <SampleMessage>(sampleMessage)).Wait(); } } }
static async Task MainAsync(string[] args) { // This queue will be the source of message for InMemoryQueuePollingMessageSource. Queue <SampleMessage> queue = new Queue <SampleMessage>(); // This message source will check the queue for any newly enqueued message every 1 second. IMessageSource <SampleMessage> messageSource = new InMemoryQueuePollingMessageSource(queue, pollingInterval: TimeSpan.FromSeconds(1)); // This message processor will process messages received and published by the message source. MessageProcessor <SampleMessage> messageProcessor = new SampleMessageProcessor(messageSource); Console.WriteLine("Press any key to start message processing."); Console.ReadLine(); Console.WriteLine("Starting..."); // Will not block. await messageProcessor.StartAsync(); while (true) { Console.WriteLine("Enter number of messages to queue:"); string input = Console.ReadLine(); if (string.Equals(input, "stop", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("Stopping..."); // Wait till last message is finished. await messageProcessor.StopAsync(); break; } if (int.TryParse(input, out int num)) { for (int i = 0; i < num; i++) { var message = new SampleMessage(); Console.WriteLine($"Message {message.Id}: Queued for processing."); // Newly queued message will be detected by the InMemoryQueuePollingMessageSource // and will publish the new message to be processed by SampleMessageProcessor. queue.Enqueue(message); } } } }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { var count = 0; while (!stoppingToken.IsCancellationRequested) { var sampleMessage = new SampleMessage($"sample-key-{count}", "sample-property"); await _messageProducer.ProduceAsync(sampleMessage.Key, sampleMessage, stoppingToken); var anotherSampleMessage = new AnotherSampleMessage($"another-sample-key-{count}", "another-property"); await _messageProducer.ProduceAsync(anotherSampleMessage.Key, anotherSampleMessage, stoppingToken); var otherSampleMessage = new OtherSampleMessage($"other-sample-key-{count}", "some-other-property"); await _messageProducer.ProduceAsync(otherSampleMessage.Key, otherSampleMessage, stoppingToken); _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); count++; } }
public async Task <IActionResult> Post([FromBody] SampleMessage value) { if (value == null) { return(BadRequest(new { error = "Request body missing" })); } try { await _messageSender.SendMessage(new SampleMessage { Body = value.Body ?? "empty" }); return(Ok()); } catch (Exception ex) { _logger?.LogError(ex, "Failed to send message"); } return(StatusCode((int)HttpStatusCode.InternalServerError, new { error = "Failed to send message." })); }
public void HandleLogsSampleMessageProperties() { var mockLogger = new Mock <ILogger <SampleMessageLoggerHandler> >(); var sut = new SampleMessageLoggerHandler(mockLogger.Object); const string expectedKey = "some-key"; const string expectedSomePropertyValue = "some-property-value"; var sampleMessage = new SampleMessage(expectedKey, expectedSomePropertyValue); sut.Handle(new MessageNotification <SampleMessage>(sampleMessage), CancellationToken.None); mockLogger.Verify( x => x.Log( LogLevel.Information, It.IsAny <EventId>(), It.Is <It.IsAnyType>((o, t) => string.Equals( $"Sample message received with key: {expectedKey} and value: {expectedSomePropertyValue}", o.ToString(), StringComparison.InvariantCultureIgnoreCase)), It.IsAny <Exception>(), (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()), Times.Once); }
private void HandleSampleMessage(SampleMessage message) { System.Console.WriteLine($"Recieved message:\n {JsonConvert.SerializeObject(message)}"); }
public void Handle(SampleMessage message) { throw new NotImplementedException(); }
public Task Handle(SampleMessage message) { throw new NotImplementedException(); }
public void Handle(SampleMessage message) { }
public bool OnSampleMessage(SampleMessage message) { Assert.Pass("Ok!"); return true; }
private void ReceiveSampleMessage(SampleMessage message) { CanInvokeService = true; InvokedMessage = string.Format(LabelTextTemplate, message.InvokedCount); }
static async Task Main(string[] args) { var services = new ServiceCollection(); const string producerName = "sample-producer"; services.AddKafka( kafka => kafka .UseConsoleLog() .AddCluster( cluster => cluster .WithBrokers(new[] { "localhost:9092" }) // .AddConsumer(consumer => consumer // .Topic("test-topic") // .WithGroupId("print-console-handler") // .WithBufferSize(100) // .WithWorkersCount(10) // .WithAutoOffsetReset(AutoOffsetReset.Latest) // .AddMiddlewares(middlewares => middlewares // // Install KafkaFlow.Compressor and Install KafkaFlow.Compressor.Gzip // .AddCompressor<GzipMessageCompressor>() // // Install KafkaFlow.Serializer and Install KafkaFlow.Serializer.Protobuf // .AddSerializer<ProtobufMessageSerializer>() // // Install KafkaFlow.TypedHandler // .AddTypedHandlers(handlers => handlers // .WithHandlerLifetime(InstanceLifetime.Singleton) // .AddHandler<PrintConsoleHandler>()) // ) // ) .AddProducer( producerName, producer => producer .DefaultTopic("presentation-topic") .AddMiddlewares( middlewares => middlewares .AddSerializer <NewtonsoftJsonMessageSerializer>() ) ) ) ); var provider = services.BuildServiceProvider(); var bus = provider.CreateKafkaBus(); var producer = bus.Producers[producerName]; while (true) { Console.WriteLine("Message count: "); var input = Console.ReadLine(); if (input == "exit") { return; } if (int.TryParse(input, out var count)) { for (int i = 0; i < count; i++) { var message = new SampleMessage { Id = Guid.NewGuid(), Value = "Message Value - " + Guid.NewGuid() }; producer.Produce(message.Id.ToString(), message); } } } }
public void OnMessageReceived(SampleMessage message) => _logger.LogInformation($"Received {message.Number}");
public void CreateSampleMessageName(string sampleMessageName) { _message = new SampleMessage { Name = sampleMessageName, SagaId = Guid.NewGuid() }; }