private void Send_Click(object sender, EventArgs e) { if (senderLink == null) { AddSender(); if (senderLink == null) { return; } } Data data = new Data(); data.Binary = input.SelectedBinaryValue; Amqp.Message message = new Amqp.Message(); message.BodySection = data; message.Header = new Header() { }; message.Properties = new Amqp.Framing.Properties(); if (!string.IsNullOrWhiteSpace(subject.Text)) { message.Properties.Subject = subject.Text; } try { senderLink.Send(message, (s, m, outcome, state) => { }, null); } catch (AmqpException ex) { MessageBox.Show(this, ex.Message); return; } }
private void AckReleased(IMessageDelivery delivery) { Message.Message nmsMessage = delivery.Message; Tracer.DebugFormat("Consumer {0} Acking Released for Message {1} ", ConsumerId, nmsMessage.NMSMessageId); Amqp.Message amqpMessage = (nmsMessage.GetMessageCloak() as Message.AMQP.AMQPMessageCloak).AMQPMessage; this.Link.Release(amqpMessage); }
async Task ReplyAsync(RequestContext requestContext) { if (this.offset == 0) { this.offset = (int)requestContext.Message.ApplicationProperties["offset"]; } while (this.offset < 1000) { try { Message response = new Message("reply" + this.offset); response.ApplicationProperties = new ApplicationProperties(); response.ApplicationProperties["offset"] = this.offset; requestContext.ResponseLink.SendMessage(response); this.offset++; } catch (Exception exception) { Console.WriteLine("Exception: " + exception.Message); if (requestContext.State == ContextState.Aborted) { Console.WriteLine("Request is aborted. Last offset: " + this.offset); return; } } await Task.Delay(1000); } requestContext.Complete(new Message("done")); }
/// <summary> /// Receives the next transport message or null if none is available. Can block if it wants to, just respect the <paramref name="cancellationToken"/> /// </summary> public override async Task<TransportMessage> Receive(ITransactionContext context, CancellationToken cancellationToken) { if (amqpReceiver == null) return null; AmqpLite.Message msg = await amqpReceiver.ReceiveAsync(TimeSpan.FromSeconds(0.5)); if (msg == null) return null; if (!(msg.Properties?.AbsoluteExpiryTime != DateTime.MinValue && msg.Properties?.AbsoluteExpiryTime.ToUniversalTime() > DateTime.Now.ToUniversalTime())) return null; context.OnCompleted(async ctx => { amqpReceiver.Accept(msg); }); context.OnAborted(async ctx => { amqpReceiver.Modify(msg, true); }); context.OnDisposed(async ctx => { //amqpReceiver.Close(); }); var result = new TransportMessage(GetHeaders(msg), GetBytes(msg.Body.ToString())); return result; }
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)); } }
public Task<byte[]> DeclareAsync() { Message message = new Message(new Declare()); TaskCompletionSource<byte[]> tcs = new TaskCompletionSource<byte[]>(); this.Send(message, null, OnOutcome, tcs); return tcs.Task; }
public Task DischargeAsync(byte[] txnId, bool fail) { Message message = new Message(new Discharge() { TxnId = txnId, Fail = fail }); TaskCompletionSource<byte[]> tcs = new TaskCompletionSource<byte[]>(); this.Send(message, null, OnOutcome, tcs); return tcs.Task; }
public void TestMethod_BasicSendReceive() { string testName = "BasicSendReceive"; const int nMsgs = 200; Connection connection = new Connection(testTarget.Address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "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); } ReceiverLink receiver = new ReceiverLink(session, "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); } sender.Close(); receiver.Close(); session.Close(); connection.Close(); }
public async Task CustomMessgeBody() { string testName = "CustomMessgeBody"; Connection connection = await Connection.Factory.CreateAsync(this.address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); Student student = new Student("Tom"); student.Age = 16; student.Address = new StreetAddress() { FullAddress = "100 Main St. Small Town" }; student.DateOfBirth = new System.DateTime(1988, 5, 1, 1, 2, 3, 100, System.DateTimeKind.Utc); Message message = new Message(student); message.Properties = new Properties() { MessageId = "student" }; await sender.SendAsync(message); ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); Message message2 = await receiver.ReceiveAsync(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message2.Properties); receiver.Accept(message); await sender.CloseAsync(); await receiver.CloseAsync(); await session.CloseAsync(); await connection.CloseAsync(); Student student2 = message2.GetBody<Student>(); Assert.AreEqual(student.Age, student2.Age - 1); // incremented in OnDeserialized Assert.AreEqual(student.DateOfBirth, student2.DateOfBirth); Assert.AreEqual(student.Address.FullAddress, student2.Address.FullAddress); }
private static void OnOutcome(ILink sender, Amqp.Message message, Outcome outcome, object state) { var tcs = (TaskCompletionSource <bool>)state; var link = (Link)sender; if (outcome.Descriptor.Code == MessageOutcomes.Accepted.Descriptor.Code) { tcs.TrySetResult(true); } else if (link.IsDetaching() || link.IsClosed) { tcs.TrySetException(new ProducerClosedException("Producer detached.")); } else if (outcome.Descriptor.Code == MessageOutcomes.Rejected.Descriptor.Code) { var rejected = (Rejected)outcome; tcs.TrySetException(new MessageSendException(rejected.Error.Description, rejected.Error.Condition)); } else if (outcome.Descriptor.Code == MessageOutcomes.Released.Descriptor.Code) { tcs.TrySetException(new MessageSendException("Message was released by remote peer.", ErrorCode.MessageReleased)); } else { tcs.TrySetException(new MessageSendException(outcome.ToString(), ErrorCode.InternalError)); } }
public async Task WebSocketSendReceiveAsync() { string testName = "WebSocketSendReceiveAsync"; // assuming it matches the broker's setup and port is not taken Address wsAddress = new Address("ws://*****:*****@localhost:18080"); int nMsgs = 50; Connection connection = await Connection.Factory.CreateAsync(wsAddress); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); 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); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); for (int i = 0; i < nMsgs; ++i) { Message message = await receiver.ReceiveAsync(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.ApplicationProperties["sn"]); receiver.Accept(message); } await sender.CloseAsync(); await receiver.CloseAsync(); await session.CloseAsync(); await connection.CloseAsync(); }
public void SendData(string data) { if (_connection == null) { Connect(); } Amqp.Message message = new Amqp.Message() { BodySection = new Amqp.Framing.Data() { Binary = System.Text.Encoding.UTF8.GetBytes(data) } }; ManualResetEvent acked = new ManualResetEvent(false); message.MessageAnnotations = new Amqp.Framing.MessageAnnotations(); message.MessageAnnotations[new Amqp.Types.Symbol("x-opt-partition-key")] = string.Format("pk:", _partitionkey); try { _senderlink.Send(message); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Sending failed"); _connection = null; } }
static void RunRequestClient(string address) { Connection connection = new Connection(new Address(address)); Session session = new Session(connection); string replyTo = "client-reply-to"; Attach recvAttach = new Attach() { Source = new Source() { Address = "request_processor" }, Target = new Target() { Address = replyTo } }; ReceiverLink receiver = new ReceiverLink(session, "request-client-receiver", recvAttach, null); SenderLink sender = new SenderLink(session, "request-client-sender", "request_processor"); Message request = new Message("hello"); request.Properties = new Properties() { MessageId = "request1", ReplyTo = replyTo }; sender.Send(request, null, null); Console.WriteLine("Sent request {0} body {1}", request.Properties, request.Body); Message response = receiver.Receive(); Console.WriteLine("Received response: {0} body {1}", response.Properties, response.Body); receiver.Accept(response); receiver.Close(); sender.Close(); session.Close(); connection.Close(); }
public void SetObject(object o) { if (o == null) { amqpMessage.BodySection = MessageSupport.NULL_AMQP_VALUE_BODY; } else if (IsNMSObjectTypeSupported(o)) { object value = null; if (o is IList) { value = ConversionSupport.ListToAmqp(o as IList); } else if (o is IPrimitiveMap) { value = ConversionSupport.NMSMapToAmqp(o as IPrimitiveMap); } else { value = o; } // to copy the object being set encode a message then decode and take body Amqp.Message copy = new Amqp.Message(value); ByteBuffer buffer = copy.Encode(); copy = Message.Decode(buffer); amqpMessage.BodySection = new AmqpValue { Value = copy.Body }; } else { throw new ArgumentException("Encoding unexpected object type: " + o.GetType().Name); } }
internal JavaObjectSerializer(AMQPObjectMessageCloak msg) { amqpMessage = msg.AMQPMessage; message = msg; message.SetContentType(SymbolUtil.SERIALIZED_JAVA_OBJECT_CONTENT_TYPE); message.SetMessageAnnotation(MessageSupport.JMS_JAVA_ENCODING, SymbolUtil.BOOLEAN_TRUE); }
/// <summary> /// Sends a message asynchronously. /// </summary> /// <param name="sender">The link.</param> /// <param name="message">The message.</param> /// <returns></returns> public static async Task SendAsync(this SenderLink sender, Message message) { var txnState = await TaskExtensions.GetTransactionalStateAsync(sender); TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); sender.Send( message, txnState, (m, o, s) => { var t = (TaskCompletionSource<object>)s; if (o.Descriptor.Code == Codec.Accepted.Code) { t.SetResult(null); } else if (o.Descriptor.Code == Codec.Rejected.Code) { t.SetException(new AmqpException(((Rejected)o).Error)); } else { t.SetException(new AmqpException(ErrorCode.InternalError, o.Descriptor.Name)); } }, tcs); await tcs.Task; }
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); } }
internal AMQPMessageCloak(MessageConsumer c, Amqp.Message msg) { message = msg; consumer = c; connection = c.Session.Connection; InitMessage(); InitDeliveryAnnotations(); }
private void AckConsumed(IMessageDelivery delivery) { Message.Message nmsMessage = delivery.Message; Tracer.DebugFormat("Consumer {0} Acking Accepted for Message {1} ", ConsumerId, nmsMessage.NMSMessageId); delivered.Remove(delivery); Amqp.Message amqpMessage = (nmsMessage.GetMessageCloak() as Message.AMQP.AMQPMessageCloak).AMQPMessage; this.Link.Accept(amqpMessage); }
public Task <byte[]> DeclareAsync(CancellationToken cancellationToken) { var message = new Amqp.Message(new Declare()); var tcs = TaskUtil.CreateTaskCompletionSource <byte[]>(cancellationToken); _senderLink.Send(message, null, _onDeclareOutcome, tcs); return(tcs.Task); }
private static void OnOutcome(ILink sender, Amqp.Message message, Outcome outcome, object state) { var tcs = (TaskCompletionSource <Message>)state; if (outcome.Descriptor.Code != MessageOutcomes.Accepted.Descriptor.Code) { tcs.TrySetException(new MessageSendException(outcome.ToString(), ErrorCode.InternalError)); } }
public void TransactedPosting() { string testName = "TransactedPosting"; int nMsgs = 5; Connection connection = new Connection(this.address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); // commit using (var ts = new TransactionScope()) { for (int i = 0; i < nMsgs; i++) { Message message = new Message("test"); message.Properties = new Properties() { MessageId = "commit" + i, GroupId = testName }; sender.Send(message); } ts.Complete(); } // rollback using (var ts = new TransactionScope()) { for (int i = nMsgs; i < nMsgs * 2; i++) { Message message = new Message("test"); message.Properties = new Properties() { MessageId = "rollback" + i, GroupId = testName }; sender.Send(message); } } // commit using (var ts = new TransactionScope()) { for (int i = 0; i < nMsgs; i++) { Message message = new Message("test"); message.Properties = new Properties() { MessageId = "commit" + i, GroupId = testName }; sender.Send(message); } ts.Complete(); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); for (int i = 0; i < nMsgs * 2; i++) { Message message = receiver.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId); receiver.Accept(message); Assert.IsTrue(message.Properties.MessageId.StartsWith("commit")); } connection.Close(); }
/// <summary> /// Constructor from an AMQP message /// </summary> /// <param name="amqpMessage">AMQP message</param> internal BrokeredMessage(Message amqpMessage) : this() { if (amqpMessage == null) throw new ArgumentNullException("amqpMessage"); MessageConverter.AmqpMessageToBrokeredMessage(amqpMessage, this); this.bodyStream = (amqpMessage.Body != null) ? new MemoryStream((byte[])amqpMessage.Body) : null; }
private void AckModified(IMessageDelivery delivery, bool deliveryFailed, bool undeliverableHere = false) { Message.Message nmsMessage = delivery.Message; Tracer.DebugFormat("Consumer {0} Acking Modified for Message {1}{2}{3}.", ConsumerId, nmsMessage.NMSMessageId, deliveryFailed ? " Delivery Failed" : "", undeliverableHere ? " Undeliveryable Here" : ""); Amqp.Message amqpMessage = (nmsMessage.GetMessageCloak() as Message.AMQP.AMQPMessageCloak).AMQPMessage; //TODO use Link.Modified from amqpNetLite 2.0.0 this.Link.Modify(amqpMessage, deliveryFailed, undeliverableHere, null); }
static void PrintMessage(Message message) { if (message.Header != null) Console.WriteLine(message.Header.ToString()); if (message.DeliveryAnnotations != null) Console.WriteLine(message.DeliveryAnnotations.ToString()); if (message.MessageAnnotations != null) Console.WriteLine(message.MessageAnnotations.ToString()); if (message.Properties != null) Console.WriteLine(message.Properties.ToString()); if (message.ApplicationProperties != null) Console.WriteLine(message.ApplicationProperties.ToString()); if (message.BodySection != null) Console.WriteLine("body:{0}", message.Body.ToString()); if (message.Footer != null) Console.WriteLine(message.Footer.ToString()); }
public Task DischargeAsync(byte[] txnId, bool fail, CancellationToken cancellationToken) { var message = new Amqp.Message(new Discharge { TxnId = txnId, Fail = fail }); var tcs = TaskUtil.CreateTaskCompletionSource <bool>(cancellationToken); _senderLink.Send(message, null, _onDischargeOutcome, tcs); return(tcs.Task); }
// // Sample invocation: Interop.Spout.exe --broker localhost:5672 --timeout 30 --address my-queue // static int Main(string[] args) { const int ERROR_SUCCESS = 0; const int ERROR_OTHER = 2; int exitCode = ERROR_SUCCESS; Connection connection = null; try { Options options = new Options(args); Address address = new Address(options.Url); connection = new Connection(address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-spout", options.Address); // TODO: ReplyTo Stopwatch stopwatch = new Stopwatch(); TimeSpan timespan = new TimeSpan(0, 0, options.Timeout); stopwatch.Start(); for (int nSent = 0; (0 == options.Count || nSent < options.Count) && (0 == options.Timeout || stopwatch.Elapsed <= timespan); nSent++) { string id = options.Id; if (id.Equals("")) { Guid g = Guid.NewGuid(); id = g.ToString(); } id += ":" + nSent.ToString(); Message message = new Message(options.Content); message.Properties = new Properties() { MessageId = id }; sender.Send(message); if (options.Print) { Console.WriteLine("Message(Properties={0}, ApplicationProperties={1}, Body={2}", message.Properties, message.ApplicationProperties, message.Body); } } sender.Close(); session.Close(); connection.Close(); } catch (Exception e) { Console.WriteLine("Exception {0}.", e); if (null != connection) connection.Close(); exitCode = ERROR_OTHER; } return exitCode; }
private void DischargeMatcher(Amqp.Message message, byte[] txnId, bool dischargeState) { Assert.IsNotNull(message); var bodySection = message.BodySection as AmqpValue; Assert.IsNotNull(bodySection); var discharge = bodySection.Value as Discharge; Assert.AreEqual(dischargeState, discharge.Fail); CollectionAssert.AreEqual(txnId, discharge.TxnId); }
void SendMessages(int count) { for (int i = 0; i < count; ++i) { Message message = new Message("hello"); message.Properties = new Properties() { MessageId = "msg" + i, GroupId = "perf" }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; this.sender.Send(message, onOutcome, this); } }
// // Sample invocation: Interop.Drain.exe --broker localhost:5672 --timeout 30 --address my-queue // static int Main(string[] args) { const int ERROR_SUCCESS = 0; const int ERROR_NO_MESSAGE = 1; const int ERROR_OTHER = 2; int exitCode = ERROR_SUCCESS; Connection connection = null; try { Options options = new Options(args); Address address = new Address(options.Url); connection = new Connection(address); Session session = new Session(connection); ReceiverLink receiver = new ReceiverLink(session, "receiver-drain", options.Address); int timeout = int.MaxValue; if (!options.Forever) timeout = 1000 * options.Timeout; Message message = new Message(); int nReceived = 0; receiver.SetCredit(options.InitialCredit); while ((message = receiver.Receive(timeout)) != null) { nReceived++; if (!options.Quiet) { Console.WriteLine("Message(Properties={0}, ApplicationProperties={1}, Body={2}", message.Properties, message.ApplicationProperties, message.Body); } receiver.Accept(message); if (options.Count > 0 && nReceived == options.Count) { break; } } if (message == null) { exitCode = ERROR_NO_MESSAGE; } receiver.Close(); session.Close(); connection.Close(); } catch (Exception e) { Console.WriteLine("Exception {0}.", e); if (null != connection) connection.Close(); exitCode = ERROR_OTHER; } return exitCode; }
protected void GetPartitions(Session session) { ReceiverLink receiverLink = null; SenderLink senderLink = null; try { // create a pair of links for request/response Trace.WriteLine(TraceLevel.Information, "Creating a request and a response link..."); string clientNode = "client-temp-node"; senderLink = new SenderLink(session, "mgmt-sender", "$management"); receiverLink = new ReceiverLink( session, "mgmt-receiver", new Attach() { Source = new Source() { Address = "$management" }, Target = new Target() { Address = clientNode } }, null); var request = new Amqp.Message(); request.Properties = new Properties() { MessageId = "request1", ReplyTo = clientNode }; request.ApplicationProperties = new ApplicationProperties(); request.ApplicationProperties["operation"] = "READ"; request.ApplicationProperties["name"] = settings.EventHubName; request.ApplicationProperties["type"] = "com.microsoft:eventhub"; senderLink.Send(request, null, null); var response = receiverLink.Receive(15000); // time out after 15 seconds if (response == null) { throw new Exception("No get partitions response was received."); } receiverLink.Accept(response); Trace.WriteLine(TraceLevel.Information, "Partition info {0}", response.Body.ToString()); var partitionStrings = (string[])((Map)response.Body)["partition_ids"]; Trace.WriteLine(TraceLevel.Information, "Partitions {0}", string.Join(",", partitionStrings)); this.partitions = new List<string>(partitionStrings); } catch (Exception x) { Trace.WriteLine(TraceLevel.Error, "Error retrieving partitions:\r\n{0}", x.ToString()); throw x; } finally { if (receiverLink != null) receiverLink.Close(); if (senderLink != null) senderLink.Close(); } }
/// <summary> /// Receive messages from specified azure iothub on specified partition. The MessageManager parses the received message and displays it accordingly /// </summary> /// <param name="partition"></param> /// <param name="offset"></param> /// <param name="msgman"></param> /// <param name="hubData"></param> /// <returns></returns> public static async Task ReceiveMessages(string partition, DateTime offset, MessageManager msgman, IoTAccountData hubData) { string port = hubData.EventHubInfo.EventHubPort.Replace("sb://", ""); port = port.Replace("/", ""); Address address = new Address(port, 5671, hubData.SharedAccessPolicy, hubData.PrimaryKey, "/", "amqps"); Connection connection = await Connection.Factory.CreateAsync(address); Session session = new Session(connection); string totalMilliseconds = ((long)(offset - new DateTime(StartOfEpoch, DateTimeKind.Utc)).TotalMilliseconds).ToString(); Map filters = new Map(); filters.Add(new Amqp.Types.Symbol("apache.org:selector-filter:string"), new DescribedValue( new Amqp.Types.Symbol("apache.org:selector-filter:string"), "amqp.annotation.x-opt-enqueuedtimeutc > " + totalMilliseconds + "")); ReceiverLink receiver = new ReceiverLink(session, "my-receiver", new global::Amqp.Framing.Source() { Address = hubData.EventHubInfo.EventHubEntity + "/ConsumerGroups/$Default/Partitions/" + partition, FilterSet = filters }, null); Amqp.Types.Symbol deviceIdKey = new Amqp.Types.Symbol("iothub-connection-device-id"); string deviceId = hubData.DeviceName; while (true) { Amqp.Message m = await receiver.ReceiveAsync(10000); if (m != null) { var id = m.MessageAnnotations.Map[deviceIdKey].ToString(); if (id == deviceId) { Data data = (Data)m.BodySection; string msg = System.Text.Encoding.UTF8.GetString(data.Binary, 0, data.Binary.Length); bool isValid = msgman.parseMessage(msg); if (isValid) { receiver.Accept(m); } else { receiver.Release(m); } } } } }
Dictionary<string, string> GetHeaders(AmqpLite.Message msg) { if (msg.ApplicationProperties == null) return new Dictionary<string, string>(); var result = new Dictionary<string, string>(); foreach (var item in msg.ApplicationProperties.Map) { result.Add(item.Key.ToString(), item.Value.ToString()); } return result; }
protected void DoAMQPSendAsync(Amqp.Message amqpMessage, OutcomeCallback ackCallback) { try { this.link.Send(amqpMessage, ackCallback, this); MsgsSentOnLink++; } catch (Exception ex) { Tracer.ErrorFormat("Encountered Error on sending message from Producer {0}. Message: {1}. Stack : {2}.", Id, ex.Message, ex.StackTrace); throw ExceptionSupport.Wrap(ex); } }
static void OnSendComplete(Message m, Outcome o, object state) { PerfTests thisPtr = (PerfTests)state; int sentCount = Interlocked.Increment(ref thisPtr.completedCount); if (sentCount >= thisPtr.totalCount) { thisPtr.done.Set(); } else if (sentCount % thisPtr.batchCount == 0) { thisPtr.SendMessages(thisPtr.batchCount); } }
public async Task SendMessageToDevice(string messageToDevice) { var sender = new SenderLink(session, "sender-link", "/messages/devicebound"); var message = new Message(System.Text.Encoding.UTF8.GetBytes(messageToDevice)); message.Properties = new Properties(); message.Properties.To = $"/devices/{Constants.DeviceId}/messages/devicebound"; message.Properties.MessageId = Guid.NewGuid().ToString(); message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["iothub-ack"] = "full"; await sender.SendAsync(message); await sender.CloseAsync(); }
static string[] GetPartitions() { Trace.WriteLine(TraceLevel.Information, "Retrieving partitions..."); Trace.WriteLine(TraceLevel.Information, "Establishing a connection..."); Address address = new Address(sbNamespace, 5671, keyName, keyValue); Connection connection = new Connection(address); Trace.WriteLine(TraceLevel.Information, "Creating a session..."); Session session = new Session(connection); // create a pair of links for request/response Trace.WriteLine(TraceLevel.Information, "Creating a request and a response link..."); string clientNode = "client-temp-node"; SenderLink sender = new SenderLink(session, "mgmt-sender", "$management"); ReceiverLink receiver = new ReceiverLink( session, "mgmt-receiver", new Attach() { Source = new Source() { Address = "$management" }, Target = new Target() { Address = clientNode } }, null); Message request = new Message(); request.Properties = new Properties() { MessageId = "request1", ReplyTo = clientNode }; request.ApplicationProperties = new ApplicationProperties(); request.ApplicationProperties["operation"] = "READ"; request.ApplicationProperties["name"] = entity; request.ApplicationProperties["type"] = "com.microsoft:eventhub"; sender.Send(request, null, null); Message response = receiver.Receive(); if (response == null) { throw new Exception("No response was received."); } receiver.Accept(response); receiver.Close(); sender.Close(); connection.Close(); Trace.WriteLine(TraceLevel.Information, "Partition info {0}", response.Body.ToString()); string[] partitions = (string[])((Map)response.Body)["partition_ids"]; Trace.WriteLine(TraceLevel.Information, "Partitions {0}", string.Join(",", partitions)); Trace.WriteLine(TraceLevel.Information, ""); return partitions; }
async Task PutTokenAsync(Connection connection) { var session = new Session(connection); string cbsClientAddress = "cbs-client-reply-to"; var cbsSender = new SenderLink(session, "cbs-sender", "$cbs"); var receiverAttach = new Attach() { Source = new Source() { Address = "$cbs" }, Target = new Target() { Address = cbsClientAddress } }; var cbsReceiver = new ReceiverLink(session, "cbs-receiver", receiverAttach, null); var sasToken = GetSASToken(this.KeyName, this.KeyValue, string.Format("http://{0}/{1}", this.Namespace, this.Entity), TimeSpan.FromMinutes(20)); Trace.WriteLine(TraceLevel.Information, " sas token: {0}", sasToken); // construct the put-token message var request = new Message(sasToken); request.Properties = new Properties(); request.Properties.MessageId = "1"; request.Properties.ReplyTo = cbsClientAddress; request.ApplicationProperties = new ApplicationProperties(); request.ApplicationProperties["operation"] = "put-token"; request.ApplicationProperties["type"] = "servicebus.windows.net:sastoken"; request.ApplicationProperties["name"] = string.Format("amqp://{0}/{1}", this.Namespace, this.Entity); await cbsSender.SendAsync(request); Trace.WriteLine(TraceLevel.Information, " request: {0}", request.Properties); Trace.WriteLine(TraceLevel.Information, " request: {0}", request.ApplicationProperties); // receive the response var response = await cbsReceiver.ReceiveAsync(); if (response == null || response.Properties == null || response.ApplicationProperties == null) { throw new Exception("invalid response received"); } // validate message properties and status code. Trace.WriteLine(TraceLevel.Information, " response: {0}", response.Properties); Trace.WriteLine(TraceLevel.Information, " response: {0}", response.ApplicationProperties); int statusCode = (int)response.ApplicationProperties["status-code"]; if (statusCode != (int)HttpStatusCode.Accepted && statusCode != (int)HttpStatusCode.OK) { throw new Exception("put-token message was not accepted. Error code: " + statusCode); } // the sender/receiver may be kept open for refreshing tokens await cbsSender.CloseAsync(); await cbsReceiver.CloseAsync(); await session.CloseAsync(); }
public void ExpectLinkFlowRespondWithTransfer(Amqp.Message message, int count = 1) { Action <uint> creditMatcher = credit => Assert.Greater(credit, 0); ExpectLinkFlowRespondWithTransfer( message: message, count: count, drain: false, sendDrainFlowResponse: false, sendSettled: false, addMessageNumberProperty: false, creditMatcher: creditMatcher, nextIncomingId: 1 ); }
bool OnFrame(Stream stream, ByteBuffer buffer) { buffer.Complete(1); byte type = AmqpBitConverter.ReadUByte(buffer); ushort channel = AmqpBitConverter.ReadUShort(buffer); DescribedList command = (DescribedList)Encoder.ReadDescribed(buffer, Encoder.ReadFormatCode(buffer)); Amqp.Message message = null; if (command.Descriptor.Code == FrameCodes.TRANSFER) { message = Amqp.Message.Decode(buffer); } return(testAmqpPeer.OnFrame(stream, channel, command, message)); }
public static string ToString(Amqp.Message message) { if (message == null) { return("null"); } string result = "Type=" + message.GetType().Name + ":\n"; if (message.Header != null) { result += "Message Header: " + message.Header.ToString() + "\n"; } return(result); }
public virtual void SendMessage(Message message) { if (_senderLink == null || _senderLink.IsClosed || _senderLink.Session.IsClosed) { if (_senderLink != null) { _senderLink.Detach(); _senderLink.Close(); } _senderLink = new SenderLink(_session, _clientName + "-sender", _queueName); } _senderLink.Send(message); }
public Task WriteAsync(string messageToSend) { return (Task.Run(() => { // not sure where the async went? var message = new Message() { BodySection = new Data() { Binary = Encoding.UTF8.GetBytes(messageToSend) } }; this.senderLink.Value.Send(message); })); }
static void OnOutcome(Message message, Outcome outcome, object state) { var tcs = (TaskCompletionSource<byte[]>)state; if (outcome.Descriptor.Code == Codec.Declared.Code) { tcs.SetResult(((Declared)outcome).TxnId); } else if (outcome.Descriptor.Code == Codec.Rejected.Code) { tcs.SetException(new AmqpException(((Rejected)outcome).Error)); } else { tcs.SetCanceled(); } }
static async Task<int> SslConnectionTestAsync(string brokerUrl, string address, string certfile) { try { ConnectionFactory factory = new ConnectionFactory(); factory.TCP.NoDelay = true; factory.TCP.SendBufferSize = 16 * 1024; factory.TCP.SendTimeout = 30000; factory.TCP.ReceiveBufferSize = 16 * 1024; factory.TCP.ReceiveTimeout = 30000; factory.SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true; factory.SSL.ClientCertificates.Add(X509Certificate.CreateFromCertFile(certfile)); factory.SSL.CheckCertificateRevocation = false; factory.AMQP.MaxFrameSize = 64 * 1024; factory.AMQP.HostName = "host.example.com"; factory.AMQP.ContainerId = "amq.topic"; Address sslAddress = new Address(brokerUrl); Connection connection = await factory.CreateAsync(sslAddress); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender1", address); ReceiverLink receiver = new ReceiverLink(session, "helloworld-receiver", address); Message helloOut = new Message("Hello - using client cert"); await sender.SendAsync(helloOut); Message helloIn = await receiver.ReceiveAsync(); receiver.Accept(helloIn); await connection.CloseAsync(); Console.WriteLine("{0}", helloIn.Body.ToString()); Console.WriteLine("Press enter key to exit..."); Console.ReadLine(); return 0; } catch (Exception e) { Console.WriteLine("Exception {0}.", e); return 1; } }
private static Message ReceiveMessage(string queue) { var connection = new Connection(new Address("localhost", 5672, "user", "pass", "/", "AMQP")); var session = new Amqp.Session(connection); Amqp.Framing.Attach rcvAttach = new Amqp.Framing.Attach() { Source = new Amqp.Framing.Source() { Address = "/queue/" + queue, Durable = 1 }, Target = new Amqp.Framing.Target() { Durable = 1 } }; var receiver = new Amqp.ReceiverLink(session, "foo-receiver", rcvAttach, null); Amqp.Message amqpMessage = null; try { amqpMessage = receiver.Receive(new TimeSpan(0, 0, 5)); // wait - timeout 5 seconds if (amqpMessage == null) { // nothing received - timeout expired // queue is empty ! Console.WriteLine("No message received, queue is empty ..."); return(null); } else { receiver.Accept(amqpMessage); return(amqpMessage); } } catch (Exception ex) { throw ex; } }
private bool PutCbsToken(Connection connection, string host, string shareAccessSignature, string audience) { bool result = true; Session session = new Session(connection); string cbsReplyToAddress = "cbs-reply-to"; var cbsSender = new SenderLink(session, "cbs-sender", "$cbs"); var cbsReceiver = new ReceiverLink(session, cbsReplyToAddress, "$cbs"); // construct the put-token message var request = new Amqp.Message(shareAccessSignature); request.Properties = new Amqp.Framing.Properties(); request.Properties.MessageId = Guid.NewGuid().ToString(); request.Properties.ReplyTo = cbsReplyToAddress; request.ApplicationProperties = new Amqp.Framing.ApplicationProperties(); request.ApplicationProperties["operation"] = "put-token"; request.ApplicationProperties["type"] = "azure-devices.net:sastoken"; request.ApplicationProperties["name"] = audience; cbsSender.Send(request); // receive the response var response = cbsReceiver.Receive(); if (response == null || response.Properties == null || response.ApplicationProperties == null) { result = false; } else { int statusCode = (int)response.ApplicationProperties["status-code"]; string statusCodeDescription = (string)response.ApplicationProperties["status-description"]; if (statusCode != 202 && statusCode != 200) // !Accepted && !OK { result = false; } } // the sender/receiver may be kept open for refreshing tokens cbsSender.Close(); cbsReceiver.Close(); session.Close(); return(result); }
private static void OnDischargeOutcome(ILink link, Amqp.Message message, Outcome outcome, object state) { var tcs = (TaskCompletionSource <bool>)state; if (outcome.Descriptor.Code == MessageOutcomes.Accepted.Descriptor.Code) { tcs.SetResult(true); } else if (outcome.Descriptor.Code == MessageOutcomes.Rejected.Descriptor.Code) { var rejected = (Rejected)outcome; tcs.SetException(new TransactionException(rejected.Error?.Description, rejected.Error?.Condition)); } else { tcs.SetCanceled(); } }
/// <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); } }
public void Send(OutgoingTransportMessage transportMessage, IEnumerable<string> addresses) { var messageBuffer = messageEncoder.Encode(transportMessage.Message); var message = new Message(messageBuffer); message.Header = new Header(); message.Header.Durable = true; message.Properties = new Properties(); message.Properties.CreationTime = DateTime.UtcNow; message.Properties.MessageId = Guid.NewGuid().ToString(); message.Properties.ReplyTo = "TODO"; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["LightRail.ContentType"] = messageEncoder.ContentType; message.ApplicationProperties["LightRail.EnclosedMessageTypes"] = string.Join(",", messageMapper.GetEnclosedMessageTypes(transportMessage.Message.GetType()).Distinct()); foreach (var pair in transportMessage.Headers) { message.ApplicationProperties[pair.Key] = pair.Value; } var connection = new Connection(amqpAddress); var session = new Session(connection); // Azure does not support Amqp transactions "The server was unable to process the request; please retry the operation. If the problem persists, please contact your Service Bus administrator and provide the tracking id..TrackingId:583da4f8d58d4fa59dc9521c6f799cb8_GWIN-AN5B307EEHM,TimeStamp:11.7.2014. 7:44:17" try { foreach (var address in addresses) { logger.Info("Sending Message {0} to {1}", message.Properties.MessageId, address); var senderLink = new SenderLink(session, Guid.NewGuid().ToString(), address); try { senderLink.Send(message); } finally { senderLink.Close(); } } } finally { session.Close(); connection.Close(); } }
internal AMQPObjectMessageCloak(MessageConsumer mc, Amqp.Message message) : base(mc, message) { if (message.Properties.ContentType.Equals(SymbolUtil.SERIALIZED_JAVA_OBJECT_CONTENT_TYPE)) { if (message.MessageAnnotations.Map.ContainsKey(MessageSupport.JMS_JAVA_ENCODING) && message.MessageAnnotations.Map[MessageSupport.JMS_JAVA_ENCODING].Equals(SymbolUtil.BOOLEAN_TRUE)) { InitializeObjectSerializer(AMQPObjectEncodingType.JAVA_SERIALIZABLE); } else { InitializeObjectSerializer(AMQPObjectEncodingType.DOTNET_SERIALIZABLE); } } else { InitializeObjectSerializer(AMQPObjectEncodingType.AMQP_TYPE); } }
async Task SendReceiveAsync(int count) { Trace.WriteLine(TraceLevel.Information, "Establishing a connection..."); Connection connection = await Connection.Factory.CreateAsync(this.GetAddress()); Trace.WriteLine(TraceLevel.Information, "Creating a session..."); Session session = new Session(connection); Trace.WriteLine(TraceLevel.Information, "Creating a sender link..."); SenderLink sender = new SenderLink(session, "sessionful-sender-link", this.Entity); Trace.WriteLine(TraceLevel.Information, "Sending {0} messages...", count); for (int i = 0; i < count; i++) { Message message = new Message(); message.Properties = new Properties() { MessageId = "topic-test-" + i }; message.BodySection = new Data() { Binary = Encoding.UTF8.GetBytes("message #" + i) }; await sender.SendAsync(message); } Trace.WriteLine(TraceLevel.Information, "Closing sender..."); await sender.CloseAsync(); Trace.WriteLine(TraceLevel.Information, "Receiving messages from subscription..."); ReceiverLink receiver = new ReceiverLink(session, "receiver-link", this.Entity + "/Subscriptions/sub1"); for (int i = 0; i < count; i++) { Message message = await receiver.ReceiveAsync(30000); if (message == null) { break; } receiver.Accept(message); } Trace.WriteLine(TraceLevel.Information, "Closing receiver..."); await receiver.CloseAsync(); Trace.WriteLine(TraceLevel.Information, "Shutting down..."); await session.CloseAsync(); await connection.CloseAsync(); }
async static Task<bool> PutCbsToken(Connection connection, string host, string shareAccessSignature, string audience) { bool result = true; Session session = new Session(connection); string cbsReplyToAddress = "cbs-reply-to"; var cbsSender = new SenderLink(session, "cbs-sender", "$cbs"); var cbsReceiver = new ReceiverLink(session, cbsReplyToAddress, "$cbs"); // construct the put-token message var request = new Message(shareAccessSignature); request.Properties = new Properties(); request.Properties.MessageId = Guid.NewGuid().ToString(); request.Properties.ReplyTo = cbsReplyToAddress; request.ApplicationProperties = new ApplicationProperties(); request.ApplicationProperties["operation"] = "put-token"; request.ApplicationProperties["type"] = "azure-devices.net:sastoken"; request.ApplicationProperties["name"] = audience; await cbsSender.SendAsync(request); // receive the response var response = await cbsReceiver.ReceiveAsync(); if (response == null || response.Properties == null || response.ApplicationProperties == null) { result = false; } else { int statusCode = (int)response.ApplicationProperties["status-code"]; string statusCodeDescription = (string)response.ApplicationProperties["status-description"]; if (statusCode != (int)202 && statusCode != (int)200) // !Accepted && !OK { result = false; } } // the sender/receiver may be kept open for refreshing tokens await cbsSender.CloseAsync(); await cbsReceiver.CloseAsync(); await session.CloseAsync(); return result; }
public static Message CreateMessage(string eventType, string data, string correlationId) { var messageId = Guid.NewGuid().ToString(); var message = new Message(data) { Header = new Header { Durable = false }, ApplicationProperties = new ApplicationProperties(), MessageAnnotations = new MessageAnnotations(), Properties = new Properties { MessageId = messageId, GroupId = eventType, CorrelationId = correlationId } }; message.ApplicationProperties[MESSAGE_TYPE_KEY] = eventType; return(message); }
public void SendTransferToLastOpenedLinkOnLastOpenedSession(Amqp.Message message, uint nextIncomingId) { lock (matchersLock) { var lastMatcher = GetLastMatcher(); ByteBuffer payload = message.Encode(); lastMatcher.WithOnComplete(context => { var transfer = new Transfer() { DeliveryId = nextIncomingId, DeliveryTag = Encoding.UTF8.GetBytes("theDeliveryTag" + nextIncomingId), MessageFormat = 0, Settled = false, Handle = lastInitiatedLinkHandle, }; context.SendCommand(transfer, payload); }); } }
static void RunMessageClient(string address) { const int nMsgs = 10; Connection connection = new Connection(new Address(address)); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "message-client", "message_processor"); for (int i = 0; i < nMsgs; ++i) { Message message = new Message("hello"); message.Properties = new Properties() { MessageId = "msg" + i }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; sender.Send(message); Console.WriteLine("Sent message {0} body {1}", message.Properties, message.Body); } sender.Close(); session.Close(); connection.Close(); }
static async Task Run() { string address = "amqp://*****:*****@localhost:5672"; Connection connection = await Connection.Factory.CreateAsync(new Address(address)); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "test-sender", "q1"); Message message1 = new Message("Hello AMQP!"); await sender.SendAsync(message1); ReceiverLink receiver = new ReceiverLink(session, "test-receiver", "q1"); Message message2 = await receiver.ReceiveAsync(); Console.WriteLine(message2.GetBody<string>()); receiver.Accept(message2); await sender.CloseAsync(); await receiver.CloseAsync(); await session.CloseAsync(); await connection.CloseAsync(); }
public void Accept(Message message) { Fx.AssertAndThrow(ErrorCode.ReceiverAcceptInvalidState, this.State < 0xff); if (!message.settled) { this.client.SendDisposition(true, message.deliveryId, true, new DescribedValue(0x24ul, new List())); } if (this.credit < uint.MaxValue) { lock (this) { this.credit++; if (++this.restored >= this.flowThreshold) { this.restored = 0; this.client.SendFlow(this.Handle, this.deliveryCount, this.credit); } } } }
string[] GetPartitions() { Address address = new Address(sbNamespace, 5671, ReckeyName, ReckeyValue); Connection connection = new Connection(address); Session session = new Session(connection); // create a pair of links for request/response string clientNode = "client-temp-node"; SenderLink sender = new SenderLink(session, "mgmt-sender", "$management"); ReceiverLink receiver = new ReceiverLink( session, "mgmt-receiver", new Attach() { Source = new Source() { Address = "$management" }, Target = new Target() { Address = clientNode } }, null); Message request = new Message(); request.Properties = new Properties() { MessageId = "request1", ReplyTo = clientNode }; request.ApplicationProperties = new ApplicationProperties(); request.ApplicationProperties["operation"] = "READ"; request.ApplicationProperties["name"] = entity; request.ApplicationProperties["type"] = "com.microsoft:eventhub"; sender.Send(request, null, null); Message response = receiver.Receive(); if (response == null) { throw new Exception("No response was received."); } receiver.Accept(response); receiver.Close(); sender.Close(); connection.Close(); string[] partitions = (string[])((Map)response.Body)["partition_ids"]; return partitions; }
public async Task BasicSendReceiveAsync() { string testName = "BasicSendReceiveAsync"; int nMsgs = 100; Connection connection = await Connection.Factory.CreateAsync(this.testTarget.Address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "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); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = await receiver.ReceiveAsync(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.ApplicationProperties["sn"]); receiver.Accept(message); } await sender.CloseAsync(); await receiver.CloseAsync(); await session.CloseAsync(); await connection.CloseAsync(); }