public ReliableQueueClient(string sbNamespace, TokenProvider tokenProvider, string path, ReceiveMode receiveMode, RetryPolicy<ServiceBusTransientErrorDetectionStrategy> policy) : base(sbNamespace, tokenProvider,path,policy) { //create the queue if it doesn't exist bool needsCreation = false; try { needsCreation = !mRetryPolicy.ExecuteAction<bool>(() => mNamespaceManager.QueueExists(path)); } catch (MessagingEntityNotFoundException) { needsCreation = true; } if (needsCreation) { try { mRetryPolicy.ExecuteAction<QueueDescription>(() => mNamespaceManager.CreateQueue(path)); } catch (MessagingEntityAlreadyExistsException) { //ignore this exception because queue already exists } } mRetryPolicy.ExecuteAction(() => mQueueClient = mMessagingFactory.CreateQueueClient(path, receiveMode)); }
public static string BytesToText(List<byte> bytesBuffer, ReceiveMode mode, Encoding encoding) { string result = ""; if (mode == ReceiveMode.Character) { return encoding.GetString(bytesBuffer.ToArray<byte>()); } foreach (var item in bytesBuffer) { switch (mode) { case ReceiveMode.Hex: result += Convert.ToString(item, 16).ToUpper() + " "; break; case ReceiveMode.Decimal: result += Convert.ToString(item, 10) + " "; break; case ReceiveMode.Octal: result += Convert.ToString(item, 8) + " "; break; case ReceiveMode.Binary: result += Convert.ToString(item, 2) + " "; break; default: break; } } return result; }
public BrokeredServiceBehavior(ServiceEndpoint endpoint, TokenProvider tokenProvider, ReceiveMode receiveMode, Dictionary<string, string> actionMap) { this.endpoint = endpoint; this.tokenProvider = tokenProvider; this.receiveMode = receiveMode; this.actionMap = actionMap; }
/// <summary> /// Construcotr /// </summary> /// <param name="factory">Messaging factory instance</param> /// <param name="path">Entity path</param> /// <param name="receiveMode">Receive mode</param> internal AmqpMessageReceiver(AmqpMessagingFactory factory, string path, ReceiveMode receiveMode) : base(factory, path) { this.factory = factory; this.receiveMode = receiveMode; this.peekedMessages = new Hashtable(); }
public static SubscriptionClient CreateSubscriptionClient(this ServiceBusSettings settings, string topic, string subscription, ReceiveMode mode = ReceiveMode.PeekLock) { var tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey); var serviceUri = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath); var messagingFactory = MessagingFactory.Create(serviceUri, tokenProvider); return messagingFactory.CreateSubscriptionClient(topic, subscription, mode); }
public static void StartListener(this QueueClient queueClient, object singletonInstance, ReceiveMode receiveMode = ReceiveMode.PeekLock, bool requiresSession = false) { var address = new Uri(queueClient.MessagingFactory.Address, queueClient.Path); var host = new BrokeredServiceHost(singletonInstance, address, queueClient.MessagingFactory.GetSettings().TokenProvider, receiveMode, requiresSession); RegisteredQueueHosts.Add(queueClient, host); host.Open(); }
public static void StartListener(this SubscriptionClient subscriptionClient, object singletonInstance, ReceiveMode receiveMode = ReceiveMode.PeekLock, bool requiresSession = false) { var address = new Uri(subscriptionClient.MessagingFactory.Address, subscriptionClient.TopicPath + "/Subscriptions/" + subscriptionClient.Name); var host = new BrokeredServiceHost(singletonInstance, address, subscriptionClient.MessagingFactory.GetSettings().TokenProvider, receiveMode, requiresSession); RegisteredSubscriptionHosts.Add(subscriptionClient, host); host.Open(); }
public static void StartListener(this QueueClient queueClient, Type serviceType, ReceiveMode receiveMode = ReceiveMode.PeekLock, bool requiresSession = false) { Uri address = new Uri(queueClient.MessagingFactory.Address, queueClient.Path); BrokeredServiceHost host = new BrokeredServiceHost(serviceType, address, queueClient.MessagingFactory.GetSettings().TokenProvider, receiveMode, requiresSession); registeredQueueHosts.Add(queueClient, host); host.Open(); }
/// <summary> /// Constructor /// </summary> /// <param name="factory">Messaging factory</param> /// <param name="topicPath">Path to the topic related entity</param> /// <param name="name">Name of the subscription</param> /// <param name="receiveMode">Receive mode</param> internal SubscriptionClient(MessagingFactory factory, string topicPath, string name, ReceiveMode receiveMode) { this.MessagingFactory = factory; this.TopicPath = topicPath; this.Name = name; this.Mode = receiveMode; this.SubscriptionPath = topicPath + "/Subscriptions/" + name; }
private void AddBrokeredServiceBehavior(Type serviceType, Uri address, TokenProvider tokenProvider, ReceiveMode receiveMode, bool requiresSession) { this.receiveMode = receiveMode; this.requiresSession = requiresSession; ContractDescription contractDescription = CreateContractDescription(serviceType); ServiceEndpoint endpoint = new ServiceEndpoint(contractDescription, new BrokeredBinding(), address != null ? new EndpointAddress(address) : null); this.Description.Behaviors.Insert(0, new BrokeredServiceBehavior(endpoint, tokenProvider, receiveMode, this.actionMap)); }
public async static Task<SubscriptionClient> EnsureSubscriptionAsync(this MessagingFactory factory, SubscriptionDescription subscriptionDescription, ReceiveMode mode = ReceiveMode.PeekLock) { await new NamespaceManager(factory.Address, factory.GetSettings().TokenProvider) .TryCreateEntity( mgr => SubscriptionCreateAsync(mgr, subscriptionDescription), mgr => SubscriptionShouldExistAsync(mgr, subscriptionDescription)); return factory.CreateSubscriptionClient(subscriptionDescription.TopicPath, subscriptionDescription.Name, mode); }
public async static Task<QueueClient> EnsureQueueAsync(this MessagingFactory factory, QueueDescription queueDescription, ReceiveMode mode = ReceiveMode.PeekLock) { await new NamespaceManager(factory.Address, factory.GetSettings().TokenProvider) .TryCreateEntity( mgr => QueueCreateAsync(mgr, queueDescription), mgr => QueueShouldExistAsync(mgr, queueDescription)); return factory.CreateQueueClient(queueDescription.Path, mode); }
public BrokeredServiceHost( Type serviceType, Uri address, TokenProvider tokenProvider, ReceiveMode receiveMode, bool requiresSession) : base(serviceType) { AddBrokeredServiceBehavior(serviceType, address, tokenProvider, receiveMode, requiresSession); }
public MockSubscriptionClient(IBus serviceBus, string topicPath, string name, ReceiveMode receiveMode) { Guard.ArgumentNotNull(serviceBus, "serviceBus"); Guard.ArgumentNotNull(topicPath, "topicPath"); Guard.ArgumentNotNull(name, "name"); this.serviceBus = serviceBus as IMockServiceBus; Guard.ArgumentNotNull(this.serviceBus, "serviceBus"); this.topicPath = topicPath; this.name = name; this.receiveMode = receiveMode; }
public BrokeredServiceHost( object singletonInstance, Uri address, TokenProvider tokenProvider, ReceiveMode receiveMode, bool requiresSession) : base(singletonInstance) { AddBrokeredServiceBehavior(singletonInstance.GetType(), address, tokenProvider, receiveMode, requiresSession); }
public static SubscriptionClient GetSubscriptionClient(string topicPath, string subscriptionName, ReceiveMode receiveMode) { var connectionString = CloudConfigurationManager.GetSetting(ServicebusConnectionString); var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); if (!namespaceManager.SubscriptionExists(topicPath, subscriptionName)) namespaceManager.CreateSubscription(topicPath, subscriptionName); return SubscriptionClient.CreateFromConnectionString(connectionString, topicPath, subscriptionName, receiveMode); }
public ReliableQueueClient(string sbNamespace, TokenProvider tokenProvider, string path, ReceiveMode receiveMode) : this(sbNamespace, tokenProvider, path, receiveMode, new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(new FixedInterval(3, TimeSpan.FromMilliseconds(100)))) { }
private void Send( string uri, ReceiveMode mode, WriteDataCallback wdcb, SuccessCallback scb, BinarySuccessCallback bcb, ErrorCallback ecb, FinishedCallback fcb) { if (!LoggedIn && uri != "/login" && uri != "/crashreport") { throw new InvalidOperationException("Not logged in"); } var req = WebRequest.CreateHttp(((uri == "/login" || uri == "/crashreport") ? DefaultRootUrl : RootUrl) + uri); req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; var waitHandle = new ManualResetEvent(false); req.BeginGetRequestStream(ar => { try { using (var requestStream = req.EndGetRequestStream(ar)) { using (var sr = new StreamWriter(requestStream)) { wdcb(sr); } } req.BeginGetResponse( a => { waitHandle.Set(); try { var response = (HttpWebResponse)req.EndGetResponse(a); var responseStream = response.GetResponseStream(); if (mode == ReceiveMode.Blob) { var data = new byte[response.ContentLength]; responseStream.BeginRead( data, 0, (int)response.ContentLength, result => { if (result.IsCompleted) { bcb(response.ContentType, data); } else { ecb("Incomplete response"); } }, null ); } else { using (var sr = new StreamReader(responseStream)) { switch (mode) { case ReceiveMode.Lines: string line; while ((line = sr.ReadLine()) != null) { if (line != string.Empty) { scb(line); } } break; case ReceiveMode.SingleString: scb(sr.ReadToEnd()); break; } if (fcb != null) { fcb(); } } } } catch (WebException e) { if (e.Status == WebExceptionStatus.RequestCanceled) { ecb(""); return; } var response = (HttpWebResponse)e.Response; if (response.StatusCode == HttpStatusCode.Forbidden) { LoggedIn = false; } try { using (var responseStream = response.GetResponseStream()) { using (var sr = new StreamReader(responseStream)) { ecb(sr.ReadToEnd()); } } } catch (Exception ex) { // What is wrong with this platform?! ecb(ex.Message + "\n" + e.Message); } } }, null ); } catch (WebException) { // The request was aborted ecb(""); } }, null); ThreadPool.QueueUserWorkItem( state => { if (!waitHandle.WaitOne(MessageTimeout)) { (state as HttpWebRequest).Abort(); } }, req ); }
private void Send( string uri, ReceiveMode mode, WriteDataCallback wdcb, SuccessCallback scb, BinarySuccessCallback bcb, ErrorCallback ecb, FinishedCallback fcb) { if (!LoggedIn && uri != "/login" && uri != "/crashreport") { throw new InvalidOperationException("Not logged in"); } var req = WebRequest.CreateHttp(((uri == "/login" || uri == "/crashreport") ? DefaultRootUrl : RootUrl) + uri); req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; var waitHandle = new ManualResetEvent(false); req.BeginGetRequestStream(ar => { try { using (var requestStream = req.EndGetRequestStream(ar)) { using (var sr = new StreamWriter(requestStream)) { wdcb(sr); } } req.BeginGetResponse( a => { waitHandle.Set(); try { var response = (HttpWebResponse) req.EndGetResponse(a); var responseStream = response.GetResponseStream(); if (mode == ReceiveMode.Blob) { var data = new byte[response.ContentLength]; responseStream.BeginRead( data, 0, (int) response.ContentLength, result => { if (result.IsCompleted) { bcb(response.ContentType, data); } else { ecb("Incomplete response"); } }, null ); } else { using (var sr = new StreamReader(responseStream)) { switch (mode) { case ReceiveMode.Lines: string line; while ((line = sr.ReadLine()) != null) { if (line != string.Empty) { scb(line); } } break; case ReceiveMode.SingleString: scb(sr.ReadToEnd()); break; } if (fcb != null) { fcb(); } } } } catch (WebException e) { if(e.Status == WebExceptionStatus.RequestCanceled) { ecb(""); return; } var response = (HttpWebResponse) e.Response; if (response.StatusCode == HttpStatusCode.Forbidden) { LoggedIn = false; } try { using (var responseStream = response.GetResponseStream()) { using (var sr = new StreamReader(responseStream)) { ecb(sr.ReadToEnd()); } } } catch (Exception ex) { // What is wrong with this platform?! ecb(ex.Message + "\n" + e.Message); } } }, null ); } catch(WebException) { // The request was aborted ecb(""); } }, null); ThreadPool.QueueUserWorkItem( state => { if (!waitHandle.WaitOne(MessageTimeout)) { (state as HttpWebRequest).Abort(); } }, req ); }
public virtual QueueClient GetInputQueue(string queueName, ReceiveMode mode) { return QueueClient.CreateFromConnectionString(ConnectionString, queueName, mode); }
protected EventDrivenMessagePump(MessageClientEntity messageClient, ReceiveMode mode, string @namespace, string path, OnMessageOptions defaultOptions) : base(mode, @namespace, path) { _messageClient = messageClient; _defaultOptions = defaultOptions ?? new OnMessageOptions(); }
private async Task OnMessageTestAsync(bool partitioned, bool sessionEnabled, int maxConcurrentCalls, ReceiveMode mode, bool autoComplete) { const int messageCount = 10; await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) => { var topicClient = new TopicClient(TestUtility.NamespaceConnectionString, topicName); var subscriptionClient = new SubscriptionClient( TestUtility.NamespaceConnectionString, topicName, subscriptionName, mode); try { await this.OnMessageAsyncTestCase( topicClient.InnerSender, subscriptionClient.InnerSubscriptionClient.InnerReceiver, maxConcurrentCalls, autoComplete, messageCount); } finally { await subscriptionClient.CloseAsync(); await topicClient.CloseAsync(); } }); }
public static Task<QueueClient> EnsureQueueAsync(this MessagingFactory factory, string queueName, bool requiresSession = false, ReceiveMode mode = ReceiveMode.PeekLock) { return EnsureQueueAsync(factory, new QueueDescription(queueName) { RequiresSession = requiresSession }, mode); }
protected override IAsyncResult OnBeginCreateReceiver(ReceiveMode receiveMode, TimeSpan timeout, AsyncCallback callback, object state) { return(this.OnBeginCreateReceiver(base.SubscriptionPath, base.Name, receiveMode, timeout, callback, state)); }
protected override IAsyncResult OnBeginCreateReceiver(string subQueuePath, string subQueueName, ReceiveMode receiveMode, TimeSpan timeout, AsyncCallback callback, object state) { CreateReceiverLinkSettings createReceiverLinkSetting = new CreateReceiverLinkSettings((SbmpMessagingFactory)base.MessagingFactory, subQueuePath, subQueueName, new MessagingEntityType?(MessagingEntityType.Subscriber), receiveMode, this.ControlMessageCreator, base.RetryPolicy, false); return(new CompletedAsyncResult <SbmpMessageReceiver>(createReceiverLinkSetting.MessageReceiver, callback, state)); }
public void ProcessMessages() { // Get receive mode (PeekLock or ReceiveAndDelete) from queueClient. ReceiveMode mode = this.queueClient.Mode; while (true) { Console.Write("Press [Enter] to retrieve a message from the queue (type quit to exit): "); string line = Console.ReadLine(); if (!string.IsNullOrEmpty(line) && string.Equals(line, "quit", StringComparison.OrdinalIgnoreCase)) { break; } // Retrieve a message from the queue. Console.WriteLine("Waiting for a message from the queue... "); BrokeredMessage message; try { message = this.queueClient.Receive(); // Check if the message received. if (message != null) { try { // Verify EntityLogicalName and RequestName message properties // to only process specific message sent from Microsoft Dynamics CRM. string keyRoot = "https://schemas.microsoft.com/xrm/2011/Claims/"; string entityLogicalNameKey = "EntityLogicalName"; string requestNameKey = "RequestName"; object entityLogicalNameValue; object requestNameValue; message.Properties.TryGetValue(keyRoot + entityLogicalNameKey, out entityLogicalNameValue); message.Properties.TryGetValue(keyRoot + requestNameKey, out requestNameValue); // Filter message with specific message properties. i.e. EntityLogicalName=letter and RequestName=Create if (entityLogicalNameValue != null && requestNameValue != null) { if (entityLogicalNameValue.ToString() == "letter" && requestNameValue.ToString() == "Create") { Console.WriteLine("--------------------------------"); Console.WriteLine(string.Format("Message received: Id = {0}", message.MessageId)); // Display message properties that are set on the brokered message. Utility.PrintMessageProperties(message.Properties); // Display body details. Utility.Print(message.GetBody <RemoteExecutionContext>()); Console.WriteLine("--------------------------------"); } else { continue; } } else { continue; } // If receive mode is PeekLock then set message complete to remove message from queue. if (mode == ReceiveMode.PeekLock) { message.Complete(); } } catch (System.Exception ex) { // Indicate a problem, unlock message in queue. if (mode == ReceiveMode.PeekLock) { message.Abandon(); } Console.WriteLine(ex.Message); continue; } } else { break; } } catch (System.TimeoutException e) { Console.WriteLine(e.Message); continue; } catch (System.ServiceModel.FaultException e) { Console.WriteLine(e.Message); continue; } } }
public BrokeredServiceBehavior(ServiceEndpoint endpoint, TokenProvider tokenProvider, ReceiveMode receiveMode, Dictionary <string, string> actionMap) { this.endpoint = endpoint; this.tokenProvider = tokenProvider; this.receiveMode = receiveMode; this.actionMap = actionMap; }
/// <summary> /// Method created to connect and process the Topic/Subscription in the azure. /// </summary> /// <returns></returns> private void ProcessSubscription() { try { foreach (var topic in _topics) { MethodInfo method = GetMethod(topic); string topicName = topic.Value.TopicName; string subscriptName = topic.Value.Subscription; ReceiveMode receiveMode = ReceiveMode.PeekLock; if (topic.Value.DeleteAfterRead) { receiveMode = ReceiveMode.ReceiveAndDelete; } int takeQuantity = topic.Value.TakeQuantity; //Register Trace on the telemetry SubscriptionClient subscriptionClient = new SubscriptionClient(GetConnection(topic), topicName, subscriptName, receiveMode, null); //Register the method to process receive message //The RegisterMessageHandler is validate for all register exist on the queue, without need loop for items subscriptionClient.RegisterMessageHandler( async(message, cancellationToken) => { try { InvokeProcess(method, message.Body); await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken); } catch (Exception exRegister) { Exception moreInfo = new Exception($"Exception reading message from topic {topicName} and subscriptName {subscriptName}. See inner exception for details. Message={exRegister.Message}", exRegister); //Use the class instead of interface because tracking exceptions directly is not supposed to be done outside AMAW (i.e. by the business code) ((LightTelemetry)WorkBench.Telemetry).TrackException(moreInfo); var exceptionDetails = $"{exRegister.Message}"; //If there is a business error or a invlida input, set DeadLetter on register if (subscriptionClient.ReceiveMode == ReceiveMode.PeekLock) { if (exRegister.InnerException != null) { exceptionDetails = $"{exceptionDetails} \n {exRegister.InnerException?.Message}"; if (exRegister.InnerException is InvalidInputException) { var inputErrors = (exRegister.InnerException as InvalidInputException).InputErrors; string jsonString = (new { critics = inputErrors }).ToStringCamelCase(); exceptionDetails = $"{exceptionDetails} \n {jsonString}"; //This operation is only allowed PeekLock await subscriptionClient.DeadLetterAsync(message.SystemProperties.LockToken, exceptionDetails, $"{exRegister.StackTrace}"); } if (exRegister.InnerException is BusinessValidationException) { var inputErrors = (exRegister.InnerException as BusinessValidationException).InputErrors; string jsonString = (new { critics = inputErrors }).ToStringCamelCase(); exceptionDetails = $"{exceptionDetails} \n {jsonString}"; //This operation is only allowed PeekLock await subscriptionClient.DeadLetterAsync(message.SystemProperties.LockToken, exceptionDetails, $"{exRegister.StackTrace}"); } } } } }, new MessageHandlerOptions((e) => ExceptionReceivedHandler(e)) { AutoComplete = false, MaxConcurrentCalls = takeQuantity }); } } catch (Exception exception) { Exception moreInfo = new Exception($"Error setting up subscription consumption from service bus. See inner exception for details. Message={exception.Message}", exception); //Use the class instead of interface because tracking exceptions directly is not supposed to be done outside AMAW (i.e. by the business code) ((LightTelemetry)WorkBench.Telemetry).TrackException(moreInfo); } }
public async Task <IEnumerable <BrokeredMessage> > ReceiveAsync(string connectionString, string topic, string subscription, ReceiveMode receiveMode, int batchSize, int timeoutMilliSeconds) { SubscriptionClient subscribeClient = ServiceBusConnectionsFactory.GetSubscriptionClient(connectionString, topic, subscription); return(await subscribeClient.ReceiveBatchAsync(1000, new TimeSpan(0, 0, 0, 0, timeoutMilliSeconds))); }
/// <summary> /// Initialize the message pump. /// </summary> /// <param name="mode"></param> /// <param name="namespace"></param> /// <param name="path"></param> protected MessagePump(ReceiveMode mode, string @namespace, string path) { _mode = mode; _namespace = @namespace; _path = path; }
/// <summary> /// Create a message receiver instance /// </summary> /// <param name="path">Path to the entity</param> /// <param name="receiveMode">Receive mode</param> /// <returns>Message receiver instance</returns> public abstract MessageReceiver CreateMessageReceiver(string path, ReceiveMode receiveMode);
public SbmpSubscriptionClient(SbmpMessagingFactory messagingFactory, string topicPath, string name, ReceiveMode receiveMode) : base(messagingFactory, topicPath, name, receiveMode) { this.ControlMessageCreator = new Lazy <SbmpMessageCreator>(new Func <SbmpMessageCreator>(this.InitializeControlLink)); }
/// <summary> /// Create a new subscription client /// </summary> /// <param name="topicPath">Path to the topic related entity</param> /// <param name="name">Name of the subscription</param> /// <param name="receiveMode">Receive mode</param> /// <returns>Subscription client instance</returns> public abstract SubscriptionClient CreateSubscriptionClient(string topicPath, string name, ReceiveMode receiveMode);
protected override IAsyncResult OnBeginAcceptMessageSession(string sessionId, ReceiveMode receiveMode, TimeSpan serverWaitTime, TimeSpan timeout, AsyncCallback callback, object state) { IAsyncResult acceptMessageSessionAsyncResult; try { acceptMessageSessionAsyncResult = new AcceptMessageSessionAsyncResult((SbmpMessagingFactory)base.MessagingFactory, base.SubscriptionPath, sessionId, new MessagingEntityType?(MessagingEntityType.Subscriber), receiveMode, base.PrefetchCount, this.ControlMessageCreator, base.RetryPolicy, serverWaitTime, timeout, callback, state); } catch (CommunicationException communicationException1) { CommunicationException communicationException = communicationException1; throw Microsoft.ServiceBus.Messaging.FxTrace.Exception.AsError(MessagingExceptionHelper.Unwrap(communicationException, base.IsClosedOrClosing), null); } catch (Exception exception1) { Exception exception = exception1; if (!Fx.IsFatal(exception) && base.IsClosedOrClosing) { throw new OperationCanceledException(SRClient.EntityClosedOrAborted, exception); } throw; } return(acceptMessageSessionAsyncResult); }
/// <summary> /// Instantiates a new <see cref="SubscriptionClient"/> to perform operations on a subscription. /// </summary> /// <param name="connectionString">Namespace connection string. Must not contain topic or subscription information.</param> /// <param name="receiveMode">Mode of receive of messages. Defaults to <see cref="ReceiveMode"/>.PeekLock.</param> /// <param name="retryPolicy">Retry policy for subscription operations. Defaults to <see cref="RetryPolicy.Default"/></param> /// <remarks>Creates a new connection to the subscription, which is opened during the first receive operation.</remarks> public SubscriptionClient(string connectionString, string topicPath, string subscriptionName, ReceiveMode receiveMode = ReceiveMode.PeekLock, RetryPolicy retryPolicy = null) : this(new ServiceBusConnection(connectionString), topicPath, subscriptionName, receiveMode, retryPolicy ?? RetryPolicy.Default) { if (string.IsNullOrWhiteSpace(connectionString)) { throw Fx.Exception.ArgumentNullOrWhiteSpace(connectionString); } this.OwnsConnection = true; }
public static void StartListener(this QueueClient queueClient, object singletonInstance, ReceiveMode receiveMode = ReceiveMode.PeekLock, bool requiresSession = false) { Uri address = new Uri(queueClient.MessagingFactory.Address, queueClient.Path); BrokeredServiceHost host = new BrokeredServiceHost(singletonInstance, address, queueClient.MessagingFactory.GetSettings().TokenProvider, receiveMode, requiresSession); registeredQueueHosts.Add(queueClient, host); host.Open(); }
protected MessageReceiver(ReceiveMode receiveMode, TimeSpan operationTimeout) : base(nameof(MessageReceiver) + StringUtility.GetRandomString()) { this.ReceiveMode = receiveMode; this.operationTimeout = operationTimeout; }
public static void StartListener(this SubscriptionClient subscriptionClient, object singletonInstance, ReceiveMode receiveMode = ReceiveMode.PeekLock, bool requiresSession = false) { Uri address = new Uri(subscriptionClient.MessagingFactory.Address, subscriptionClient.TopicPath + "/Subscriptions/" + subscriptionClient.Name); BrokeredServiceHost host = new BrokeredServiceHost(singletonInstance, address, subscriptionClient.MessagingFactory.GetSettings().TokenProvider, receiveMode, requiresSession); registeredSubscriptionHosts.Add(subscriptionClient, host); host.Open(); }
/// <summary> /// Constructor /// </summary> /// <param name="factory">Messaging factory instance</param> /// <param name="subscriptionPath">Path to subscription entity</param> /// <param name="receiveMode">Receive mode</param> internal AmqpSubscriptionClient(AmqpMessagingFactory factory, string subscriptionPath, ReceiveMode receiveMode) : base(factory, subscriptionPath, receiveMode) { }
public static Task<SubscriptionClient> EnsureSubscriptionAsync(this MessagingFactory factory, string topicPath, string subscriptionName, bool requiresSession = false, ReceiveMode mode = ReceiveMode.PeekLock) { return EnsureSubscriptionAsync(factory, new SubscriptionDescription(topicPath, subscriptionName) { RequiresSession = requiresSession }, mode); }
public AzureServiceBusConsumer(string topicName, string subscriptionName, IAmAMessageProducer messageProducer, IManagementClientWrapper managementClientWrapper, IMessageReceiverProvider messageReceiverProvider, int batchSize = 10, ReceiveMode receiveMode = ReceiveMode.ReceiveAndDelete, OnMissingChannel makeChannels = OnMissingChannel.Create) { _subscriptionName = subscriptionName; _topicName = topicName; _messageProducer = messageProducer; _managementClientWrapper = managementClientWrapper; _messageReceiverProvider = messageReceiverProvider; _batchSize = batchSize; _makeChannel = makeChannels; _receiveMode = receiveMode; GetMessageReceiverProvider(); }
async Task OnSessionTestAsync(bool partitioned, bool sessionEnabled, int maxConcurrentCalls, ReceiveMode mode, bool autoComplete) { await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) => { TestUtility.Log($"Topic: {topicName}, MaxConcurrentCalls: {maxConcurrentCalls}, Receive Mode: {mode.ToString()}, AutoComplete: {autoComplete}"); var topicClient = new TopicClient(TestUtility.NamespaceConnectionString, topicName); var subscriptionClient = new SubscriptionClient( TestUtility.NamespaceConnectionString, topicClient.TopicName, subscriptionName, ReceiveMode.PeekLock); try { var sessionHandlerOptions = new SessionHandlerOptions(ExceptionReceivedHandler) { MaxConcurrentSessions = 5, MessageWaitTimeout = TimeSpan.FromSeconds(5), AutoComplete = true }; var testSessionHandler = new TestSessionHandler( subscriptionClient.ReceiveMode, sessionHandlerOptions, topicClient.InnerSender, subscriptionClient.SessionPumpHost); // Send messages to Session await testSessionHandler.SendSessionMessages(); // Register handler testSessionHandler.RegisterSessionHandler(sessionHandlerOptions); // Verify messages were received. await testSessionHandler.VerifyRun(); } finally { await subscriptionClient.CloseAsync(); await topicClient.CloseAsync(); } }); }
private Task <IDisposable> Subscribe(string topicName, string subscriptionName, Func <BrokeredMessage, BrokeredMessageResults> message, ReceiveMode receiveMode = ReceiveMode.ReceiveAndDelete) { var sc = GetFactoryAsync() .ContinueWith(t => t.Result.CreateSubscriptionClient(topicName, subscriptionName, receiveMode)) .ContinueWith(st => { st.Result.OnMessageAsync(m => { Trace(topicName, "Got message " + JsonConvert.SerializeObject(m.MessageId)); return(Task.Run(() => message(m)) .ContinueWith(t => { var result = t.IsFaulted || t.IsCanceled || t.Result == BrokeredMessageResults.Dead ? BrokeredMessageResults.Dead : t.Result == BrokeredMessageResults.Reject ? BrokeredMessageResults.Reject : BrokeredMessageResults.Ack; Trace(topicName, "Result for message " + m.MessageId + " is " + result); return result == BrokeredMessageResults.Dead ? m.DeadLetterAsync() : result == BrokeredMessageResults.Reject ? m.AbandonAsync() : m.CompleteAsync(); }) .Unwrap()); }); return(st.Result); }) .ContinueWith(t => new Subscription(t) as IDisposable); return(sc); }
public SessionClient(ServiceBusConnection serviceBusConnection, string entityPath, ReceiveMode receiveMode) : base(serviceBusConnection, entityPath, receiveMode, RetryPolicy.Default) { }
public OutServiceBusPipeStep(IConfiguration configration, ReceiveMode receiveMode = ReceiveMode.PeekLock, RetryPolicy retryPolicy = null) { _serviceBusConnectionString = configration[ServiceBusConnectionConfigKey]; _receiveMode = receiveMode; _retryPolicy = retryPolicy; }
public QueueClient(ServiceBusConnection serviceBusConnection, string entityPath, ReceiveMode receiveMode, RetryPolicy retryPolicy) { var factory = BuildMessagingFactory(serviceBusConnection); factory.RetryPolicy = retryPolicy; this.queueClient = factory.CreateQueueClient(entityPath, receiveMode); }
public async Task Should_return_true_for_message_that_was_sent_and_received(ReceiveMode receiveMode) { await ServiceBusScope.UsingQueueAsync(partitioned : false, sessionEnabled : false, async queueName => { var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, receiveMode); try { await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); var receivedMessages = await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 1); Assert.True(receivedMessages.First().SystemProperties.IsReceived); // TODO: remove when per test cleanup is possible if (receiveMode == ReceiveMode.PeekLock) { await queueClient.CompleteAsync(receivedMessages.First().SystemProperties.LockToken); } } finally { await queueClient.CloseAsync(); } }); }
/// <summary> /// Creates a new queue client /// </summary> /// <param name="path">Path to the entity</param> /// <param name="receiveMode">Receive mode</param> /// <returns>Queue client instance</returns> public abstract QueueClient CreateQueueClient(string path, ReceiveMode receiveMode);
public void SetRecvMode(ReceiveMode mode) { this.recvMode = mode; }
protected EventDrivenSessionMessagePump(MessageClientEntity messageClient, ReceiveMode mode, string @namespace, string path) : base(mode, @namespace, path) { _messageClient = messageClient; }
protected override IAsyncResult OnBeginAcceptSessionReceiver(string entityName, string sessionId, ReceiveMode receiveMode, TimeSpan timeout, AsyncCallback callback, object state) { IAsyncResult acceptMessageSessionAsyncResult; try { MessagingEntityType?nullable = null; acceptMessageSessionAsyncResult = new Microsoft.ServiceBus.Messaging.Sbmp.AcceptMessageSessionAsyncResult(this, entityName, sessionId, nullable, receiveMode, Constants.DefaultMessageSessionPrefetchCount, null, timeout, timeout, callback, state); } catch (CommunicationException communicationException1) { CommunicationException communicationException = communicationException1; throw Microsoft.ServiceBus.Messaging.FxTrace.Exception.AsError(MessagingExceptionHelper.Unwrap(communicationException, base.IsClosedOrClosing), null); } catch (Exception exception1) { Exception exception = exception1; if (!Fx.IsFatal(exception) && base.IsClosedOrClosing) { throw new OperationCanceledException(SRClient.EntityClosedOrAborted, exception); } throw; } return(acceptMessageSessionAsyncResult); }
public ISubscriptionClient CreateSubscriptionClient(string topicPath, string name, ReceiveMode receiveMode) { var retVal = _subscriptions.FirstOrDefault(item => item.Description.TopicPath.Equals(topicPath) && item.Description.Name.Equals(name)); if (retVal != null) { retVal.Client = new MockSubscriptionClient(this, topicPath, name, receiveMode); return(retVal.Client); } throw new MessagingEntityNotFoundException(name); }
protected override IAsyncResult OnBeginCreateMessageReceiver(string entityName, ReceiveMode receiveMode, TimeSpan timeout, AsyncCallback callback, object state) { MessagingEntityType? nullable = null; CreateReceiverLinkSettings createReceiverLinkSetting = new CreateReceiverLinkSettings(this, entityName, entityName, nullable, receiveMode, null, false); return(new CompletedAsyncResult <SbmpMessageReceiver>(createReceiverLinkSetting.MessageReceiver, callback, state)); }
public static void StartListener(this SubscriptionClient subscriptionClient, OnReceiveMessageCallback onReceiveMessageCallback, ReceiveMode receiveMode = ReceiveMode.PeekLock, bool requiresSession = false) { subscriptionClient.StartListener(new OnReceiveMessageCallbackDelegator(onReceiveMessageCallback), receiveMode, requiresSession); }
protected override QueueClient OnCreateQueueClient(string path, ReceiveMode receiveMode) { return(new SbmpQueueClient(this, path, receiveMode)); }
public Subscription(Topic topic, SubscriptionDescription subscriptionDescription, ReceiveMode receiveMode = ReceiveMode.PeekLock) { _topic = topic; Client = topic.CreateSubscriptionClient(subscriptionDescription.Name, receiveMode); }
/// <summary> /// Constructor /// </summary> /// <param name="factory">Messaging factory instance</param> /// <param name="topicPath">Path to the topic related entity</param> /// <param name="name">Name of the subscription</param> /// <param name="receiveMode">Receive mode</param> internal AmqpSubscriptionClient(AmqpMessagingFactory factory, string topicPath, string name, ReceiveMode receiveMode) : base(factory, topicPath, name, receiveMode) { }
public Task <IDisposable> SubscribeWithRoutingKey(string topicName, string subscriptionName, Func <GenericPayloadDeliverInfo, BrokeredMessageResults> message, ReceiveMode receiveMode = ReceiveMode.ReceiveAndDelete) { return(Subscribe(topicName, subscriptionName, brokeredMessage => { var body = new GenericPayloadDeliverInfo { BrokeredMessage = brokeredMessage, Payload = brokeredMessage.GetBody <GenericPayload>() }; return message(body); }, receiveMode)); }