예제 #1
0
        private static string GetMessagePayload(BrokeredMessage message)
        {
            string ret = string.Empty;
            //try
            //{
            //    var o = message.GetBody<System.IO.Stream>();
            //    using (var r = new StreamReader(o))
            //    {
            //        ret = r.ReadToEnd();
            //    }

            //}
            //catch
            //{
            //    ret = message.GetBody<string>();
            //}
            //return ret;
            if (message.Properties.Keys.Contains("message-source") && (string)message.Properties["message-source"] == "evh")
            {
                var o = message.GetBody<System.IO.Stream>();
                using (var r = new StreamReader(o))
                {
                    ret = r.ReadToEnd();
                }
            }
            else
            {
                ret = message.GetBody<string>();

            }
            return ret;
        }
        public async Task SendBatch()
        {
            var msgs = new BrokeredMessage[] { new BrokeredMessage(), new BrokeredMessage(), new BrokeredMessage(), new BrokeredMessage() };

            var bq = new BusTopicClient(TopicClient.CreateFromConnectionString(connection, this.name));
            await bq.Send(msgs);
        }
 /// <summary>
 /// Creates an instance of the handler factory.
 /// </summary>
 /// <returns>
 /// The created instance.
 /// </returns>
 /// <param name="session">The message session.</param>
 /// <param name="message">The message.</param>
 IMessageSessionAsyncHandler IMessageSessionAsyncHandlerFactory.CreateInstance(MessageSession session, BrokeredMessage message)
 {
     return new SessionHandler(
         msg => messageSubject.OnNext(msg),
         ex => exceptionSubject.OnNext(ex),
         scheduler);
 }
        public JsonResult SendMessage(string topicName, string message, bool messageIsUrgent, bool messageIsImportant)
        {
            TopicClient topicClient = this.messagingFactory.CreateTopicClient(topicName);
            var customMessage = new CustomMessage() { Body = message, Date = DateTime.Now };
            bool success = false;
            BrokeredMessage bm = null;

            try
            {
                bm = new BrokeredMessage(customMessage);
                bm.Properties["Urgent"] = messageIsUrgent ? "1" : "0";
                bm.Properties["Important"] = messageIsImportant ? "1" : "0";
                bm.Properties["Priority"] = "Low";
                topicClient.Send(bm);
                success = true;
            }
            catch (Exception)
            {
                // TODO: do something
            }
            finally
            {
                if (bm != null)
                {
                    bm.Dispose();
                }
            }

            return this.Json(success, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// Save Message to Queue
        /// </summary>
        /// <param name="message">Message</param>
        /// <returns>Task</returns>
        public async Task Send(BrokeredMessage message)
        {
            if (null == message)
            {
                throw new ArgumentNullException("message");
            }

            while (true)
            {
                try
                {
                    await this.client.Send(message);

                    break;
                }
                catch (MessagingException ex)
                {
                    if (ex.IsTransient)
                    {
                        this.HandleTransientError(ex);
                    }
                    else
                    {
                        Trace.TraceError("Error: '{0}'", ex.ToString());

                        throw;
                    }
                }
            }
        }
예제 #6
0
        async Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
        {
            foreach (EventData eventData in messages)
            {
                byte[] data = eventData.GetBytes();

                if (eventData.Properties.ContainsKey("messageType") && (string)eventData.Properties["messageType"] == "interactive")
                {
                    var messageId = (string)eventData.SystemProperties["message-id"];

                    var queueMessage = new BrokeredMessage(new MemoryStream(data));
                    queueMessage.MessageId = messageId;
                    queueMessage.Properties["messageType"] = "interactive";
                    await queueClient.SendAsync(queueMessage);

                    WriteHighlightedMessage(string.Format("Received interactive message: {0}", messageId));
                    continue;
                }

                if (toAppend.Length + data.Length > MAX_BLOCK_SIZE || stopwatch.Elapsed > MAX_CHECKPOINT_TIME)
                {
                    await AppendAndCheckpoint(context);
                }
                await toAppend.WriteAsync(data, 0, data.Length);

                Console.WriteLine(string.Format("Message received.  Partition: '{0}', Data: '{1}'",
                  context.Lease.PartitionId, Encoding.UTF8.GetString(data)));
            }
        }
예제 #7
0
        public static void AddToAzureQueue(this object o, string queueName, string nameSpace, string issuerName, string issuerKey)
        {
            if (_queueClient == null || queueName.ToLower() != _queueName || nameSpace.ToLower() != _nameSpace || issuerName.ToLower() != _issuerName || issuerKey.ToLower() != _issuerKey)
            {
                _queueName = queueName.ToLower();
                _nameSpace = nameSpace.ToLower();
                _issuerName = issuerName.ToLower();
                _issuerKey = issuerKey.ToLower();

                ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;
                System.Net.ServicePointManager.DefaultConnectionLimit = int.MaxValue;
                System.Net.ServicePointManager.Expect100Continue = false;
                System.Net.ServicePointManager.UseNagleAlgorithm = false;

                var credentials = GetToken(issuerName, issuerKey);

                // Get a client to the queue
                var messagingFactory = MessagingFactory.Create(GetAddress(nameSpace), credentials);
                _queueClient = messagingFactory.CreateQueueClient(queueName);
            }

            BrokeredMessage message = new BrokeredMessage(o);

            _queueClient.Send(message);
        }
        public ServiceBusReceiveContext(Uri inputAddress, BrokeredMessage message, IReceiveObserver observer, ISendEndpointProvider sendEndpointProvider, IPublishEndpointProvider publishEndpointProvider)
            : base(inputAddress, message.DeliveryCount > 1, observer, sendEndpointProvider, publishEndpointProvider)
        {
            _message = message;

            GetOrAddPayload<BrokeredMessageContext>(() => this);
        }
예제 #9
0
        /// <summary>
        /// Convert the brokered message to an envelope.
        /// </summary>
        /// <param name="brokeredMessage"></param>
        /// <returns></returns>
        public async Task<IEnvelope<IMessage>> BuildMessage(BrokeredMessage brokeredMessage)
        {
            using (var stream = brokeredMessage.GetBody<Stream>())
            using (var ms = new MemoryStream())
            {
                var messageType = brokeredMessage.ContentType;

                // Log.
                MessagingEventSource.Log.DeserializingMessage(messageType, brokeredMessage.MessageId, brokeredMessage.CorrelationId, brokeredMessage.SessionId);

                // Helps us get access to the byte array.
                await stream.CopyToAsync(ms);

                // Build the envelope.
                var envelope = Envelope.Create<IMessage>(null)
                    .CorrelationId(brokeredMessage.CorrelationId)
                    .SessionId(brokeredMessage.SessionId)
                    .TimeToLive(brokeredMessage.TimeToLive)
                    .Properties(brokeredMessage.Properties);

                // Handle interceptors, then deserialize.
                var serializedMessage = await Configuration.MessageFilterInvoker.BeforeDeserialization(envelope, ms.ToArray());
                var message = await Configuration.Serializer.Deserialize<IMessage>(serializedMessage);

                // Log.
                MessagingEventSource.Log.DeserializationComplete(messageType, brokeredMessage.MessageId, brokeredMessage.CorrelationId, brokeredMessage.SessionId);

                // Done.
                return envelope.Body(message);
            }
        }
        private void SendToQueue_Click(object sender, RoutedEventArgs e)
        {
            Trace.WriteLine("SendMessage()");

            var namespaceManager = NamespaceManager.Create();

            if (namespaceManager.QueueExists(QueueName))
            {
                try
                {
                    BrokeredMessage message = new BrokeredMessage(messageBody);
                    message.MessageId = messageId;

                    queueClient.Send(message);
                }
                catch (MessagingException ex)
                {
                    if (!ex.IsTransient)
                    {
                        Trace.WriteLine(ex.Message);
                        throw;
                    }
                    else
                    {
                        HandleTransientErrors(e);
                    }
                }
            }
            else
            {
                Trace.WriteLine("Queue does not exist: " + QueueName);
            }
        }
        private void OnBrokerMessage(BrokeredMessage brokeredMessage)
        {
            try
            {
                //Ignore messages from self
                if (brokeredMessage.Properties[SidAttributeName].ToString() == _sid)
                {
                    brokeredMessage.Complete();
                    return;
                }

                var json = brokeredMessage.Properties[DataAttributeName].ToString();
                var message = _jsonSerializer.DeserializeFromString<Message>(json);

                var pipeline = Composable.GetExport<IXSocketPipeline>();
                var controller = Composable.GetExports<IXSocketController>().First(p => p.Alias == message.Controller);
                controller.ProtocolInstance = new XSocketInternalProtocol();
                pipeline.OnIncomingMessage(controller, message);
                brokeredMessage.Complete();
            }
            catch (Exception ex)
            {
                Composable.GetExport<IXLogger>().Error(ex.ToString());

                // Indicates a problem
                if (brokeredMessage.DeliveryCount > 3)
                {
                    brokeredMessage.DeadLetter();
                }
                else
                {
                    brokeredMessage.Abandon();
                }
            }
        }
예제 #12
0
        public TransportMessage ToTransportMessage(BrokeredMessage message)
        {
            TransportMessage t;
            var rawMessage = message.GetBody<byte[]>();

            if (message.Properties.Count == 0)
            {
                t = DeserializeMessage(rawMessage);
            }
            else
            {
                t = new TransportMessage(message.MessageId, message.Properties.ToDictionary(kvp=>kvp.Key,kvp=>kvp.Value.ToString()))
                        {
                            CorrelationId = message.CorrelationId,
                            TimeToBeReceived = message.TimeToLive
                        };

                t.MessageIntent =
                    (MessageIntentEnum)
                    Enum.Parse(typeof(MessageIntentEnum), message.Properties[Headers.MessageIntent].ToString());

                if ( !String.IsNullOrWhiteSpace( message.ReplyTo ) )
                {
                    t.ReplyToAddress = Address.Parse( message.ReplyTo ); // Will this work?
                }

                t.Body = rawMessage;
            }

            return t;
        }
예제 #13
0
        protected override void PumpMessage(BrokeredMessage message)
        {
            var correlationId = Guid.Parse(message.CorrelationId);
            var responseCorrelationWrapper = _requestResponseCorrelator.TryGetWrapper(correlationId);
            if (responseCorrelationWrapper == null)
            {
                Logger.Debug("Could not find correlation wrapper for reply {0} ({1}", correlationId, message.Properties[MessagePropertyKeys.MessageType]);
                return;
            }

            var success = (bool) message.Properties[MessagePropertyKeys.RequestSuccessfulKey];
            if (success)
            {
                Logger.Debug("Request {0} was successful. Dispatching reply to correlation wrapper.", correlationId);

                var responseType = responseCorrelationWrapper.ResponseType;
                var response = message.GetBody(responseType);
                responseCorrelationWrapper.Reply(response);

                Logger.Debug("Response {0} dispatched.", correlationId);
            }
            else
            {
                var exceptionMessage = (string) message.Properties[MessagePropertyKeys.ExceptionMessageKey];
                var exceptionStackTrace = (string) message.Properties[MessagePropertyKeys.ExceptionStackTraceKey];

                Logger.Debug("Request {0} failed. Dispatching exception to correlation wrapper: {1} {2}", correlationId, exceptionMessage, exceptionStackTrace);

                responseCorrelationWrapper.Throw(exceptionMessage, exceptionStackTrace);
            }
        }
예제 #14
0
        public static string SendMessage(MessageFormat msg,string SharedKey)
        {
            try
            {
                string connectionString = string.Format("Endpoint=sb://myflow-ns.servicebus.windows.net/;SharedAccessKeyName={0};SharedAccessKey={1}", msg.PolicyName, SharedKey);
                string JsonMessage = JsonConvert.SerializeObject(msg);
                var jsonObjStream = new MemoryStream(Encoding.UTF8.GetBytes(JsonMessage));
                MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connectionString);
                MessageSender MessageSender = factory.CreateMessageSender("flowspec");
                BrokeredMessage Message = new BrokeredMessage(jsonObjStream);
                MessageSender.Send(Message);
                if (msg.Action == "Add")
                {
                    return "The Filter is added";
                }
                else
                {
                    return "The Filter is removed";
                }

            }
            catch (MessagingCommunicationException)
            {

                return "Client is not able to establish a connection to Service Bus.";
            }

            catch (UnauthorizedAccessException)
            {
                return "PolicyName or SharedAccessKey is incorrect";
            }
        }
예제 #15
0
        private BrokeredMessage BuildMessage(Envelope<ICommand> command)
        {
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);
            this.serializer.Serialize(writer, command.Body);
            stream.Position = 0;

            var message = new BrokeredMessage(stream, true);
            if (!default(Guid).Equals(command.Body.Id))
            {
                message.MessageId = command.Body.Id.ToString();
            }

            var metadata = this.metadataProvider.GetMetadata(command.Body);
            if (metadata != null)
            {
                foreach (var pair in metadata)
                {
                    message.Properties[pair.Key] = pair.Value;
                }
            }

            if (command.Delay != TimeSpan.Zero)
                message.ScheduledEnqueueTimeUtc = DateTime.UtcNow.Add(command.Delay);

            return message;
        }
예제 #16
0
    static void Main()
    {
        var connectionString = Environment.GetEnvironmentVariable("AzureServiceBus.ConnectionString");
        var queueClient = QueueClient.CreateFromConnectionString(connectionString, "Samples.ASB.NativeIntegration");

        #region SerializedMessage

        var nativeMessage = @"{""Content"":""Hello from native sender"",""SendOnUtc"":""2015-10-27T20:47:27.4682716Z""}";

        #endregion

        var nativeMessageAsStream = new MemoryStream(Encoding.UTF8.GetBytes(nativeMessage));

        var message = new BrokeredMessage(nativeMessageAsStream)
        {
            MessageId = Guid.NewGuid().ToString()
        };

        #region NecessaryHeaders

        message.Properties["NServiceBus.EnclosedMessageTypes"] = "NativeMessage";
        message.Properties["NServiceBus.MessageIntent"] = "Send";

        #endregion

        queueClient.Send(message);

        Console.WriteLine("Native message sent");
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }
예제 #17
0
        static void Main(string[] args)
        {
            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");

            NamespaceManager ConnectorNamespaceMgr = NamespaceManager.CreateFromConnectionString(connectionString);
            if (!ConnectorNamespaceMgr.QueueExists("TestQueue"))
            {
                ConnectorNamespaceMgr.CreateQueue("TestQueue");
            }

            QueueClient Client = QueueClient.CreateFromConnectionString(connectionString, "TestQueue", ReceiveMode.PeekLock);

            for (int i = 0; i < 5; i++)
            {
                // Create message, passing a string message for the body.
                BrokeredMessage message = new BrokeredMessage("Test message " + i);

                // Set some addtional custom app-specific properties.
                message.Properties["TestProperty"] = "TestValue";
                message.Properties["Message number"] = i;

                // Send message to the queue.
                Client.Send(message);
            }
            ReceiveQueueMessages(Client);
        }
예제 #18
0
 private static BrokeredMessage CreateSampleMessage(string messageId, string messageBody)
 {
     BrokeredMessage message = new BrokeredMessage(messageBody);
     message.MessageId = messageId;
     message.Properties["IdNumber"] = Convert.ToInt32(messageId);
     return message;
 }
 protected override async Task When()
 {
     _request = new BrokeredMessage();
     _sessionId = Guid.NewGuid().ToString();
     _request.ReplyToSessionId = _sessionId;
     _response = await Subject.CreateFailedResponse(_request, new Exception());
 }
        private async Task ProcessMessage(BrokeredMessage message)
        {
            try
            {
                if (!this.IsValidMessage(message))
                {
                    // Send the message to the Dead Letter queue for further analysis.
                    await message.DeadLetterAsync("Invalid message", "The message Id is invalid");
                    Trace.WriteLine("Invalid Message. Sending to Dead Letter queue");
                }

                // Simulate message processing.
                await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false);

                Trace.WriteLine("Consumer " + RoleEnvironment.CurrentRoleInstance.Id + " : Message processed successfully: " + message.MessageId);

                // Complete the message.
                await message.CompleteAsync();
            }
            catch (Exception ex)
            {
                // Abandon the message when appropriate.  If the message reaches the MaxDeliveryCount limit, it will be automatically deadlettered.
                message.Abandon();
                Trace.TraceError("An error has occurred while processing the message: " + ex.Message);
            }
        }
        public void TheyShouldBeResolvable()
        {
            var interceptorTypes = new[] {typeof (DummyInterceptor)};

            var builder = new ContainerBuilder();
            var typeProvider = Substitute.For<ITypeProvider>();
            typeProvider.InterceptorTypes.Returns(interceptorTypes);

            builder.RegisterZombus(typeProvider);

            using (var container = builder.Build())
            using (var dependencyResolver = container.Resolve<IDependencyResolver>())
            using (var scope = dependencyResolver.CreateChildScope())
            {
                var interceptorSetting = new GlobalOutboundInterceptorTypesSetting
                                         {
                                             Value = interceptorTypes
                                         };
                var outboundInterceptorFactory = new OutboundInterceptorFactory(interceptorSetting,
                                                                                new PropertyInjector(Substitute.For<IClock>(),
                                                                                    Substitute.For<IDispatchContextManager>(),
                                                                                                     Substitute.For<ILargeMessageBodyStore>()));

                var dummyBrokeredMessage = new BrokeredMessage();
                var interceptors = outboundInterceptorFactory.CreateInterceptors(scope, dummyBrokeredMessage);

                interceptors.Count().ShouldBe(1);
            }
        }
 public static SBMessage FromBrokeredMessage(BrokeredMessage message)
 {
     SBMessage ret = new SBMessage(message.GetBody());
     foreach (var key in message.Properties.Keys)
         ret.Headers.Add(key, message.Properties[key]);
     return ret;
 }
예제 #23
0
 private static void SendMessage(string name, string message)
 {
     Greeting g = new Greeting() { Name = name, Message = message };
     while(true){
         try
         {
             BrokeredMessage bmsg = new BrokeredMessage(g);
             queueClient.Send(bmsg);
             Console.Out.WriteLine("Sent message with id {0}", bmsg.MessageId);
             break;
         }
         catch (MessagingException mex)
         {
             if (!mex.IsTransient)
             {
                 throw;
             }
             else
             {
                 Console.Out.WriteLine("We experienced a temporary setback due to {0}", mex.Message);
                 Console.Out.WriteLine("Retrying in 2 seconds.");
                 Thread.Sleep(2000);
             }
         }
     }
 }
예제 #24
0
파일: SBMessage.cs 프로젝트: foxjazz/IRCAL
 public void SendSBM(string msg, string channel)
 {
     message = new BrokeredMessage(msg);
     message.Properties["channel"] = channel;
     message.TimeToLive = timetolive;
     client.Send(message);
 }
예제 #25
0
파일: SBMessage.cs 프로젝트: foxjazz/IRCAL
        public void SendSBM(string msg){

            message = new BrokeredMessage(msg) { TimeToLive = timetolive };
        client.Send(message);

            
        }
        /// <summary>
        /// Create a new session handler.
        /// </summary>
        /// <param name="session"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public IMessageSessionAsyncHandler CreateInstance(MessageSession session, BrokeredMessage message)
        {
            ServiceBusEventSource.Log.SessonAccepted(_receiverNamespace, _receiverPath, session.SessionId, message.MessageId, message.CorrelationId);

            // Use the current handler.
            return new SessionMessageAsyncHandler(_receiverNamespace, _receiverPath, session, _messageHandler, _options);
        }
 protected override async Task When()
 {
     _request = new BrokeredMessage();
     _sessionId = Guid.NewGuid().ToString();
     _request.ReplyToSessionId = _sessionId;
     _response = await Subject.CreateSuccessfulResponse(new TestResponse(), _request);
 }
        public async Task Enqueue(object message)
        {
            var brokeredMessage = new BrokeredMessage(message);

            var topicClient = QueueClient.CreateFromConnectionString(_serviceBusNamespaceConnectionString, QueueName);
            await topicClient.SendAsync(brokeredMessage);
        }
예제 #29
0
        static void Main(string[] args)
        {

            try
            {
                //ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;

                string topicName = "sb-salesorder-topic";
                string sbconnection = "Endpoint=sb://sb-twocents-ns.servicebus.windows.net/;SharedAccessKeyName=Sender;SharedAccessKey=TzYnAEaXHAP3dVJ0J/knLc+2+99C/E2ytbo8qDJQ+TI=";
                MessagingFactory factory = MessagingFactory.CreateFromConnectionString(sbconnection);
                TopicClient client = factory.CreateTopicClient(topicName);

                string postBody = "{'ServiceNumber': 'TST100', 'AddressCode': 'HAG', 'ServiceContractNumber': 'SOC920001', Description': 'Testmelding'}";

                BrokeredMessage msg = new BrokeredMessage(postBody);
                msg.Properties["Priority"] = 1;

                client.Send(msg);

                msg = null;

                Console.WriteLine("Press Enter");
                Console.Read();

            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Error: {0}", ex.ToString()));
                Console.Read();
            }

        }
예제 #30
0
        public void HandleMessage(BrokeredMessage message)
        {
            if (message.GetMessageType() == "Create")
            {
                var virtualMachine = message.GetObject<VirtualMachine>();
                var imageName = CloudConfigurationManager.GetSetting("VirtualMachineBaseImageName");
                var dataDiskBase = CloudConfigurationManager.GetSetting("DataDiskName");
                var dataDiskName = String.Format("{0}-{1}", dataDiskBase, virtualMachine.Name);
                var sourceVhdName = String.Format("{0}.vhd", dataDiskBase);
                var storageContainerUrl = CloudConfigurationManager.GetSetting("StorageContainerUrl");
                var vhdContainerName = CloudConfigurationManager.GetSetting("VhdContainerName"); //TODO: does this work with multiple storage accounts?
                var serviceName = CloudConfigurationManager.GetSetting("ServiceName");

                //var subscriptionId = CloudConfigurationManager.GetSetting("Azure.SubscriptionId");
                //var managementCertificateString = CloudConfigurationManager.GetSetting("Azure.ManagementCertificate");
                //var managementCertificate = new X509Certificate2(Convert.FromBase64String(managementCertificateString));
                //var credentials = new CertificateCloudCredentials(subscriptionId, managementCertificate);

                //TODO: find a subscription?

                //TODO: get storage account?

                if (AzureVmExists(_executor, virtualMachine) == false)
                {
                    CreateNewVirtualMachine(_executor, virtualMachine, imageName, serviceName, sourceVhdName, storageContainerUrl, vhdContainerName, dataDiskName);
                }
            }
            else
            {
                throw new ArgumentException("Invalid Message Type.", "message");
            }
        }
예제 #31
0
        protected virtual void ReceiveEvent(BrokeredMessage message)
        {
            DateTimeOffset startedAt     = DateTimeOffset.UtcNow;
            Stopwatch      mainStopWatch = Stopwatch.StartNew();
            string         responseCode  = "200";
            // Null means it was skipped
            bool?              wasSuccessfull      = true;
            string             telemetryName       = string.Format("Cqrs/Handle/Event/{0}", message.MessageId);
            ISingleSignOnToken authenticationToken = null;

            IDictionary <string, string> telemetryProperties = new Dictionary <string, string> {
                { "Type", "Azure/Servicebus" }
            };
            object value;

            if (message.Properties.TryGetValue("Type", out value))
            {
                telemetryProperties.Add("MessageType", value.ToString());
            }
            TelemetryHelper.TrackMetric("Cqrs/Handle/Event", CurrentHandles++, telemetryProperties);
            var brokeredMessageRenewCancellationTokenSource = new CancellationTokenSource();

            try
            {
                Logger.LogDebug(string.Format("An event message arrived with the id '{0}'.", message.MessageId));
                string messageBody = message.GetBody <string>();

                IEvent <TAuthenticationToken> @event = AzureBusHelper.ReceiveEvent(messageBody, ReceiveEvent,
                                                                                   string.Format("id '{0}'", message.MessageId),
                                                                                   () =>
                {
                    wasSuccessfull = null;
                    telemetryName  = string.Format("Cqrs/Handle/Event/Skipped/{0}", message.MessageId);
                    responseCode   = "204";
                    // Remove message from queue
                    try
                    {
                        message.Complete();
                    }
                    catch (MessageLockLostException exception)
                    {
                        throw new MessageLockLostException(string.Format("The lock supplied for the skipped event message '{0}' is invalid.", message.MessageId), exception);
                    }
                    Logger.LogDebug(string.Format("An event message arrived with the id '{0}' but processing was skipped due to event settings.", message.MessageId));
                    TelemetryHelper.TrackEvent("Cqrs/Handle/Event/Skipped", telemetryProperties);
                },
                                                                                   () =>
                {
                    AzureBusHelper.RefreshLock(brokeredMessageRenewCancellationTokenSource, message, "event");
                }
                                                                                   );

                if (wasSuccessfull != null)
                {
                    if (@event != null)
                    {
                        telemetryName       = string.Format("{0}/{1}", @event.GetType().FullName, @event.Id);
                        authenticationToken = @event.AuthenticationToken as ISingleSignOnToken;

                        var telemeteredMessage = @event as ITelemeteredMessage;
                        if (telemeteredMessage != null)
                        {
                            telemetryName = telemeteredMessage.TelemetryName;
                        }

                        telemetryName = string.Format("Cqrs/Handle/Event/{0}", telemetryName);
                    }
                    // Remove message from queue
                    try
                    {
                        message.Complete();
                    }
                    catch (MessageLockLostException exception)
                    {
                        throw new MessageLockLostException(string.Format("The lock supplied for event '{0}' of type {1} is invalid.", @event.Id, @event.GetType().Name), exception);
                    }
                }
                Logger.LogDebug(string.Format("An event message arrived and was processed with the id '{0}'.", message.MessageId));

                IList <IEvent <TAuthenticationToken> > events;
                if (EventWaits.TryGetValue(@event.CorrelationId, out events))
                {
                    events.Add(@event);
                }
            }
            catch (MessageLockLostException exception)
            {
                IDictionary <string, string> subTelemetryProperties = new Dictionary <string, string>(telemetryProperties);
                subTelemetryProperties.Add("TimeTaken", mainStopWatch.Elapsed.ToString());
                TelemetryHelper.TrackException(exception, null, subTelemetryProperties);
                if (ThrowExceptionOnReceiverMessageLockLostExceptionDuringComplete)
                {
                    Logger.LogError(exception.Message, exception: exception);
                    // Indicates a problem, unlock message in queue
                    message.Abandon();
                    wasSuccessfull = false;
                }
                else
                {
                    Logger.LogWarning(exception.Message, exception: exception);
                    try
                    {
                        message.DeadLetter("LockLostButHandled", "The message was handled but the lock was lost.");
                    }
                    catch (Exception)
                    {
                        // Oh well, move on.
                        message.Abandon();
                    }
                }
                responseCode = "599";
            }
            catch (Exception exception)
            {
                TelemetryHelper.TrackException(exception, null, telemetryProperties);
                // Indicates a problem, unlock message in queue
                Logger.LogError(string.Format("An event message arrived with the id '{0}' but failed to be process.", message.MessageId), exception: exception);
                message.Abandon();
                wasSuccessfull = false;
                responseCode   = "500";
                telemetryProperties.Add("ExceptionType", exception.GetType().FullName);
                telemetryProperties.Add("ExceptionMessage", exception.Message);
            }
            finally
            {
                // Cancel the lock of renewing the task
                brokeredMessageRenewCancellationTokenSource.Cancel();
                TelemetryHelper.TrackMetric("Cqrs/Handle/Event", CurrentHandles--, telemetryProperties);

                mainStopWatch.Stop();
                TelemetryHelper.TrackRequest
                (
                    telemetryName,
                    authenticationToken,
                    startedAt,
                    mainStopWatch.Elapsed,
                    responseCode,
                    wasSuccessfull == null || wasSuccessfull.Value,
                    telemetryProperties
                );

                TelemetryHelper.Flush();
            }
        }
예제 #32
0
 public MessageContext(BrokeredMessage brokeredMessage)
 {
     BrokeredMessage         = brokeredMessage;
     SentTime                = DateTime.Now;
     ToBeSentMessageContexts = new List <IMessageContext>();
 }
 public override async Task CompleteProcessingMessageAsync(BrokeredMessage message, Executors.FunctionResult result, CancellationToken cancellationToken)
 {
     _trace.Info("Custom processor End called!");
     await base.CompleteProcessingMessageAsync(message, result, cancellationToken);
 }
 public override async Task <bool> BeginProcessingMessageAsync(BrokeredMessage message, CancellationToken cancellationToken)
 {
     _trace.Info("Custom processor Begin called!");
     return(await base.BeginProcessingMessageAsync(message, cancellationToken));
 }
 // Second listerner for the topic
 public static void SBTopicListener2(
     [ServiceBusTrigger(TopicName, QueueNamePrefix + "topic-2", AccessRights.Listen)] BrokeredMessage message)
 {
     SBTopicListener2Impl(message);
 }
 // Passes a service bus message from a queue to topic using a brokered message
 public static void SBQueue2SBTopic(
     [ServiceBusTrigger(QueueNamePrefix + "1", AccessRights.Listen)] string message,
     [ServiceBus(TopicName, AccessRights.Send)] out BrokeredMessage output)
 {
     output = SBQueue2SBTopic_GetOutputMessage(message);
 }
 // Passes a service bus message from a queue to topic using a brokered message
 public static void SBQueue2SBTopic(
     [ServiceBusTrigger(QueueNamePrefix + "1")] string message,
     [ServiceBus(TopicName)] out BrokeredMessage output)
 {
     output = SBQueue2SBTopic_GetOutputMessage(message);
 }
 protected override Task SendMessageAsync(BrokeredMessage message, Instant?publishTime = null) =>
 this.sendMessageAsyncDelegate(message, publishTime);
예제 #39
0
        public static void Execute([ServiceBusTrigger("%Subroute.ServiceBus.RequestTopicName%", "%Subroute.ServiceBus.RequestSubscriptionName%")] BrokeredMessage message, [ServiceBus("%Subroute.ServiceBus.ResponseTopicName%")] out BrokeredMessage response)
        {
            var stopwatch = Stopwatch.StartNew();

            ExecuteInternal(message, out response);
            stopwatch.Stop();

            Trace.TraceInformation($"Trace 'Total Execution' - Elapsed {stopwatch.ElapsedMilliseconds}");
        }
예제 #40
0
 public Task SendAsync(BrokeredMessage brokeredMessage)
 {
     return(_messageSender.SendAsync(brokeredMessage));
 }
예제 #41
0
 public void Send(BrokeredMessage message)
 {
     queueClient.Send(message);
 }
예제 #42
0
        private static void ExecuteInternal(BrokeredMessage message, out BrokeredMessage response)
        {
            // We must set the out parameter no matter what, so do that first.
            response = new BrokeredMessage();

            // We'll create the app domain in the outer scope so we can unload it when we are finished (if it was created).
            AppDomain sandboxDomain = null;

            try
            {
                var requestId = (int)message.Properties["RequestId"];

                // Set correlation id of response message using the correlation ID of the request message.
                response.CorrelationId           = message.CorrelationId;
                response.Properties["RequestId"] = requestId;

                // The request will also load the associated route, so we'll use that feature
                // to reduce the number of SQL calls we make.
                var requestTask = TraceUtility.TraceTime("Get Load Request Task", () => Program.RequestRepository.GetRequestByIdAsync(requestId));
                TraceUtility.TraceTime("Load Request", () => requestTask.Wait());

                var request       = requestTask.Result;
                var route         = request.Route;
                var routeSettings = route.RouteSettings;

                // Trace the incoming request URI.
                Trace.TraceInformation("Trace 'Request Uri' - {0}", request.Uri);

                try
                {
                    var ev = new Evidence();
                    ev.AddHostEvidence(new Zone(SecurityZone.Internet));
                    var assemblyType         = typeof(ExecutionSandbox);
                    var assemblyPath         = Path.GetDirectoryName(assemblyType.Assembly.Location);
                    var sandboxPermissionSet = TraceUtility.TraceTime("Create Sandbox Permission Set", () => SecurityManager.GetStandardSandbox(ev));

                    // Exit with an error code if for some reason we can't get the sandbox permission set.
                    if (sandboxPermissionSet == null)
                    {
                        throw new EntryPointException("Unable to load the sandbox environment, please contact Subroute.io for help with this error.");
                    }

                    TraceUtility.TraceTime("Reconfigure Appropriate Permission Sets", () =>
                    {
                        // Remove access to UI components since we are in a headless environment.
                        sandboxPermissionSet.RemovePermission(typeof(UIPermission));

                        // Remove access to the File System Dialog since we are headless.
                        sandboxPermissionSet.RemovePermission(typeof(FileDialogPermission));

                        // Add the ability to use reflection for invocation and serialization.
                        sandboxPermissionSet.AddPermission(new ReflectionPermission(PermissionState.Unrestricted));

                        // Add the ability to make web requests.
                        sandboxPermissionSet.AddPermission(new WebPermission(PermissionState.Unrestricted));

                        // Add the ability to use the XmlSerializer and the DataContractSerializer.
                        sandboxPermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));
                    });

                    // We'll create a new folder to hold an empty config file we create, and by
                    // doing this, it prevents the user from gaining access to our configuration
                    // file and the settings within, such as connection strings, infrastructure
                    // and other sensitive information we don't want them to have. Plus it will
                    // allow us to change any configuration settings that are specific to their
                    // application domain, such as default settings and other infrastructure.
                    // We must ensure that we have at least the root configuration XML tag in
                    // the configuration file we create or various dependencies will fail
                    // such as XmlSerializer and DataContractSerializer.
                    var tempDirectory       = Path.GetTempPath();
                    var userConfigDirectory = Path.Combine(tempDirectory, route.Uri);
                    var userConfigFilePath  = Path.Combine(userConfigDirectory, "app.config");
                    TraceUtility.TraceTime("Create Sandbox Directory", () => Directory.CreateDirectory(userConfigDirectory));

                    var configFile = TraceUtility.TraceTime("Generate App.Config File", () => routeSettings.Aggregate(@"<?xml version=""1.0"" encoding=""utf-8"" ?><configuration><appSettings>",
                                                                                                                      (current, setting) => current + $"<add key=\"{setting.Name}\" value=\"{setting.Value}\" />{Environment.NewLine}",
                                                                                                                      result => $"{result}</appSettings></configuration>"));

                    TraceUtility.TraceTime("Write App.Config to Disk", () => File.WriteAllText(userConfigFilePath, configFile));

                    // We'll add one last permission to allow the user access to their own private folder.
                    TraceUtility.TraceTime("Add Permission to Read App.Config File", () => sandboxPermissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, new[] { userConfigDirectory })));

                    TraceUtility.TraceTime("Create AppDomain", () =>
                    {
                        var appDomainSetup = new AppDomainSetup {
                            ApplicationBase = assemblyPath, ConfigurationFile = userConfigFilePath
                        };
                        sandboxDomain = AppDomain.CreateDomain("Sandboxed", ev, appDomainSetup, sandboxPermissionSet);
                    });

                    // The ExecutionSandbox is a MarshalByRef type that allows us to dynamically
                    // load their assemblies via a byte array and execute methods inside of
                    // their app domain from out full-trust app domain. It's the bridge that
                    // cross the app domain boundary.
                    var executionSandbox = TraceUtility.TraceTime("Create ExecutionSandbox Instance", () => (ExecutionSandbox)sandboxDomain.CreateInstance(
                                                                      assemblyType.Assembly.FullName,
                                                                      assemblyType.FullName,
                                                                      false,
                                                                      BindingFlags.Public | BindingFlags.Instance,
                                                                      null, null, null, null)
                                                                  .Unwrap());

                    // Build the ExecutionRequest object that represents the incoming request
                    // which holds the payload, headers, method, etc. The class is serialized
                    // so it can cross the app domain boundary. So it's serialized in our
                    // full-trust host app domain, and deserialized and reinstantiated in
                    // the sandbox app domain.
                    var uri = new Uri(request.Uri, UriKind.Absolute);
                    var executionRequest = TraceUtility.TraceTime("Create RouteRequest Instance", () => new RouteRequest(uri, request.Method)
                    {
                        IpAddress = request.IpAddress,
                        Headers   = HeaderHelpers.DeserializeHeaders(request.RequestHeaders),
                        Body      = request.RequestPayload
                    });

                    try
                    {
                        // The ExecutionSandbox we'll attempt to locate the best method to execute
                        // based on the incoming request method (GET, POST, DELETE, etc.) and
                        // will pass the ExecutionRequest we created above. In return, we receive
                        // an instance of ExecutionResponse that has been serialized like the request
                        // and deserialized in our full-trust host domain.
                        var executionResponse = TraceUtility.TraceTime("Load and Execute Route", () => executionSandbox.Execute(route.Assembly, executionRequest));

                        // We'll use the data that comes back from the response to fill out the
                        // remaineder of the database request record which will return the status
                        // code, message, payload, and headers. Then we update the database.
                        TraceUtility.TraceTime("Update Request Record", () =>
                        {
                            request.CompletedOn     = DateTimeOffset.UtcNow;
                            request.StatusCode      = (int)executionResponse.StatusCode;
                            request.StatusMessage   = executionResponse.StatusMessage;
                            request.ResponsePayload = executionResponse.Body;
                            request.ResponseHeaders = Common.RouteResponse.SerializeHeaders(executionResponse.Headers);

                            Program.RequestRepository.UpdateRequestAsync(request).Wait();
                        });

                        // We'll pass back a small bit of data indiciating to the subscribers of
                        // the response topic listening for our specific correlation ID that indicates
                        // the route code was executed successfully and to handle it as such.
                        response.Properties["Result"]  = (int)ExecutionResult.Success;
                        response.Properties["Message"] = "Completed Successfully";
                    }
                    catch (TargetInvocationException invokationException)
                    {
                        // These exceptions can occur when we encounter a permission exception where
                        // the user doesn't have permission to execute a particular block of code.
                        var securityException = invokationException.InnerException as SecurityException;
                        if (securityException != null)
                        {
                            throw new RoutePermissionException(GetPermissionErrorMessage(securityException), invokationException);
                        }

                        // Check for BadRequestException, we need to wrap it with the core exception.
                        // These exceptions can occur when query string parsing fails, and since the
                        // user's code doesn't have access to the core exceptions, we'll need to wrap
                        // it instead manually.
                        var badRequestException = invokationException.InnerException as Common.BadRequestException;
                        if (badRequestException != null)
                        {
                            throw new Core.Exceptions.BadRequestException(badRequestException.Message, badRequestException);
                        }

                        // Otherwise it is most likely a custom user exception.
                        throw new CodeException(invokationException.InnerException?.Message ?? "Route raised a custom exception.", invokationException.InnerException);
                    }
                    catch (EntryPointException entryPointException)
                    {
                        // These exceptions occur when an entry point could not be located.
                        // Since we don't have a reference to core in the common library.
                        // We'll instead wrap this exception in a core
                        // exception to apply a status code.
                        throw new RouteEntryPointException(entryPointException.Message, entryPointException);
                    }
                    catch (SecurityException securityException)
                    {
                        // These exceptions can occur when we encounter a permission exception where
                        // the user doesn't have permission to execute a particular block of code.
                        throw new RoutePermissionException(GetPermissionErrorMessage(securityException), securityException);
                    }
                    catch (Common.BadRequestException badRequestException)
                    {
                        // These exceptions can occur when query string parsing fails, and since the
                        // user's code doesn't have access to the core exceptions, we'll need to wrap
                        // it instead manually.
                        throw new Core.Exceptions.BadRequestException(badRequestException.Message, badRequestException);
                    }
                    catch (Exception routeException)
                    {
                        // These are all other exceptions that occur during the execution of
                        // a route. These exceptions are raised by the users code.
                        throw new RouteException(routeException.Message, routeException);
                    }
                }
                catch (Exception appDomainException)
                {
                    // This exception relates to exceptions configuring the AppDomain and we'll still notify the
                    // user, we just won't give them specific information that could reveal our infrastructure
                    // unless an IStatusCodeException was thrown, meaning it's a public exception.
                    var    statusCode          = 500;
                    var    statusMessage       = "An unexpected exception has occurred. Please contact Subroute.io regarding this error.";
                    var    statusCodeException = appDomainException as IStatusCodeException;
                    string stackTrace          = null;

                    if (statusCodeException != null)
                    {
                        statusCode    = (int)statusCodeException.StatusCode;
                        statusMessage = appDomainException.Message;

                        if (appDomainException is CodeException)
                        {
                            stackTrace = appDomainException.ToString();
                        }
                    }

                    request.CompletedOn     = DateTimeOffset.UtcNow;
                    request.StatusCode      = statusCode;
                    request.ResponsePayload = PayloadHelpers.CreateErrorPayload(statusMessage, stackTrace);
                    request.ResponseHeaders = HeaderHelpers.GetDefaultHeaders();

                    Program.RequestRepository.UpdateRequestAsync(request).Wait();

                    response.Properties["Result"]  = (int)ExecutionResult.Failed;
                    response.Properties["Message"] = appDomainException.Message;
                }
            }
            catch (Exception fatalException)
            {
                // These exceptions are absolutely fatal. We'll have to notify the waiting thread
                // via the service bus message, because we're unable to load a related request.
                response.Properties["Result"]  = (int)ExecutionResult.Fatal;
                response.Properties["Message"] = fatalException.Message;
            }
            finally
            {
                // Unload the users app domain to recover all memory used by it.
                if (sandboxDomain != null)
                {
                    TraceUtility.TraceTime("Unload AppDomain", () => AppDomain.Unload(sandboxDomain));
                }
            }
        }
 public static void TestJob_AccountOverride(
     [ServiceBusTriggerAttribute("test"),
      ServiceBusAccount("testaccount")] BrokeredMessage message)
 {
     message = new BrokeredMessage();
 }
예제 #44
0
 public void SendAsync(BrokeredMessage message)
 {
     queueClient.BeginSend(message, x => ProcessEndSend(x, message), queueClient);
 }
 public static Stream GetBodyStream(this BrokeredMessage message)
 {
     return(bodyStreamPropertyInfo.GetValue(message) as Stream);
 }
 public static void TestJob(
     [ServiceBusTriggerAttribute("test")] BrokeredMessage message)
 {
     message = new BrokeredMessage();
 }
예제 #47
0
        async Task OnMessage(BrokeredMessage message)
        {
            int current = Interlocked.Increment(ref _currentPendingDeliveryCount);

            while (current > _maxPendingDeliveryCount)
            {
                Interlocked.CompareExchange(ref _maxPendingDeliveryCount, current, _maxPendingDeliveryCount);
            }

            long deliveryCount = Interlocked.Increment(ref _deliveryCount);

            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("Receiving {0}:{1} - {2}", deliveryCount, message.MessageId, _receiveSettings.QueueDescription.Path);
            }

            var context = new ServiceBusReceiveContext(_inputAddress, message, _receiveObserver);

            try
            {
                if (_shuttingDown)
                {
                    await _completeTask.Task.ConfigureAwait(false);

                    throw new TransportException(_inputAddress, "Transport shutdown in progress, abandoning message");
                }

                await _receiveObserver.PreReceive(context).ConfigureAwait(false);

                await _receivePipe.Send(context).ConfigureAwait(false);

                await context.CompleteTask.ConfigureAwait(false);

                await message.CompleteAsync().ConfigureAwait(false);

                await _receiveObserver.PostReceive(context).ConfigureAwait(false);

                if (_log.IsDebugEnabled)
                {
                    _log.DebugFormat("Receive completed: {0}", message.MessageId);
                }
            }
            catch (Exception ex)
            {
                if (_log.IsErrorEnabled)
                {
                    _log.Error($"Received faulted: {message.MessageId}", ex);
                }

                await message.AbandonAsync().ConfigureAwait(false);

                await _receiveObserver.ReceiveFault(context, ex).ConfigureAwait(false);
            }
            finally
            {
                int pendingCount = Interlocked.Decrement(ref _currentPendingDeliveryCount);
                if (pendingCount == 0 && _shuttingDown)
                {
                    _completeTask.TrySetResult(this);
                }
            }
        }
 public static void SetBodyStream(this BrokeredMessage message, Stream stream)
 {
     bodyStreamPropertyInfo.SetValue(message, stream);
 }
        public static async Task BookFlight(BrokeredMessage message, MessageSender nextStepQueue, MessageSender compensatorQueue)
        {
            try
            {
                using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    var via = (message.Properties.ContainsKey("Via")
                        ? ((string)message.Properties["Via"] + ",")
                        : string.Empty) +
                              "bookflight";

                    if (message.Label != null &&
                        message.ContentType != null &&
                        message.Label.Equals(TravelBookingLabel, StringComparison.InvariantCultureIgnoreCase) &&
                        message.ContentType.Equals(ContentTypeApplicationJson, StringComparison.InvariantCultureIgnoreCase))
                    {
                        var     body          = message.GetBody <Stream>();
                        dynamic travelBooking = DeserializeTravelBooking(body);


                        // do we want to book a flight? No? Let's just forward the message to
                        // the next destination via transfer queue
                        if (travelBooking.flight == null)
                        {
                            await nextStepQueue.SendAsync(CreateForwardMessage(message, travelBooking, via));

                            // done with this job
                            await message.CompleteAsync();
                        }
                        else
                        {
                            lock (Console.Out)
                            {
                                Console.ForegroundColor = ConsoleColor.Cyan;
                                Console.WriteLine("Booking Flight");
                                Console.ResetColor();
                            }

                            // now we're going to simulate the work of booking a flight,
                            // which usually involves a call to a third party

                            // every 9th flight booking sadly goes wrong
                            if (message.SequenceNumber % 9 == 0)
                            {
                                await message.DeadLetterAsync(
                                    new Dictionary <string, object>
                                {
                                    { "DeadLetterReason", "TransactionError" },
                                    { "DeadLetterErrorDescription", "Failed to perform flight reservation" },
                                    { "Via", via }
                                });
                            }
                            else
                            {
                                // every operation executed in the first 3 secs of any minute
                                // tanks completely (simulates some local or external unexpected issue)
                                if (DateTime.UtcNow.Second <= 3)
                                {
                                    throw new Exception("O_o");
                                }

                                // let's pretend we booked something
                                travelBooking.flight.reservationId = "A1B2C3";

                                await nextStepQueue.SendAsync(CreateForwardMessage(message, travelBooking, via));

                                // done with this job
                                await message.CompleteAsync();
                            }
                        }
                    }
                    else
                    {
                        await message.DeadLetterAsync(
                            new Dictionary <string, object>
                        {
                            { "DeadLetterReason", "BadMessage" },
                            { "DeadLetterErrorDescription", "Unrecognized input message" },
                            { "Via", via }
                        });
                    }
                    scope.Complete();
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                await message.AbandonAsync();
            }
        }
예제 #50
0
        static void Main()
        {
            const string queueName = "QueueDeadLetterDemo";
            
            //Create a NamespaceManager instance (for management operations)
            var namespaceManager = NamespaceManager.Create();


            var queue = new QueueDescription(queueName)
                {
                    //Make sure expired messages go to the dead letter queue
                    EnableDeadLetteringOnMessageExpiration = true,
                    //Set the expiration to 1 second so all messages expire quickly (1 second is the minimum for this)
                    //DefaultMessageTimeToLive = TimeSpan.FromSeconds(1)
           
                };

            
            if (namespaceManager.QueueExists(queueName))
            {
                namespaceManager.DeleteQueue(queueName);
            }
            queue = namespaceManager.CreateQueue(queue);

            Console.WriteLine("EnableDeadLetterOnExpiration = {0}", queue.EnableDeadLetteringOnMessageExpiration);
            //Console.WriteLine("DefaultMessageTimeToLive = {0}", queue.DefaultMessageTimeToLive);
            

            //Create a MessagingFactory instance (for sending and receiving messages)
            var messageFactory = MessagingFactory.Create();
            
            //Create a queue client to send and receive messages to and from the queue
            var queueClient = messageFactory.CreateQueueClient(queueName, ReceiveMode.ReceiveAndDelete);

            //Create a simple brokered message and send it to the queue
            var sendMessage = new BrokeredMessage("Hello World!");
          
            //Set an expiration on the message
            sendMessage.TimeToLive = TimeSpan.FromSeconds(1);
            queueClient.Send(sendMessage);
            Console.WriteLine("Message sent: Body = {0}", sendMessage.GetBody<string>());
            
            Console.WriteLine();
            Console.WriteLine("Waiting to begin receiving...");
            System.Threading.Thread.Sleep(5000);
            Console.WriteLine("Receiving...");

            //Verify the message did expire
            //NOTE: Messages are NOT expired/deadlettered until a client attempts to receive messages
            var receivedMessage = queueClient.Receive(TimeSpan.FromSeconds(5));
            if (receivedMessage != null)
            {
                Console.WriteLine("Queue message received: Body = {0}", receivedMessage.GetBody<string>());
                receivedMessage.Complete();
            }
            else
            {
                Console.WriteLine("No queue message received.");
            }

            //Create a queue client for the dead letter queue
            string deadLetterQueuePath = QueueClient.FormatDeadLetterPath(queueName);
            var deadletterQueueClient = messageFactory.CreateQueueClient(deadLetterQueuePath);

            //Receive the message from the dead letter queue
            BrokeredMessage deadLetterMessage = null;

            while (deadLetterMessage == null)
            {
                deadLetterMessage = deadletterQueueClient.Receive(TimeSpan.FromSeconds(5));
                if (deadLetterMessage != null)
                {
                    Console.WriteLine("Dead letter message received: Body = {0}", deadLetterMessage.GetBody<string>());
                    deadLetterMessage.Complete();
                }
                else
                {
                    Console.WriteLine("No message received yet... waiting...");
                    System.Threading.Thread.Sleep(2000);
                    Console.WriteLine("Trying again...");
                }
            }
            //Close the connection to the Service Bus
            messageFactory.Close();

            Console.WriteLine("Press Enter to close.");
            Console.ReadLine();

        }
예제 #51
0
        async Task IMessageSessionAsyncHandler.OnMessageAsync(MessageSession session, BrokeredMessage message)
        {
            if (_receiver.IsStopping)
            {
                await WaitAndAbandonMessage(message).ConfigureAwait(false);

                return;
            }

            using (_tracker.BeginDelivery())
            {
                await _messageReceiver.Handle(message, context =>
                {
                    context.GetOrAddPayload <MessageSessionContext>(() => new BrokeredMessageSessionContext(session));
                    context.GetOrAddPayload(() => _context);
                }).ConfigureAwait(false);
            }
        }
        public static async Task CancelRentalCar(BrokeredMessage message, MessageSender nextStepQueue, MessageSender compensatorQueue)
        {
            try
            {
                var via = (message.Properties.ContainsKey("Via")
                    ? ((string)message.Properties["Via"] + ",")
                    : string.Empty) +
                          "cancelcar";

                using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    if (message.Label != null &&
                        message.ContentType != null &&
                        message.Label.Equals(TravelBookingLabel, StringComparison.InvariantCultureIgnoreCase) &&
                        message.ContentType.Equals(ContentTypeApplicationJson, StringComparison.InvariantCultureIgnoreCase))
                    {
                        var     body          = message.GetBody <Stream>();
                        dynamic travelBooking = DeserializeTravelBooking(body);

                        // do we want to book a flight? No? Let's just forward the message to
                        // the next destination via transfer queue
                        if (travelBooking.car != null &&
                            travelBooking.car.reservationId != null)
                        {
                            lock (Console.Out)
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("Cancelling Rental Car");
                                Console.ResetColor();
                            }

                            // undo the reservation (or pretend to fail)
                            if (DateTime.UtcNow.Second <= 3)
                            {
                                throw new Exception("O_o");
                            }

                            // reset the id
                            travelBooking.car.reservationId = null;

                            // forward
                            await nextStepQueue.SendAsync(CreateForwardMessage(message, travelBooking, via));
                        }
                        else
                        {
                            await nextStepQueue.SendAsync(CreateForwardMessage(message, travelBooking, via));
                        }
                        // done with this job
                        await message.CompleteAsync();
                    }
                    else
                    {
                        await message.DeadLetterAsync(
                            new Dictionary <string, object>
                        {
                            { "DeadLetterReason", "BadMessage" },
                            { "DeadLetterErrorDescription", "Unrecognized input message" },
                            { "Via", via }
                        });
                    }
                    scope.Complete();
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                await message.AbandonAsync();
            }
        }
예제 #53
0
 public abstract BrokeredMessage Execute(BrokeredMessage message);
예제 #54
0
        public MessageForm(BrokeredMessage brokeredMessage, ServiceBusHelper serviceBusHelper, WriteToLogDelegate writeToLog)
        {
            this.brokeredMessage  = brokeredMessage;
            this.serviceBusHelper = serviceBusHelper;
            this.writeToLog       = writeToLog;
            InitializeComponent();

            cboBodyType.SelectedIndex = 0;

            messagePropertyGrid.SelectedObject = brokeredMessage;

            BodyType bodyType;

            txtMessageText.Text = XmlHelper.Indent(serviceBusHelper.GetMessageText(brokeredMessage, out bodyType));

            // Initialize the DataGridView.
            bindingSource.DataSource = new BindingList <MessagePropertyInfo>(brokeredMessage.Properties.Select(p => new MessagePropertyInfo(p.Key,
                                                                                                                                            GetShortValueTypeName(p.Value),
                                                                                                                                            p.Value)).ToList());
            propertiesDataGridView.AutoGenerateColumns = false;
            propertiesDataGridView.AutoSize            = true;
            propertiesDataGridView.DataSource          = bindingSource;
            propertiesDataGridView.ForeColor           = SystemColors.WindowText;

            // Create the Name column
            var textBoxColumn = new DataGridViewTextBoxColumn
            {
                DataPropertyName = PropertyKey,
                Name             = PropertyKey,
                Width            = 138
            };

            propertiesDataGridView.Columns.Add(textBoxColumn);

            // Create the Type column
            var comboBoxColumn = new DataGridViewComboBoxColumn
            {
                DataSource       = types,
                DataPropertyName = PropertyType,
                Name             = PropertyType,
                Width            = 90,
                FlatStyle        = FlatStyle.Flat
            };

            propertiesDataGridView.Columns.Add(comboBoxColumn);

            // Create the Value column
            textBoxColumn = new DataGridViewTextBoxColumn
            {
                DataPropertyName = PropertyValue,
                Name             = PropertyValue,
                Width            = 138
            };
            propertiesDataGridView.Columns.Add(textBoxColumn);

            // Set Grid style
            propertiesDataGridView.EnableHeadersVisualStyles = false;

            // Set the selection background color for all the cells.
            propertiesDataGridView.DefaultCellStyle.SelectionBackColor = Color.FromArgb(92, 125, 150);
            propertiesDataGridView.DefaultCellStyle.SelectionForeColor = SystemColors.Window;

            // Set RowHeadersDefaultCellStyle.SelectionBackColor so that its default
            // value won't override DataGridView.DefaultCellStyle.SelectionBackColor.
            propertiesDataGridView.RowHeadersDefaultCellStyle.SelectionBackColor = Color.FromArgb(153, 180, 209);

            // Set the background color for all rows and for alternating rows.
            // The value for alternating rows overrides the value for all rows.
            propertiesDataGridView.RowsDefaultCellStyle.BackColor = SystemColors.Window;
            propertiesDataGridView.RowsDefaultCellStyle.ForeColor = SystemColors.ControlText;
            //propertiesDataGridView.AlternatingRowsDefaultCellStyle.BackColor = Color.White;
            //propertiesDataGridView.AlternatingRowsDefaultCellStyle.ForeColor = SystemColors.ControlText;

            // Set the row and column header styles.
            propertiesDataGridView.RowHeadersDefaultCellStyle.BackColor    = Color.FromArgb(215, 228, 242);
            propertiesDataGridView.RowHeadersDefaultCellStyle.ForeColor    = SystemColors.ControlText;
            propertiesDataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(215, 228, 242);
            propertiesDataGridView.ColumnHeadersDefaultCellStyle.ForeColor = SystemColors.ControlText;

            // Get Brokered Message Inspector classes
            cboSenderInspector.Items.Add(SelectBrokeredMessageInspector);
            cboSenderInspector.SelectedIndex = 0;

            if (serviceBusHelper.BrokeredMessageInspectors == null)
            {
                return;
            }
            foreach (var key in serviceBusHelper.BrokeredMessageInspectors.Keys)
            {
                cboSenderInspector.Items.Add(key);
            }
        }
 public MessageSessionAsyncHandler(ConnectionContext context, ITaskSupervisor supervisor, ISessionReceiver receiver, MessageSession session, BrokeredMessage message)
 {
     _context    = context;
     _supervisor = supervisor;
     _receiver   = receiver;
     _session    = session;
     _message    = message;
 }
예제 #56
0
 internal abstract BrokeredMessage Execute(BrokeredMessage message, RuleExecutionContext context);
예제 #57
0
 Task <long> SendEndpointContext.ScheduleSend(BrokeredMessage message, DateTime scheduleEnqueueTimeUtc)
 {
     return(_context.ScheduleSend(message, scheduleEnqueueTimeUtc));
 }
        async Task IMessageSessionAsyncHandler.OnMessageAsync(MessageSession session, BrokeredMessage message)
        {
            if (_receiver.IsShuttingDown)
            {
                await WaitAndAbandonMessage(message).ConfigureAwait(false);

                return;
            }

            var deliveryCount = _receiver.IncrementDeliveryCount();

            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("Receiving {0}:{1}({3}) - {2}", deliveryCount, message.MessageId, _receiver.QueuePath, session.SessionId);
            }

            var context = new ServiceBusReceiveContext(_receiver.InputAddress, message, _receiver.ReceiveObserver);

            context.GetOrAddPayload <MessageSessionContext>(() => new BrokeredMessageSessionContext(session));
            context.GetOrAddPayload(() => _context);

            try
            {
                await _receiver.ReceiveObserver.PreReceive(context).ConfigureAwait(false);

                await _receiver.ReceivePipe.Send(context).ConfigureAwait(false);

                await context.CompleteTask.ConfigureAwait(false);

                await message.CompleteAsync().ConfigureAwait(false);

                await _receiver.ReceiveObserver.PostReceive(context).ConfigureAwait(false);

                if (_log.IsDebugEnabled)
                {
                    _log.DebugFormat("Receive completed: {0}", message.MessageId);
                }
            }
            catch (Exception ex)
            {
                if (_log.IsErrorEnabled)
                {
                    _log.Error($"Received faulted: {message.MessageId}", ex);
                }

                await message.AbandonAsync().ConfigureAwait(false);

                await _receiver.ReceiveObserver.ReceiveFault(context, ex).ConfigureAwait(false);
            }
            finally
            {
                _receiver.DeliveryComplete();
            }
        }
예제 #59
0
 Task SendEndpointContext.Send(BrokeredMessage message)
 {
     return(_context.Send(message));
 }
예제 #60
0
 public async Task OnMessageAsync(MessageSession session, BrokeredMessage message)
 {
     try
     {
         if (message == null)
         {
             return;
         }
         if (session == null)
         {
             return;
         }
         if (configuration == null)
         {
             return;
         }
         if (configuration.MessageInspector != null)
         {
             message = configuration.MessageInspector.AfterReceiveMessage(message);
         }
         if (configuration.Logging)
         {
             var builder = new StringBuilder(string.Format(MessageSuccessfullyReceived,
                                                           string.IsNullOrWhiteSpace(message.MessageId)
                                                 ? NullValue
                                                 : message.MessageId,
                                                           string.IsNullOrWhiteSpace(message.SessionId)
                                                 ? NullValue
                                                 : message.SessionId,
                                                           string.IsNullOrWhiteSpace(message.Label)
                                                 ? NullValue
                                                 : message.Label,
                                                           message.Size));
             if (configuration.Verbose)
             {
                 configuration.ServiceBusHelper.GetMessageAndProperties(builder, message, configuration.MessageEncoder);
             }
             configuration.WriteToLog(builder.ToString(), false);
         }
         if (configuration.Tracking)
         {
             configuration.TrackMessage(message.Clone());
         }
         configuration.UpdateStatistics(1, configuration.GetElapsedTime(), message.Size);
         if (configuration.ReceiveMode == ReceiveMode.PeekLock && !configuration.AutoComplete)
         {
             await message.CompleteAsync();
         }
         if (!SessionDictionary.ContainsKey(message.SessionId))
         {
             SessionDictionary.Add(message.SessionId, 1);
         }
         else
         {
             SessionDictionary[message.SessionId]++;
         }
     }
     catch (Exception ex)
     {
         HandleException(ex);
     }
 }