public void Order(OrderItem orderItem)
        {
            // Get the BrokeredMessageProperty from OperationContext
            var incomingProperties           = OperationContext.Current.IncomingMessageProperties;
            BrokeredMessageProperty property = (BrokeredMessageProperty)incomingProperties[BrokeredMessageProperty.Name];

            // Get the current ServiceBus SessionId
            if (this.sessionId == string.Empty)
            {
                this.sessionId = property.SessionId;
            }

            // Print message
            if (this.messageCounter == 0)
            {
                SampleManager.OutputMessageInfo("Process Order", "Started processing order.", this.sessionId);
            }

            //Complete the Message
            ReceiveContext receiveContext;

            if (ReceiveContext.TryGet(incomingProperties, out receiveContext))
            {
                receiveContext.Complete(TimeSpan.FromSeconds(10.0d));
                this.orderItems.Add(orderItem);
                this.messageCounter++;
            }
            else
            {
                throw new InvalidOperationException("Receiver is in peek lock mode but receive context is not available!");
            }
        }
 public static void CreateIfRequired(ImmutableDispatchRuntime dispatchRuntime, ref MessageRpc messageRpc)
 {
     if (messageRpc.Operation.ReceiveContextAcknowledgementMode != ReceiveContextAcknowledgementMode.ManualAcknowledgement)
     {
         ReceiveContext property = null;
         if (!ReceiveContext.TryGet(messageRpc.Request, out property))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxReceiveContextPropertyMissing", new object[] { typeof(ReceiveContext).Name })));
         }
         messageRpc.Request.Properties.Remove(ReceiveContext.Name);
         if ((messageRpc.Operation.ReceiveContextAcknowledgementMode == ReceiveContextAcknowledgementMode.AutoAcknowledgeOnReceive) && !messageRpc.Operation.TransactionRequired)
         {
             AcknowledgementCompleteCallbackState state = new AcknowledgementCompleteCallbackState {
                 DispatchRuntime = dispatchRuntime,
                 Rpc             = messageRpc
             };
             IAsyncResult result = new AcknowledgementCompleteAsyncResult(property, TimeSpan.MaxValue, ref messageRpc, null, handleEndComplete, state);
             if (result.CompletedSynchronously)
             {
                 AcknowledgementCompleteAsyncResult.End(result);
             }
         }
         else
         {
             messageRpc.ReceiveContext = new ReceiveContextRPCFacet(property);
         }
     }
 }
        public async Task SubmitSequenceItemAsync(SequenceItem sequenceItem)
        {
            // Get the BrokeredMessageProperty from OperationContext
            var incomingProperties = OperationContext.Current.IncomingMessageProperties;
            var property           = (BrokeredMessageProperty)incomingProperties[BrokeredMessageProperty.Name];

            // Get the current ServiceBus SessionId
            if (this.sessionId == string.Empty)
            {
                this.sessionId = property.SessionId;
            }

            // Print message
            if (this.messageCounter == 0)
            {
                Console.WriteLine("{0}: {1} - ContextId {2}.", "Process Sequence", "Started processing sequence.", this.sessionId);
            }

            //Complete the Message
            ReceiveContext receiveContext;

            if (ReceiveContext.TryGet(incomingProperties, out receiveContext))
            {
                receiveContext.Complete(TimeSpan.FromSeconds(10.0d));
                this.sequenceItems.Add(sequenceItem);
                this.messageCounter++;
            }
            else
            {
                throw new InvalidOperationException("Receiver is in peek lock mode but receive context is not available!");
            }
        }
Exemple #4
0
        public override void PrepareMessageForDispatch(Message message)
        {
            ReceiveContext context = null;

            if (ReceiveContext.TryGet(message, out context) && !(context is ReceiveContextBusyCountWrapper))
            {
                ReceiveContextBusyCountWrapper wrapper = new ReceiveContextBusyCountWrapper(context);
                message.Properties.Remove(ReceiveContext.Name);
                message.Properties.Add(ReceiveContext.Name, wrapper);
            }
        }
        public override IAspNetMessageProperty PrepareMessageForDispatch(Message message)
        {
            ReceiveContext property = null;

            if (ReceiveContext.TryGet(message, out property) && !(property is ReceiveContextBusyCountWrapper))
            {
                ReceiveContextBusyCountWrapper wrapper = new ReceiveContextBusyCountWrapper(property);
                message.Properties.Remove(ReceiveContext.Name);
                message.Properties.Add(ReceiveContext.Name, wrapper);
            }
            return(this.GetHostingProperty(message, true));
        }
        public MessageRpc(Message message, OperationContext operationContext, bool impersonationRequired)
        {
            Fx.Assert(message != null, "message cannot be null");
            Fx.Assert(operationContext != null, "operationContext cannot be null");

            this.originalMessage  = message;
            this.OperationContext = operationContext;

            if (Fx.Trace.IsEtwProviderEnabled)
            {
                this.eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
            }

            //passing in true causes this to return null if the thread is not impersonating.
            this.windowsIdentity = WindowsIdentity.GetCurrent(true);
            if (impersonationRequired && !AspNetEnvironment.Current.AspNetCompatibilityEnabled)
            {
                if (this.windowsIdentity == null || this.windowsIdentity.ImpersonationLevel != TokenImpersonationLevel.Impersonation)
                {
                    //Temporarily revert impersonation to process token to throw an exception
                    IDisposable autoRevert = null;
                    try
                    {
                        try { }
                        finally
                        {
                            autoRevert = WindowsIdentity.Impersonate(IntPtr.Zero);
                        }

                        Win32Exception errorDetail = new Win32Exception(ERROR_BAD_IMPERSONATION_LEVEL);
                        throw FxTrace.Exception.AsError(new SecurityNegotiationException(errorDetail.Message));
                    }
                    finally
                    {
                        if (autoRevert != null)
                        {
                            autoRevert.Dispose();
                        }
                    }
                }
            }

            ReceiveContext.TryGet(message, out this.receiveContext);

            this.transaction = Transaction.Current;
            if (this.transaction == null)
            {
                this.transaction = TransactionMessageProperty.TryGetTransaction(message);
            }
        }
        //Called from ProcessMessage1
        //ManualAcknowledgementMode : No-Op.
        //Non-transacted V1 Operation : Remove RC; RC.Complete;(Will pause RPC if truly async)
        //Else : Create and Attach RCFacet to MessageRPC.
        public static void CreateIfRequired(ImmutableDispatchRuntime dispatchRuntime, ref MessageRpc messageRpc)
        {
            if (messageRpc.Operation.ReceiveContextAcknowledgementMode == ReceiveContextAcknowledgementMode.ManualAcknowledgement)
            {
                //Manual mode, user owns the acknowledgement.
                return;
            }

            //Retrieve RC from request and ensure it is removed from Message.
            ReceiveContext receiveContext = null;

            if (!ReceiveContext.TryGet(messageRpc.Request, out receiveContext))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new InvalidOperationException(
                              SR.GetString(SR.SFxReceiveContextPropertyMissing,
                                           typeof(ReceiveContext).Name)));
            }
            messageRpc.Request.Properties.Remove(ReceiveContext.Name);

            if (messageRpc.Operation.ReceiveContextAcknowledgementMode == ReceiveContextAcknowledgementMode.AutoAcknowledgeOnReceive)
            {
                if (!messageRpc.Operation.TransactionRequired)
                {
                    //Attempt to complete the ReceiveContext.
                    //Async Result Ensures RPC is paused if it goes ASYNC.
                    IAsyncResult result = new AcknowledgementCompleteAsyncResult(
                        receiveContext,
                        TimeSpan.MaxValue,
                        ref messageRpc,
                        null,
                        handleEndComplete,
                        new AcknowledgementCompleteCallbackState
                    {
                        DispatchRuntime = dispatchRuntime,
                        Rpc             = messageRpc
                    });

                    if (result.CompletedSynchronously)
                    {
                        AcknowledgementCompleteAsyncResult.End(result);
                    }
                    return;
                }
            }
            //We have to create a Facet for acknowledgement at later stage.
            messageRpc.ReceiveContext = new ReceiveContextRPCFacet(receiveContext);
        }
            public ControlOperationAsyncResult(ControlOperationInvoker invoker, object[] inputs, IInvokeReceivedNotification notification, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state)
            {
                this.instanceKey      = InstanceKey.InvalidKey;
                this.additionalKeys   = emptyKeyCollection;
                this.outputs          = ControlOperationInvoker.emptyObjectArray;
                this.invoker          = invoker;
                this.inputs           = inputs;
                this.timeoutHelper    = new TimeoutHelper(timeout);
                this.transaction      = Transaction.Current;
                this.operationContext = OperationContext.Current;
                base.OnCompleting     = onCompleting;
                bool flag  = false;
                bool flag2 = false;

                try
                {
                    if (notification != null)
                    {
                        if (this.operationContext.SessionId == null)
                        {
                            notification.NotifyInvokeReceived();
                        }
                        else
                        {
                            this.notification = notification;
                        }
                    }
                    if (invoker.BufferedReceiveManager != null)
                    {
                        ReceiveContext.TryGet(this.operationContext.IncomingMessageProperties, out this.receiveContext);
                    }
                    flag  = this.Process();
                    flag2 = true;
                }
                finally
                {
                    if (!flag2)
                    {
                        Finally(this, null);
                    }
                }
                if (flag)
                {
                    base.Complete(true);
                }
            }
Exemple #9
0
        public void ProcessExplicit(string data)
        {
            // Print message
            Console.WriteLine("Receive: Message [{0}].", data);

            //Complete the Message
            ReceiveContext receiveContext;

            if (ReceiveContext.TryGet(OperationContext.Current.IncomingMessageProperties, out receiveContext))
            {
                receiveContext.Complete(TimeSpan.FromSeconds(10.0d));
            }
            else
            {
                throw new InvalidOperationException("Receiver is in peek lock mode but receive context is not available!");
            }
        }
        private WorkflowOperationContext(object[] inputs, System.ServiceModel.OperationContext operationContext, string operationName, bool performanceCountersEnabled, bool propagateActivity, Transaction currentTransaction, WorkflowServiceInstance workflowInstance, IInvokeReceivedNotification notification, WorkflowOperationBehavior behavior, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state)
        {
            this.inputs                     = inputs;
            this.operationName              = operationName;
            this.OperationContext           = operationContext;
            this.CurrentTransaction         = currentTransaction;
            this.performanceCountersEnabled = performanceCountersEnabled;
            this.propagateActivity          = propagateActivity;
            this.timeoutHelper              = new TimeoutHelper(timeout);
            this.workflowInstance           = workflowInstance;
            this.thisLock                   = new object();
            this.notification               = notification;
            base.OnCompleting               = onCompleting;
            this.bookmark                   = behavior.OnResolveBookmark(this, out this.bookmarkScope, out this.bookmarkValue);
            bool flag = false;

            try
            {
                if (TraceUtility.MessageFlowTracingOnly)
                {
                    this.e2eActivityId         = TraceUtility.GetReceivedActivityId(this.OperationContext);
                    DiagnosticTrace.ActivityId = this.e2eActivityId;
                }
                if (this.workflowInstance.BufferedReceiveManager != null)
                {
                    ReceiveContext.TryGet(this.OperationContext.IncomingMessageProperties, out this.receiveContext);
                    this.OperationContext.IncomingMessageProperties.Remove(ReceiveContext.Name);
                }
                flag = this.ProcessRequest();
            }
            catch (Exception exception)
            {
                if (Fx.IsFatal(exception))
                {
                    throw;
                }
                base.OnCompleting(this, exception);
                throw;
            }
            if (flag)
            {
                base.Complete(true);
            }
        }
        public void Ping(PingData pingData)
        {
            // Get the message properties
            var incomingProperties           = OperationContext.Current.IncomingMessageProperties;
            BrokeredMessageProperty property = (BrokeredMessageProperty)incomingProperties[BrokeredMessageProperty.Name];

            // Print message
            SampleManager.OutputMessageInfo("Receive", pingData);

            //Complete the Message
            ReceiveContext receiveContext;

            if (ReceiveContext.TryGet(incomingProperties, out receiveContext))
            {
                receiveContext.Complete(TimeSpan.FromSeconds(10.0d));
            }
            else
            {
                throw new InvalidOperationException("Receiver is in peek lock mode but receive context is not available!");
            }
        }
Exemple #12
0
        public void CalculateProduct(int firstNumber, int secondNumber)
        {
            ReceiveContext receiveContext;

            if (!ReceiveContext.TryGet(OperationContext.Current.IncomingMessageProperties, out receiveContext))
            {
                Console.WriteLine("ReceiveContext not installed/found on this machine.");
                return;
            }

            // Pseudo-randomly decide whether to process the message based on its content.
            if ((firstNumber * secondNumber) % 2 == (receiveCount % 2))
            {
                receiveContext.Complete(TimeSpan.MaxValue);
                Console.WriteLine("{0} x {1} = {2}", firstNumber, secondNumber, firstNumber * secondNumber);
            }
            else
            {
                receiveContext.Abandon(TimeSpan.MaxValue);
                Console.WriteLine("{0} & {1} not processed", firstNumber, secondNumber);
            }
            receiveCount++;
        }
        public void ProcessData(int employeeId)
        {
            // There is not much processing logic here...
            // We are assuming that the organization has 50 employees with sequential Employee Ids
            // If the employeeId  > 50, we are sending an Http Status code of 500 (Internal Server Error) back to the client
            // else, we assume that the processing is successful and send an Http Status code of 200 (Successfull)
            ReceiveContext receiveContext;

            if (!ReceiveContext.TryGet(OperationContext.Current.IncomingMessageProperties, out receiveContext))
            {
                Console.WriteLine("ReceiveContext property was not found in the message...");
                return;
            }

            if (employeeId > 50)
            {
                // Abandon
                receiveContext.Abandon(TimeSpan.MaxValue);
            }
            else
            {
                // Complete in Transaction block.
                CommittableTransaction committableTransaction = new CommittableTransaction();
                Transaction.Current = committableTransaction;
                try
                {
                    receiveContext.Complete(TimeSpan.MaxValue);
                    committableTransaction.Commit();
                }
                catch
                {
                    committableTransaction.Rollback();
                    // If the transaction was not completed we call Abandon explicitly which sends an Http 500 to the client
                    receiveContext.Abandon(TimeSpan.MaxValue);
                }
            }
        }
Exemple #14
0
        WorkflowOperationContext(object[] inputs, OperationContext operationContext, string operationName,
                                 bool performanceCountersEnabled, bool propagateActivity, Transaction currentTransaction,
                                 WorkflowServiceInstance workflowInstance, IInvokeReceivedNotification notification, WorkflowOperationBehavior behavior, ServiceEndpoint endpoint,
                                 TimeSpan timeout, AsyncCallback callback, object state)
            : base(callback, state)
        {
            this.inputs                     = inputs;
            this.operationName              = operationName;
            this.OperationContext           = operationContext;
            this.ServiceEndpoint            = endpoint;
            this.CurrentTransaction         = currentTransaction;
            this.performanceCountersEnabled = performanceCountersEnabled;
            this.propagateActivity          = propagateActivity;
            this.timeoutHelper              = new TimeoutHelper(timeout);
            this.workflowInstance           = workflowInstance;
            this.thisLock                   = new object();
            this.notification               = notification;
            this.OnCompleting               = onCompleting;

            // Resolve bookmark
            Fx.Assert(behavior != null, "behavior must not be null!");
            this.bookmark = behavior.OnResolveBookmark(this, out this.bookmarkScope, out this.bookmarkValue);
            Fx.Assert(this.bookmark != null, "bookmark must not be null!");

            bool completeSelf = false;

            try
            {
                // set activity ID on the executing thread (
                if (TraceUtility.MessageFlowTracingOnly)
                {
                    this.e2eActivityId             = TraceUtility.GetReceivedActivityId(this.OperationContext);
                    DiagnosticTraceBase.ActivityId = this.e2eActivityId;
                }

                if (Fx.Trace.IsEtwProviderEnabled)
                {
                    this.eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(this.OperationContext.IncomingMessage);
                }

                // Take ownership of the ReceiveContext when buffering is enabled by removing the property
                if (this.workflowInstance.BufferedReceiveManager != null)
                {
                    if (!ReceiveContext.TryGet(this.OperationContext.IncomingMessageProperties, out this.receiveContext))
                    {
                        Fx.Assert("ReceiveContext expected when BufferedReceives are enabled");
                    }

                    this.OperationContext.IncomingMessageProperties.Remove(ReceiveContext.Name);
                }

                completeSelf = ProcessRequest();
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                // Failing synchronously is one case where AsyncResult won't handle calling OnCompleting
                OnCompleting(this, e);
                throw;
            }

            if (completeSelf)
            {
                base.Complete(true);
            }
        }
Exemple #15
0
        static void ReceiveSessionMessages()
        {
            // Read messages from queue until queue is empty:
            Console.WriteLine("Reading messages from queue {0}...", SampleManager.SessionQueueName);
            Console.WriteLine("Receiver Type: PeekLock");

            // Create listener and channel using custom binding
            CustomBinding   customBinding = new CustomBinding("customBinding");
            EndpointAddress address       = SampleManager.GetEndpointAddress(SampleManager.SessionQueueName, serviceBusNamespace);
            TransportClientEndpointBehavior securityBehavior = new TransportClientEndpointBehavior();

            securityBehavior.TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(serviceBusKeyName, serviceBusKey);
            customBinding.GetProperty <IReceiveContextSettings>(new BindingParameterCollection()).Enabled = true;

            IChannelListener <IInputSessionChannel> inputSessionChannelListener = null;

            try
            {
                inputSessionChannelListener = customBinding.BuildChannelListener <IInputSessionChannel>(address.Uri, securityBehavior);
                inputSessionChannelListener.Open();

                while (true)
                {
                    IInputSessionChannel inputSessionChannel = null;
                    try
                    {
                        // Create a new session channel for every new session available. If no more sessions available,
                        // then the operation throws a TimeoutException.
                        inputSessionChannel = inputSessionChannelListener.AcceptChannel(acceptSessionReceiverTimeout);
                        inputSessionChannel.Open();

                        // TryReceive operation returns true if message is available otherwise it returns false.
                        Message receivedMessage;
                        while (inputSessionChannel.TryReceive(receiveSessionMessageTimeout, out receivedMessage))
                        {
                            if (receivedMessage != null)
                            {
                                SampleManager.OutputMessageInfo("Receive", receivedMessage);

                                // Since the message body contains a serialized string one can access it like this:
                                //string soapBody = receivedMessage.GetBody<string>();

                                // Since the binding has ReceiveContext enabled, a manual complete operation is mandatory
                                // if the message was processed successfully.
                                ReceiveContext rc;
                                if (ReceiveContext.TryGet(receivedMessage, out rc))
                                {
                                    rc.Complete(TimeSpan.FromSeconds(10.0d));
                                }
                                else
                                {
                                    throw new InvalidOperationException("Receiver is in peek lock mode but receive context is not available!");
                                }
                            }
                            else
                            {
                                // This IInputSessionChannel doesn't have any more messages
                                break;
                            }
                        }

                        // Close session channel
                        inputSessionChannel.Close();
                        inputSessionChannel = null;
                    }
                    catch (TimeoutException)
                    {
                        break;
                    }
                    finally
                    {
                        if (inputSessionChannel != null)
                        {
                            inputSessionChannel.Abort();
                        }
                    }
                }

                // Close channel listener
                inputSessionChannelListener.Close();
            }
            catch (Exception)
            {
                if (inputSessionChannelListener != null)
                {
                    inputSessionChannelListener.Abort();
                }
                throw;
            }
        }