public async Task BasicTopicCrudOperations() { var topicName = nameof(BasicTopicCrudOperations).ToLower() + Recording.Random.NewGuid().ToString("D").Substring(0, 8); var client = CreateClient(); var options = new CreateTopicOptions(topicName) { AutoDeleteOnIdle = TimeSpan.FromHours(1), DefaultMessageTimeToLive = TimeSpan.FromDays(2), DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1), EnableBatchedOperations = true, EnablePartitioning = false, MaxSizeInMegabytes = 1024, RequiresDuplicateDetection = true, UserMetadata = nameof(BasicTopicCrudOperations) }; options.AuthorizationRules.Add(new SharedAccessAuthorizationRule( "allClaims", new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen })); Response <TopicProperties> createdTopicResponse = await client.CreateTopicAsync(options); Response rawResponse = createdTopicResponse.GetRawResponse(); Assert.NotNull(rawResponse.ClientRequestId); Assert.IsTrue(rawResponse.ContentStream.CanRead); Assert.AreEqual(0, rawResponse.ContentStream.Position); TopicProperties createdTopic = createdTopicResponse.Value; if (Mode == RecordedTestMode.Playback) { // Auth rules use a randomly generated key, but we don't want to store // these in our test recordings, so we skip the auth rule comparison // when in playback mode. Assert.AreEqual(options, new CreateTopicOptions(createdTopic) { AuthorizationRules = options.AuthorizationRules.Clone() }); Assert.AreEqual(createdTopic, new TopicProperties(options) { AuthorizationRules = createdTopic.AuthorizationRules.Clone() }); } else { Assert.AreEqual(options, new CreateTopicOptions(createdTopic)); Assert.AreEqual(createdTopic, new TopicProperties(options)); } Response <TopicProperties> getTopicResponse = await client.GetTopicAsync(options.Name); rawResponse = getTopicResponse.GetRawResponse(); Assert.NotNull(rawResponse.ClientRequestId); Assert.IsTrue(rawResponse.ContentStream.CanRead); Assert.AreEqual(0, rawResponse.ContentStream.Position); TopicProperties getTopic = getTopicResponse.Value; Assert.AreEqual(createdTopic, getTopic); getTopic.EnableBatchedOperations = false; getTopic.DefaultMessageTimeToLive = TimeSpan.FromDays(3); getTopic.DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(2); getTopic.EnableBatchedOperations = false; getTopic.MaxSizeInMegabytes = 1024; Response <TopicProperties> updatedTopicResponse = await client.UpdateTopicAsync(getTopic); rawResponse = updatedTopicResponse.GetRawResponse(); Assert.NotNull(rawResponse.ClientRequestId); Assert.IsTrue(rawResponse.ContentStream.CanRead); Assert.AreEqual(0, rawResponse.ContentStream.Position); TopicProperties updatedTopic = updatedTopicResponse.Value; Assert.AreEqual(getTopic, updatedTopic); bool exists = await client.TopicExistsAsync(topicName); Assert.True(exists); List <TopicProperties> topicList = new List <TopicProperties>(); await foreach (TopicProperties topic in client.GetTopicsAsync()) { topicList.Add(topic); } topicList = topicList.Where(e => e.Name.StartsWith(nameof(BasicTopicCrudOperations).ToLower())).ToList(); Assert.True(topicList.Count == 1, $"Expected 1 topic but {topicList.Count} topics returned"); Assert.AreEqual(topicList.First().Name, topicName); Response response = await client.DeleteTopicAsync(updatedTopic.Name); Assert.NotNull(response.ClientRequestId); Assert.IsTrue(response.ContentStream.CanRead); Assert.AreEqual(0, response.ContentStream.Position); Assert.That( async() => await client.GetTopicAsync(options.Name), Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason)).EqualTo(ServiceBusFailureReason.MessagingEntityNotFound)); exists = await client.TopicExistsAsync(topicName); Assert.False(exists); }
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); 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); }
public IBuilder UseTopicProperties(TopicProperties properties) { ApplyParameters(properties); return(this); }
public async Task BasicTopicCrudOperations() { var topicName = nameof(BasicTopicCrudOperations).ToLower() + Guid.NewGuid().ToString("D").Substring(0, 8); var client = new ServiceBusManagementClient(TestEnvironment.ServiceBusConnectionString); var options = new CreateTopicOptions(topicName) { AutoDeleteOnIdle = TimeSpan.FromHours(1), DefaultMessageTimeToLive = TimeSpan.FromDays(2), DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1), EnableBatchedOperations = true, EnablePartitioning = false, MaxSizeInMegabytes = 2048, RequiresDuplicateDetection = true, UserMetadata = nameof(BasicTopicCrudOperations) }; options.AuthorizationRules.Add(new SharedAccessAuthorizationRule( "allClaims", new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen })); TopicProperties createdTopic = await client.CreateTopicAsync(options); Assert.AreEqual(options, new CreateTopicOptions(createdTopic)); TopicProperties getTopic = await client.GetTopicAsync(options.Name); Assert.AreEqual(createdTopic, getTopic); getTopic.EnableBatchedOperations = false; getTopic.DefaultMessageTimeToLive = TimeSpan.FromDays(3); getTopic.DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(2); getTopic.EnableBatchedOperations = false; getTopic.MaxSizeInMegabytes = 1024; TopicProperties updatedTopic = await client.UpdateTopicAsync(getTopic); Assert.AreEqual(getTopic, updatedTopic); bool exists = await client.TopicExistsAsync(topicName); Assert.True(exists); List <TopicProperties> topicList = new List <TopicProperties>(); await foreach (TopicProperties topic in client.GetTopicsAsync()) { topicList.Add(topic); } topicList = topicList.Where(e => e.Name.StartsWith(nameof(BasicTopicCrudOperations).ToLower())).ToList(); Assert.True(topicList.Count == 1, $"Expected 1 topic but {topicList.Count} topics returned"); Assert.AreEqual(topicList.First().Name, topicName); await client.DeleteTopicAsync(updatedTopic.Name); Assert.That( async() => await client.GetTopicAsync(options.Name), Throws.InstanceOf <ServiceBusException>().And.Property(nameof(ServiceBusException.Reason)).EqualTo(ServiceBusException.FailureReason.MessagingEntityNotFound)); exists = await client.TopicExistsAsync(topicName); Assert.False(exists); }
public async Task CreateTopicAndSubscription() { string adminTopicName = Guid.NewGuid().ToString("D").Substring(0, 8); string adminSubscriptionName = Guid.NewGuid().ToString("D").Substring(0, 8); string adminConnectionString = TestEnvironment.ServiceBusConnectionString; try { #region Snippet:CreateTopicAndSubscription #if SNIPPET string connectionString = "<connection_string>"; string topicName = "<topic_name>"; #else string connectionString = adminConnectionString; string topicName = adminTopicName; #endif var client = new ServiceBusAdministrationClient(connectionString); var topicOptions = new CreateTopicOptions(topicName) { AutoDeleteOnIdle = TimeSpan.FromDays(7), DefaultMessageTimeToLive = TimeSpan.FromDays(2), DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1), EnableBatchedOperations = true, EnablePartitioning = false, MaxSizeInMegabytes = 2048, RequiresDuplicateDetection = true, UserMetadata = "some metadata" }; topicOptions.AuthorizationRules.Add(new SharedAccessAuthorizationRule( "allClaims", new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen })); TopicProperties createdTopic = await client.CreateTopicAsync(topicOptions); #if SNIPPET string subscriptionName = "<subscription_name>"; #else string subscriptionName = adminSubscriptionName; #endif var subscriptionOptions = new CreateSubscriptionOptions(topicName, subscriptionName) { AutoDeleteOnIdle = TimeSpan.FromDays(7), DefaultMessageTimeToLive = TimeSpan.FromDays(2), EnableBatchedOperations = true, UserMetadata = "some metadata" }; SubscriptionProperties createdSubscription = await client.CreateSubscriptionAsync(subscriptionOptions); #endregion Assert.AreEqual(topicOptions, new CreateTopicOptions(createdTopic) { MaxMessageSizeInKilobytes = topicOptions.MaxMessageSizeInKilobytes }); Assert.AreEqual(subscriptionOptions, new CreateSubscriptionOptions(createdSubscription)); } finally { await new ServiceBusAdministrationClient(adminConnectionString).DeleteTopicAsync(adminTopicName); } }
static async Task Main(string[] args) { Console.WriteLine("Hello World!"); #region Creating Objects QueueProperties queue = await ServiceBusObjects.GetQueueAsync(ConnectionString, QueueName); if (queue == null) { queue = await ServiceBusObjects.CreateQueueAsync(ConnectionString, QueueName); } QueueProperties sessionQueue = await ServiceBusObjects.GetQueueAsync(ConnectionString, SessionQueueName); if (sessionQueue == null) { sessionQueue = await ServiceBusObjects.CreateQueueAsync(ConnectionString, SessionQueueName, true); } TopicProperties topic = await ServiceBusObjects.GetTopicAsync(TopicName, ConnectionString); if (topic == null) { topic = await ServiceBusObjects.CreateTopicAsync(TopicName, ConnectionString); } SubscriptionProperties subscription = await ServiceBusObjects.GetSubscriptionAsync(TopicName, ConnectionString, SubscriptionName); if (subscription == null) { subscription = await ServiceBusObjects.CreateSubscriptionAsync(TopicName, ConnectionString, SubscriptionName); } #endregion #region Sending and Receiving Messages int count = 0; //sending messages await SendAndReceiveMessage.SendMessageAsync(ConnectionString, QueueName, $"Message {count++}"); await SendAndReceiveMessage.SendMessageBatchAsync(ConnectionString, QueueName, new System.Collections.Generic.List <string> { $"Message {count++}", $"Message {count++}", $"Message {count++}", $"Message {count++}" }); await SendAndReceiveMessage.SendMessageSafeBatchAsync(ConnectionString, QueueName, new System.Collections.Generic.List <string> { $"Message {count++}", $"Message {count++}", $"Message {count++}", $"Message {count++}" }); long firstScheduledMessageNumber = await SendAndReceiveMessage.SendScheduledMessageAsync(ConnectionString, QueueName, $"Message {count++}", new DateTimeOffset(DateTime.Now.AddMinutes(10))); long secondScheduledMessageNumber = await SendAndReceiveMessage.SendScheduledMessageAsync(ConnectionString, QueueName, $"Message {count++}", new DateTimeOffset(DateTime.Now.AddMinutes(10))); await SendAndReceiveMessage.CancelScheduledMessageAsync(ConnectionString, QueueName, firstScheduledMessageNumber); long deferredMessageNumber = await SendAndReceiveMessage.DeferMessageAsync(ConnectionString, QueueName); Console.WriteLine((await SendAndReceiveMessage.GetDeferredMessageAsync(ConnectionString, QueueName, deferredMessageNumber)).Body); await SendAndReceiveMessage.DeadLetterMessageAsync(ConnectionString, QueueName); Console.WriteLine((await SendAndReceiveMessage.GetDeadLetterMessageAsync(ConnectionString, QueueName)).Body); Console.WriteLine((await SendAndReceiveMessage.GetMessageAsync(ConnectionString, QueueName)).Body); await SendAndReceiveMessage.CompleteOrAbandonMessageAsync(ConnectionString, QueueName, false); await SendAndReceiveMessage.CompleteOrAbandonMessageAsync(ConnectionString, QueueName, true); #endregion #region Sending and Receiving Session Messages await SendAndReceiveMessage.SendSessionMessageAsync(ConnectionString, SessionQueueName, $"Message {count++}", "session id 1"); Console.WriteLine((await SendAndReceiveMessage.GetMessageFromSessionAsync(ConnectionString, SessionQueueName, "session id 1")).Body); #endregion #region Messages Processor await Processor.RunProcessor(ConnectionString, QueueName, new TimeSpan(0, 0, 10)); #endregion #region Session Processor await SessionProcessor.RunSessionProcessor(ConnectionString, SessionQueueName, new TimeSpan(0, 0, 10)); #endregion }
/// <summary> /// The main function in the sample. /// </summary> /// <param name="args"></param> public override void SampleCall(string[] args) { #region Parse Arguments ArgParser cmdLineParser = new ArgParser(); if (!cmdLineParser.Parse(args)) { // parse failed PrintUsage(INVALID_ARGUMENTS_ERROR); return; } cmdLineParser.Config.DeliveryMode = MessageDeliveryMode.Direct; #endregion #region Initialize properties from command line // Initialize the properties. ContextProperties contextProps = new ContextProperties(); SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config); #endregion // Define IContext and three ISessions. IContext context = null; ISession session = null; ISession dtoSession1 = null; ISession dtoSession2 = null; try { InitContext(cmdLineParser.LogLevel); #region Create the Context Console.WriteLine("About to create the context ..."); context = ContextFactory.Instance.CreateContext(contextProps, null); Console.WriteLine("Context successfully created. "); #endregion #region Create and Connect 3 sessions Console.WriteLine("About to create the sessions ..."); // To demontrate where the messages are being received, a // custom message handler class is used. This message handler // enables a session name to be specified. The name is included in // the ouptut when a message is received. DtoPrintingMessageHandler sessionMessageHandler1 = new DtoPrintingMessageHandler("DTO Override Session"); DtoPrintingMessageHandler sessionMessageHandler2 = new DtoPrintingMessageHandler("DTO Session 1"); DtoPrintingMessageHandler sessionMessageHandler3 = new DtoPrintingMessageHandler("DTO Session 2"); session = context.CreateSession(sessionProps, sessionMessageHandler1.onReceive, SampleUtils.HandleSessionEvent); dtoSession1 = context.CreateSession(sessionProps, sessionMessageHandler2.onReceive, SampleUtils.HandleSessionEvent); dtoSession2 = context.CreateSession(sessionProps, sessionMessageHandler3.onReceive, SampleUtils.HandleSessionEvent); Console.WriteLine("Sessions successfully created."); Console.WriteLine("About to connect the sessions ..."); if ((session.Connect() == ReturnCode.SOLCLIENT_OK) && (dtoSession1.Connect() == ReturnCode.SOLCLIENT_OK) && (dtoSession2.Connect() == ReturnCode.SOLCLIENT_OK)) { Console.WriteLine("Sessions successfully connected"); Console.WriteLine(GetRouterInfo(session)); } #endregion #region Define and subscribe to topics on all 3 sessions // All clients subscribe to the same Topic. TopicProperties topicProps = new TopicProperties(); topicProps.Topic = SampleUtils.SAMPLE_TOPIC; // Create a Topic subscription with Deliver Always enabled. topicProps.IsReceiveAllDeliverToOne = true; ITopic myTopic_deliverAlways = ContextFactory.Instance.CreateTopic(topicProps); // Create a Topic subscription with Deliver Always disabled. topicProps.IsReceiveAllDeliverToOne = false; ITopic myTopic = ContextFactory.Instance.CreateTopic(topicProps); // Add the subscriptions. bool waitForConfirm = true; session.Subscribe(myTopic_deliverAlways, waitForConfirm); dtoSession1.Subscribe(myTopic, waitForConfirm); dtoSession2.Subscribe(myTopic, waitForConfirm); #endregion // Create an empty message to send to our topic. The message // can be empty because we only care about where it gets // delivered and not what the contents are. IMessage msg = SampleUtils.CreateMessage(cmdLineParser.Config, session); msg.Destination = myTopic; msg.DeliverToOne = true; Console.WriteLine(string.Format("About to send {0} messages ...", NumberOfMessagesToPublish)); for (int i = 0; i < NumberOfMessagesToPublish; i++) { // This call accesses custom header data and could impact performance. msg.SequenceNumber = i + 1; if (session.Send(msg) == ReturnCode.SOLCLIENT_OK) { Console.WriteLine("Message {0} sent.", i + 1); } Thread.Sleep(500); // wait for 0.5 seconds } Console.WriteLine(string.Format("\nDone\n Sleeping for {0} secs before exiting ", Timeout / 1000)); Thread.Sleep(Timeout); } catch (Exception ex) { PrintException(ex); } finally { if (session != null) { session.Dispose(); } if (dtoSession1 != null) { dtoSession1.Dispose(); } if (dtoSession2 != null) { dtoSession2.Dispose(); } if (context != null) { context.Dispose(); } // Must cleanup after. CleanupContext(); } }