public OrchestrationHistoryEventEntity(string instanceId, string executionId, int sequenceNumber,
            DateTime taskTimeStamp, HistoryEvent historyEvent)
        {
            InstanceId = instanceId;
            ExecutionId = executionId;
            SequenceNumber = sequenceNumber;
            TaskTimeStamp = taskTimeStamp;
            HistoryEvent = historyEvent;

            PartitionKey = TableConstants.InstanceHistoryEventPrefix +
                           TableConstants.JoinDelimiter + InstanceId;
            RowKey = ExecutionId + TableConstants.JoinDelimiter + SequenceNumber;
        }
示例#2
0
        public ScreenHistory()
        {
            InitializeComponent();

            this.historyService = Win32ServiceManager.SharedManager.HistoryService;

            this.historyService.onHistoryEvent += this.historyService_onHistoryEvent;

            this.filterItems = new List <FilterItem>(new FilterItem[]
            {
                new FilterItem("All Events", "/BogheApp;component/embedded/16/date_time_16.png", HistoryEvent.StatusType.All, MediaType.All),
                new FilterItem("All Calls", "/BogheApp;component/embedded/16/call_16.png", HistoryEvent.StatusType.All, MediaType.AudioVideo),
                new FilterItem("Outgoing Calls", "/BogheApp;component/embedded/16/call_outgoing_16.png", HistoryEvent.StatusType.Outgoing, MediaType.AudioVideo),
                new FilterItem("Incoming Calls", "/BogheApp;component/embedded/16/call_incoming_16.png", HistoryEvent.StatusType.Incoming, MediaType.AudioVideo),
                new FilterItem("Missed Calls", "/BogheApp;component/embedded/16/call_missed_16.png", HistoryEvent.StatusType.Missed, MediaType.AudioVideo),
                new FilterItem("Messaging", "/BogheApp;component/embedded/16/messages_16.png", HistoryEvent.StatusType.All, MediaType.Messaging),
                new FilterItem("File Transfers", "/BogheApp;component/embedded/16/document_up_down_16.png", HistoryEvent.StatusType.All, MediaType.FileTransfer),
            });

            this.listBox.ItemTemplateSelector = new DataTemplateSelectorHistory();
            this.UpdateSource();

            this.comboBoxFilterCriteria.ItemsSource   = this.filterItems;
            this.comboBoxFilterCriteria.SelectedIndex = 0;

            this.historyView.Filter = delegate(object @event)
            {
                HistoryEvent hEvent = @event as HistoryEvent;
                if (hEvent == null)
                {
                    return(false);
                }
                if (((hEvent.Status & this.statusToDisplay) == hEvent.Status) &&
                    ((hEvent.MediaType & this.mediaTypeToDisplay) == hEvent.MediaType))
                {
                    return(hEvent.DisplayName.StartsWith(this.textBoxSearchCriteria.Text, StringComparison.InvariantCultureIgnoreCase));
                }
                return(false);
            };
        }
示例#3
0
        public OrchestrationRuntimeStateDump GetOrchestrationRuntimeStateDump()
        {
            var runtimeStateDump = new OrchestrationRuntimeStateDump
            {
                Events    = new List <HistoryEvent>(),
                NewEvents = new List <HistoryEvent>(),
            };

            foreach (HistoryEvent evt in Events)
            {
                HistoryEvent abridgeEvent = GenerateAbridgedEvent(evt);
                runtimeStateDump.Events.Add(abridgeEvent);
            }

            foreach (HistoryEvent evt in NewEvents)
            {
                HistoryEvent abridgeEvent = GenerateAbridgedEvent(evt);
                runtimeStateDump.NewEvents.Add(abridgeEvent);
            }

            return(runtimeStateDump);
        }
示例#4
0
        public void ProcessDecisionContextChildWorkflowExecutionCompletedTest([Frozen] HistoryEvent historyEvent)
        {
            historyEvent.EventType = EventType.ChildWorkflowExecutionCompleted;
            historyEvent.ChildWorkflowExecutionCompletedEventAttributes = new ChildWorkflowExecutionCompletedEventAttributes
            {
                WorkflowType = new WorkflowType
                {
                    Name    = "WorkflowName",
                    Version = "Workflow Version"
                },
                Result = "Success!",
            };

            var newShcheduledEvent = Substitute.For <HistoryEvent>();

            newShcheduledEvent.EventType = EventType.ActivityTaskScheduled;
            newShcheduledEvent.StartChildWorkflowExecutionInitiatedEventAttributes = new StartChildWorkflowExecutionInitiatedEventAttributes
            {
                Control = "ImportantData",
            };


            _processor = Substitute.For <SDK.Workflow.WorkflowEventsProcessor>(_decisionTask, _workflowBase, _pollforDecisionTaskRequest, _amazonSwf);

            _processor.FindEventTypeById(1).ReturnsForAnyArgs(info => newShcheduledEvent);

            _decisionContext = Substitute.For <WorkflowDecisionContext>();
            _processor.ProcessDecisionContext(historyEvent, _decisionContext);


            Assert.Equal(_decisionContext.ChildWorkflowName, historyEvent.ChildWorkflowExecutionCompletedEventAttributes.WorkflowType.Name);
            Assert.Equal(_decisionContext.ChildWorkflowVersion, historyEvent.ChildWorkflowExecutionCompletedEventAttributes.WorkflowType.Version);
            Assert.Equal(_decisionContext.Result, historyEvent.ChildWorkflowExecutionCompletedEventAttributes.Result);

            Assert.Equal(_decisionContext.Control,
                         newShcheduledEvent.StartChildWorkflowExecutionInitiatedEventAttributes.Control);

            Assert.Equal(_decisionContext.DecisionType, historyEvent.EventType);
        }
        /// <summary>
        /// Read an entity properties based on the supplied dictionary or entity properties
        /// </summary>
        /// <param name="properties">Dictionary of properties to read for the entity</param>
        /// <param name="operationContext">The operation context</param>
        public override void ReadEntity(IDictionary <string, EntityProperty> properties,
                                        OperationContext operationContext)
        {
            InstanceId     = GetValue("InstanceId", properties, property => property.StringValue);
            ExecutionId    = GetValue("ExecutionId", properties, property => property.StringValue);
            SequenceNumber = GetValue("SequenceNumber", properties, property => property.Int32Value).GetValueOrDefault();
            TaskTimeStamp  =
                GetValue("TaskTimeStamp", properties, property => property.DateTimeOffsetValue)
                .GetValueOrDefault()
                .DateTime;

            string serializedHistoryEvent = GetValue("HistoryEvent", properties, property => property.StringValue);

            HistoryEvent = JsonConvert.DeserializeObject <HistoryEvent>(serializedHistoryEvent,
                                                                        new JsonSerializerSettings {
                TypeNameHandling = TypeNameHandling.Objects,
#if NETSTANDARD2_0
                SerializationBinder = new PackageUpgradeSerializationBinder()
#else
                Binder = new PackageUpgradeSerializationBinder()
#endif
            });
示例#6
0
        public void SeekToLastBookmark(bool createBookmark)
        {
            // Setup
            using (LocalMachine machine = LocalMachine.New("test", null))
            {
                machine.Core.IdleRequest = () => CoreRequest.RunUntil(machine.Core.Ticks + 1000);
                machine.Auditors        += _mockAuditor.Object;

                if (createBookmark)
                {
                    RunForAWhile(machine);
                    machine.AddBookmark(false);
                }

                UInt64       ticks         = machine.Core.Ticks;
                HistoryEvent bookmarkEvent = machine.History.CurrentEvent;
                byte[]       state         = machine.Core.GetState();

                RunForAWhile(machine);

                // Act
                machine.JumpToMostRecentBookmark();

                // Verify
                Assert.AreEqual(machine.History.CurrentEvent, bookmarkEvent);
                Assert.AreEqual(machine.Core.Ticks, ticks);
                Assert.AreEqual(state, machine.Core.GetState());

                if (createBookmark)
                {
                    _mockAuditor.Verify(a => a(It.Is <CoreAction>(c => c.Type == CoreRequest.Types.LoadCore && c.Ticks == ticks)), Times.Once);
                }
                else
                {
                    _mockAuditor.Verify(a => a(It.Is <CoreAction>(c => c.Type == CoreRequest.Types.Reset && c.Ticks == 0)), Times.Once);
                }
            }
        }
        public static int GetTaskEventId(HistoryEvent historyEvent)
        {
            switch (historyEvent.EventType)
            {
            case EventType.TaskCompleted:
                return(((TaskCompletedEvent)historyEvent).TaskScheduledId);

            case EventType.TaskFailed:
                return(((TaskFailedEvent)historyEvent).TaskScheduledId);

            case EventType.SubOrchestrationInstanceCompleted:
                return(((SubOrchestrationInstanceCompletedEvent)historyEvent).TaskScheduledId);

            case EventType.SubOrchestrationInstanceFailed:
                return(((SubOrchestrationInstanceFailedEvent)historyEvent).TaskScheduledId);

            case EventType.TimerFired:
                return(((TimerFiredEvent)historyEvent).TimerId);

            default:
                return(historyEvent.EventId);
            }
        }
        void SetMarkerEvents(HistoryEvent historyEvent)
        {
            if (historyEvent is ExecutionStartedEvent startedEvent)
            {
                if (ExecutionStartedEvent != null)
                {
                    throw new InvalidOperationException(
                              "Multiple ExecutionStartedEvent found, potential corruption in state storage");
                }

                ExecutionStartedEvent = startedEvent;
            }
            else if (historyEvent is ExecutionCompletedEvent completedEvent)
            {
                if (ExecutionCompletedEvent != null)
                {
                    throw new InvalidOperationException(
                              "Multiple ExecutionCompletedEvent found, potential corruption in state storage");
                }

                ExecutionCompletedEvent = completedEvent;
            }
        }
示例#9
0
        public static bool TryGetPayloadText(HistoryEvent e, out string?payloadText)
        {
            payloadText = e.EventType switch
            {
                EventType.ContinueAsNew => ((ContinueAsNewEvent)e).Result,
                EventType.EventRaised => ((EventRaisedEvent)e).Input,
                EventType.EventSent => ((EventSentEvent)e).Input,
                EventType.ExecutionCompleted => ((ExecutionCompletedEvent)e).Result,
                EventType.ExecutionFailed => ((ExecutionCompletedEvent)e).Result,
                EventType.ExecutionStarted => ((ExecutionStartedEvent)e).Input,
                EventType.ExecutionTerminated => ((ExecutionTerminatedEvent)e).Input,
                EventType.GenericEvent => ((GenericEvent)e).Data,
                EventType.SubOrchestrationInstanceCompleted => ((SubOrchestrationInstanceCompletedEvent)e).Result,
                EventType.SubOrchestrationInstanceCreated => ((SubOrchestrationInstanceCreatedEvent)e).Input,
                EventType.SubOrchestrationInstanceFailed => ((SubOrchestrationInstanceFailedEvent)e).Details,
                EventType.TaskCompleted => ((TaskCompletedEvent)e).Result,
                EventType.TaskFailed => ((TaskFailedEvent)e).Details,
                EventType.TaskScheduled => ((TaskScheduledEvent)e).Input,
                _ => null,
            };

            return(payloadText != null);
        }
示例#10
0
        public void ProcessDecisionContextDecisionTaskCompletedTest([Frozen] HistoryEvent historyEvent)
        {
            historyEvent.EventType = EventType.DecisionTaskCompleted;
            historyEvent.DecisionTaskCompletedEventAttributes = new DecisionTaskCompletedEventAttributes
            {
                ScheduledEventId = 10,
                StartedEventId   = 10,
                ExecutionContext = _executionContext
            };

            _processor = new SDK.Workflow.WorkflowEventsProcessor(_decisionTask, _workflowBase, _pollforDecisionTaskRequest, _amazonSwf);

            _decisionContext = Substitute.For <WorkflowDecisionContext>();
            _processor.ProcessDecisionContext(historyEvent, _decisionContext);


            AssertObjectEquals.PropertyValuesAreEqual(_decisionContext.ExecutionContext, WorkflowStateSerializer.Deserialize(_executionContext));

            Assert.Equal(_decisionContext.StartedEventId,
                         historyEvent.DecisionTaskCompletedEventAttributes.StartedEventId);
            Assert.Equal(_decisionContext.ScheduledEventId,
                         historyEvent.DecisionTaskCompletedEventAttributes.ScheduledEventId);
        }
示例#11
0
        private void testTran()
        {
            //数据库上下文
            using (var context = new ModernHisContext())
            {
                //开启事务
                using (var scope = context.Database.BeginTransaction())
                {
                    try
                    {
                        //添加一个famousePerson
                        var famousePerson = new FamousPerson();
                        context.FamousPersons.Add(famousePerson);
                        //添加一个historyEvent
                        var historyEvent = new HistoryEvent();
                        context.HistoryEvents.Add(historyEvent);

                        scope.Commit();            //正常完成就可以提交,famousePerson和historyEvent都会添加
                    }
                    catch (Exception ex)
                    {
                        scope.Rollback();            //发生异常就回滚,famousePerson和historyEvent都不会添加
                    }
                }
            }
            //数据库上下文
            using (var context = new ModernHisContext())
            {
                //添加一个famousePerson
                var famousePerson = new FamousPerson();
                context.FamousPersons.Add(famousePerson);
                //添加一个historyEvent
                var historyEvent = new HistoryEvent();
                context.HistoryEvents.Add(historyEvent);
                context.SaveChanges();        //savechanges方法会将对数据库的多个封装为一个完整的事务
            }
        }
        private void AddMessagingEvent(HistoryEvent @event)
        {
            this.historyDataSource.Add(@event);

            if (this.chatHistoryEvent != null)
            {
                this.chatHistoryEvent.Messages.Add(@event as HistoryShortMessageEvent);
            }
            else
            {
                switch (@event.MediaType)
                {
                case BogheCore.MediaType.ShortMessage:
                case BogheCore.MediaType.SMS:
                    this.historyService.AddEvent(@event);
                    break;
                }
            }

            if (@event.Status == HistoryEvent.StatusType.Incoming)
            {
                this.soundService.PlayNewEvent();
            }
        }
示例#13
0
        private void AddMessagingEvent(HistoryEvent @event)
        {
            this.historyDataSource.Add(@event);

            if (this.chatHistoryEvent != null)
            {
                this.chatHistoryEvent.Messages.Add(@event as HistoryShortMessageEvent);
            }
            else
            {
                switch (@event.MediaType)
                {
                    case BogheCore.MediaType.ShortMessage:
                    case BogheCore.MediaType.SMS:
                        this.historyService.AddEvent(@event);
                        break;
                }
            }

            if (@event.Status == HistoryEvent.StatusType.Incoming)
            {
                this.soundService.PlayNewEvent();
            }
        }
        internal bool IsOutOfOrderMessage(MessageData message)
        {
            int taskScheduledId = Utils.GetTaskEventId(message.TaskMessage.Event);

            if (taskScheduledId < 0)
            {
                // This message does not require ordering (RaiseEvent, ExecutionStarted, Terminate, etc.).
                return(false);
            }

            // This message is a response to a task. Search the history to make sure that we've recorded the fact that
            // this task was scheduled. We don't have the luxery of transactions between queues and tables, so queue
            // messages are always written before we update the history in table storage. This means that in some
            // cases the response message could get picked up before we're ready for it.
            HistoryEvent mostRecentTaskEvent = this.RuntimeState.Events.LastOrDefault(e => e.EventId == taskScheduledId);

            if (mostRecentTaskEvent != null)
            {
                return(false);
            }

            // The message is out of order and cannot be handled by the current session.
            return(true);
        }
示例#15
0
 public static WorkflowItemEvent CreateTimerEventFor(this HistoryEvent historyEvent, IEnumerable <HistoryEvent> allHistoryEvents)
 {
     if (historyEvent.IsTimerFiredEvent())
     {
         return(new TimerFiredEvent(historyEvent, allHistoryEvents));
     }
     if (historyEvent.IsTimerStartedEvent())
     {
         return(new TimerStartedEvent(historyEvent, allHistoryEvents));
     }
     if (historyEvent.IsTimerStartFailedEvent())
     {
         return(new TimerStartFailedEvent(historyEvent));
     }
     if (historyEvent.IsTimerCancelledEvent())
     {
         return(new TimerCancelledEvent(historyEvent, allHistoryEvents));
     }
     if (historyEvent.IsTimerCancellationFailedEvent())
     {
         return(new TimerCancellationFailedEvent(historyEvent));
     }
     return(null);
 }
 internal RecordMarkerFailedEvent(HistoryEvent recordMarkerFailedEvent): base(recordMarkerFailedEvent.EventId)
 {
     _eventAttributes = recordMarkerFailedEvent.RecordMarkerFailedEventAttributes;
 }
示例#17
0
 // OnSelctionChangedEvent will apply filter
 public void Select(HistoryEvent.StatusType statusToDisplay, MediaType mediaTypeToDisplay)
 {
     int index = this.filterItems.FindIndex(x => x.Media == mediaTypeToDisplay && x.Status == statusToDisplay);
     if (index != -1)
     {
         this.comboBoxFilterCriteria.SelectedIndex = index;
     }
 }
示例#18
0
 internal WorkflowCancellationFailedEvent(HistoryEvent cancellationFailedEvent)
     : base(cancellationFailedEvent.EventId)
 {
     _eventAttributes = cancellationFailedEvent.CancelWorkflowExecutionFailedEventAttributes;
 }
示例#19
0
 public void UpdateEvent(HistoryEvent @event)
 {
 }
示例#20
0
        public void AddEvent(HistoryEvent historyEvent)
        {
            ++this.statEventsAdded;

            this.ValidatePrewarm();

            if (historyEvent.tick <= 0UL)
            {
                // Tick fix if it is zero
                historyEvent.tick = 1UL;
            }

            SortedList <long, HistoryEvent> list;

            if (this.events.TryGetValue(historyEvent.tick, out list) == true)
            {
                list.Add(MathUtils.GetKey(historyEvent.order, historyEvent.localOrder), historyEvent);
            }
            else
            {
                list = PoolSortedList <long, HistoryEvent> .Spawn(2);

                list.Add(MathUtils.GetKey(historyEvent.order, historyEvent.localOrder), historyEvent);
                this.events.Add(historyEvent.tick, list);
            }

            if (this.currentTick >= historyEvent.tick)
            {
                var tick         = this.currentTick;
                var searchTick   = historyEvent.tick - 1;
                var historyState = this.GetStateBeforeTick(searchTick);
                //var cloneState = this.world.CreateState();
                //cloneState.Initialize(this.world, freeze: true, restore: false);
                if (historyState != null)
                {
                    // State found - simulate from this state to current tick
                    this.world.GetState().CopyFrom(historyState);
                    this.world.GetState().tick = tick;
                    //cloneState.CopyFrom(state);
                    //this.world.SetState(cloneState);
                    if (this.beginAddEvents == false)
                    {
                        this.world.SetPreviousTick(historyState.tick);
                        this.world.Simulate(tick);
                    }
                }
                else
                {
                    // Previous state was not found - need to rewind from initial state
                    var resetState = this.world.GetResetState();
                    this.world.GetState().CopyFrom(resetState);
                    this.world.GetState().tick = tick;
                    //cloneState.CopyFrom(resetState);
                    //this.world.SetState(cloneState);
                    if (this.beginAddEvents == false)
                    {
                        this.world.SetPreviousTick(resetState.tick);
                        this.world.Simulate(tick);
                    }

                    //throw new StateNotFoundException("Tick: " + searchTick);
                }
            }
        }
        async Task OnProcessWorkItemAsync(TaskActivityWorkItem workItem)
        {
            Task renewTask = null;
            var  renewCancellationTokenSource = new CancellationTokenSource();

            TaskMessage           taskMessage           = workItem.TaskMessage;
            OrchestrationInstance orchestrationInstance = taskMessage.OrchestrationInstance;
            TaskScheduledEvent    scheduledEvent        = null;
            Activity diagnosticActivity = null;

            try
            {
                if (string.IsNullOrWhiteSpace(orchestrationInstance?.InstanceId))
                {
                    this.logHelper.TaskActivityDispatcherError(
                        workItem,
                        $"The activity worker received a message that does not have any OrchestrationInstance information.");
                    throw TraceHelper.TraceException(
                              TraceEventType.Error,
                              "TaskActivityDispatcher-MissingOrchestrationInstance",
                              new InvalidOperationException("Message does not contain any OrchestrationInstance information"));
                }

                if (taskMessage.Event.EventType != EventType.TaskScheduled)
                {
                    this.logHelper.TaskActivityDispatcherError(
                        workItem,
                        $"The activity worker received an event of type '{taskMessage.Event.EventType}' but only '{EventType.TaskScheduled}' is supported.");
                    throw TraceHelper.TraceException(
                              TraceEventType.Critical,
                              "TaskActivityDispatcher-UnsupportedEventType",
                              new NotSupportedException("Activity worker does not support event of type: " +
                                                        taskMessage.Event.EventType));
                }

                // call and get return message
                scheduledEvent = (TaskScheduledEvent)taskMessage.Event;
                this.logHelper.TaskActivityStarting(orchestrationInstance, scheduledEvent);
                TaskActivity taskActivity = this.objectManager.GetObject(scheduledEvent.Name, scheduledEvent.Version);
                if (taskActivity == null)
                {
                    throw new TypeMissingException($"TaskActivity {scheduledEvent.Name} version {scheduledEvent.Version} was not found");
                }

                if (workItem.LockedUntilUtc < DateTime.MaxValue)
                {
                    // start a task to run RenewUntil
                    renewTask = Task.Factory.StartNew(
                        () => this.RenewUntil(workItem, renewCancellationTokenSource.Token),
                        renewCancellationTokenSource.Token);
                }

                // TODO : pass workflow instance data
                var          context        = new TaskContext(taskMessage.OrchestrationInstance);
                HistoryEvent eventToRespond = null;

                var dispatchContext = new DispatchMiddlewareContext();
                dispatchContext.SetProperty(taskMessage.OrchestrationInstance);
                dispatchContext.SetProperty(taskActivity);
                dispatchContext.SetProperty(scheduledEvent);

                // correlation
                CorrelationTraceClient.Propagate(() =>
                {
                    workItem.TraceContextBase?.SetActivityToCurrent();
                    diagnosticActivity = workItem.TraceContextBase?.CurrentActivity;
                });

                await this.dispatchPipeline.RunAsync(dispatchContext, async _ =>
                {
                    try
                    {
                        string output  = await taskActivity.RunAsync(context, scheduledEvent.Input);
                        eventToRespond = new TaskCompletedEvent(-1, scheduledEvent.EventId, output);
                    }
                    catch (TaskFailureException e)
                    {
                        TraceHelper.TraceExceptionInstance(TraceEventType.Error, "TaskActivityDispatcher-ProcessTaskFailure", taskMessage.OrchestrationInstance, e);
                        string details = this.IncludeDetails ? e.Details : null;
                        eventToRespond = new TaskFailedEvent(-1, scheduledEvent.EventId, e.Message, details);
                        this.logHelper.TaskActivityFailure(orchestrationInstance, scheduledEvent.Name, (TaskFailedEvent)eventToRespond, e);
                        CorrelationTraceClient.Propagate(() => CorrelationTraceClient.TrackException(e));
                    }
                    catch (Exception e) when(!Utils.IsFatal(e) && !Utils.IsExecutionAborting(e))
                    {
                        TraceHelper.TraceExceptionInstance(TraceEventType.Error, "TaskActivityDispatcher-ProcessException", taskMessage.OrchestrationInstance, e);
                        string details = this.IncludeDetails
                            ? $"Unhandled exception while executing task: {e}\n\t{e.StackTrace}"
                            : null;
                        eventToRespond = new TaskFailedEvent(-1, scheduledEvent.EventId, e.Message, details);
                        this.logHelper.TaskActivityFailure(orchestrationInstance, scheduledEvent.Name, (TaskFailedEvent)eventToRespond, e);
                    }

                    if (eventToRespond is TaskCompletedEvent completedEvent)
                    {
                        this.logHelper.TaskActivityCompleted(orchestrationInstance, scheduledEvent.Name, completedEvent);
                    }
                });

                var responseTaskMessage = new TaskMessage
                {
                    Event = eventToRespond,
                    OrchestrationInstance = orchestrationInstance
                };

                await this.orchestrationService.CompleteTaskActivityWorkItemAsync(workItem, responseTaskMessage);
            }
            catch (SessionAbortedException e)
            {
                // The activity aborted its execution
                this.logHelper.TaskActivityAborted(orchestrationInstance, scheduledEvent, e.Message);
                TraceHelper.TraceInstance(TraceEventType.Warning, "TaskActivityDispatcher-ExecutionAborted", orchestrationInstance, "{0}: {1}", scheduledEvent.Name, e.Message);
                await this.orchestrationService.AbandonTaskActivityWorkItemAsync(workItem);
            }
            finally
            {
                diagnosticActivity?.Stop(); // Ensure the activity is stopped here to prevent it from leaking out.
                if (renewTask != null)
                {
                    renewCancellationTokenSource.Cancel();
                    try
                    {
                        // wait the renewTask finish
                        await renewTask;
                    }
                    catch (OperationCanceledException)
                    {
                        // ignore
                    }
                }
            }
        }
 internal WorkflowSignaledEvent(HistoryEvent signaledEvent)
     : base(signaledEvent)
 {
     _eventAttributes = signaledEvent.WorkflowExecutionSignaledEventAttributes;
 }
示例#23
0
 private void Filter(HistoryEvent.StatusType statusToDisplay, MediaType mediaTypeToDisplay)
 {
     this.statusToDisplay = statusToDisplay;
     this.mediaTypeToDisplay = mediaTypeToDisplay;
     this.historyView.Refresh();
 }
示例#24
0
 public FilterItem(String text, String imageSource, HistoryEvent.StatusType status, MediaType media)
 {
     this.text = text;
     this.imageSource = imageSource;
     this.status = status;
     this.media = media;
 }
示例#25
0
        /// <summary>
        /// Adds the event history to the control.
        /// </summary>
        public void AddEventHistory(HistoryEvent events)
        {
            for (int ii = 0; ii < events.Events.Count; ii++)
            {
                ListViewItem item = CreateListItem(m_filter, events.Events[ii].EventFields);
                EventsLV.Items.Add(item);
            }

            // adjust the width of the columns.
            for (int ii = 0; ii < EventsLV.Columns.Count; ii++)
            {
                EventsLV.Columns[ii].Width = -2;
            }
        }
示例#26
0
        public void UpdateEvent(HistoryEvent @event)
        {
            HistoryEventArgs eargs = new HistoryEventArgs(HistoryEventTypes.UPDATED);
            eargs.AddExtra(HistoryEventArgs.EXTRA_EVENT, @event);
            EventHandlerTrigger.TriggerEvent<HistoryEventArgs>(this.onHistoryEvent, this, eargs);

            this.DeferredSave();
        }
示例#27
0
        public void AddEvent(HistoryEvent @event)
        {
            this.events.Insert(0, @event);

            HistoryEventArgs eargs = new HistoryEventArgs(HistoryEventTypes.ADDED);
            eargs.AddExtra(HistoryEventArgs.EXTRA_EVENT, @event);
            EventHandlerTrigger.TriggerEvent<HistoryEventArgs>(this.onHistoryEvent, this, eargs);

            this.DeferredSave();
        }
示例#28
0
 public async Task <bool> SaveHistoryEvents(HistoryEvent he)
 {
     UndeliveredEvents.Add(he);
     return(true);
 }
示例#29
0
 internal ActivityTimedoutEvent(HistoryEvent activityTimedoutEvent, IEnumerable <HistoryEvent> allHistoryEvents) : base(activityTimedoutEvent.EventId)
 {
     _eventAttributes = activityTimedoutEvent.ActivityTaskTimedOutEventAttributes;
     PopulateActivityFrom(allHistoryEvents, _eventAttributes.StartedEventId, _eventAttributes.ScheduledEventId);
 }
示例#30
0
 internal LambdaStartedEvent(HistoryEvent startedEvent, IEnumerable <HistoryEvent> allEvents)
     : base(startedEvent)
 {
     IsActive = true;
     PopulateProperties(startedEvent.LambdaFunctionStartedEventAttributes.ScheduledEventId, allEvents);
 }
 public void AddEvent(HistoryEvent historyEvent)
 {
     AddEvent(historyEvent, true);
 }
示例#32
0
 public void UpdateEvent(HistoryEvent @event)
 {
 }
 void SetMarkerEvents(HistoryEvent historyEvent)
 {
     if (historyEvent is ExecutionStartedEvent)
     {
         if (ExecutionStartedEvent != null)
         {
             throw new InvalidOperationException(
                 "Multiple ExecutionStartedEvent found, potential corruption in state storage");
         }
         ExecutionStartedEvent = (ExecutionStartedEvent) historyEvent;
     }
     else if (historyEvent is ExecutionCompletedEvent)
     {
         if (ExecutionCompletedEvent != null)
         {
             throw new InvalidOperationException(
                 "Multiple ExecutionCompletedEvent found, potential corruption in state storage");
         }
         ExecutionCompletedEvent = (ExecutionCompletedEvent) historyEvent;
     }
 }
示例#34
0
 public StudentHistory(HistoryEvent e, string studentId)
 {
     StudentId   = studentId;
     TimeOfEvent = DateTime.Now;
     Event       = e;
 }
示例#35
0
        static public bool HistoryEventsEqual(HistoryEvent event1, HistoryEvent event2)
        {
            if (event1 == event2)
            {
                return(true);
            }

            if (event1 == null || event2 == null)
            {
                return(false);
            }

            if (event1.Id != event2.Id)
            {
                return(false);
            }

            if (event1.Children.Count != event2.Children.Count)
            {
                return(false);
            }

            if (event1.Ticks != event2.Ticks)
            {
                return(false);
            }

            // Should be implemented as a virtual Equals method.
            switch (event1)
            {
            case BookmarkHistoryEvent bookmarkEvent1:
                if (event2 is BookmarkHistoryEvent bookmarkEvent2)
                {
                    if (!BookmarksEqual(bookmarkEvent1.Bookmark, bookmarkEvent2.Bookmark))
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }

                break;

            case CoreActionHistoryEvent coreActionEvent1:
                if (event2 is CoreActionHistoryEvent coreActionEvent2)
                {
                    if (!CoreActionsEqual(coreActionEvent1.CoreAction, coreActionEvent2.CoreAction))
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
                break;

            case RootHistoryEvent _:
                if (!(event2 is RootHistoryEvent))
                {
                    return(false);
                }
                break;

            default:
                throw new Exception(String.Format("Unknown history event type {0}", event1.GetType().Name));
            }

            // This assumes the children are in the same order. Might need to change this in the future...
            for (int i = 0; i < event1.Children.Count; i++)
            {
                if (!HistoryEventsEqual(event1.Children[i], event2.Children[i]))
                {
                    return(false);
                }
            }

            return(true);
        }
 void ProcessEvent(HistoryEvent historyEvent)
 {
     switch (historyEvent.EventType)
     {
         case EventType.ExecutionStarted:
             var executionStartedEvent = (ExecutionStartedEvent) historyEvent;
             result = taskOrchestration.Execute(context, executionStartedEvent.Input);
             break;
         case EventType.ExecutionTerminated:
             context.HandleExecutionTerminatedEvent((ExecutionTerminatedEvent) historyEvent);
             break;
         case EventType.TaskScheduled:
             context.HandleTaskScheduledEvent((TaskScheduledEvent) historyEvent);
             break;
         case EventType.TaskCompleted:
             context.HandleTaskCompletedEvent((TaskCompletedEvent) historyEvent);
             break;
         case EventType.TaskFailed:
             context.HandleTaskFailedEvent((TaskFailedEvent) historyEvent);
             break;
         case EventType.SubOrchestrationInstanceCreated:
             context.HandleSubOrchestrationCreatedEvent((SubOrchestrationInstanceCreatedEvent) historyEvent);
             break;
         case EventType.SubOrchestrationInstanceCompleted:
             context.HandleSubOrchestrationInstanceCompletedEvent(
                 (SubOrchestrationInstanceCompletedEvent) historyEvent);
             break;
         case EventType.SubOrchestrationInstanceFailed:
             context.HandleSubOrchestrationInstanceFailedEvent((SubOrchestrationInstanceFailedEvent) historyEvent);
             break;
         case EventType.TimerCreated:
             context.HandleTimerCreatedEvent((TimerCreatedEvent) historyEvent);
             break;
         case EventType.TimerFired:
             context.HandleTimerFiredEvent((TimerFiredEvent) historyEvent);
             break;
         case EventType.EventRaised:
             var eventRaisedEvent = (EventRaisedEvent) historyEvent;
             taskOrchestration.RaiseEvent(context, eventRaisedEvent.Name, eventRaisedEvent.Input);
             break;
     }
 }
示例#37
0
        public void DeleteEvent(HistoryEvent @event)
        {
            this.events.Remove(@event);

            HistoryEventArgs eargs = new HistoryEventArgs(HistoryEventTypes.REMOVED);
            eargs.AddExtra(HistoryEventArgs.EXTRA_EVENT, @event);
            EventHandlerTrigger.TriggerEvent<HistoryEventArgs>(this.onHistoryEvent, this, eargs);

            this.DeferredSave();
        }
        void ProcessEvent(HistoryEvent historyEvent)
        {
            switch (historyEvent.EventType)
            {
            case EventType.ExecutionStarted:
                var executionStartedEvent = (ExecutionStartedEvent)historyEvent;
                this.result = this.taskOrchestration.Execute(this.context, executionStartedEvent.Input);
                break;

            case EventType.ExecutionTerminated:
                this.context.HandleExecutionTerminatedEvent((ExecutionTerminatedEvent)historyEvent);
                break;

            case EventType.TaskScheduled:
                this.context.HandleTaskScheduledEvent((TaskScheduledEvent)historyEvent);
                break;

            case EventType.TaskCompleted:
                this.context.HandleTaskCompletedEvent((TaskCompletedEvent)historyEvent);
                break;

            case EventType.TaskFailed:
                this.context.HandleTaskFailedEvent((TaskFailedEvent)historyEvent);
                break;

            case EventType.SubOrchestrationInstanceCreated:
                this.context.HandleSubOrchestrationCreatedEvent((SubOrchestrationInstanceCreatedEvent)historyEvent);
                break;

            case EventType.SubOrchestrationInstanceCompleted:
                this.context.HandleSubOrchestrationInstanceCompletedEvent(
                    (SubOrchestrationInstanceCompletedEvent)historyEvent);
                break;

            case EventType.SubOrchestrationInstanceFailed:
                this.context.HandleSubOrchestrationInstanceFailedEvent((SubOrchestrationInstanceFailedEvent)historyEvent);
                break;

            case EventType.TimerCreated:
                this.context.HandleTimerCreatedEvent((TimerCreatedEvent)historyEvent);
                break;

            case EventType.TimerFired:
                this.context.HandleTimerFiredEvent((TimerFiredEvent)historyEvent);
                break;

            case EventType.EventSent:
                this.context.HandleEventSentEvent((EventSentEvent)historyEvent);
                break;

            case EventType.EventRaised:
                if (this.skipCarryOverEvents || !this.context.HasContinueAsNew)
                {
                    var eventRaisedEvent = (EventRaisedEvent)historyEvent;
                    this.taskOrchestration.RaiseEvent(this.context, eventRaisedEvent.Name, eventRaisedEvent.Input);
                }
                else
                {
                    this.context.AddEventToNextIteration(historyEvent);
                }
                break;
            }
        }
        /// <summary>
        /// Reads history events.
        /// </summary>
        protected override void HistoryReadEvents(
            ServerSystemContext context,
            ReadEventDetails details,
            TimestampsToReturn timestampsToReturn,
            IList<HistoryReadValueId> nodesToRead,
            IList<HistoryReadResult> results,
            IList<ServiceResult> errors,
            List<NodeHandle> nodesToProcess,
            IDictionary<NodeId, NodeState> cache)
        {
            for (int ii = 0; ii < nodesToProcess.Count; ii++)
            {
                NodeHandle handle = nodesToProcess[ii];
                HistoryReadValueId nodeToRead = nodesToRead[handle.Index];
                HistoryReadResult result = results[handle.Index];

                HistoryReadRequest request = null;

                // load an exising request.
                if (nodeToRead.ContinuationPoint != null)
                {
                    request = LoadContinuationPoint(context, nodeToRead.ContinuationPoint);

                    if (request == null)
                    {
                        errors[handle.Index] = StatusCodes.BadContinuationPointInvalid;
                        continue;
                    }
                }

                // create a new request.
                else
                {
                    request = CreateHistoryReadRequest(
                        context,
                        details,
                        handle,
                        nodeToRead);
                }

                // process events until the max is reached.
                HistoryEvent events = new HistoryEvent();

                while (request.NumValuesPerNode == 0 || events.Events.Count < request.NumValuesPerNode)
                {
                    if (request.Events.Count == 0)
                    {
                        break;
                    }

                    BaseEventState e = null;

                    if (request.TimeFlowsBackward)
                    {
                        e = request.Events.Last.Value;
                        request.Events.RemoveLast();
                    }
                    else
                    {
                        e = request.Events.First.Value;
                        request.Events.RemoveFirst();
                    }

                    events.Events.Add(GetEventFields(request, e));
                }

                errors[handle.Index] = ServiceResult.Good;

                // check if a continuation point is requred.
                if (request.Events.Count > 0)
                {
                    // only set if both end time and start time are specified.
                    if (details.StartTime != DateTime.MinValue && details.EndTime != DateTime.MinValue)
                    {
                        result.ContinuationPoint = SaveContinuationPoint(context, request);
                    }
                }

                // check if no data returned.
                else
                {
                    errors[handle.Index] = StatusCodes.GoodNoData;
                }

                // return the data.
                result.HistoryData = new ExtensionObject(events);
            }
        }
 void AddEvent(HistoryEvent historyEvent, bool isNewEvent)
 {
     Events.Add(historyEvent);
     if (isNewEvent)
     {
         NewEvents.Add(historyEvent);
     }
     SetMarkerEvents(historyEvent);
 }
 internal WorkflowCancelRequestFailedEvent(HistoryEvent cancelRequestFailedEvent) : base(cancelRequestFailedEvent.EventId)
 {
     _eventAttributes = cancelRequestFailedEvent.RequestCancelExternalWorkflowExecutionFailedEventAttributes;
 }
        HistoryEvent GenerateAbridgedEvent(HistoryEvent evt)
        {
            HistoryEvent returnedEvent = evt;

            if (evt is TaskScheduledEvent)
            {
                var sourceEvent = (TaskScheduledEvent) evt;
                returnedEvent = new TaskScheduledEvent(sourceEvent.EventId)
                {
                    Timestamp = sourceEvent.Timestamp,
                    IsPlayed = sourceEvent.IsPlayed,
                    Name = sourceEvent.Name,
                    Version = sourceEvent.Version,
                    Input = "[..snipped..]",
                };
            }
            else if (evt is TaskCompletedEvent)
            {
                var sourceEvent = (TaskCompletedEvent) evt;
                returnedEvent = new TaskCompletedEvent(sourceEvent.EventId, sourceEvent.TaskScheduledId, "[..snipped..]")
                {
                    Timestamp = sourceEvent.Timestamp,
                    IsPlayed = sourceEvent.IsPlayed,
                };
            }
            else if (evt is SubOrchestrationInstanceCreatedEvent)
            {
                var sourceEvent = (SubOrchestrationInstanceCreatedEvent) evt;
                returnedEvent = new SubOrchestrationInstanceCreatedEvent(sourceEvent.EventId)
                {
                    Timestamp = sourceEvent.Timestamp,
                    IsPlayed = sourceEvent.IsPlayed,
                    Name = sourceEvent.Name,
                    Version = sourceEvent.Version,
                    Input = "[..snipped..]",
                };
            }
            else if (evt is SubOrchestrationInstanceCompletedEvent)
            {
                var sourceEvent = (SubOrchestrationInstanceCompletedEvent) evt;
                returnedEvent = new SubOrchestrationInstanceCompletedEvent(sourceEvent.EventId,
                    sourceEvent.TaskScheduledId, "[..snipped..]")
                {
                    Timestamp = sourceEvent.Timestamp,
                    IsPlayed = sourceEvent.IsPlayed,
                };
            }
            else if (evt is TaskFailedEvent)
            {
                var sourceEvent = (TaskFailedEvent) evt;
                returnedEvent = new TaskFailedEvent(sourceEvent.EventId,
                    sourceEvent.TaskScheduledId, sourceEvent.Reason, "[..snipped..]")
                {
                    Timestamp = sourceEvent.Timestamp,
                    IsPlayed = sourceEvent.IsPlayed,
                };
            }
            else if (evt is SubOrchestrationInstanceFailedEvent)
            {
                var sourceEvent = (SubOrchestrationInstanceFailedEvent) evt;
                returnedEvent = new SubOrchestrationInstanceFailedEvent(sourceEvent.EventId,
                    sourceEvent.TaskScheduledId, sourceEvent.Reason, "[..snipped..]")
                {
                    Timestamp = sourceEvent.Timestamp,
                    IsPlayed = sourceEvent.IsPlayed,
                };
            }
            else if (evt is ExecutionStartedEvent)
            {
                var sourceEvent = (ExecutionStartedEvent) evt;
                returnedEvent = new ExecutionStartedEvent(sourceEvent.EventId, "[..snipped..]")
                {
                    Timestamp = sourceEvent.Timestamp,
                    IsPlayed = sourceEvent.IsPlayed,
                };
            }
            else if (evt is ExecutionCompletedEvent)
            {
                var sourceEvent = (ExecutionCompletedEvent) evt;
                returnedEvent = new ExecutionCompletedEvent(sourceEvent.EventId, "[..snipped..]",
                    sourceEvent.OrchestrationStatus)
                {
                    Timestamp = sourceEvent.Timestamp,
                    IsPlayed = sourceEvent.IsPlayed,
                };
            }
            else if (evt is ExecutionTerminatedEvent)
            {
                var sourceEvent = (ExecutionTerminatedEvent) evt;
                returnedEvent = new ExecutionTerminatedEvent(sourceEvent.EventId, "[..snipped..]")
                {
                    Timestamp = sourceEvent.Timestamp,
                    IsPlayed = sourceEvent.IsPlayed,
                };
            }
            // ContinueAsNewEvent is covered by the ExecutionCompletedEvent block

            return returnedEvent;
        }
示例#43
0
 protected internal virtual bool isInitialEvent(HistoryEvent historyEvent)
 {
     return(string.ReferenceEquals(historyEvent.EventType, null) || historyEvent.isEventOfType(HistoryEventTypes.ACTIVITY_INSTANCE_START) || historyEvent.isEventOfType(HistoryEventTypes.PROCESS_INSTANCE_START) || historyEvent.isEventOfType(HistoryEventTypes.TASK_INSTANCE_CREATE) || historyEvent.isEventOfType(HistoryEventTypes.FORM_PROPERTY_UPDATE) || historyEvent.isEventOfType(HistoryEventTypes.INCIDENT_CREATE) || historyEvent.isEventOfType(HistoryEventTypes.CASE_INSTANCE_CREATE) || historyEvent.isEventOfType(HistoryEventTypes.DMN_DECISION_EVALUATE) || historyEvent.isEventOfType(HistoryEventTypes.BATCH_START) || historyEvent.isEventOfType(HistoryEventTypes.IDENTITY_LINK_ADD) || historyEvent.isEventOfType(HistoryEventTypes.IDENTITY_LINK_DELETE));
 }
示例#44
0
        public async Task <string> UpdateStatus(IncidentStatusRequest statusRequest)
        {
            Services.Log.Info("Incident Status Update Request [Hub]");
            string responseText;

            var currentUserID = ((ServiceUser)Context.User).Id;

            stranddContext context = new stranddContext();

            //Retrieve Incident
            Incident updateIncident = await(from r in context.Incidents where (r.Id == statusRequest.IncidentGUID) select r).FirstOrDefaultAsync();

            //Find the Incident to Edit and return Bad Response if not found
            if (updateIncident != null)
            {
                //Check for Submitted Status and Update
                if (statusRequest.NewStatusCode != null)
                {
                    updateIncident.StatusCode            = statusRequest.NewStatusCode;
                    updateIncident.StatusCustomerConfirm = false;
                    updateIncident.StatusProviderConfirm = false;
                }

                //Check for Submitted Pricing and Update
                if (statusRequest.ServiceFee != 0)
                {
                    updateIncident.ServiceFee = statusRequest.ServiceFee;
                }

                //Check if ETA and Save Arrival Time
                if (statusRequest.ETA != 0)
                {
                    if (statusRequest.NewStatusCode == "ARRIVED")
                    {
                        updateIncident.ProviderArrivalTime = System.DateTime.Now;
                    }
                    else
                    {
                        DateTimeOffset?priorETA = updateIncident.ProviderArrivalTime;
                        updateIncident.ProviderArrivalTime = System.DateTime.Now.AddMinutes(statusRequest.ETA);

                        if (priorETA != null)
                        {
                            DateTimeOffset compareETA = (DateTimeOffset)priorETA;

                            compareETA = compareETA.AddMinutes(Convert.ToInt32(WebConfigurationManager.AppSettings["RZ_DelayMinuteBuffer"]));
                            if (DateTimeOffset.Compare(compareETA, (DateTimeOffset)updateIncident.ProviderArrivalTime) < 0)
                            {
                                statusRequest.Delayed = true;
                            }
                        }
                    }
                }
            }
            else
            {
                // Return Failed Response
                responseText = "Incident not found [" + statusRequest.IncidentGUID + "] in the system";
                Services.Log.Warn(responseText);
                return(responseText);
            }

            //Save record
            await context.SaveChangesAsync();

            Services.Log.Info("Incident [" + updateIncident.Id + "] Status Updated" + " to Code: " + updateIncident.StatusCode);

            await HistoryEvent.logHistoryEventAsync("INCIDENT_STATUS_ADMIN", updateIncident.StatusCode, updateIncident.Id, currentUserID, null, null);

            IncidentController.ProcessStatusRequestBehavior(statusRequest, updateIncident, Services);

            //Return Successful Response
            responseText = "Status Updated";
            return(responseText);
        }
        async Task OnProcessWorkItemAsync(TaskActivityWorkItem workItem)
        {
            Task renewTask = null;
            var  renewCancellationTokenSource = new CancellationTokenSource();

            try
            {
                TaskMessage           taskMessage           = workItem.TaskMessage;
                OrchestrationInstance orchestrationInstance = taskMessage.OrchestrationInstance;
                if (string.IsNullOrWhiteSpace(orchestrationInstance?.InstanceId))
                {
                    throw TraceHelper.TraceException(
                              TraceEventType.Error,
                              "TaskActivityDispatcher-MissingOrchestrationInstance",
                              new InvalidOperationException("Message does not contain any OrchestrationInstance information"));
                }

                if (taskMessage.Event.EventType != EventType.TaskScheduled)
                {
                    throw TraceHelper.TraceException(
                              TraceEventType.Critical,
                              "TaskActivityDispatcher-UnsupportedEventType",
                              new NotSupportedException("Activity worker does not support event of type: " +
                                                        taskMessage.Event.EventType));
                }

                // call and get return message
                var          scheduledEvent = (TaskScheduledEvent)taskMessage.Event;
                TaskActivity taskActivity   = this.objectManager.GetObject(scheduledEvent.Name, scheduledEvent.Version);
                if (taskActivity == null)
                {
                    throw new TypeMissingException($"TaskActivity {scheduledEvent.Name} version {scheduledEvent.Version} was not found");
                }

                renewTask = Task.Factory.StartNew(() => RenewUntil(workItem, renewCancellationTokenSource.Token), renewCancellationTokenSource.Token);

                // TODO : pass workflow instance data
                var          context        = new TaskContext(taskMessage.OrchestrationInstance);
                HistoryEvent eventToRespond = null;

                var dispatchContext = new DispatchMiddlewareContext();
                dispatchContext.SetProperty(taskMessage.OrchestrationInstance);
                dispatchContext.SetProperty(taskActivity);
                dispatchContext.SetProperty(scheduledEvent);

                await this.dispatchPipeline.RunAsync(dispatchContext, async _ =>
                {
                    try
                    {
                        string output  = await taskActivity.RunAsync(context, scheduledEvent.Input);
                        eventToRespond = new TaskCompletedEvent(-1, scheduledEvent.EventId, output);
                    }
                    catch (TaskFailureException e)
                    {
                        TraceHelper.TraceExceptionInstance(TraceEventType.Error, "TaskActivityDispatcher-ProcessTaskFailure", taskMessage.OrchestrationInstance, e);
                        string details = IncludeDetails ? e.Details : null;
                        eventToRespond = new TaskFailedEvent(-1, scheduledEvent.EventId, e.Message, details);
                    }
                    catch (Exception e) when(!Utils.IsFatal(e))
                    {
                        TraceHelper.TraceExceptionInstance(TraceEventType.Error, "TaskActivityDispatcher-ProcessException", taskMessage.OrchestrationInstance, e);
                        string details = IncludeDetails
                            ? $"Unhandled exception while executing task: {e}\n\t{e.StackTrace}"
                            : null;
                        eventToRespond = new TaskFailedEvent(-1, scheduledEvent.EventId, e.Message, details);
                    }
                });

                var responseTaskMessage = new TaskMessage
                {
                    Event = eventToRespond,
                    OrchestrationInstance = orchestrationInstance
                };

                await this.orchestrationService.CompleteTaskActivityWorkItemAsync(workItem, responseTaskMessage);
            }
            finally
            {
                if (renewTask != null)
                {
                    renewCancellationTokenSource.Cancel();
                    renewTask.Wait(renewCancellationTokenSource.Token);
                }
            }
        }
        /// <inheritdoc />
        public override async Task UpdateStateAsync(OrchestrationRuntimeState runtimeState, string instanceId, string executionId)
        {
            IList <HistoryEvent> newEvents = runtimeState.NewEvents;
            IList <HistoryEvent> allEvents = runtimeState.Events;

            var newEventListBuffer = new StringBuilder(4000);
            var historyEventBatch  = new TableBatchOperation();

            EventType?orchestratorEventType = null;

            string eTagValue = this.GetETagValue(instanceId);

            DynamicTableEntity orchestrationInstanceUpdate = new DynamicTableEntity(instanceId, "")
            {
                Properties =
                {
                    ["CustomStatus"]    = new EntityProperty(runtimeState.Status),
                    ["ExecutionId"]     = new EntityProperty(executionId),
                    ["LastUpdatedTime"] = new EntityProperty(newEvents.Last().Timestamp),
                }
            };

            for (int i = 0; i < newEvents.Count; i++)
            {
                HistoryEvent       historyEvent = newEvents[i];
                DynamicTableEntity entity       = this.tableEntityConverter.ConvertToTableEntity(historyEvent);

                await this.CompressLargeMessageAsync(entity);

                newEventListBuffer.Append(historyEvent.EventType.ToString()).Append(',');

                // The row key is the sequence number, which represents the chronological ordinal of the event.
                long sequenceNumber = i + (allEvents.Count - newEvents.Count);
                entity.RowKey       = sequenceNumber.ToString("X16");
                entity.PartitionKey = instanceId;
                entity.Properties["ExecutionId"] = new EntityProperty(executionId);

                // Replacement can happen if the orchestration episode gets replayed due to a commit failure in one of the steps below.
                historyEventBatch.InsertOrReplace(entity);

                // Table storage only supports inserts of up to 100 entities at a time.
                if (historyEventBatch.Count == 99)
                {
                    eTagValue = await this.UploadHistoryBatch(instanceId, executionId, historyEventBatch, newEventListBuffer, newEvents.Count, eTagValue);

                    // Reset local state for the next batch
                    newEventListBuffer.Clear();
                    historyEventBatch.Clear();
                }

                // Monitor for orchestration instance events
                switch (historyEvent.EventType)
                {
                case EventType.ExecutionStarted:
                    orchestratorEventType = historyEvent.EventType;
                    ExecutionStartedEvent executionStartedEvent = (ExecutionStartedEvent)historyEvent;
                    orchestrationInstanceUpdate.Properties["Name"]          = new EntityProperty(executionStartedEvent.Name);
                    orchestrationInstanceUpdate.Properties["Version"]       = new EntityProperty(executionStartedEvent.Version);
                    orchestrationInstanceUpdate.Properties["CreatedTime"]   = new EntityProperty(executionStartedEvent.Timestamp);
                    orchestrationInstanceUpdate.Properties["RuntimeStatus"] = new EntityProperty(OrchestrationStatus.Running.ToString());
                    this.SetTablePropertyForMessage(entity, orchestrationInstanceUpdate, InputProperty, InputProperty, executionStartedEvent.Input);
                    break;

                case EventType.ExecutionCompleted:
                    orchestratorEventType = historyEvent.EventType;
                    ExecutionCompletedEvent executionCompleted = (ExecutionCompletedEvent)historyEvent;
                    this.SetTablePropertyForMessage(entity, orchestrationInstanceUpdate, ResultProperty, OutputProperty, executionCompleted.Result);
                    orchestrationInstanceUpdate.Properties["RuntimeStatus"] = new EntityProperty(executionCompleted.OrchestrationStatus.ToString());
                    break;

                case EventType.ExecutionTerminated:
                    orchestratorEventType = historyEvent.EventType;
                    ExecutionTerminatedEvent executionTerminatedEvent = (ExecutionTerminatedEvent)historyEvent;
                    this.SetTablePropertyForMessage(entity, orchestrationInstanceUpdate, InputProperty, OutputProperty, executionTerminatedEvent.Input);
                    orchestrationInstanceUpdate.Properties["RuntimeStatus"] = new EntityProperty(OrchestrationStatus.Terminated.ToString());
                    break;

                case EventType.ContinueAsNew:
                    orchestratorEventType = historyEvent.EventType;
                    ExecutionCompletedEvent executionCompletedEvent = (ExecutionCompletedEvent)historyEvent;
                    this.SetTablePropertyForMessage(entity, orchestrationInstanceUpdate, ResultProperty, OutputProperty, executionCompletedEvent.Result);
                    orchestrationInstanceUpdate.Properties["RuntimeStatus"] = new EntityProperty(OrchestrationStatus.ContinuedAsNew.ToString());
                    break;
                }
            }

            // First persistence step is to commit history to the history table. Messages must come after.
            if (historyEventBatch.Count > 0)
            {
                eTagValue = await this.UploadHistoryBatch(instanceId, executionId, historyEventBatch, newEventListBuffer, newEvents.Count, eTagValue);
            }

            if (orchestratorEventType == EventType.ExecutionCompleted ||
                orchestratorEventType == EventType.ExecutionFailed ||
                orchestratorEventType == EventType.ExecutionTerminated)
            {
                this.eTagValues.TryRemove(instanceId, out _);
            }
            else
            {
                this.eTagValues[instanceId] = eTagValue;
            }

            Stopwatch orchestrationInstanceUpdateStopwatch = Stopwatch.StartNew();

            await this.instancesTable.ExecuteAsync(TableOperation.InsertOrMerge(orchestrationInstanceUpdate));

            this.stats.StorageRequests.Increment();
            this.stats.TableEntitiesWritten.Increment();

            AnalyticsEventSource.Log.InstanceStatusUpdate(
                this.storageAccountName,
                this.taskHubName,
                instanceId,
                executionId,
                orchestratorEventType?.ToString() ?? string.Empty,
                orchestrationInstanceUpdateStopwatch.ElapsedMilliseconds);
        }
        public override void ReadEntity(IDictionary<string, EntityProperty> properties,
            OperationContext operationContext)
        {
            InstanceId = GetValue("InstanceId", properties, property => property.StringValue);
            ExecutionId = GetValue("ExecutionId", properties, property => property.StringValue);
            SequenceNumber = GetValue("SequenceNumber", properties, property => property.Int32Value).GetValueOrDefault();
            TaskTimeStamp =
                GetValue("TaskTimeStamp", properties, property => property.DateTimeOffsetValue)
                    .GetValueOrDefault()
                    .DateTime;

            string serializedHistoryEvent = GetValue("HistoryEvent", properties, property => property.StringValue);
            HistoryEvent = JsonConvert.DeserializeObject<HistoryEvent>(serializedHistoryEvent,
                new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.Objects});
        }