private void OnMessage(IReceiverLink receiver, global::Amqp.Message amqpMessage) { NmsMessage message; try { message = AmqpCodec.DecodeMessage(this, amqpMessage).AsMessage(); } catch (Exception e) { Tracer.Error($"Error on transform: {e.Message}"); // Mark message as undeliverable link.Modify(amqpMessage, true, true); return; } // Let the message do any final processing before sending it onto a consumer. // We could defer this to a later stage such as the NmsConnection or even in // the NmsMessageConsumer dispatch method if we needed to. message.OnDispatch(); InboundMessageDispatch inboundMessageDispatch = new InboundMessageDispatch { Message = message, ConsumerId = info.Id, ConsumerInfo = info, }; AddMessage(inboundMessageDispatch); IProviderListener providerListener = session.Connection.Provider.Listener; providerListener.OnInboundMessage(inboundMessageDispatch); }
private void OnMessage(IReceiverLink receiverLink, Message message) { try { var ret = false; try { ret = _MessageReceiver(message); } catch (Exception e) { Logger.Error("Exception in onMessageReceived!", e); } if (ret) { Logger.Debug("Message has been accepted."); receiverLink?.Accept(message); } } catch (Exception ex) { Logger.Error(ex.Message); } }
private static void OnMessageReceived(IReceiverLink receiver, Message message) { // Ack that we got the message. receiver.Accept(message); // Ignore messages that don't have a body if (message.Body == null) { return; } // Ignore messages that are not a serialized FiniteDto var dtoName = JsonDtoSerializer.GetDtoName(message.Body.ToString()); if (string.IsNullOrWhiteSpace(dtoName)) { return; } // TODO: recode this to not be a switch (instead a map) switch (dtoName) { case "DescriptiveTextDto": var dto = JsonDtoSerializer.DeserializeAs <DescriptiveTextDto>(message.Body.ToString()); Windows.WriteMainWindowDescriptiveText($"\r\n{dto.Text}"); break; } }
private static void OnMessage(IReceiverLink receiver, Message message) { AmqpTrace.WriteLine(TraceLevel.Information, "received command from controller"); int button = (int)message.ApplicationProperties["button"]; OnAction(button); }
public void Create(IMessageOptions options = null) { if (options != null) { if (options.Timeout > 0) { this._timeout = options.Timeout; } } var nodeAddress = this.ParseRpcNodeAddress(this._amqpNode); this._amqpNode = nodeAddress.Address; if (!string.IsNullOrEmpty(nodeAddress.Subject)) { this._subject = nodeAddress.Subject; } var _receiverSource = new Source() { Dynamic = true, Address = nodeAddress.Address }; this._receiver = this._session.CreateReceiver(name: $"AmqpNetLiteRpcClientReceiver-{this._amqpNode}", source: _receiverSource, onAttached: OnReceiverLinkAttached); this._receiver.Start(credit: int.MaxValue, onMessage: this.processResponse); this._sender = this._session.CreateSender(name: $"AmqpNetLiteRpcClientSender-{this._amqpNode}", target: new Target(), onAttached: OnSenderLinkAttached); if (!_receiverAttached.WaitOne(this._receiverAttacheTimeout)) { throw new Exception($"Failed to create receiver connection in {this._receiverAttacheTimeout}"); } }
protected void OnInboundMessage(IReceiverLink link, Amqp.Message message) { Message.Message msg = null; try { IMessage nmsMessage = Message.AMQP.AMQPMessageBuilder.CreateProviderMessage(this, message); msg = nmsMessage as Message.Message; if ( Session.AcknowledgementMode.Equals(AcknowledgementMode.AutoAcknowledge) || Session.AcknowledgementMode.Equals(AcknowledgementMode.ClientAcknowledge) ) { msg.GetMessageCloak().AckHandler = new Message.MessageAcknowledgementHandler(this, msg); } } catch (Exception e) { this.Session.OnException(e); } if (msg != null) { transportMsgCount++; SendForDelivery(new MessageDelivery(msg)); } }
protected virtual async void OnMessageCallback(IReceiverLink receiver, Message message) { try { // Get the body var rawBody = message.Body as string; var typeString = message.ApplicationProperties[MESSAGE_TYPE_KEY] as string; var dataType = EventTypeLookup[typeString]; var handlerType = typeof(IDomainEventHandler <>).MakeGenericType(dataType); var data = JsonConvert.DeserializeObject(rawBody, dataType); var handler = Provider.GetService(handlerType); if (handler != null) { //TODO: Update the way "Handle" is retrieved in a type safe way. var method = handlerType.GetTypeInfo().GetDeclaredMethod("Handle"); await(Task) method.Invoke(handler, new object[] { data }); receiver.Accept(message); } else { var desc = $"Handler not found for {typeString}"; Logger.LogWarning(desc); receiver.Reject(message); } } catch (Exception ex) { Logger.LogError(101, ex, ex.Message); receiver.Reject(message); } }
static void TheCallback(IReceiverLink link, Message message) { Interlocked.Increment(ref ReceivedMessages); try { var settings = new JsonSerializerSettings(); settings.TypeNameHandling = TypeNameHandling.Auto; settings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore; settings.DateParseHandling = DateParseHandling.None; var point = JsonConvert.DeserializeObject <Point>(message.Body.ToString(), settings); if (point.X > 99900) { sw1.Stop(); Console.WriteLine(sw1.Elapsed); } } catch (Exception err) { Console.WriteLine(err.Message); } Console.WriteLine(message.Body.ToString()); link.Accept(message); }
private static void OnMessage(IReceiverLink receiver, Message message) { // command received int setTemperature = (int)message.ApplicationProperties["settemp"]; OnAction(setTemperature); }
public void TestMethod_InterfaceSendReceive() { string testName = "InterfaceSendReceive"; const int nMsgs = 200; IConnection connection = new Connection(testTarget.Address); ISession session = connection.CreateSession(); ISenderLink sender = session.CreateSender("sender-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = new Message("msg" + i); message.Properties = new Properties() { GroupId = "abcdefg" }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; sender.Send(message, null, null); } IReceiverLink receiver = session.CreateReceiver("receiver-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = receiver.Receive(); Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.ApplicationProperties["sn"]); receiver.Accept(message); } connection.Close(); }
private static void ProcessMessage(IReceiverLink receiver, Message message) { var msg = Encoding.UTF8.GetString((byte[])message.Body); _receivedMessages.Add(msg); receiver.Accept(message); }
private void OnMessageReceived(IReceiverLink receiver, Message message) { List <CFXEnvelope> envelopes = null; try { envelopes = AmqpUtilities.EnvelopesFromMessage(message); } catch (Exception ex) { envelopes = null; AppLog.Error(ex); } if (envelopes != null && OnCFXMessageReceived != null) { try { receiver.Accept(message); envelopes.ForEach(env => OnCFXMessageReceived(new AmqpChannelAddress() { Uri = NetworkUri, Address = receiver.Name }, env)); } catch (Exception ex) { AppLog.Error(ex); } } }
static void TheCallback(IReceiverLink link, Message message) { //Interlocked.Increment(ref ReceivedMessages); //Console.WriteLine((Point)message.Body); link.Accept(message); }
private void OnMessage(IReceiverLink receiverLink, Message message) { _logger.LogDebug($"QueueListener Message received"); var pakjeMessage = message.GetBody <PakjeMessage>(); _receiverLink.Accept(message); Task.Run(() => _hubcontext.Clients.All.SendAsync("broadcastMessage", "queue", pakjeMessage)); }
// Método que será chamado toda vez que uma mensagem for recebida. private static void OnMessageCallback(IReceiverLink receiver, Message message) { try { /* * var serializer = new AmqpSerializer(new ContractResolver() * { * PrefixList = new[] { "Receiver" } * }); * * Cliente cliente = message.GetBody<Cliente>(serializer); * Console.WriteLine("Received {0}", cliente); * receiver.Accept(message); */ // Lendo a propriedade customizada var messageType = message.ApplicationProperties["Message.Type.FullName"]; // Variável para salvar o corpo da mensagem string body = string.Empty; // Pega o corpo var rawBody = message.Body; // Se o corpo é byte [] assume que foi enviado como uma BrokeredMessage // desserialize-o usando um XmlDictionaryReader if (rawBody is byte[]) { using (var reader = XmlDictionaryReader.CreateBinaryReader( new MemoryStream(rawBody as byte[]), null, XmlDictionaryReaderQuotas.Max)) { var doc = new XmlDocument(); doc.Load(reader); body = doc.InnerText; } } else // Se o corpo for uma string { body = rawBody.ToString(); } // Escrevendo o corpo no console Console.WriteLine(body); // Aceitando a mensagem receiver.Accept(message); } catch (Exception ex) { receiver.Reject(message); Console.WriteLine(ex); } }
protected override void ProcessMessage(IReceiverLink rec, Message msg) { var json = Encoding.UTF8.GetString((byte[])msg.Body); var record = JsonConvert.DeserializeObject <ChangeRecord <Solutions> >(json); var solution = record.NewVersion; // create SharePoint folder structure if (solution.Status == SolutionStatus.Registered) { _evidenceBlobStoreLogic.PrepareForSolution(solution.Id); } }
private async void RemoveReceiver_Click(object sender, EventArgs e) { if (receiversListBox.SelectedItem == null) { return; } ReceiverLinkWrapper wrapper = (ReceiverLinkWrapper)receiversListBox.SelectedItem; IReceiverLink receiverLink = wrapper.ReceiverLink; await receiverLink.CloseAsync(); receivers.Remove(wrapper); }
public void OnMessage(IReceiverLink link, Message message) { ConnectionManager.WriteLine($"Called, and using the message: {message.Body}"); ConnectionManager.WriteLine($"Accepting message number ..please wait"); var content = message.Body; var bytes = (byte[])content; File.WriteAllBytes($@"C:\Temp\ELNOutput\{message.ApplicationProperties["CamelFileName"]}", bytes); link.Accept(message); }
static private void OnMessage(IReceiverLink receiveLink, Message message) { Data data = (Data)message.BodySection; Console.WriteLine(UTF8Encoding.UTF8.GetString(data.Binary)); if (message.ApplicationProperties != null) { foreach (var property in message.ApplicationProperties.Map) { Console.WriteLine($" Key:{property.Key} Value:{property.Value}"); } } receiveLink.Accept(message); }
private void OnMessageCallback(IReceiverLink receiver, Message message) { try { //var messageType = message.ApplicationProperties["Message.Type.FullName"]; this.cliente = message.GetBody <Cliente>(serializer); Console.WriteLine("Received {0}", this.cliente); receiver.Accept(message); } catch (Exception ex) { receiver.Reject(message); Console.WriteLine(ex); } }
private static void OnMessage(IReceiverLink receiver, Message message) { Console.WriteLine("Message received"); try { // command received double.TryParse((string)message.ApplicationProperties["setlat"], out latitude); double.TryParse((string)message.ApplicationProperties["setlon"], out longitude); Console.WriteLine($"== Received new Location setting: Lat - {latitude}, Lon - {longitude} =="); } catch (Exception ex) { Console.WriteLine($"-- C2D Error - {ex.Message} --"); } }
private void processResponse(IReceiverLink receiver, Message message) { receiver.Accept(message); if (!this._pendingRequests.TryRemove(message.Properties.CorrelationId, out var tcs)) { Console.WriteLine($"No pending response for {message.Properties.CorrelationId}"); } if (!this._isTimedout) { var response = message.GetBody <AmqpRpcResponse>(); if (tcs != null) { tcs.SetResult(response); } } }
public void EurexMessageCallback(IReceiverLink receiver, Message message) { Log.DebugFormat("EurexMessageCallback"); if (message == null) { Log.WarnFormat("receiver.Receive(600000) is timeout."); return; } Amqp.Framing.Data payload = (Amqp.Framing.Data)message.BodySection; String payloadText = Encoding.UTF8.GetString(payload.Binary); Log.DebugFormat("Received message: {0}", payloadText); receiver.Accept(message); }
private void OnMessageReceived(IReceiverLink receiver, Message message) { List <CFXEnvelope> envelopes = null; try { envelopes = AmqpUtilities.EnvelopesFromMessage(message); } catch (Exception ex) { envelopes = null; AppLog.Error(ex); } if (envelopes == null || (envelopes != null && envelopes.Count < 1)) { try { receiver.Accept(message); AppLog.Error(string.Format("Malformed Message Received: {0}", AmqpUtilities.MessagePreview(message))); Endpoint?.Channel_OnMalformedMessageReceived(new AmqpChannelAddress() { Uri = NetworkUri, Address = receiver.Name }, AmqpUtilities.StringFromEnvelopes(message)); } catch (Exception ex) { AppLog.Error(ex); } } else if (envelopes != null && OnCFXMessageReceived != null) { try { receiver.Accept(message); envelopes.ForEach(env => OnCFXMessageReceived(new AmqpChannelAddress() { Uri = NetworkUri, Address = receiver.Name }, env)); } catch (Exception ex) { AppLog.Error(ex); } } }
public void TestMethod_InterfaceSendReceiveOnAttach() { string testName = "InterfaceSendReceiveOnAttach"; const int nMsgs = 200; int nAttaches = 0; OnAttached onAttached = (link, attach) => { nAttaches++; }; IConnection connection = new Connection(testTarget.Address); ISession session = connection.CreateSession(); ISenderLink sender = session.CreateSender("sender-" + testName, new Target() { Address = testTarget.Path }, onAttached); for (int i = 0; i < nMsgs; ++i) { Message message = new Message("msg" + i); message.Properties = new Properties() { GroupId = "abcdefg" }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; sender.Send(message, null, null); } IReceiverLink receiver = session.CreateReceiver("receiver-" + testName, new Source() { Address = testTarget.Path }, onAttached); for (int i = 0; i < nMsgs; ++i) { Message message = receiver.Receive(); Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.ApplicationProperties["sn"]); receiver.Accept(message); } Assert.AreEqual(2, nAttaches); connection.Close(); }
/// <summary> /// Method that will be called every time a message is received. /// </summary> static void OnMessageCallback(IReceiverLink receiver, Amqp.Message message) { try { // You can read the custom property var messageType = message.ApplicationProperties["Message.Type.FullName"]; // Variable to save the body of the message. string body = string.Empty; // Get the body var rawBody = message.Body; // If the body is byte[] assume it was sent as a BrokeredMessage // and deserialize it using a XmlDictionaryReader if (rawBody is byte[]) { using (var reader = XmlDictionaryReader.CreateBinaryReader( new MemoryStream(rawBody as byte[]), null, XmlDictionaryReaderQuotas.Max)) { var doc = new XmlDocument(); doc.Load(reader); body = doc.InnerText; } } else // Asume the body is a string { body = rawBody.ToString(); } // Write the body to the Console. Console.WriteLine(body); // Accept the messsage. receiver.Accept(message); } catch (Exception ex) { receiver.Reject(message); Console.WriteLine(ex); } }
private void InvokeHandler( IReceiverLink receiverLink, Message amqpMessage, IMessage message, HostItemSubscriber subscriber) { try { DispatchModule.InvokeDispatcherInNewLifetimeScopeAsync( subscriber.DispatchInfo, message).GetAwaiter().GetResult(); receiverLink.Accept(amqpMessage); } catch (Exception ex) { LogMessageReceiveEx(ex, message, subscriber.DispatchInfo); receiverLink.Reject(amqpMessage); } }
public async Task InterfaceSendReceiveAsync() { string testName = "BasicSendReceiveAsync"; int nMsgs = 100; IConnectionFactory factory = new ConnectionFactory(); IConnection connection = await factory.CreateAsync(this.testTarget.Address); ISession session = connection.CreateSession(); ISenderLink sender = session.CreateSender("sender-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = new Message(); message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; await sender.SendAsync(message); } IReceiverLink receiver = session.CreateReceiver("receiver-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = await receiver.ReceiveAsync(Timeout.InfiniteTimeSpan); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.ApplicationProperties["sn"]); receiver.Accept(message); } await sender.CloseAsync(); await receiver.CloseAsync(); await session.CloseAsync(); await connection.CloseAsync(); }
protected void ReceiveMessages(HostItemSubscriber subscriber, IReceiverLink receiverLink) { subscriber.SetReceiverLink(receiverLink); receiverLink.Closed += (sender, error) => { LogItemClosed(error); }; // Start message pump that will be called when a message // is published to the host item. receiverLink.Start(subscriber.HostItemAttribute.LinkCredit, (receiver, amqpMessage) => { // Deserialize the message body into the the .NET types associated // with the handler to which the message should be dispatched. Type messageType = subscriber.DispatchInfo.MessageType; IMessage message = DeserializeMessage(amqpMessage, messageType); SetMessageApplicationProperties(amqpMessage, message); // Invoke the handler associated with the message. InvokeHandler(receiver, amqpMessage, message, subscriber); }); }
private void OnMessage(IReceiverLink receiverLink, Message message) { Logger.Debug($"Message Received: Queue {_queueName}\n{message?.Body}"); try { if (MessageReceiver == null) { return; } //var props = message.ApplicationProperties?.Map; //if (props == null) //{ // _receiverLink?.Accept(message); // return; //} var ret = false; try { ret = MessageReceiver.Invoke(message); } catch (Exception e) { Logger.Error("Exception in onMessageReceived!", e); } if (ret) { Logger.Debug("Message has been accepted."); _receiverLink?.Accept(message); } } catch (Exception ex) { Logger.Error(ex.Message); } }