public static void Main(string[] args) { String url = (args.Length > 0) ? args[0] : "amqps://127.0.0.1:443"; String address = (args.Length > 1) ? args[1] : "myqueue"; Trace.TraceLevel = TraceLevel.Frame; Trace.TraceListener = (l, f, a) => Console.WriteLine( DateTime.Now.ToString("[hh:mm:ss.fff]") + " " + string.Format(f, a)); Connection.DisableServerCertValidation = true; Connection connection = new Connection(new Address(url)); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "test-sender", address); Message messageSent = new Message("Test Message"); sender.Send(messageSent); ReceiverLink receiver = new ReceiverLink(session, "test-receiver", address); Message messageReceived = receiver.Receive(TimeSpan.FromSeconds(2)); Console.WriteLine(messageReceived.Body); receiver.Accept(messageReceived); sender.Close(); receiver.Close(); session.Close(); connection.Close(); }
public void stop() { running = false; _receiever.Close(); _session.Close(); }
static Tuple <string, DateTime> ReceiveMessages(string scenario, int count, string filter, string partition) { Trace.WriteLine(TraceLevel.Information, "Running scenario '{0}', filter '{1}'...", scenario, filter); 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); Trace.WriteLine(TraceLevel.Information, "Creating a receiver link on partition {0}...", partition); string partitionAddress = entity + "/ConsumerGroups/$default/Partitions/" + partition;; Map filters = new Map(); if (filter != null) { filters.Add(new Symbol("apache.org:selector-filter:string"), new DescribedValue(new Symbol("apache.org:selector-filter:string"), filter)); } string lastOffset = "-1"; long lastSeqNumber = -1; DateTime lastEnqueueTime = DateTime.MinValue; ReceiverLink receiver = new ReceiverLink( session, "receiver-" + partition, new Source() { Address = partitionAddress, FilterSet = filters }, null); int i; for (i = 0; i < count; i++) { Message message = receiver.Receive(30000); if (message == null) { break; } receiver.Accept(message); lastOffset = (string)message.MessageAnnotations[new Symbol("x-opt-offset")]; lastSeqNumber = (long)message.MessageAnnotations[new Symbol("x-opt-sequence-number")]; lastEnqueueTime = (DateTime)message.MessageAnnotations[new Symbol("x-opt-enqueued-time")]; } receiver.Close(); Trace.WriteLine(TraceLevel.Information, "Received {0} messages on partition {1}", i, partition); Trace.WriteLine(TraceLevel.Information, " offset: '{0}', sn: {1}, enqueue time: {2}", lastOffset, lastSeqNumber, lastEnqueueTime.ToString("hh:ss.fff")); Trace.WriteLine(TraceLevel.Information, ""); session.Close(); connection.Close(); return(Tuple.Create(lastOffset, lastEnqueueTime)); }
public void TestMethod_BasicSendReceive() { string testName = "BasicSendReceive"; const int nMsgs = 200; Connection connection = new Connection(address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); 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, "q1"); for (int i = 0; i < nMsgs; ++i) { Message message = receiver.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.ApplicationProperties["sn"]); receiver.Accept(message); } sender.Close(); receiver.Close(); session.Close(); connection.Close(); }
public void TestMethod_DynamicSenderLink() { string testName = "DynamicSenderLink"; Connection connection = new Connection(address); Session session = new Session(connection); string targetAddress = null; OnAttached onAttached = (link, attach) => { targetAddress = ((Target)attach.Target).Address; }; SenderLink sender = new SenderLink(session, "sender-" + testName, new Target() { Dynamic = true }, onAttached); Message message = new Message("hello"); sender.Send(message, 60000); Assert.IsTrue(targetAddress != null, "dynamic target not attached"); ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, targetAddress); message = receiver.Receive(); Assert.IsTrue(message != null, "no message was received."); receiver.Accept(message); sender.Close(); receiver.Close(); session.Close(); connection.Close(); }
static void Main(string[] args) { string broker = args.Length >= 1 ? args[0] : "amqp://localhost:8583"; string address = args.Length >= 2 ? args[1] : "address.helloworld"; Address brokerAddr = new Address(broker); Connection connection = new Connection(brokerAddr); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "dotnetclient-sender", address); ReceiverLink receiver = new ReceiverLink(session, "dotnetclient-receiver", address); Message helloOut = new Message("This is an AMQP message sent by a Dot Net client!"); sender.Send(helloOut); Message helloIn = receiver.Receive(); receiver.Accept(helloIn); Console.WriteLine(helloIn.Body.ToString()); receiver.Close(); sender.Close(); session.Close(); connection.Close(); }
// this function is used to receive the feed back for the message sent private void ReceiveFeedback(ReceivedFeedBackData callback, string filter) { string audience = Fx.Format("{0}/messages/servicebound/feedback", HOST); string resourceUri = Fx.Format("{0}/messages/servicebound/feedback", HOST); string sasToken = GetSharedAccessSignature(SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, resourceUri, new TimeSpan(1, 0, 0)); bool cbs = PutCbsToken(connection, HOST, sasToken, audience); if (cbs) { string entity = "/messages/servicebound/feedback"; // Form the filter for receiving message based on the time stamp Map filters = new Map(); if (filter != null) { filters.Add(new Amqp.Types.Symbol("apache.org:selector-filter:string"), new DescribedValue(new Amqp.Types.Symbol("apache.org:selector-filter:string"), filter)); } ReceiverLink receiveLink = new ReceiverLink(session, "receive-link", new Source() { Address = entity, FilterSet = filters }, null); Message received = receiveLink.Receive(); if (received != null) { receiveLink.Accept(received); Data data = (Data)received.BodySection; callback(Encoding.UTF8.GetString(data.Binary)); Debug.WriteLine(Encoding.UTF8.GetString(data.Binary)); } receiveLink.Close(); } }
protected override void Renew(Session session) { oldReceiver = receiver; receiver = new ReceiverLink(session, "receiver", Environment.GetEnvironmentVariable("SERVICE_BUS_NAME")); receiver.Start(20, (receiver, message) => { Console.WriteLine($"[{DateTime.UtcNow.ToString("dd/MM/yyyy HH:mm:ss")}] -> received message"); try { var queueMessage = JsonConvert.DeserializeObject <QueueMessage>(message.GetBody <string>()); OnMessage(queueMessage); receiver.Accept(message); } catch (Exception e) { Console.WriteLine($"[{DateTime.UtcNow.ToString("dd/MM/yyyy HH:mm:ss")}] -> message threw an exception: {e.Message}"); receiver.Reject(message); } }); if (oldReceiver != null) { oldReceiver.Close(); oldReceiver = null; } }
public void TestMethod_ConnectionWithIPAddress() { string testName = "ConnectionWithIPAddress"; const int nMsgs = 20; Address address = new Address("127.0.0.1", 5672, "guest", "guest", "/", "amqp"); Connection connection = new Connection(address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); 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, "q1"); 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(); }
void RunOnce(int id) { Connection connection = this.CreateConnection(new Address(this.Args.Address)); Session session = new Session(connection); Attach attach = new Attach() { Source = new Source() { Address = this.Args.Node }, Target = new Target(), SndSettleMode = this.Args.SenderMode, RcvSettleMode = this.Args.ReceiverMode }; ReceiverLink receiver = new ReceiverLink(session, "perf-test-receiver" + id, attach, null); receiver.Start( this.Args.Queue, (r, m) => { r.Accept(m); m.Dispose(); this.OnComplete(); }); this.Wait(); receiver.Close(); session.Close(); connection.Close(); }
public void TestMethod_DynamicReceiverLink() { string testName = "DynamicReceiverLink"; Connection connection = new Connection(address); Session session = new Session(connection); string remoteSource = null; ManualResetEvent attached = new ManualResetEvent(false); OnAttached onAttached = (link, attach) => { remoteSource = ((Source)attach.Source).Address; attached.Set(); }; ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, new Source() { Dynamic = true }, onAttached); attached.WaitOne(10000, waitExitContext); Assert.IsTrue(remoteSource != null, "dynamic source not attached"); SenderLink sender = new SenderLink(session, "sender-" + testName, remoteSource); Message message = new Message("hello"); sender.Send(message, 60000); message = receiver.Receive(); Assert.IsTrue(message != null, "no message was received."); receiver.Accept(message); sender.Close(); receiver.Close(); session.Close(); connection.Close(); }
public void TestMethod_ConnectionFrameSize() { string testName = "ConnectionFrameSize"; const int nMsgs = 200; Connection connection = new Connection(address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); int frameSize = 16 * 1024; for (int i = 0; i < nMsgs; ++i) { Message message = new Message(new string('A', frameSize + (i - nMsgs / 2))); sender.Send(message, null, null); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); for (int i = 0; i < nMsgs; ++i) { Message message = receiver.Receive(); string value = (string)message.Body; Trace.WriteLine(TraceLevel.Information, "receive: {0}x{1}", value[0], value.Length); receiver.Accept(message); } sender.Close(); receiver.Close(); session.Close(); connection.Close(); }
static void Main(string[] args) { string url = (args.Length > 0) ? args[0] : "amqp://localhost:5672"; int count = (args.Length > 2) ? Convert.ToInt32(args[2]) : 10; Address peerAddr = new Address(url); Connection connection = new Connection(peerAddr); Session session = new Session(connection); Map filters = new Map(); filters.Add(new Symbol("store123"), new DescribedValue(new Symbol("apache.org:selector-filter:string"), "store = 123")); Source ordersSource123 = new Source() { Address = "orders", FilterSet = filters }; ordersSource123.DistributionMode = new Symbol("move"); filters = new Map(); filters.Add(new Symbol("store456"), new DescribedValue(new Symbol("apache.org:selector-filter:string"), "store = 456")); Source ordersSource456 = new Source() { Address = "orders", FilterSet = filters }; ordersSource456.DistributionMode = new Symbol("move"); SenderLink sender = new SenderLink(session, "sender", "orders"); ReceiverLink biReceiver = new ReceiverLink(session, "BI", "orders"); ReceiverLink otherReceiver = new ReceiverLink(session, "other-service", "orders"); ReceiverLink store123Receiver = new ReceiverLink(session, "s123", ordersSource123, null); ReceiverLink store456Receiver = new ReceiverLink(session, "s456", ordersSource456, null); Message message = new Message("order placed for store 123"); message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["store"] = 123; sender.Send(message); message = new Message("order placed for store 456"); message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["store"] = 456; sender.Send(message); LogReceivedMessage(biReceiver); LogReceivedMessage(otherReceiver); LogReceivedMessage(biReceiver); LogReceivedMessage(otherReceiver); LogReceivedMessage(store123Receiver); LogReceivedMessage(store456Receiver); sender.Close(); store123Receiver.Close(); store456Receiver.Close(); biReceiver.Close(); session.Close(); connection.Close(); }
public void TestMethod_ReceiveWaiter() { string testName = "ReceiveWaiter"; Connection connection = new Connection(address); Session session = new Session(connection); ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); Thread t = new Thread(() => { Message message = receiver.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId); receiver.Accept(message); }); t.Start(); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); Message msg = new Message() { Properties = new Properties() { MessageId = "123456" } }; sender.Send(msg, null, null); t.Join(10000); sender.Close(); receiver.Close(); session.Close(); connection.Close(); }
public virtual void StopListening(TimeSpan timeout = default(TimeSpan), Error error = null) { if (_receiverLink == null || _receiverLink.IsClosed) { return; } if (timeout == default(TimeSpan)) { _receiverLink.Close(); } else { _receiverLink.Close(timeout, error); } }
public void TestMethod_ConnectionFrameSize() { string testName = "ConnectionFrameSize"; const int nMsgs = 200; int frameSize = 4 * 1024; Connection connection = new Connection(testTarget.Address, null, new Open() { ContainerId = "c1", MaxFrameSize = (uint)frameSize }, null); 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(new string('A', frameSize + (i - nMsgs / 2))); 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(); string value = (string)message.Body; Trace.WriteLine(TraceLevel.Verbose, "receive: {0}x{1}", value[0], value.Length); receiver.Accept(message); } sender.Close(); receiver.Close(); session.Close(); connection.Close(); }
// This function is the core receive function void ReceiveMessages(string scenario, int count, string filter, string partition, ReceivedData callback) { Trace.WriteLine(Amqp.TraceLevel.Information, "Running scenario '{0}', filter '{1}'...", scenario, filter); Trace.WriteLine(Amqp.TraceLevel.Information, "Establishing a connection..."); Address address = new Address(sbNamespace, PORT, keyName, keyValue); Connection connection = new Connection(address); Trace.WriteLine(Amqp.TraceLevel.Information, "Creating a session..."); Session session = new Session(connection); Trace.WriteLine(Amqp.TraceLevel.Information, "Creating a receiver link on partition {0}...", partition); string partitionAddress = entity + "/ConsumerGroups/$default/Partitions/" + partition; // Form the filter for receiving message based on the time stamp Map filters = new Map(); if (filter != null) { filters.Add(new Amqp.Types.Symbol("apache.org:selector-filter:string"), new DescribedValue(new Amqp.Types.Symbol("apache.org:selector-filter:string"), filter)); } string lastOffset = "-1"; long lastSeqNumber = -1; DateTime lastEnqueueTime = DateTime.MinValue; ReceiverLink receiver = new ReceiverLink( session, "receiver-" + partition, new Source() { Address = partitionAddress, FilterSet = filters }, null); // loop runs until clean up is called for (; g_bThreadActive;) { Message message = receiver.Receive(5000); if (message == null) { continue; } receiver.Accept(message); Data data = (Data)message.BodySection; // Get the data such as offset, Seq number and Devicename from the response header lastOffset = (string)message.MessageAnnotations[new Amqp.Types.Symbol("x-opt-offset")]; lastSeqNumber = (long)message.MessageAnnotations[new Amqp.Types.Symbol("x-opt-sequence-number")]; lastEnqueueTime = (DateTime)message.MessageAnnotations[new Amqp.Types.Symbol("x-opt-enqueued-time")]; var DeviceName = (string)message.MessageAnnotations[new Amqp.Types.Symbol("iothub-connection-device-id")]; callback(data.Binary, DeviceName); } receiver.Close(); session.Close(); connection.Close(); }
public void ContainerHostMessageSourceTest() { string name = "ContainerHostMessageSourceTest"; int count = 100; Queue <Message> messages = new Queue <Message>(); for (int i = 0; i < count; i++) { messages.Enqueue(new Message("test") { Properties = new Properties() { MessageId = name + i } }); } var source = new TestMessageSource(messages); this.host.RegisterMessageSource(name, source); var connection = new Connection(Address); var session = new Session(connection); var receiver = new ReceiverLink(session, "receiver0", name); int released = 0; int rejected = 0; int ignored = 0; for (int i = 1; i <= count; i++) { Message message = receiver.Receive(); if (i % 5 == 0) { receiver.Reject(message); rejected++; } else if (i % 17 == 0) { receiver.Release(message); released++; } else if (i % 36 == 0) { ignored++; } else { receiver.Accept(message); } } receiver.Close(); session.Close(); connection.Close(); Thread.Sleep(500); Assert.AreEqual(released + ignored, messages.Count, string.Join(",", messages.Select(m => m.Properties.MessageId))); Assert.AreEqual(rejected, source.DeadletterMessage.Count, string.Join(",", source.DeadletterMessage.Select(m => m.Properties.MessageId))); }
// // 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); TimeSpan timeout = TimeSpan.MaxValue; if (!options.Forever) { timeout = TimeSpan.FromSeconds(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.Error.WriteLine("Exception {0}.", e); if (null != connection) { connection.Close(); } exitCode = ERROR_OTHER; } return(exitCode); }
string[] GetEventHubPartitions() { Trace.WriteLine(TraceLevel.Information, "Retrieving partitions..."); Trace.WriteLine(TraceLevel.Information, "Establishing a connection..."); Connection connection = new Connection(this.GetAddress()); 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"] = this.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"]; return(partitions); }
public void Dispose() { Trace.WriteLine(Amqp.TraceLevel.Information, "Closing sender..."); _sender.Close(); _consumer.Close(); _amqpSession.Close(); _connection.Close(); }
public void TestMethod_OnMessage() { string testName = "OnMessage"; const int nMsgs = 200; Connection connection = new Connection(address); Session session = new Session(connection); ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); ManualResetEvent done = new ManualResetEvent(false); int received = 0; receiver.Start(10, (link, m) => { Trace.WriteLine(TraceLevel.Information, "receive: {0}", m.ApplicationProperties["sn"]); link.Accept(m); received++; if (received == nMsgs) { done.Set(); } }); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); for (int i = 0; i < nMsgs; ++i) { Message message = new Message() { BodySection = new Data() { Binary = Encoding.UTF8.GetBytes("msg" + i) } }; message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; sender.Send(message, null, null); } int last = -1; while (!done.WaitOne(10000, waitExitContext) && received > last) { last = received; } sender.Close(); receiver.Close(); session.Close(); connection.Close(); Assert.AreEqual(nMsgs, received, "not all messages are received."); }
public void Retry() { string name = "Retry"; List <Message> messages = new List <Message>(); host.RegisterMessageProcessor(name, new TestMessageProcessor(50, messages)); linkProcessor = new TestLinkProcessor(); host.RegisterLinkProcessor(linkProcessor); int count = 80; var connection = new Connection(Address); var session = new Session(connection); var sender = new SenderLink(session, "send-link", name); for (int i = 0; i < count; i++) { var m = new Message("msg" + i) { ApplicationProperties = new ApplicationProperties(), Header = new Header() { DeliveryCount = 0 }, Properties = new Properties() { MessageId = name + i, GroupId = name } }; sender.Send(m, Timeout); } sender.Close(); host.RegisterMessageSource(name, new TestMessageSource(new Queue <Message>(messages))); var receiver = new ReceiverLink(session, "recv-link", name); var message = receiver.Receive(); var deliveryCount = message.Header.DeliveryCount; var delay = 10 * deliveryCount; var scheduleTime = DateTime.UtcNow.AddSeconds(delay); using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { var sndr = new SenderLink(session, "retry", "test.queue"); // create a new message to be queued with scheduled delivery time var retry = new Message(message.GetBody <string>()) { Header = message.Header, Footer = message.Footer, Properties = message.Properties, ApplicationProperties = message.ApplicationProperties }; retry.ApplicationProperties[Constants.SCHEDULED_ENQUEUE_TIME_UTC] = scheduleTime; sndr.Send(retry); receiver.Accept(message); } receiver.Close(); session.Close(); connection.Close(); }
public static void Disconnect(string reason) { var reasonError = new Error(ErrorCode.ConnectionForced); reasonError.Description = reason; receiver?.Close(TimeSpan.Zero, reasonError); session?.Close(TimeSpan.Zero, reasonError); connection?.Close(TimeSpan.Zero, reasonError); }
public void Disconnect() { _Connection.Closed -= OnClosed; _Session.Closed -= OnClosed; _ReceiverLink.Closed -= OnClosed; _ReceiverLink.Close(); _Session.Close(); _Connection.Close(); }
public static void PutCsbToken(Connection connection, ServiceBusConfiguration config, string audience) { var tokenProvider = new ManagedIdentityTokenProvider(); var token = tokenProvider.GetTokenAsync($"sb://{config.Host}/"); var session = new Session(connection); var cbsClientAddress = "cbs-client-reply-to"; var cbsSender = new SenderLink(session, config.Subscription, "$cbs"); var cbsReceiver = new ReceiverLink(session, cbsClientAddress, "$cbs"); // construct the put-token message var request = new Message(token.TokenValue) { Properties = new Properties { MessageId = Guid.NewGuid().ToString(), ReplyTo = cbsClientAddress }, ApplicationProperties = new ApplicationProperties { ["operation"] = "put-token", ["type"] = token.TokenType, ["expiration"] = token.ExpiresAtUtc, ["name"] = audience } }; cbsSender.SendAsync(request).Wait(); Trace.WriteLine(TraceLevel.Information, " request: {0}", request.Properties); Trace.WriteLine(TraceLevel.Information, " request: {0}", request.ApplicationProperties); // receive the response var response = cbsReceiver.ReceiveAsync().Result; if (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 cbsSender.Close(); cbsReceiver.Close(); session.Close(); }
Message[] ReceiveMessages(string scenario, int count, string filter, string partition) { Trace.WriteLine(TraceLevel.Information, "Running scenario '{0}', filter '{1}'...", scenario, filter); Trace.WriteLine(TraceLevel.Information, "Establishing a connection..."); Connection connection = new Connection(this.GetAddress()); Trace.WriteLine(TraceLevel.Information, "Creating a session..."); Session session = new Session(connection); Trace.WriteLine(TraceLevel.Information, "Creating a receiver link on partition {0}...", partition); string partitionAddress = this.Entity + "/ConsumerGroups/$default/Partitions/" + partition;; Map filters = new Map(); if (filter != null) { filters.Add(new Symbol("apache.org:selector-filter:string"), new DescribedValue(new Symbol("apache.org:selector-filter:string"), filter)); } ReceiverLink receiver = new ReceiverLink( session, "receiver-" + partition, new Source() { Address = partitionAddress, FilterSet = filters }, null); Message[] messages = new Message[count]; for (int i = 0; i < count; i++) { Message message = receiver.Receive(30000); if (message == null) { break; } receiver.Accept(message); Trace.WriteLine( TraceLevel.Information, "Received a message. sn: {0}, offset: '{1}', enqueue time: {2}", (long)message.MessageAnnotations[new Symbol("x-opt-sequence-number")], (string)message.MessageAnnotations[new Symbol("x-opt-offset")], (DateTime)message.MessageAnnotations[new Symbol("x-opt-enqueued-time")]); messages[i] = message; } receiver.Close(); session.Close(); connection.Close(); return(messages); }
public void TestMethod_AdvancedLinkFlowControl() { string testName = "AdvancedLinkFlowControl"; int nMsgs = 20; Connection connection = new Connection(address); 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 }; sender.Send(message, null, null); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); receiver.SetCredit(2, false); Message m1 = receiver.Receive(); Message m2 = receiver.Receive(); Assert.AreEqual("msg0", m1.Properties.MessageId); Assert.AreEqual("msg1", m2.Properties.MessageId); receiver.Accept(m1); receiver.Accept(m2); ReceiverLink receiver2 = new ReceiverLink(session, "receiver2-" + testName, "q1"); receiver2.SetCredit(2, false); Message m3 = receiver2.Receive(); Message m4 = receiver2.Receive(); Assert.AreEqual("msg2", m3.Properties.MessageId); Assert.AreEqual("msg3", m4.Properties.MessageId); receiver2.Accept(m3); receiver2.Accept(m4); receiver.SetCredit(4); for (int i = 4; i < nMsgs; i++) { Message m = receiver.Receive(); Assert.AreEqual("msg" + i, m.Properties.MessageId); receiver.Accept(m); } sender.Close(); receiver.Close(); receiver2.Close(); session.Close(); connection.Close(); }
public void ContainerHostProcessorOrderTest() { string name = "ContainerHostProcessorOrderTest"; List <Message> messages = new List <Message>(); var processor = new TestMessageProcessor(50, messages); host.RegisterMessageProcessor(name, processor); linkProcessor = new TestLinkProcessor(); host.RegisterLinkProcessor(linkProcessor); int count = 80; var connection = new Connection(Address); var session = new Session(connection); var sender = new SenderLink(session, "send-link", name); for (int i = 0; i < count; i++) { var message = new Message("msg" + i); message.Properties = new Properties() { GroupId = name }; sender.Send(message, Timeout); } sender.Close(); Assert.Equal(count, messages.Count); host.RegisterMessageSource(name, new TestMessageSource(new Queue <Message>(messages))); var receiver = new ReceiverLink(session, "recv-link", name); for (int i = 0; i < count; i++) { var message = receiver.Receive(); receiver.Accept(message); } receiver.Close(); sender = new SenderLink(session, "send-link", "any"); for (int i = 0; i < count; i++) { var message = new Message("msg" + i); message.Properties = new Properties() { GroupId = name }; sender.Send(message, Timeout); } sender.Close(); session.Close(); connection.Close(); }
public void ContainerHostSourceLinkEndpointTest() { string name = "ContainerHostSourceLinkEndpointTest"; int count = 100; Queue <Message> messages = new Queue <Message>(); for (int i = 0; i < count; i++) { messages.Enqueue(new Message("test") { Properties = new Properties() { MessageId = name + i } }); } var source = new TestMessageSource(messages); this.linkProcessor = new TestLinkProcessor(link => new SourceLinkEndpoint(source, link)); this.host.RegisterLinkProcessor(this.linkProcessor); var connection = new Connection(Address); var session = new Session(connection); var receiver = new ReceiverLink(session, "receiver0", name); int released = 0; int rejected = 0; for (int i = 1; i <= count; i++) { Message message = receiver.Receive(); if (i % 5 == 0) { receiver.Reject(message); rejected++; } else if (i % 17 == 0) { receiver.Release(message); released++; } else { receiver.Accept(message); } } receiver.Close(); session.Close(); connection.Close(); Thread.Sleep(200); Assert.AreEqual(released, messages.Count); Assert.AreEqual(rejected, source.DeadletterMessage.Count); }