protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            if (executionContext == null)
            {
                throw new ArgumentNullException("executionContext");
            }
            if (this.Fault == null)
            {
                throw new InvalidOperationException(SR.GetString(CultureInfo.CurrentCulture, "Error_PropertyNotSet", new object[] { FaultProperty.Name }));
            }
            WorkflowQueuingService service = executionContext.GetService <WorkflowQueuingService>();

            base.RaiseEvent(SendingFaultEvent, this, EventArgs.Empty);
            WebServiceInputActivity activityByName = base.GetActivityByName(this.InputActivityName) as WebServiceInputActivity;
            IComparable             queueName      = new EventQueueName(activityByName.InterfaceType, activityByName.MethodName, activityByName.QualifiedName);
            IMethodResponseMessage  message        = null;
            WorkflowQueue           workflowQueue  = service.GetWorkflowQueue(queueName);

            if (workflowQueue.Count != 0)
            {
                message = workflowQueue.Dequeue() as IMethodResponseMessage;
            }
            message.SendException(this.Fault);
            return(ActivityExecutionStatus.Closed);
        }
Exemplo n.º 2
0
        private bool ProcessQueueItem(ActivityExecutionContext context)
        {
            WorkflowQueuingService qService = context.GetService <WorkflowQueuingService>();

            if (!qService.Exists(this.QueueName))
            {
                return(false);
            }

            WorkflowQueue queue = qService.GetWorkflowQueue(this.QueueName);

            // If the queue has messages, then process the first one
            if (queue.Count == 0)
            {
                return(false);
            }

            FileWatcherEventArgs e = (FileWatcherEventArgs)queue.Dequeue();

            // Raise the FileSystemEvent
            base.RaiseGenericEvent <FileWatcherEventArgs>(FileSystemEvent.FileWatcherEventHandlerEvent, this, e);

            DoUnsubscribe(context, this);
            DeleteQueue(context);
            return(true);
        }
Exemplo n.º 3
0
        protected override void Initialize(IServiceProvider provider)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }
            if (this.Parent != null)
            {
                throw new InvalidOperationException("This is a root Activity");
            }

            _queueName = new EventQueueName(this.Type, this.MethodName);
            WorkflowQueuingService queueService = (WorkflowQueuingService)provider.GetService(typeof(WorkflowQueuingService));

            if (queueService != null)
            {
                WorkflowQueue queue = null;
                if (queueService.Exists(_queueName))
                {
                    queue         = queueService.GetWorkflowQueue(_queueName);
                    queue.Enabled = true;
                }
                else
                {
                    queue = queueService.CreateWorkflowQueue(_queueName, true);
                }
            }
            base.Initialize(provider);
        }
        internal override void Execute(ActivityExecutionContext context)
        {
            base.Execute(context);
            StateActivity         rootState = StateMachineHelpers.GetRootState(base.State);
            Queue <StateActivity> queue     = new Queue <StateActivity>();

            queue.Enqueue(rootState);
            while (queue.Count > 0)
            {
                foreach (Activity activity3 in queue.Dequeue().EnabledActivities)
                {
                    EventDrivenActivity eventDriven = activity3 as EventDrivenActivity;
                    if (eventDriven != null)
                    {
                        IComparable queueName = StateMachineHelpers.GetEventActivity(eventDriven).QueueName;
                        if (queueName != null)
                        {
                            WorkflowQueue workflowQueue = StateMachineSubscriptionManager.GetWorkflowQueue(context, queueName);
                            if (workflowQueue != null)
                            {
                                workflowQueue.Enabled = base.SubscriptionManager.Subscriptions.ContainsKey(queueName);
                            }
                        }
                    }
                    else
                    {
                        StateActivity item = activity3 as StateActivity;
                        if (item != null)
                        {
                            queue.Enqueue(item);
                        }
                    }
                }
            }
        }
        internal void Unsubscribe(ActivityExecutionContext context)
        {
            WorkflowQueuingService workflowQueuingService = context.GetService <WorkflowQueuingService>();
            WorkflowQueue          workflowQueue          = workflowQueuingService.GetWorkflowQueue(StateMachineWorkflowActivity.SetStateQueueName);

            workflowQueue.UnregisterForQueueItemAvailable(this);
        }
Exemplo n.º 6
0
        void q_QueueItemAvailable(object sender, QueueEventArgs e)
        {
            ActivityExecutionContext aec = sender as ActivityExecutionContext;

            if (aec != null)
            {
                WorkflowQueuingService qs = aec.GetService <WorkflowQueuingService>();

                WorkflowQueue q = qs.GetWorkflowQueue(e.QueueName);
                //get the outparameters from the workflow
                object o = q.Dequeue();
                //delete the queue
                qs.DeleteWorkflowQueue(e.QueueName);
                Dictionary <string, object> outparams = o as Dictionary <string, object>;
                if (outparams != null)
                {
                    foreach (KeyValuePair <string, object> item in outparams)
                    {
                        if (this.Parameters.Contains(item.Key))
                        {
                            //modify the value
                            this.Parameters[item.Key].SetValue(WorkflowParameterBinding.ValueProperty, item.Value);
                        }
                    }
                }
                aec.CloseActivity();
            }
        }
Exemplo n.º 7
0
        public async Task HandleWorkflowsUntilPunctuation(Immutable <IndexWorkflowRecordNode> workflowRecords)
        {
            try
            {
                var workflows = workflowRecords.Value;
                while (workflows != null)
                {
                    Dictionary <IIndexableGrain, HashSet <Guid> > grainsToActiveWorkflows = null;
                    if (IsFaultTolerant)
                    {
                        grainsToActiveWorkflows = await GetActiveWorkflowsListsFromGrains(workflows);
                    }
                    var updatesToIndexes = CreateAMapForUpdatesToIndexes();
                    PopulateUpdatesToIndexes(workflows, updatesToIndexes, grainsToActiveWorkflows);
                    await Task.WhenAll(PrepareIndexUpdateTasks(updatesToIndexes));

                    if (IsFaultTolerant)
                    {
                        Task.WhenAll(RemoveFromActiveWorkflowsInGrainsTasks(grainsToActiveWorkflows)).Ignore();
                    }
                    workflows = (await WorkflowQueue.GiveMoreWorkflowsOrSetAsIdle()).Value;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemplo n.º 8
0
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext aec)
        {
            //get the services needed
            //custom service to run the workflow
            CallWorkflowService ws = aec.GetService <CallWorkflowService>();

            //Queuing service to setup the queue so the service can "callback"
            WorkflowQueuingService qs = aec.GetService <WorkflowQueuingService>();
            //create the queue the service can call back on when the child workflow is done
            //you might want the queuename to be something different
            string        qn = String.Format("{0}:{1}:{2}", this.WorkflowInstanceId.ToString(), Type.Name, this.Name);
            WorkflowQueue q  = qs.CreateWorkflowQueue(qn, false);

            q.QueueItemAvailable += new EventHandler <QueueEventArgs>(q_QueueItemAvailable);
            //copy the params to a new collection
            Dictionary <string, object> inparams = new Dictionary <string, object>();

            foreach (WorkflowParameterBinding bp in this.Parameters)
            {
                PropertyInfo pi = Type.GetProperty(bp.ParameterName);
                if (pi.CanWrite)
                {
                    inparams.Add(bp.ParameterName, bp.Value);
                }
            }
            //ask the service to start the workflow
            ws.StartWorkflow(Type, inparams, this.WorkflowInstanceId, qn);
            return(ActivityExecutionStatus.Executing);
        }
Exemplo n.º 9
0
        private static void CreateFollowerEntry(IServiceProvider context, Type interfaceType, string followermethodName, string initializermethodName)
        {
            if (!CorrelationResolver.IsInitializingMember(interfaceType, initializermethodName, null))
            {
                return;
            }

            WorkflowQueuingService queueSvcs = (WorkflowQueuingService)context.GetService(typeof(WorkflowQueuingService));
            FollowerQueueCreator   follower  = new FollowerQueueCreator(followermethodName);

            WorkflowActivityTrace.Activity.TraceEvent(TraceEventType.Information, 0, "Creating follower {0} on initializer {1}", interfaceType.Name + followermethodName, interfaceType.Name + initializermethodName);

            ICollection <CorrelationProperty> corrValues = CorrelationResolver.ResolveCorrelationValues(interfaceType, initializermethodName, null, true);
            EventQueueName key = new EventQueueName(interfaceType, initializermethodName, corrValues);
            WorkflowQueue  initializerQueue = null;

            if (queueSvcs.Exists(key))
            {
                initializerQueue = queueSvcs.GetWorkflowQueue(key);
            }
            else
            {
                // traversed follower before initializer
                initializerQueue         = queueSvcs.CreateWorkflowQueue(key, true);
                initializerQueue.Enabled = false;
            }

            initializerQueue.RegisterForQueueItemArrived(follower);
        }
Exemplo n.º 10
0
            public async Task RunAsync(TimeSpan delay)
            {
                var delayStub = Workflow.NewLocalActivityStub <ISignalBlastDelayActivity, SignalBlastDelayActivity>();

                signalQueue = await Workflow.NewQueueAsync <SignalRequest <string> >(int.MaxValue);

                // Process messages until we get one that passes NULL.

                while (true)
                {
                    var signalRequest = await signalQueue.DequeueAsync();

                    var name  = signalRequest.Arg <string>("name");
                    var reply = (string)null;

                    if (name != null)
                    {
                        reply = $"Hello {name}!";

                        if (delay > TimeSpan.Zero)
                        {
                            await delayStub.DelayAsync(delay);
                        }
                    }

                    await signalRequest.ReplyAsync(reply);

                    if (name == null)
                    {
                        break;
                    }
                }
            }
        /// <summary>
        /// Unsubscribes to item available.
        /// </summary>
        /// <param name="ctx">The CTX.</param>
        protected void UnsubscribeFromQueueItemAvailable(ActivityExecutionContext ctx)
        {
            WorkflowQueue queue = GetQueue(ctx);

            queue.UnregisterForQueueItemAvailable(this);

            queue.QueuingService.DeleteWorkflowQueue(this.Name);
        }
Exemplo n.º 12
0
        public async Task <string> HelloAsync()
        {
            signalQueue = await Workflow.NewQueueAsync <string>();

            var name = await signalQueue.DequeueAsync();

            return($"Hello {name}!");
        }
Exemplo n.º 13
0
        protected override void Initialize(IServiceProvider provider)
        {
            ThreadMonitor.WriteToConsole(Thread.CurrentThread, "WaitForMessageActivity", "WaitForMessageActivity: Processed Initialization");

            WorkflowQueuingService queuingService = (WorkflowQueuingService)provider.GetService(typeof(WorkflowQueuingService));

            this.workflowQueue = queuingService.CreateWorkflowQueue("WaitForMessageActivityQueue", false);
            this.workflowQueue.QueueItemAvailable += this.HandleExternalEvent;
        }
Exemplo n.º 14
0
        void IEventActivity.Unsubscribe(ActivityExecutionContext parentContext, IActivityEventListener <QueueEventArgs> parentEventHandler)
        {
            WorkflowQueuingService queueService = parentContext.GetService <WorkflowQueuingService>();

            if (_queueName != null && queueService != null && parentEventHandler != null)
            {
                WorkflowQueue queue = queueService.GetWorkflowQueue(_queueName);
                queue.UnregisterForQueueItemAvailable(parentEventHandler);
            }
        }
Exemplo n.º 15
0
        private Boolean DoSubscribe(ActivityExecutionContext context, IActivityEventListener <QueueEventArgs> listener)
        {
            WorkflowQueue queue = CreateQueue(context);

            queue.RegisterForQueueItemAvailable(listener);

            FileWatcherService fileService = context.GetService <FileWatcherService>();

            this.subscriptionId = fileService.RegisterListener(this.QueueName, this.Path, this.Filter, this.NotifyFilter, this.IncludeSubdirectories);
            return(subscriptionId != Guid.Empty);
        }
Exemplo n.º 16
0
            public async Task RunResultAsync()
            {
                resultQueue = await Workflow.NewQueueAsync <SignalRequest <string> >();

                var signalRequest = await resultQueue.DequeueAsync();

                SignalProcessed = true;
                Name            = signalRequest.Arg <string>("name");

                await signalRequest.ReplyAsync($"Hello {Name}!");
            }
Exemplo n.º 17
0
            public async Task RunVoidAsync()
            {
                voidQueue = await Workflow.NewQueueAsync <SignalRequest>();

                var signalRequest = await voidQueue.DequeueAsync();

                SignalProcessed = true;
                Name            = signalRequest.Arg <string>("name");

                await signalRequest.ReplyAsync();
            }
Exemplo n.º 18
0
        internal static WorkflowQueue GetWorkflowQueue(ActivityExecutionContext context, IComparable queueName)
        {
            WorkflowQueuingService workflowQueuingService = context.GetService <WorkflowQueuingService>();

            if (workflowQueuingService.Exists(queueName))
            {
                WorkflowQueue workflowQueue = workflowQueuingService.GetWorkflowQueue(queueName);
                return(workflowQueue);
            }
            return(null);
        }
        private void CreateSubscription(Guid instanceId, ActivityExecutionContext context, ICollection <CorrelationProperty> correlationValues)
        {
            WorkflowQueuingService queueSvcs = context.GetService <WorkflowQueuingService>();
            EventQueueName         queueId   = new EventQueueName(this.interfaceType, this.followerOperation, correlationValues);

            WorkflowQueue workflowQueue = null;

            if (!queueSvcs.Exists(queueId))
            {
                WorkflowActivityTrace.Activity.TraceEvent(TraceEventType.Information, 0, "CorrelationTokenInvalidatedHandler: creating q {0} ", queueId.GetHashCode());
                workflowQueue = queueSvcs.CreateWorkflowQueue(queueId, true);
                queueCreator  = true;
            }
            else
            {
                workflowQueue = queueSvcs.GetWorkflowQueue(queueId);
            }

            if (this.eventHandler != null)
            {
                workflowQueue.RegisterForQueueItemAvailable(this.eventHandler);
            }

            WorkflowSubscriptionService subscriptionService = (WorkflowSubscriptionService)context.GetService(typeof(WorkflowSubscriptionService));

            MessageEventSubscription subscription = new MessageEventSubscription(queueId, instanceId);

            this.queueName             = queueId;
            this.subscriptionId        = subscription.SubscriptionId;
            subscription.InterfaceType = this.interfaceType;
            subscription.MethodName    = this.followerOperation;

            this.interfaceType     = null;
            this.followerOperation = null;

            if (correlationValues != null)
            {
                foreach (CorrelationProperty property in correlationValues)
                {
                    subscription.CorrelationProperties.Add(property);
                }
            }

            if (this.eventHandler != null)
            {
                return;
            }

            if (subscriptionService == null)
            {
                return;
            }
            subscriptionService.CreateSubscription(subscription);
        }
Exemplo n.º 20
0
        public virtual WorkflowBase GetNextWorkflow()
        {
            if (WorkflowQueue.Count == 0)
            {
                return(null);
            }
            var wftype = WorkflowQueue.Dequeue();

            var wf = CreateInstance <WorkflowBase>(wftype);

            return(wf);
        }
        internal static void ChangeEventDrivenQueueState(ActivityExecutionContext context, EventDrivenActivity eventDriven, bool enabled)
        {
            IComparable queueName = GetQueueName(StateMachineHelpers.GetEventActivity(eventDriven));

            if (queueName != null)
            {
                WorkflowQueue workflowQueue = GetWorkflowQueue(context, queueName);
                if (workflowQueue != null)
                {
                    workflowQueue.Enabled = enabled;
                }
            }
        }
        /// <summary>
        /// Queues the item available.
        /// </summary>
        /// <param name="ctx">The CTX.</param>
        protected ActivityExecutionStatus ProcessQueueElement(ActivityExecutionContext ctx)
        {
            WorkflowQueue queue = GetQueue(ctx);

            AssignmentEntity assignment = queue.Dequeue() as AssignmentEntity;

            if (assignment != null)
            {
                return(CheckAssignmentCompletion(assignment));
            }

            return(ActivityExecutionStatus.Executing);
        }
        /// <summary>
        /// Executes the activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        /// <returns>The <see cref="ActivityExecutionStatus"/> object.</returns>
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            Logger.Instance.WriteMethodEntry(EventIdentifier.AsyncUpdateResourceExecute);

            try
            {
                // Ideally we would set CallContext in OnActivityExecutionContextLoad instead here in Execute
                // as OnActivityExecutionContextLoad gets called on each hydration and rehydration of the workflow instance
                // but looks like it's invoked on a different thread context than the rest of the workflow instance execution.
                // To minimize the loss of the CallContext on rehydration, we'll set it in the Execute of every WAL child activities.
                // It will still get lost (momentarily) when the workflow is persisted in the middle of the execution of a replicator activity, for example.
                Logger.SetContextItem(this, this.WorkflowInstanceId);

                SequentialWorkflow parentWorkflow;
                if (!SequentialWorkflow.TryGetContainingWorkflow(this, out parentWorkflow))
                {
                    throw Logger.Instance.ReportError(new InvalidOperationException(Messages.UnableToGetParentWorkflowError));
                }

                // Create the workflow program queue so we can facilitate asynchronous
                // submission of requests
                WorkflowQueue queue = CreateWorkflowProgramQueue(this.queuingService, this);

                object[] args = new object[] { this.ActorId, this.ResourceId, this.UpdateParameters, parentWorkflow.RequestId, this.ApplyAuthorizationPolicy, 0, queue.QueueName };

                Logger.Instance.WriteVerbose(EventIdentifier.AsyncUpdateResourceExecute, "Invoking DataAccessService.Update() for ActorId: '{0}', ResourceId: '{1}', ParentRequestId: '{3}' ApplyAuthorizationPolicy: '{4}' and QueueName: '{6}'.", args);

                // Submit the request via reflection and cleanup the queue
                // Added the AuthorizationTimeOut value of 0, which is "Fire and Forget"
                this.dataAccessServiceType.InvokeMember(
                    "Update",
                    BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance,
                    null,
                    this.dataAccessService,
                    args,
                    CultureInfo.InvariantCulture);

                DeleteWorkflowProgramQueue(this.queuingService, queue);

                return(base.Execute(executionContext));
            }
            catch (Exception ex)
            {
                throw Logger.Instance.ReportError(EventIdentifier.AsyncUpdateResourceExecuteError, ex);
            }
            finally
            {
                Logger.Instance.WriteMethodExit(EventIdentifier.AsyncUpdateResourceExecute);
            }
        }
Exemplo n.º 24
0
        public async Task DoItAsync()
        {
            signalQueue = await Workflow.NewQueueAsync <string>();

            while (true)
            {
                state = await signalQueue.DequeueAsync();

                if (state == "done")
                {
                    break;
                }
            }
        }
Exemplo n.º 25
0
        private void DoUnsubscribe(ActivityExecutionContext context, IActivityEventListener <QueueEventArgs> listener)
        {
            if (!this.subscriptionId.Equals(Guid.Empty))
            {
                FileWatcherService fileService = context.GetService <FileWatcherService>();
                fileService.UnregisterListener(this.subscriptionId);
                this.subscriptionId = Guid.Empty;
            }

            WorkflowQueuingService qService = context.GetService <WorkflowQueuingService>();
            WorkflowQueue          queue    = qService.GetWorkflowQueue(this.QueueName);

            queue.UnregisterForQueueItemAvailable(listener);
        }
Exemplo n.º 26
0
        void IEventActivity.Unsubscribe(ActivityExecutionContext parentContext, IActivityEventListener <QueueEventArgs> parentEventHandler)
        {
            if (parentContext == null)
            {
                throw new ArgumentNullException("parentContext");
            }
            if (parentEventHandler == null)
            {
                throw new ArgumentNullException("parentEventHandler");
            }

            System.Diagnostics.Debug.Assert(this.SubscriptionID != Guid.Empty);
            WorkflowQueuingService qService = parentContext.GetService <WorkflowQueuingService>();
            WorkflowQueue          wfQueue  = null;

            try
            {
                wfQueue = qService.GetWorkflowQueue(this.SubscriptionID);
            }
            catch
            {
                // If the queue no longer exists, eat the exception, we clear the subscription id later.
            }

            if (wfQueue != null && wfQueue.Count != 0)
            {
                wfQueue.Dequeue();
            }

            // WinOE

            Activity root = parentContext.Activity;

            while (root.Parent != null)
            {
                root = root.Parent;
            }
            TimerEventSubscriptionCollection timers = (TimerEventSubscriptionCollection)root.GetValue(TimerEventSubscriptionCollection.TimerCollectionProperty);

            Debug.Assert(timers != null, "TimerEventSubscriptionCollection on root activity should never be null, but it was");
            timers.Remove(this.SubscriptionID);

            if (wfQueue != null)
            {
                wfQueue.UnregisterForQueueItemAvailable(parentEventHandler);
                qService.DeleteWorkflowQueue(this.SubscriptionID);
            }

            this.SubscriptionID = Guid.Empty;
        }
        private StateMachineSubscription SubscribeEventActivity(ActivityExecutionContext context, IEventActivity eventActivity)
        {
            EventActivitySubscription subscription = new EventActivitySubscription();
            StateActivity             state        = (StateActivity)context.Activity;

            subscription.Subscribe(context, state, eventActivity);
            WorkflowQueue workflowQueue = GetWorkflowQueue(context, subscription.QueueName);

            if (workflowQueue != null)
            {
                workflowQueue.Enabled = true;
            }
            this.Subscriptions[subscription.QueueName] = subscription;
            return(subscription);
        }
Exemplo n.º 28
0
        internal static void ChangeEventDrivenQueueState(ActivityExecutionContext context, EventDrivenActivity eventDriven, bool enabled)
        {
            IEventActivity eventActivity = StateMachineHelpers.GetEventActivity(eventDriven);
            IComparable    queueName     = GetQueueName(eventActivity);

            if (queueName == null)
            {
                return; // skip unitialized follower
            }
            WorkflowQueue workflowQueue = GetWorkflowQueue(context, queueName);

            if (workflowQueue != null)
            {
                workflowQueue.Enabled = enabled;
            }
        }
Exemplo n.º 29
0
        void IActivityEventListener <QueueEventArgs> .OnEvent(object sender, QueueEventArgs e)
        {
            ActivityExecutionContext executionContext = sender as ActivityExecutionContext;
            WorkflowQueuingService   queueService     = executionContext.GetService <WorkflowQueuingService>();
            WorkflowQueue            queue            = queueService.GetWorkflowQueue(e.QueueName);

            if (queue.Count > 0)
            {
                object item = queue.Dequeue();
                ProcessQueueItem(executionContext, item);
                queue.UnregisterForQueueItemAvailable(this);

                // run all Activities
                base.Execute(executionContext);
            }
        }
        internal void DeleteQueue(ActivityExecutionContext context)
        {
            if (!StateMachineHelpers.IsRootExecutionContext(context))
            {
                // we only subscribe to the set state event if
                // we're at the root level. If this instance is
                // being called, it is not possible to set the
                // state from the host side directly
                return;
            }

            WorkflowQueuingService workflowQueuingService = context.GetService <WorkflowQueuingService>();
            WorkflowQueue          workflowQueue          = workflowQueuingService.GetWorkflowQueue(StateMachineWorkflowActivity.SetStateQueueName);

            workflowQueuingService.DeleteWorkflowQueue(StateMachineWorkflowActivity.SetStateQueueName);
        }