public async Task ReceiveSingleMessageInReceiveAndDeleteMode() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false)) { await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString); ServiceBusSender sender = client.CreateSender(scope.QueueName); ServiceBusMessage sentMessage = GetMessage(); await sender.SendMessageAsync(sentMessage); var clientOptions = new ServiceBusReceiverOptions() { ReceiveMode = ReceiveMode.ReceiveAndDelete, }; var receiver = client.CreateReceiver(scope.QueueName, clientOptions); var receivedMessage = await receiver.ReceiveMessageAsync(); Assert.AreEqual(sentMessage.MessageId, receivedMessage.MessageId); var message = receiver.PeekMessageAsync(); Assert.IsNull(message.Result); } }
public async Task LogsTransactionEvents() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false)) { var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString); ServiceBusSender sender = client.CreateSender(scope.QueueName); ServiceBusMessage message = ServiceBusTestUtilities.GetMessage(); using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { await sender.SendMessageAsync(message); ts.Complete(); } // Adding delay since transaction Commit/Rollback is an asynchronous operation. await Task.Delay(TimeSpan.FromSeconds(2)); _listener.SingleEventById(ServiceBusEventSource.TransactionDeclaredEvent); _listener.SingleEventById(ServiceBusEventSource.TransactionDischargedEvent); }; }
public async Task PublishAsync([NotNull] ILocalEvent localEvent) { var connectionString = GetEnvironmentVariable(LocalEventsConnectionString); await using ServiceBusClient client = new (connectionString); var queueOrTopicName = GetEnvironmentVariable(LocalEventsTopicName); ServiceBusSender sender = client.CreateSender(queueOrTopicName); var serializedMessage = _jsonSerializer.Serialize(localEvent); var message = new ServiceBusMessage(serializedMessage) { CorrelationId = localEvent.CorrelationId, Subject = localEvent.Filter, // We set 'Subject' at the moment for a better overview in the AZ portal. }; // We use this custom "filter" property to filter our messages on the ServiceBus. message.ApplicationProperties.Add("filter", localEvent.Filter); await sender.SendMessageAsync(message).ConfigureAwait(false); }
public async Task TransactionalSendMultipleSessionsRollback() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: true)) { await using var client = CreateClient(); ServiceBusSender sender = client.CreateSender(scope.QueueName); ServiceBusMessage message1 = GetMessage("session1"); ServiceBusMessage message2 = GetMessage("session2"); using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { await sender.SendMessageAsync(message1); await sender.ScheduleMessageAsync(message2, DateTimeOffset.UtcNow.AddMinutes(1)); } Assert.That( async() => await CreateNoRetryClient().AcceptNextSessionAsync(scope.QueueName), Throws.InstanceOf <ServiceBusException>() .And.Property(nameof(ServiceBusException.Reason)) .EqualTo(ServiceBusFailureReason.ServiceTimeout)); }; }
static async Task SendMessageAsync(string connectionString, string queueName) { // create a Service Bus client await using (ServiceBusClient client = new ServiceBusClient(connectionString)) { // create a sender for the queue ServiceBusSender sender = client.CreateSender(queueName); // create a message that we can send ServiceBusMessage message = new ServiceBusMessage("State of Ohio"); message.MessageId = "9348750lkgjlk"; message.ApplicationProperties.Add("state", "Ohio"); TimeSpan t = new TimeSpan(0, 3, 0); message.TimeToLive = t; // send the message await sender.SendMessageAsync(message); Console.WriteLine($"Sent a single message to the queue: {queueName}"); } }
public async Task <bool> EnviarAsync([FromBody] Data data) { string connectionString = "Endpoint=sb://queuedark.servicebus.windows.net/;SharedAccessKeyName=Enviar;SharedAccessKey=l1yedScAfo4YJRo1r0tAEkl480Q8PfckAXNdX9AXfxs=;EntityPath=cola1"; string queueName = "cola1"; //JsonSerializer json = new JsonSerializer(); Instalamos un nugget Newton string mensaje = JsonConvert.SerializeObject(data); await using (ServiceBusClient client = new ServiceBusClient(connectionString)) { // create a sender for the queue ServiceBusSender sender = client.CreateSender(queueName); // create a message that we can send ServiceBusMessage message = new ServiceBusMessage(mensaje); // send the message await sender.SendMessageAsync(message); Console.WriteLine($"Sent a single message to the queue: {queueName}"); } return(true); }
public async Task SendAndReceiveMessage() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false)) { string connectionString = TestEnvironment.ServiceBusConnectionString; string queueName = scope.QueueName; #region Snippet:ServiceBusSendAndReceive #region Snippet:ServiceBusSendSingleMessage //@@ string connectionString = "<connection_string>"; //@@ string queueName = "<queue_name>"; // since ServiceBusClient implements IAsyncDisposable we create it with "await using" await using var client = new ServiceBusClient(connectionString); // create the sender ServiceBusSender sender = client.CreateSender(queueName); // create a message that we can send. UTF-8 encoding is used when providing a string. ServiceBusMessage message = new ServiceBusMessage("Hello world!"); // send the message await sender.SendMessageAsync(message); #endregion #region Snippet:ServiceBusReceiveSingleMessage // create a receiver that we can use to receive the message ServiceBusReceiver receiver = client.CreateReceiver(queueName); // the received message is a different type as it contains some service set properties ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync(); // get the message body as a string string body = receivedMessage.Body.ToString(); Console.WriteLine(body); #endregion #endregion Assert.AreEqual("Hello world!", receivedMessage.Body.ToString()); } }
public async Task DeadLetterMessage() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false)) { string connectionString = TestEnvironment.ServiceBusConnectionString; string queueName = scope.QueueName; // since ServiceBusClient implements IAsyncDisposable we create it with "await using" await using var client = new ServiceBusClient(connectionString); // create the sender ServiceBusSender sender = client.CreateSender(queueName); // create a message that we can send ServiceBusMessage message = new ServiceBusMessage("Hello world!"); // send the message await sender.SendMessageAsync(message); // create a receiver that we can use to receive and settle the message ServiceBusReceiver receiver = client.CreateReceiver(queueName); #region Snippet:ServiceBusDeadLetterMessage ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync(); // dead-letter the message, thereby preventing the message from being received again without receiving from the dead letter queue. await receiver.DeadLetterMessageAsync(receivedMessage); // receive the dead lettered message with receiver scoped to the dead letter queue. ServiceBusReceiver dlqReceiver = client.CreateReceiver(queueName, new ServiceBusReceiverOptions { SubQueue = SubQueue.DeadLetter }); ServiceBusReceivedMessage dlqMessage = await dlqReceiver.ReceiveMessageAsync(); #endregion Assert.IsNotNull(dlqMessage); } }
public async Task <bool> EnviarAsync([FromBody] Data data) { string connectionString = "Endpoint=sb://queuealejandra.servicebus.windows.net/;SharedAccessKeyName=Enviar;SharedAccessKey=P+OTZO46Jawz+f/ym1JBbW3RCXR0siIchNRoqQzldgE=;EntityPath=colaexamen"; string queueName = "colaexamen"; string mensaje = JsonConvert.SerializeObject(data); // create a Service Bus client await using (ServiceBusClient client = new ServiceBusClient(connectionString)) { // create a sender for the queue ServiceBusSender sender = client.CreateSender(queueName); // create a message that we can send ServiceBusMessage message = new ServiceBusMessage(mensaje); // send the message await sender.SendMessageAsync(message); Console.WriteLine($"Sent a single message to the queue: {queueName}"); } return(true); }
/// <summary> /// Send Message /// </summary> /// <param name="msg"></param> /// <returns></returns> public async Task SendMessageAsync(Model.Message msg) { var a = new Appsettings(); await using var queueClient = new ServiceBusClient(Appsettings.app("ServiceBus", "PrimaryConnectionString")); try { // create the sender ServiceBusSender sender = queueClient.CreateSender(Appsettings.app("ServiceBus", "QueueName")); string messageBody = JsonSerializer.Serialize(msg); // create a message that we can send. UTF-8 encoding is used when providing a string. ServiceBusMessage message = new ServiceBusMessage(messageBody); // send the message await sender.SendMessageAsync(message); Console.WriteLine($"Sending message: {messageBody} success"); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public async Task <bool> EnviarAsync([FromBody] Data data) { string connectionString = "Endpoint=sb://queuematias.servicebus.windows.net/;SharedAccessKeyName=EnviarEscuchar;SharedAccessKey=lYoAp1ZH4bl82XopQWgqWp5v2b1r8jF++31YX9qqF5U=;EntityPath=telemetria"; string queueName = "telemetria"; string mensaje = JsonConvert.SerializeObject(data); // create a Service Bus client await using (ServiceBusClient client = new ServiceBusClient(connectionString)) { // create a sender for the queue ServiceBusSender sender = client.CreateSender(queueName); // create a message that we can send ServiceBusMessage message = new ServiceBusMessage(mensaje); // send the message await sender.SendMessageAsync(message); Console.WriteLine($"Sent a single message to the queue: {queueName}"); } return(true); }
public async Task <bool> EnviarAsync([FromBody] Doble doble) { string connectionString = "Endpoint=sb://qimpar1.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=B8AJ5zfVsOdJ+5bl9wIn2WZSjOGFtnHMeipdkqcbHoI="; string queueName = "qImpar1"; string mensaje = JsonConvert.SerializeObject(doble); // create a Service Bus client await using (ServiceBusClient client = new ServiceBusClient(connectionString)) { // create a sender for the queue ServiceBusSender sender = client.CreateSender(queueName); // create a message that we can send ServiceBusMessage message = new ServiceBusMessage(mensaje); // send the message await sender.SendMessageAsync(message); Console.WriteLine($"Sent a single message to the queue: {queueName}"); } return(true); }
public async Task <bool> EnviarAsync([FromBody] Random random) { string connectionString = "Endpoint=sb://queueimpar.servicebus.windows.net/;SharedAccessKeyName=Enviar;SharedAccessKey=E0taZrbR5+FvaHyCrmlncvUIyGyx+Zb+EoU91OYoFFY=;EntityPath=colaimpar"; string queueName = "colaImpar"; string mensaje = JsonConvert.SerializeObject(random); await using (ServiceBusClient client = new ServiceBusClient(connectionString)) { // create a sender for the queue ServiceBusSender sender = client.CreateSender(queueName); // create a message that we can send ServiceBusMessage message = new ServiceBusMessage(mensaje); // send the message await sender.SendMessageAsync(message); Console.WriteLine($"Sent a single message to the queue: {queueName}"); } return(true); }
static async Task Main(string[] args) { string connectionString = "<connection_string>"; string queueName = "<queue_name>"; // Because ServiceBusClient implements IAsyncDisposable, we'll create it // with "await using" so that it is automatically disposed for us. await using var client = new ServiceBusClient(connectionString); // The sender is responsible for publishing messages to the queue. ServiceBusSender sender = client.CreateSender(queueName); ServiceBusMessage message = new ServiceBusMessage("Hello world!"); await sender.SendMessageAsync(message); // The receiver is responsible for reading messages from the queue. ServiceBusReceiver receiver = client.CreateReceiver(queueName); ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync(); string body = receivedMessage.Body.ToString(); Console.WriteLine(body); }
public async Task <bool> EnviarAsync([FromBody] Data data) { string connectionString = "Endpoint=sb://asrservicebusexamen.servicebus.windows.net/;SharedAccessKeyName=Enviar;SharedAccessKey=lojvYiX4m9RMFw5ffl0fCSQlzUw8NHAYqOZVPtAAfpk=;EntityPath=asrcolaexamen"; string queueName = "asrcolaexamen"; string mensaje = JsonConvert.SerializeObject(data); // create a Service Bus client await using (ServiceBusClient client = new ServiceBusClient(connectionString)) { // create a sender for the queue ServiceBusSender sender = client.CreateSender(queueName); // create a message that we can send ServiceBusMessage message = new ServiceBusMessage(mensaje); // send the message await sender.SendMessageAsync(message); Console.WriteLine($"Sent a single message to the queue: {queueName}"); } return(true); }
public async Task <bool> EnviarAsync([FromBody] Data data) { string connectionString = "Endpoint=sb://queuealdo.servicebus.windows.net/;SharedAccessKeyName=Enviar;SharedAccessKey=JtBQdG776rTy57FzgCL1vOdWevmnQ6UU+j2U8zGHWPo=;EntityPath=practica"; string queueName = "practica"; string mensaje = JsonConvert.SerializeObject(data); // create a Service Bus client await using (ServiceBusClient client = new ServiceBusClient(connectionString)) { // create a sender for the queue ServiceBusSender sender = client.CreateSender(queueName); // create a message that we can send ServiceBusMessage message = new ServiceBusMessage(mensaje); // send the message await sender.SendMessageAsync(message); Console.WriteLine($"Sent a single message to the queue: {queueName}"); } return(true); }
public async Task SendMessage(string queueOrTopicName, ServiceBusReceivedMessage message, CancellationToken cancellationToken) { ServiceBusSender publisher = null; try { publisher = _client.CreateSender(queueOrTopicName); var serviceBusMessage = new ServiceBusMessage(message); await publisher.SendMessageAsync(serviceBusMessage, cancellationToken); } catch (Exception ex) { _logger.LogError(ex, "Service Bus message sending error"); throw new ServiceBusPublisherOperationException("Service Bus message sending error", ex); } finally { if (publisher != null) { await publisher.DisposeAsync(); } } }
private async Task SendItems(ServiceBusClient client, string store) { // create the sender ServiceBusSender tc = client.CreateSender(TopicName); for (int i = 0; i < NrOfMessagesPerStore; i++) { Random r = new Random(); Item item = new Item(r.Next(5), r.Next(5), r.Next(5)); // Note the extension class which is serializing an deserializing messages ServiceBusMessage message = item.AsMessage(); message.To = store; message.ApplicationProperties.Add("StoreId", store); message.ApplicationProperties.Add("Price", item.GetPrice().ToString()); message.ApplicationProperties.Add("Color", item.GetColor()); message.ApplicationProperties.Add("Category", item.GetItemCategory()); await tc.SendMessageAsync(message); Console.WriteLine($"Sent item to Store {store}. Price={item.GetPrice()}, Color={item.GetColor()}, Category={item.GetItemCategory()}");; } }
public async Task <bool> EnviarAsync([FromBody] Data data) { string connectionString = "Endpoint=sb://queueahlo.servicebus.windows.net/;SharedAccessKeyName=Enviar;SharedAccessKey=kyuoXCuzFT5g6/D8fOQG9cW27f35AgMj8aF15W6pdKM=;EntityPath=cola1"; string queueName = "cola1"; string mensaje = JsonConvert.SerializeObject(data); // create a Service Bus client await using (ServiceBusClient client = new ServiceBusClient(connectionString)) { // create a sender for the queue ServiceBusSender sender = client.CreateSender(queueName); // create a message that we can send ServiceBusMessage message = new ServiceBusMessage(mensaje); // send the message await sender.SendMessageAsync(message); Console.WriteLine($"Sent a single message to the queue: {queueName}"); } return(true); }
public async Task <bool> EnviarAsync([FromBody] Odometro odometro) { string connectionString = "Endpoint=sb://queuematias.servicebus.windows.net/;SharedAccessKeyName=enviar;SharedAccessKey=/NoSg88zhM6W5wCoN6kmMdFNv1hebNZ2V3rSFz21zWA=;EntityPath=ejercicios"; string queueName = "ejercicios"; string mensaje = JsonConvert.SerializeObject(odometro); // create a Service Bus client await using (ServiceBusClient client = new ServiceBusClient(connectionString)) { // create a sender for the queue ServiceBusSender sender = client.CreateSender(queueName); // create a message that we can send ServiceBusMessage message = new ServiceBusMessage(mensaje); // send the message await sender.SendMessageAsync(message); Console.WriteLine($"Sent a single message to the queue: {queueName}"); } return(true); }
public async Task <bool> EnviarAsync([FromBody] Data data) { string connectionString = "Endpoint=sb://queuehoracio.servicebus.windows.net/;SharedAccessKeyName=enviar;SharedAccessKey=SDC8MDPHqYiSJoZzlkS5bR/EHVyDWWMlTziLWmoTzMM=;EntityPath=cola1"; string queueName = "cola1"; string mensaje = JsonConvert.SerializeObject(data); // create a Service Bus client await using (ServiceBusClient client = new ServiceBusClient(connectionString)) { // create a sender for the queue ServiceBusSender sender = client.CreateSender(queueName); // create a message that we can send ServiceBusMessage message = new ServiceBusMessage(mensaje); // send the message await sender.SendMessageAsync(message); Console.WriteLine($"Sent a single message to the queue: {queueName}"); } return(true); }
public async Task <bool> EnviarAsync([FromBody] Data data) { string connectionString = "Endpoint=sb://yabetaholding.servicebus.windows.net/;SharedAccessKeyName=Enviar;SharedAccessKey=eyjajSQdPQkGy4qICD9XZe8wfBQOVoXdlmv2u7ReFBw=;EntityPath=practica"; string queueName = "practica"; string mensaje = JsonConvert.SerializeObject(data); // create a Service Bus client await using (ServiceBusClient client = new ServiceBusClient(connectionString)) { // create a sender for the queue ServiceBusSender sender = client.CreateSender(queueName); // create a message that we can send ServiceBusMessage message = new ServiceBusMessage(mensaje); // send the message await sender.SendMessageAsync(message); Console.WriteLine($"Sent a single message to the queue: {queueName}"); } return(true); }
public async Task <bool> EnviarAsync([FromBody] Data data) { string connectionString = "Endpoint=sb://yabetaholding.servicebus.windows.net/;SharedAccessKeyName=Enviar;SharedAccessKey=RypdtkeHAdSf8LxbIx2LWJoEbetcsuvzxMrp5mEs+gM=;EntityPath=cola1"; string queueName = "cola1"; string mensaje = JsonConvert.SerializeObject(data); // create a Service Bus client await using (ServiceBusClient client = new ServiceBusClient(connectionString)) { // create a sender for the queue ServiceBusSender sender = client.CreateSender(queueName); // create a message that we can send ServiceBusMessage message = new ServiceBusMessage(mensaje); // send the message await sender.SendMessageAsync(message); Console.WriteLine($"Sent a single message to the queue: {queueName}"); } return(true); }
public async Task CompleteMessage() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false)) { #region Snippet:ServiceBusCompleteMessage #if SNIPPET string connectionString = "<connection_string>"; string queueName = "<queue_name>"; #else string connectionString = TestEnvironment.ServiceBusConnectionString; string queueName = scope.QueueName; #endif // since ServiceBusClient implements IAsyncDisposable we create it with "await using" await using var client = new ServiceBusClient(connectionString); // create the sender ServiceBusSender sender = client.CreateSender(queueName); // create a message that we can send ServiceBusMessage message = new ServiceBusMessage("Hello world!"); // send the message await sender.SendMessageAsync(message); // create a receiver that we can use to receive and settle the message ServiceBusReceiver receiver = client.CreateReceiver(queueName); // the received message is a different type as it contains some service set properties ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync(); // complete the message, thereby deleting it from the service await receiver.CompleteMessageAsync(receivedMessage); #endregion Assert.IsNull(await CreateNoRetryClient().CreateReceiver(queueName).ReceiveMessageAsync()); } }
// Passes service bus message from a queue to another queue public async Task SBQueue2SBQueue( [ServiceBusTrigger(FirstQueueNameKey)] string body, int deliveryCount, string lockToken, string deadLetterSource, DateTime expiresAtUtc, DateTime enqueuedTimeUtc, string contentType, string replyTo, string to, string subject, string label, string correlationId, IDictionary <string, object> applicationProperties, IDictionary <string, object> userProperties, ServiceBusMessageActions messageActions, [ServiceBus(SecondQueueNameKey)] ServiceBusSender messageSender) { Assert.AreEqual("E2E", body); Assert.AreEqual(1, deliveryCount); Assert.IsNotNull(lockToken); Assert.IsNull(deadLetterSource); Assert.AreEqual("replyTo", replyTo); Assert.AreEqual("to", to); Assert.AreEqual("subject", subject); Assert.AreEqual("subject", label); Assert.AreEqual("correlationId", correlationId); Assert.AreEqual("application/json", contentType); Assert.AreEqual("value", applicationProperties["key"]); Assert.AreEqual("value", userProperties["key"]); Assert.IsTrue(expiresAtUtc > DateTime.UtcNow); Assert.IsTrue(enqueuedTimeUtc < DateTime.UtcNow); var message = SBQueue2SBQueue_GetOutputMessage(body); await messageSender.SendMessageAsync(message); }
public void SendMessageExceptionLogsEvents() { var mockLogger = new Mock <ServiceBusEventSource>(); var mockTransportSender = new Mock <TransportSender>(); var mockConnection = GetMockConnection(mockTransportSender); var sender = new ServiceBusSender( "queueName", new ServiceBusSenderOptions(), mockConnection.Object, new ServiceBusPlugin[] { }) { Logger = mockLogger.Object }; mockTransportSender.Setup( sender => sender.SendAsync( It.IsAny <IReadOnlyList <ServiceBusMessage> >(), It.IsAny <CancellationToken>())) .Throws(new Exception()); Assert.That( async() => await sender.SendMessageAsync(GetMessage()), Throws.InstanceOf <Exception>()); mockLogger .Verify( log => log.SendMessageStart( sender.Identifier, 1), Times.Once); mockLogger .Verify( log => log.SendMessageException( sender.Identifier, It.IsAny <string>()), Times.Once); }
public async Task TransactionalSetSessionState() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: true)) { #region Snippet:ServiceBusTransactionalSetSessionState #if SNIPPET string connectionString = "<connection_string>"; string queueName = "<queue_name>"; // since ServiceBusClient implements IAsyncDisposable we create it with "await using" await using var client = new ServiceBusClient(connectionString); #else await using var client = CreateClient(); string queueName = scope.QueueName; #endif ServiceBusSender sender = client.CreateSender(queueName); await sender.SendMessageAsync(new ServiceBusMessage("my message") { SessionId = "sessionId" }); ServiceBusSessionReceiver receiver = await client.AcceptNextSessionAsync(queueName); ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync(); var state = Encoding.UTF8.GetBytes("some state"); using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { await receiver.CompleteMessageAsync(receivedMessage); await receiver.SetSessionStateAsync(new BinaryData(state)); ts.Complete(); } #endregion var bytes = await receiver.GetSessionStateAsync(); Assert.AreEqual(state, bytes.ToArray()); }; }
private async Task <List <QueryResponse> > PushMessageAsync(IDictionary <string, object> config, string id, Core.Mesh.Properties properties) { string connectionString = "<connection_string>"; string queueName = "<queue_name>"; await using var client = new ServiceBusClient(connectionString); var objectToSend = new AzureServiceBusMessage() { Configuration = config, Entity = AppContext.System.Organization.DataStores.PrimaryDataStore.GetById(AppContext.System.CreateExecutionContext(), new Guid(id)), ChangeSet = properties }; ServiceBusSender sender = client.CreateSender(queueName); ServiceBusMessage message = new ServiceBusMessage(JsonUtility.Serialize(objectToSend)); await sender.SendMessageAsync(message); return(new List <QueryResponse>() { new QueryResponse() { Content = string.Empty, StatusCode = System.Net.HttpStatusCode.OK } }); }
public async Task DeferMessage() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false)) { string connectionString = TestEnvironment.ServiceBusConnectionString; string queueName = scope.QueueName; // since ServiceBusClient implements IAsyncDisposable we create it with "await using" await using var client = new ServiceBusClient(connectionString); // create the sender ServiceBusSender sender = client.CreateSender(queueName); // create a message that we can send ServiceBusMessage message = new ServiceBusMessage(Encoding.UTF8.GetBytes("Hello world!")); // send the message await sender.SendMessageAsync(message); // create a receiver that we can use to receive and settle the message ServiceBusReceiver receiver = client.CreateReceiver(queueName); #region Snippet:ServiceBusDeferMessage ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync(); // defer the message, thereby preventing the message from being received again without using // the received deferred message API. await receiver.DeferMessageAsync(receivedMessage); // receive the deferred message by specifying the service set sequence number of the original // received message ServiceBusReceivedMessage deferredMessage = await receiver.ReceiveDeferredMessageAsync(receivedMessage.SequenceNumber); #endregion Assert.IsNotNull(deferredMessage); } }
public async Task GetSubscriptionRuntimeInfoTest() { var topicName = nameof(GetSubscriptionRuntimeInfoTest).ToLower() + Recording.Random.NewGuid().ToString("D").Substring(0, 8); var subscriptionName = Recording.Random.NewGuid().ToString("D").Substring(0, 8); var client = CreateClient(); await using var sbClient = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString); await client.CreateTopicAsync(topicName); TopicProperties getTopic = await client.GetTopicAsync(topicName); // Changing Last Updated Time getTopic.AutoDeleteOnIdle = TimeSpan.FromMinutes(100); await client.UpdateTopicAsync(getTopic); SubscriptionProperties subscriptionDescription = await client.CreateSubscriptionAsync(topicName, subscriptionName); // Changing Last Updated Time for subscription subscriptionDescription.AutoDeleteOnIdle = TimeSpan.FromMinutes(100); await client.UpdateSubscriptionAsync(subscriptionDescription); // Populating 1 active message, 1 dead letter message and 1 scheduled message // Changing Last Accessed Time ServiceBusSender sender = sbClient.CreateSender(topicName); await sender.SendMessageAsync(new ServiceBusMessage() { MessageId = "1" }); await sender.SendMessageAsync(new ServiceBusMessage() { MessageId = "2" }); await sender.SendMessageAsync(new ServiceBusMessage() { MessageId = "3", ScheduledEnqueueTime = DateTime.UtcNow.AddDays(1) }); ServiceBusReceiver receiver = sbClient.CreateReceiver(topicName, subscriptionName); ServiceBusReceivedMessage msg = await receiver.ReceiveMessageAsync(); await receiver.DeadLetterMessageAsync(msg.LockToken); List <SubscriptionRuntimeProperties> runtimeInfoList = new List <SubscriptionRuntimeProperties>(); await foreach (SubscriptionRuntimeProperties subscriptionRuntimeInfo in client.GetSubscriptionsRuntimePropertiesAsync(topicName)) { runtimeInfoList.Add(subscriptionRuntimeInfo); } runtimeInfoList = runtimeInfoList.Where(e => e.TopicName.StartsWith(nameof(GetSubscriptionRuntimeInfoTest).ToLower())).ToList(); Assert.True(runtimeInfoList.Count == 1, $"Expected 1 subscription but {runtimeInfoList.Count} subscriptions returned"); SubscriptionRuntimeProperties runtimeInfo = runtimeInfoList.First(); Assert.NotNull(runtimeInfo); Assert.AreEqual(topicName, runtimeInfo.TopicName); Assert.AreEqual(subscriptionName, runtimeInfo.SubscriptionName); Assert.True(runtimeInfo.CreatedAt < runtimeInfo.UpdatedAt); Assert.True(runtimeInfo.UpdatedAt < runtimeInfo.AccessedAt); Assert.AreEqual(1, runtimeInfo.ActiveMessageCount); Assert.AreEqual(1, runtimeInfo.DeadLetterMessageCount); Assert.AreEqual(2, runtimeInfo.TotalMessageCount); SubscriptionRuntimeProperties singleRuntimeInfo = await client.GetSubscriptionRuntimePropertiesAsync(topicName, subscriptionName); Assert.AreEqual(runtimeInfo.CreatedAt, singleRuntimeInfo.CreatedAt); Assert.AreEqual(runtimeInfo.AccessedAt, singleRuntimeInfo.AccessedAt); Assert.AreEqual(runtimeInfo.UpdatedAt, singleRuntimeInfo.UpdatedAt); Assert.AreEqual(runtimeInfo.SubscriptionName, singleRuntimeInfo.SubscriptionName); Assert.AreEqual(runtimeInfo.TotalMessageCount, singleRuntimeInfo.TotalMessageCount); Assert.AreEqual(runtimeInfo.ActiveMessageCount, singleRuntimeInfo.ActiveMessageCount); Assert.AreEqual(runtimeInfo.DeadLetterMessageCount, singleRuntimeInfo.DeadLetterMessageCount); Assert.AreEqual(runtimeInfo.TopicName, singleRuntimeInfo.TopicName); List <TopicRuntimeProperties> topicRuntimePropertiesList = new List <TopicRuntimeProperties>(); await foreach (TopicRuntimeProperties topicRuntime in client.GetTopicsRuntimePropertiesAsync()) { topicRuntimePropertiesList.Add(topicRuntime); } topicRuntimePropertiesList = topicRuntimePropertiesList.Where(e => e.Name.StartsWith(nameof(GetSubscriptionRuntimeInfoTest).ToLower())).ToList(); Assert.True(topicRuntimePropertiesList.Count == 1, $"Expected 1 subscription but {topicRuntimePropertiesList.Count} subscriptions returned"); TopicRuntimeProperties topicRuntimeProperties = topicRuntimePropertiesList.First(); Assert.NotNull(topicRuntimeProperties); Assert.AreEqual(topicName, topicRuntimeProperties.Name); Assert.True(topicRuntimeProperties.CreatedAt < topicRuntimeProperties.UpdatedAt); Assert.True(topicRuntimeProperties.UpdatedAt < topicRuntimeProperties.AccessedAt); Assert.AreEqual(1, topicRuntimeProperties.ScheduledMessageCount); TopicRuntimeProperties singleTopicRuntimeProperties = await client.GetTopicRuntimePropertiesAsync(topicName); Assert.AreEqual(topicRuntimeProperties.CreatedAt, singleTopicRuntimeProperties.CreatedAt); Assert.AreEqual(topicRuntimeProperties.AccessedAt, singleTopicRuntimeProperties.AccessedAt); Assert.AreEqual(topicRuntimeProperties.UpdatedAt, singleTopicRuntimeProperties.UpdatedAt); Assert.AreEqual(topicRuntimeProperties.ScheduledMessageCount, singleTopicRuntimeProperties.ScheduledMessageCount); Assert.AreEqual(topicRuntimeProperties.Name, singleTopicRuntimeProperties.Name); await client.DeleteTopicAsync(topicName); }