/// <summary> /// This function is called when the client navigates to *hostname*/CompanyListings /// </summary> /// <returns>A view to be sent to the client</returns> public ActionResult Index() { if (Globals.isLoggedIn()) { ViewBag.Companylist = null; ViewBag.Index = true; ServiceBusConnection connection = ConnectionManager.getConnectionObject(Globals.getUser()); if (connection == null) { return(RedirectToAction("Index", "Authentication")); } CompanySearchRequest request = new CompanySearchRequest(""); CompanySearchResponse response = connection.searchCompanyByName(request); if (response.result) { ViewBag.Companylist = response.list.companyNames; } return(View("Index")); } return(RedirectToAction("Index", "Authentication")); }
public async Task DelegateErrorHandlingIfConfigured() { Debug.WriteLine("Cleaning the subscription..."); await _subscriptionCleanUp; var connection = new ServiceBusConnection(ConnectionString); var topic = new TopicClient(connection, TopicName, RetryPolicy.Default); await topic.SendAsync(new Message(Encoding.UTF8.GetBytes("Hello world"))); await connection .ProcessMessages((message, ct) => throw new Exception("Test error") { Data = { ["Comment"] = "Test" } }) .FromSubscription(TopicName, SubscriptionName, ReceiveMode.PeekLock, RetryPolicy.Default) .WithErrorHandler(args => { Assert.True(args.Exception.Data.Contains("Comment")); Assert.Equal("Test", args.Exception.Data["Comment"]); return(Task.CompletedTask); }) .Take(TimeSpan.FromMilliseconds(300)) .LastOrDefaultAsync(); }
public ActionResult AsIsLogin(string usernameText, string passwordText) { LogInRequest request = new LogInRequest(usernameText, passwordText); ServiceBusResponse response = null; ServiceBusConnection connection = ConnectionManager.getConnectionObject(Globals.getUser()); if (connection == null) { response = ConnectionManager.sendLogIn(request); } else { response = connection.sendLogIn(request); } if (response.result == false) { ViewBag.AsIsResponse = "Login Failed"; return(View("Index")); } else { return(View("~/Views/Home/Index.cshtml")); } }
/// <summary> /// This function is called when the client navigates to *hostname*/CompanyListings/Search /// </summary> /// <returns>A view to be sent to the client</returns> public ActionResult Search(string textCompanyName) { if (Globals.isLoggedIn() == false) { return(RedirectToAction("Index", "Authentication")); } ServiceBusConnection connection = ConnectionManager.getConnectionObject(Globals.getUser()); if (connection == null) { return(RedirectToAction("Index", "Authentication")); } CompanySearchRequest request = new CompanySearchRequest(textCompanyName); CompanySearchResponse response = connection.searchCompanyByName(request); if (response.result == false) { return(RedirectToAction("Index", "Authentication")); } ViewBag.Companylist = response.list; return(View("Index")); }
public ActionResult SendMessage(string receiver = "", int timestamp = -1, string message = "") { if (Globals.isLoggedIn() == false) { return(RedirectToAction("Index", "Authentication")); } if ("".Equals(receiver) || "".Equals(message) || timestamp == -1) { throw new System.Exception("Did not supply all required arguments."); } ServiceBusConnection connection = ConnectionManager.getConnectionObject(Globals.getUser()); if (connection == null) { return(RedirectToAction("Index", "Authentication")); } ChatMessage chatMessage = new ChatMessage { sender = Globals.getUser(), receiver = receiver, unix_timestamp = timestamp, messageContents = message }; SendMessageRequest request = new SendMessageRequest(chatMessage); connection.sendChatMessage(request); return(null); }
public Builder( ServiceBusConnection connection, Func <Message, CancellationToken, IObservable <T> > handler) { _connection = connection ?? throw new ArgumentNullException(nameof(connection)); _messageHandler = handler ?? throw new ArgumentNullException(nameof(handler)); }
public async Task ClientsUseGlobalConnectionCloseFirstClientSecoundClientShouldSendMessage() { await ServiceBusScope.UsingQueueAsync(partitioned : true, sessionEnabled : false, async queueName => { var csb = new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString); var connection = new ServiceBusConnection(csb); var sender = new MessageSender(connection, queueName); var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, receiveMode: ReceiveMode.ReceiveAndDelete); try { var messageBody = Encoding.UTF8.GetBytes("Message"); var message = new Message(messageBody); await sender.SendAsync(message); await sender.CloseAsync(); var recivedMessage = await receiver.ReceiveAsync().ConfigureAwait(false); Assert.True(Encoding.UTF8.GetString(recivedMessage.Body) == Encoding.UTF8.GetString(messageBody)); connection = sender.ServiceBusConnection; sender = new MessageSender(connection, queueName); messageBody = Encoding.UTF8.GetBytes("Message 2"); message = new Message(messageBody); await sender.SendAsync(message); recivedMessage = await receiver.ReceiveAsync().ConfigureAwait(false); Assert.True(Encoding.UTF8.GetString(recivedMessage.Body) == Encoding.UTF8.GetString(messageBody)); } finally { await sender.CloseAsync(); await receiver.CloseAsync(); } }); }
///// <summary> ///// Initializes a new instance of the <see cref="ServiceBusReceiver"/> class. ///// </summary> ///// ///// <param name="connectionString">The connection string to use for connecting to the Service Bus namespace; it is expected that the shared key properties are contained in this connection string, but not the Service Bus entity name.</param> ///// <param name="entityName">The name of the specific Service Bus entity to associate the consumer with.</param> ///// ///// <remarks> ///// If the connection string is copied from the Service Bus entity itself, it will contain the name of the desired Service Bus entity, ///// and can be used directly without passing the <paramref name="entityName" />. The name of the Service Bus entity should be ///// passed only once, either as part of the connection string or separately. ///// </remarks> ///// //public ServiceBusReceiver( // string connectionString, // string entityName) : // this( // connectionString, // entityName, // null, // new ServiceBusReceiverClientOptions()) //{ //} ///// <summary> ///// Initializes a new instance of the <see cref="ServiceBusReceiver"/> class. ///// </summary> ///// ///// <param name="connectionString">The connection string to use for connecting to the Service Bus namespace; it is expected that the shared key properties are contained in this connection string, but not the Service Bus entity name.</param> ///// <param name="entityName">The name of the specific Service Bus entity to associate the consumer with.</param> ///// <param name="clientOptions"></param> ///// ///// <remarks> ///// If the connection string is copied from the Service Bus entity itself, it will contain the name of the desired Service Bus entity, ///// and can be used directly without passing the <paramref name="entityName" />. The name of the Service Bus entity should be ///// passed only once, either as part of the connection string or separately. ///// </remarks> ///// //public ServiceBusReceiver( // string connectionString, // string entityName, // ServiceBusReceiverClientOptions clientOptions) : // this( // connectionString, // entityName, // null, // clientOptions?.Clone() ?? new ServiceBusReceiverClientOptions()) //{ //} /// <summary> /// Initializes a new instance of the <see cref="ServiceBusReceiver"/> class. /// </summary> /// /// <param name="fullyQualifiedNamespace">The fully qualified Service Bus namespace to connect to. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param> /// <param name="entityName">The name of the specific Service Bus entity to associate the consumer with.</param> /// <param name="credential">The Azure managed identity credential to use for authorization. Access controls may be specified by the Service Bus namespace or the requested Service Bus entity, depending on Azure configuration.</param> /// <param name="sessionOptions"></param> /// <param name="clientOptions">A set of options to apply when configuring the consumer.</param> /// internal ServiceBusReceiver( string fullyQualifiedNamespace, string entityName, TokenCredential credential, SessionOptions sessionOptions, ServiceBusReceiverClientOptions clientOptions) { Argument.AssertNotNullOrEmpty(fullyQualifiedNamespace, nameof(fullyQualifiedNamespace)); Argument.AssertNotNullOrEmpty(entityName, nameof(entityName)); Argument.AssertNotNull(credential, nameof(credential)); Argument.AssertNotNull(clientOptions, nameof(clientOptions)); IsSessionReceiver = sessionOptions != null; OwnsConnection = true; Connection = new ServiceBusConnection(fullyQualifiedNamespace, entityName, credential, clientOptions.ConnectionOptions); RetryPolicy = clientOptions.RetryOptions.ToRetryPolicy(); ReceiveMode = clientOptions.ReceiveMode; Consumer = Connection.CreateTransportConsumer( retryPolicy: RetryPolicy, receiveMode: ReceiveMode, prefetchCount: PrefetchCount, sessionId: sessionOptions?.SessionId, isSessionReceiver: IsSessionReceiver); Session = new ServiceBusSession( Consumer, RetryPolicy); }
public async Task CanRegisterQueueWithConnection() { var composer = new ServiceBusComposer(); var serviceBusConnection = new ServiceBusConnection( "Endpoint=sb://labepdvsb.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=TOEhvlmrOoLjHfxhYJ3xjoLtVZrMQLqP8MUwrv5flOA="); var factory = new Mock <IQueueClientFactory>(); factory .Setup(o => o.Create(It.Is <QueueOptions>(opts => opts.Connection == serviceBusConnection))) .Returns((QueueOptions o) => new QueueClientMock("testQueue").QueueClient) .Verifiable(); composer.WithAdditionalServices( services => { services.OverrideQueueClientFactory(factory.Object); services.ConfigureServiceBus( options => { options.RegisterQueue("testQueue").WithConnection(serviceBusConnection); }); }); var provider = await composer.ComposeAndSimulateStartup(); var registry = provider.GetService <IServiceBusRegistry>(); factory.VerifyAll(); Assert.Equal("testQueue", registry.GetQueueSender("testQueue")?.Name); }
/// <inheritdoc /> public Task StartAsync(CancellationToken cancellationToken) { _logger.LogTrace($"Starting [{nameof(ShiftRegistrationQueueMonitor)}]..."); if (_configuration == null || !_configuration.MonitoringEnabled || _monitoringConfiguration == null) { _logger.LogTrace($"Monitoring not configured or disabled."); return(Task.CompletedTask); } _conn = new ServiceBusConnection(_monitoringConfiguration.ServiceBusAccessKey); _queueClient = new MessageReceiver(_conn, _monitoringConfiguration.QueueName, ReceiveMode.PeekLock, prefetchCount: 1) { OperationTimeout = TimeSpan.FromMinutes(2) }; MessageHandlerOptions options = new MessageHandlerOptions(ExceptionReceivedHandler) { AutoComplete = true, // TODO: FALSE? Depending of usage / transaction model MaxAutoRenewDuration = TimeSpan.FromMinutes(1), MaxConcurrentCalls = 3 }; _queueClient.RegisterMessageHandler(RegistrationMessageHandler, options); _logger.LogTrace($"[{nameof(ShiftRegistrationQueueMonitor)}] started."); return(Task.CompletedTask); }
public QueueClient(ServiceBusConnection serviceBusConnection, string entityPath, ReceiveMode receiveMode, RetryPolicy retryPolicy) { var factory = BuildMessagingFactory(serviceBusConnection); factory.RetryPolicy = retryPolicy; this.queueClient = factory.CreateQueueClient(entityPath, receiveMode); }
async Task <ConnectionContext> CreateConnection(ISupervisor supervisor) { var endpoint = new UriBuilder(_hostConfiguration.HostAddress) { Path = "" }.Uri.ToString(); if (supervisor.Stopping.IsCancellationRequested) { throw new OperationCanceledException($"The connection is stopping and cannot be used: {endpoint}"); } var settings = _hostConfiguration.Settings; var retryPolicy = new RetryExponential(settings.RetryMinBackoff, settings.RetryMaxBackoff, settings.RetryLimit); var connection = new ServiceBusConnection(endpoint, settings.TransportType, retryPolicy) { TokenProvider = settings.TokenProvider, OperationTimeout = settings.OperationTimeout }; var managementClient = new ManagementClient(endpoint, settings.TokenProvider); return(new ServiceBusConnectionContext(connection, managementClient, retryPolicy, settings.OperationTimeout, supervisor.Stopped)); }
public GeneralQueueRegistrationTests(ApplicationFixture application) { string?connectionString = _connectionString.Resolve(application.PropertyResolver); _serviceBusConnection = new ServiceBusConnection(connectionString !); _queueManagement = new QueueManagement(_serviceBusConnection); }
private void Connect() { this.connection = new ServiceBusConnection(levelConfig); this.connection.OnServiceBusConnected += Connection_OnServiceBusConnected; this.connection.OnEventLog += Connection_OnEventLog; this.connection.Connect(); }
public ActionResult LogIn(string username, string password) { LogInRequest request = new LogInRequest(username, password); ServiceBusResponse response; ServiceBusConnection connection = ConnectionManager.getConnectionObject(Globals.getUser()); if (connection == null) { response = ConnectionManager.sendLogIn(request); } else { response = connection.sendLogIn(request); } if (response.result) { ViewBag.LoginResponse = "Login Successful"; } else { ViewBag.LoginResponse = "Invalid Username or Password"; } return(View("Index")); }
//This class is incomplete and should be completed by the students in milestone 2 //Hint: You will need to make use of the ServiceBusConnection class. See EchoController.cs for an example. public ActionResult Login(LogInRequest login) { //Do stuff with the new Login Info LogInRequest request = login; ServiceBusResponse response; ServiceBusConnection connection = ConnectionManager.getConnectionObject(Globals.getUser()); if (connection == null) { response = ConnectionManager.sendLogIn(request); } else { response = connection.sendLogIn(request); } ViewBag.AsIsResponse = response.response; if (response.ToString().Equals("Login Successful")) { return(View("~/Home/Index")); } else { return(View("Index")); } }
public ActionResult CreationConfirmationPage(string username, string email, string password, string address, string phonenumber, AccountType users) { CreateAccount account = new CreateAccount(); account.username = username; account.password = password; account.address = address; account.phonenumber = phonenumber; account.email = email; account.type = users; CreateAccountRequest request = new CreateAccountRequest(account); ServiceBusResponse response; ServiceBusConnection connection = ConnectionManager.getConnectionObject(Globals.getUser()); if (connection == null) { response = ConnectionManager.sendNewAccountInfo(request); } else { response = connection.sendNewAccountInfo(request); } if (response.result) { return(View("Index")); } else { ViewBag.CreationMessage = response.response; return(View("CreateAccount")); } }
public ActionResult SaveAccount(CreateAccount account) { //Save this account info CreateAccountRequest request = new CreateAccountRequest(account); ServiceBusResponse response; ServiceBusConnection connection = ConnectionManager.getConnectionObject(Globals.getUser()); if (connection == null) { response = ConnectionManager.sendNewAccountInfo(request); } else { response = connection.sendNewAccountInfo(request); } ViewBag.AsIsResponse = response.response; if (response.response.Contains("Duplicate")) { return(View("CreateAccount")); } return(View("Index")); }
//[TestCase(100, 10, 1)] //[TestCase(100, 10, 2)] //[TestCase(100, 10, 3)] //[TestCase(100, 10, 4)] //[TestCase(100, 10, 5)] //[TestCase(100, 10, 6)] //[TestCase(100, 10, 7)] //[TestCase(100, 10, 8)] //[TestCase(100, 10, 9)] //[TestCase(100, 10, 10)] //[TestCase(500, 50, 11)] //[TestCase(500, 50, 12)] //[TestCase(500, 50, 13)] //[TestCase(500, 50, 14)] //[TestCase(500, 50, 15)] public async Task Time_For_Batch_Transport_To_Clear_Queue(int batchSize, int delayInSeconds, int testIndex) { Console.WriteLine($"Test: #{testIndex}, batch size: {batchSize}"); var visibleTime = DateTime.UtcNow.AddSeconds(delayInSeconds); await SendMessages(batchSize, visibleTime, config.GetBatchServiceEndpointName()).ConfigureAwait(false); var endTime = DateTime.Now.AddSeconds(delayInSeconds).Add(config.GetTimeToWait()); Console.WriteLine($"Waiting until {endTime:G} for NSB service to finish storing the messages."); var connection = new ServiceBusConnection(config.ServiceBusConnectionString); var client = new ManagementClient(config.ServiceBusConnectionString); while (DateTime.Now < endTime) { var queueInfo = await client.GetQueueRuntimeInfoAsync(config.GetBatchServiceEndpointName()) .ConfigureAwait(false); Console.WriteLine($"Time: {DateTime.Now:G}. Queue count: {queueInfo.MessageCount}, Active messages: {queueInfo.MessageCountDetails.ActiveMessageCount}, Dead letter: {queueInfo.MessageCountDetails.DeadLetterMessageCount}, Scheduled: {queueInfo.MessageCountDetails.ScheduledMessageCount}"); if (DateTime.UtcNow > visibleTime && queueInfo.MessageCount == 0) { var executionTime = DateTime.UtcNow - visibleTime; Console.WriteLine($"Time: {DateTime.Now:G}. Took: {executionTime.TotalSeconds} seconds to clear {batchSize} messages"); Assert.Pass(); } await Task.Delay(TimeSpan.FromMilliseconds(250)); } Assert.Fail("Failed to process all messages."); }
/// <summary> /// This function is called when the client navigates to *hostname*/CompanyListings/DisplayCompany/*info* /// </summary> /// <param name="id">The name of the company whos info is to be displayed</param> /// <returns>A view to be sent to the client</returns> public ActionResult DisplayCompany(string id) { if (Globals.isLoggedIn() == false) { return(RedirectToAction("Index", "Authentication")); } if ("".Equals(id)) { return(View("Index")); } ServiceBusConnection connection = ConnectionManager.getConnectionObject(Globals.getUser()); if (connection == null) { return(RedirectToAction("Index", "Authentication")); } ViewBag.CompanyName = id; GetCompanyInfoRequest infoRequest = new GetCompanyInfoRequest(new CompanyInstance(id)); GetCompanyInfoResponse infoResponse = connection.getCompanyInfo(infoRequest); ViewBag.CompanyInfo = infoResponse.companyInfo; return(View("DisplayCompany")); }
public ActionResult SaveReview() { if (Globals.isLoggedIn() == false) { return(RedirectToAction("Index", "Authentication")); } ServiceBusConnection connection = ConnectionManager.getConnectionObject(Globals.getUser()); if (connection == null) { return(RedirectToAction("Index", "Authentication")); } String review = Request.Form["reviewData"]; String company = Request.Form["companyName"]; int time = (int)DateTimeOffset.Now.ToUnixTimeSeconds(); String rating = Request.Form["star"]; string json = "{review:{companyName:\"" + company + "\"," + "username:\"" + Globals.getUser() + "\"," + "review:\"" + review + "\"," + "stars:" + rating + "," + "timestamp:" + time + "}}"; SaveReviewRequest srRequest = new SaveReviewRequest(company, json); ServiceBusResponse response = connection.saveCompanyReview(srRequest); Response.Write("<script>alert('" + response.response + "')</script>"); return(View("Index")); }
// This sample shows a successful transaction. private async Task TransactionSample(string SBCS, string QueueName) { // Note: A transaction cannot span more than one connection, hence you need to create your connection object // always before and then pass it to sender and receiver. var connection = new ServiceBusConnection(SBCS); var sender = new MessageSender(connection, QueueName); var receiver = new MessageReceiver(connection, QueueName); // Receive not part of transaction. Only operations which actually do something with the message on the broker are part of the transaction. // These are: Send, Complete, Deadletter, Defer. Receive itself already utilizes the peeklock concept on the broker. // Note the receive timeout of 2 seconds is just for demo purposes to not let the user wait in case no message is there. // Run twice to see the sample in full. var receivedMessage = await receiver.ReceiveAsync(TimeSpan.FromSeconds(5)); if (receivedMessage != null) { var msg = receivedMessage.DeserializeMsg <MyMessage>(); Console.WriteLine($"MessageId: {receivedMessage.MessageId} \n Name: {msg.Name} \n Address: {msg.Address} \n ZipCode {msg.ZipCode}"); } else { Console.WriteLine($"No message received."); } using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { try { if (receivedMessage != null) { await receiver.CompleteAsync(receivedMessage.SystemProperties.LockToken); } var myMsgBody = new MyMessage { Name = "Some name", Address = "Some street address", ZipCode = "Some zip code" }; var message = myMsgBody.AsMessage(); await sender.SendAsync(message).ConfigureAwait(false); Console.WriteLine("Message has been sent"); ts.Complete(); } catch (Exception ex) { // This rolls back send and complete in case an exception happens ts.Dispose(); Console.WriteLine(ex.ToString()); } } await sender.CloseAsync(); await receiver.CloseAsync(); }
public async Task PeekUsingConnectionStringWithSisgnature() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false)) { var options = new ServiceBusClientOptions(); var audience = ServiceBusConnection.BuildConnectionResource(options.TransportType, TestEnvironment.FullyQualifiedNamespace, scope.QueueName); var connectionString = TestEnvironment.BuildConnectionStringWithSharedAccessSignature(scope.QueueName, audience); await using var client = new ServiceBusClient(connectionString, options); var messageCt = 10; ServiceBusSender sender = client.CreateSender(scope.QueueName); using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync(); IEnumerable <ServiceBusMessage> sentMessages = AddMessages(batch, messageCt).AsEnumerable <ServiceBusMessage>(); await sender.SendMessagesAsync(batch); await using var receiver = client.CreateReceiver(scope.QueueName); var messageEnum = sentMessages.GetEnumerator(); var ct = 0; while (ct < messageCt) { foreach (ServiceBusReceivedMessage peekedMessage in await receiver.PeekMessagesAsync( maxMessages: messageCt)) { messageEnum.MoveNext(); Assert.AreEqual(messageEnum.Current.MessageId, peekedMessage.MessageId); ct++; } } Assert.AreEqual(messageCt, ct); } }
private static async Task <ReadResult> DoReadOperation(string connectionString, string path, TimeSpan timeout, bool useCached, Func <MessageReceiver, Task <ReadResult> > operation) { ServiceBusConnection connection = null; MessageReceiver requestClient = null; try { if (useCached) { requestClient = ServiceBusMessagingFactory.Instance.GetMessageReceiver(connectionString, path, timeout); } else { connection = ServiceBusMessagingFactory.CreateConnectionWithTimeout(connectionString, timeout); requestClient = new MessageReceiver(connection, path); } return(await operation.Invoke(requestClient).ConfigureAwait(false)); } finally { await(requestClient?.CloseAsync() ?? Task.CompletedTask); await(connection?.CloseAsync() ?? Task.CompletedTask); } }
public async Task ClientCanConnectUsingSharedKeyCredential() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: true, enableSession: false)) { var options = new ServiceBusClientOptions(); var audience = ServiceBusConnection.BuildConnectionResource(options.TransportType, TestEnvironment.FullyQualifiedNamespace, scope.QueueName); var credential = new AzureNamedKeyCredential(TestEnvironment.SharedAccessKeyName, TestEnvironment.SharedAccessKey); await using (var client = new ServiceBusClient(TestEnvironment.FullyQualifiedNamespace, credential, options)) { Assert.That(async() => { ServiceBusReceiver receiver = null; try { receiver = client.CreateReceiver(scope.QueueName); } finally { await(receiver?.DisposeAsync() ?? new ValueTask()); } }, Throws.Nothing); } } }
public ActionResult Login(string usernameData, string passwordData) { string username = usernameData; string password = passwordData; LogInRequest LR = new LogInRequest(username, password); ServiceBusResponse response; ServiceBusConnection connection = ConnectionManager.getConnectionObject(Globals.getUser()); if (connection == null) { response = ConnectionManager.sendLogIn(LR); } else { response = connection.sendLogIn(LR); } Response.Write("<script>alert('" + response.response + "')</script>"); return(View("../Home/Index")); }
public async Task ProcessQueue() { Debug.WriteLine("Cleaning the subscription..."); await _queueCleanUp; var connection = new ServiceBusConnection(ConnectionString); var queue = new QueueClient(connection, QueueName, ReceiveMode.PeekLock, RetryPolicy.Default); await Observable .Range(0, 3) .Select(i => Encoding.UTF8.GetBytes($"Message {i}")) .SelectMany(body => queue.SendAsync(new Message(body)).ToObservable()); var received = await connection .ProcessMessages((message, ct) => { var text = Encoding.UTF8.GetString(message.Body); return(Task.FromResult(text)); }) .FromQueue(QueueName, ReceiveMode.PeekLock, RetryPolicy.Default) .Take(TimeSpan.FromSeconds(1)) .ToList(); Assert.Equal(3, received.Count); await Observable .Range(0, 3) .Do(i => Assert.Contains($"Message {i}", received)); }
public async Task ReceiveMessagesInReceiveAndDeleteMode() { await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: true)) { await using var sender = new ServiceBusSenderClient(TestEnvironment.ServiceBusConnectionString, scope.QueueName); var messageCount = 10; var sessionId = "sessionId1"; IEnumerable <ServiceBusMessage> messages = GetMessages(messageCount, sessionId); await sender.SendBatchAsync(messages); ServiceBusConnection conn = new ServiceBusConnection(TestEnvironment.ServiceBusConnectionString, scope.QueueName); var clientOptions = new ServiceBusReceiverClientOptions() { SessionId = sessionId, IsSessionEntity = true, ReceiveMode = ReceiveMode.ReceiveAndDelete }; var receiver = new ServiceBusReceiverClient(TestEnvironment.ServiceBusConnectionString, scope.QueueName, clientOptions); var receivedMessageCount = 0; var messageEnum = messages.GetEnumerator(); foreach (var item in await receiver.ReceiveBatchAsync(messageCount)) { messageEnum.MoveNext(); Assert.AreEqual(item.SessionId, messageEnum.Current.SessionId); Assert.AreEqual(item.MessageId, messageEnum.Current.MessageId); receivedMessageCount++; } Assert.AreEqual(receivedMessageCount, messageCount); var message = receiver.PeekAsync(); Assert.IsNull(message.Result); } }
public IMessageReceiver Create(string serviceBusConnectionString, string topicName, string subscriptionName, bool dlqMode) { Validate(subscriptionName); Validate(serviceBusConnectionString); Validate(topicName); if (conn == null) { conn = new ServiceBusConnection(new ServiceBusConnectionStringBuilder(serviceBusConnectionString)); } var path = EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName); if (dlqMode) { path += "/$deadletterqueue"; } return(new MessageReceiver( conn, path, ReceiveMode.PeekLock, new RetryExponential( BackoffMin, BackoffMax, ReceiverRetryCount), ReceiverBatchSize)); }
public static AzureServiceBusReceiver Create(AzureServiceBusConfiguration config, Func <IMessageReceiver, Message, CancellationToken, Task> receiveFunc, Func <ExceptionReceivedEventArgs, Task> errorFunc) { var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(config.KeyName, config.SharedAccessSignature, TimeSpan.FromDays(1)); var queueConnection = new ServiceBusConnection(config.Endpoint, TransportType.Amqp, RetryPolicy.Default) { TokenProvider = tokenProvider }; MessageReceiver receiver = null; if (config.AllowReceiverToOwnConnection) { receiver = new MessageReceiver(config.Endpoint, config.QueueName, tokenProvider, receiveMode: ReceiveMode.PeekLock, retryPolicy: RetryPolicy.Default) { PrefetchCount = config.MaxConcurrentCalls }; } else { receiver = new MessageReceiver(queueConnection, config.QueueName, ReceiveMode.PeekLock, RetryPolicy.Default) { PrefetchCount = config.MaxConcurrentCalls }; } receiver.RegisterMessageHandler((message, token) => receiveFunc(receiver, message, token), new MessageHandlerOptions(errorFunc) { AutoComplete = false, MaxConcurrentCalls = config.MaxConcurrentCalls }); return(new AzureServiceBusReceiver(receiver)); }