Exemplo n.º 1
0
        public async Task FaultedAsync(WorkQueueItem item)
        {
            using (var databaseConnection = TryCreateConnection())
            {
                if (databaseConnection == null)
                {
                    return;
                }

                databaseConnection.Open();
                await _DatabaseMigrator.Migrate(databaseConnection, "SqliteWorkqueue");

                using (var transaction = databaseConnection.BeginTransaction().NotNull())
                {
                    var json = item.Payload.ToString();
                    var hash = _Hasher.Hash(json);
                    try
                    {
                        await databaseConnection.ExecuteAsync(
                            "INSERT INTO faulted (type, payload, hash) VALUES (@Type, @Payload, @Hash)", new { item.Type, Payload = json, Hash = hash },
                            transaction).NotNull();
                    }
                    catch (SqliteException ex) when(ex.SqliteErrorCode == _SqliteConstraintViolationErrorCode)
                    {
                        // ignored
                    }

                    transaction.Commit();
                }
            }
        }
Exemplo n.º 2
0
 private static int GetStage(WorkQueueItem item)
 {
     // read the current stage from the work item
     return(item.ExtendedProperties.ContainsKey(StageProperty)
                                 ? int.Parse(item.ExtendedProperties[StageProperty])
                                 : 0);
 }
Exemplo n.º 3
0
        private void WorkQueueItemSuspend_OnExecuteCode(object sender, EventArgs e)
        {
            Success = false;

            if (WorkflowSteps == null)
            {
                WorkflowSteps = new System.Collections.Generic.List <Mercury.Server.Workflows.WorkflowStep> ();
            }


            //Server.Core.Work.WorkQueueItem workQueueItem = Application.WorkQueueItemGet (WorkQueueItemId);

            //if (workQueueItem == null) { RaiseActivityException ("Unable to retreive Work Queue Item [" + WorkQueueItemId.ToString () + "]."); }


            WorkQueueItem.SelfAssign("Workflow Suspend Work Queue Item", false);

            Success = WorkQueueItem.Suspend(WorkflowLastStep, WorkflowNextStep, ConstraintDays, MilestoneDays, ReleaseItem);

            if (!Success)
            {
                RaiseActivityException(Application.LastException.Message);
            }


            WorkflowStepsAdd("Suspend for Next Step: " + WorkflowNextStep + "  |  Constraint Days: " + ConstraintDays.ToString() + "  |  Milestone Days: " + MilestoneDays.ToString());

            Application.WorkQueueItemWorkflowStepsSave(WorkQueueItem.Id, WorkflowSteps);

            // WorkflowSteps = WorkQueueItem.WorkflowStepsGet ();

            return;
        }
Exemplo n.º 4
0
        protected override void ActOnItem(WorkQueueItem item)
        {
            // We need to know if the target still exist.  Use the default entity flag, rather than proxy.
            var target = PersistenceScope.CurrentContext.Load <Entity>(MergeWorkQueueItem.GetTargetRef(item), EntityLoadFlags.None);

            if (target == null)
            {
                throw new TargetAlreadyDeletedException();                  // target has already been deleted somewhere else.  Nothing to act on.
            }
            var handler = CollectionUtils.SelectFirst <IMergeHandler>(
                new MergeHandlerExtensionPoint().CreateExtensions(), h => h.SupportsTarget(target));

            if (handler == null)
            {
                throw new NotSupportedException(
                          string.Format("No extension found that supports merging entities of class {0}.", target.GetClass().FullName));
            }

            var stage = GetStage(item);

            Platform.Log(LogLevel.Info, "Starting merge step on target {0} (stage {1})...", target.GetRef(), stage);

            var nextStage = handler.Merge(target, stage, PersistenceScope.CurrentContext);

            Platform.Log(LogLevel.Info, "Completed merge step on target {0} (stage {1}, next stage is {2}).", target.GetRef(), stage, nextStage);

            // update the work item with the new stage value
            item.ExtendedProperties[StageProperty] = nextStage.ToString();
        }
Exemplo n.º 5
0
        public static WorkQueueItem Create(EntityRef targetRef)
        {
            var workQueueItem = new WorkQueueItem(Tag);

            workQueueItem.ExtendedProperties.Add("Target", targetRef.Serialize());
            return(workQueueItem);
        }
Exemplo n.º 6
0
        public void TriesAreDecremented()
        {
            var work = new WorkQueueItem(() =>
            {
                throw new ArgumentException();
            }, 3, new[] { typeof(ArgumentException) });

            var result = work.DoWork();

            Assert.That(result.Success, Is.False);
            Assert.That(result.ShouldRetry, Is.True);
            Assert.That(result.Tries, Is.EqualTo(2));

            result = work.DoWork();

            Assert.That(result.Success, Is.False);
            Assert.That(result.ShouldRetry, Is.True);
            Assert.That(result.Tries, Is.EqualTo(1));

            result = work.DoWork();

            Assert.That(result.Success, Is.False);
            Assert.That(result.ShouldRetry, Is.False);
            Assert.That(result.Tries, Is.EqualTo(0));
        }
Exemplo n.º 7
0
        public void ResumeWorkflow(NativeActivityContext context, Bookmark bookmark, Object workflowManager)
        {
            // REMOVE THE BOOKMARK SO THAT IT CAN BE USED AGAIN

            context.RemoveBookmark(context.WorkflowInstanceId.ToString());


            // RESET WORKFLOW MANAGER INSTANCE

            WorkflowManager.Set(context, workflowManager);

            WorkflowManager.Get(context).WorkflowStatus = WorkflowStatus.Resumed;


            // RECORD WORKFLOW STEPS

            Workflows.Activities.CommonFunctions.WorkflowStepsAdd(

                WorkflowManager.Get(context).Application,

                1,

                WorkQueueItem.Get(context).Id,

                WorkflowSteps.Get(context),

                "Resume Workflow"

                );

            return;
        }
Exemplo n.º 8
0
        private static void EnqueueWorkItem(ReportPart reportPart, ExtensionInfo publicationAction)
        {
            var workQueueItem = new WorkQueueItem("Publication Action");

            workQueueItem.ExtendedProperties.Add("ReportPartRef", reportPart.GetRef().Serialize());
            workQueueItem.ExtendedProperties.Add("ActionType", publicationAction.ExtensionClass.FullName);
            PersistenceScope.CurrentContext.Lock(workQueueItem, DirtyState.New);
        }
        protected override void ActOnItem(Procedure procedure)
        {
            // create the workqueue item
            TimeSpan      expirationTime = TimeSpan.FromHours(_settings.ExpirationTime);
            WorkQueueItem item           = ImageAvailabilityWorkQueue.CreateWorkQueueItem(procedure, expirationTime);

            PersistenceScope.CurrentContext.Lock(item, DirtyState.New);
        }
Exemplo n.º 10
0
 protected void EnqueueWorkItem(WorkQueueItem workItem)
 {
     if (!new LogicalHL7EventSettings().EnableEvents)
     {
         return;
     }
     PersistenceScope.CurrentContext.Lock(workItem, DirtyState.New);
 }
Exemplo n.º 11
0
        /// <summary>
        /// Creates a new work item.
        /// </summary>
        /// <param name="p"></param>
        /// <param name="expirationTime"></param>
        /// <returns></returns>
        public static WorkQueueItem CreateWorkQueueItem(Procedure p, TimeSpan expirationTime)
        {
            WorkQueueItem item = new WorkQueueItem(WorkQueueItemType);

            item.ExpirationTime = Platform.Time.Add(expirationTime);
            item.ExtendedProperties.Add(ProcedureOIDKey, p.GetRef().Serialize());

            return(item);
        }
Exemplo n.º 12
0
        private void MarryTag(WorkQueueItem wqi, string tag)
        {
            if (string.IsNullOrWhiteSpace(tag))
            {
                return;
            }
            var tagItem = TagResolver.Instance.Get(tag);

            _db.ExecuteNonQuery("INSERT INTO BPAWorkQueueItemTag VALUES ({0}, {1})".FormatSql(wqi.Ident, tagItem.Id));
        }
Exemplo n.º 13
0
            public void EnqueueEvents(Order order)
            {
                var queueItem = new WorkQueueItem(WorkQueueItemType);

                queueItem.ExtendedProperties.Add("EventType", this.EventType);
                queueItem.ExtendedProperties.Add("OrderOID", order.OID.ToString());
                queueItem.ExtendedProperties.Add("AccessionNumber", order.AccessionNumber);

                EnqueueWorkItem(queueItem);
            }
Exemplo n.º 14
0
        public void ResultCanBeCalledMultipleTimes()
        {
            var work = new WorkQueueItem(() => { }, 1);

            work.DoWork();

            var result1 = work.Result;
            var result2 = work.Result;

            Assert.That(result1, Is.EqualTo(result2));
        }
        protected override void ActOnItem(WorkQueueItem item)
        {
            var actionType    = item.ExtendedProperties["ActionType"];
            var action        = (IPublicationAction) new PublicationActionExtensionPoint().CreateExtension(new ClassNameExtensionFilter(actionType));
            var reportPartRef = new EntityRef(item.ExtendedProperties["ReportPartRef"]);
            var reportPart    = PersistenceScope.CurrentContext.Load <ReportPart>(reportPartRef, EntityLoadFlags.None);

            Platform.Log(LogLevel.Info, String.Format("Processing Publication Action {0} for report part {1}", actionType, reportPart.OID));

            action.Execute(reportPart, PersistenceScope.CurrentContext);
        }
Exemplo n.º 16
0
        internal static TResult DoDeviceOperation <TResult>(this ZWaveDevice device, Func <TResult> operation)
        {
            var wasConnected = device.IsConnected;
            var network      = (ZWaveNetwork)device.Network;
            var workQueue    = network.WorkQueue;

            var retries = wasConnected == true ? InitiallyConnectedRetries : InitiallyDisconnectedRetries;

            var result = default(TResult);

            var work = new WorkQueueItem(() =>
            {
                result = operation();
            }, retries, typeof(ControlThink.ZWave.ZWaveException));

            workQueue.Add(work);

            var workResult = work.Result;

            if (workResult.Success)
            {
                device.IsConnected = true;

                if (wasConnected != true)
                {
                    var @event = DeviceEvent.Found(device, null);
                    device.AddEvent(@event);
                }

                return(result);
            }

            device.IsConnected = false;

            if (wasConnected == true)
            {
                var @event = DeviceEvent.Lost(device, null);
                device.AddEvent(@event);
            }

            var exception = workResult.Exception;

            if (exception is ControlThink.ZWave.DeviceNotRespondingException)
            {
                throw new DeviceNotRespondingException(device, exception);
            }

            if (exception is ControlThink.ZWave.CommandTimeoutException)
            {
                throw new CommandTimedOutException(device, exception);
            }

            throw new HomeAutomationException("Unexpected Z-Wave error: " + exception.Message, exception);
        }
        protected override void ActOnItem(WorkQueueItem item)
        {
            var logicalEvent = new LogicalHL7EventArgs(item);

            Platform.Log(LogLevel.Info, String.Format("Procssing HL7LogicalEvent {0}", item.OID));

            foreach (ILogicalHL7EventListener listener in new LogicalHL7EventListenerExtensionPoint().CreateExtensions())
            {
                listener.OnEvent(logicalEvent);
            }
        }
        protected override bool ShouldReschedule(WorkQueueItem item, Exception error, out DateTime rescheduleTime)
        {
            if (error == null)
            {
                return(base.ShouldReschedule(item, null, out rescheduleTime));
            }

            //todo: should we retry? things might end up being processed out of order
            rescheduleTime = Platform.Time + _failedItemRetryDelay;
            return(true);
        }
Exemplo n.º 19
0
        public Task FaultedAsync(WorkQueueItem item)
        {
            if (!IsEnabled)
            {
                return(Task.CompletedTask);
            }

            WriteToFile(new { item.Type, item.Payload }, ".faulted");

            return(Task.CompletedTask);
        }
Exemplo n.º 20
0
            public void EnqueueEvents(PatientProfile patientProfile)
            {
                var queueItem = new WorkQueueItem(WorkQueueItemType);

                queueItem.ExtendedProperties.Add("EventType", this.EventType);
                queueItem.ExtendedProperties.Add("PatientOID", patientProfile.Patient.OID.ToString());
                queueItem.ExtendedProperties.Add("PatientProfileOID", patientProfile.OID.ToString());
                queueItem.ExtendedProperties.Add("Mrn", patientProfile.Mrn.ToString());

                EnqueueWorkItem(queueItem);
            }
Exemplo n.º 21
0
        public void DoWorkWillRetryForChildrenOfRetryExceptions()
        {
            var work = new WorkQueueItem(() =>
            {
                throw new ArgumentNullException();
            }, 2, new[] { typeof(ArgumentException) });

            var result = work.DoWork();

            Assert.That(result.Success, Is.False);
            Assert.That(result.ShouldRetry, Is.True);
        }
Exemplo n.º 22
0
        public void DoWorkDoesTheWork()
        {
            var actionCompleted = false;

            var work = new WorkQueueItem(() => actionCompleted = true, 1);

            var result = work.DoWork();

            Assert.That(actionCompleted, Is.True);
            Assert.That(result.Success, Is.True);
            Assert.That(result.ShouldRetry, Is.False);
        }
Exemplo n.º 23
0
        public void DoWorkWillNotRetryForRetryExceptions()
        {
            var work = new WorkQueueItem(() =>
            {
                throw new FileLoadException();
            }, 2, new[] { typeof(ArgumentException) });

            var result = work.DoWork();

            Assert.That(result.Success, Is.False);
            Assert.That(result.ShouldRetry, Is.False);
        }
Exemplo n.º 24
0
        private void RestartItemAtStageZero(WorkQueueItem item)
        {
            var nextStage = 0;

            Platform.Log(LogLevel.Info,
                         "Failed to complete merge step on target {0} (stage {1}).  Restarting at stage {2}.",
                         MergeWorkQueueItem.GetTargetRef(item),
                         GetStage(item),
                         nextStage);

            // update the work item with the new stage value
            item.ExtendedProperties[StageProperty] = nextStage.ToString();
        }
Exemplo n.º 25
0
        private void ConsiderItemCompletedSuccessfully(WorkQueueItem item)
        {
            var nextStage = -1;

            Platform.Log(LogLevel.Info,
                         "Failed to complete merge step on target {0} (stage {1}) because target has already been deleted.  Setting to stage {2}.",
                         MergeWorkQueueItem.GetTargetRef(item),
                         GetStage(item),
                         nextStage);

            item.Complete();
            item.ExtendedProperties[StageProperty] = nextStage.ToString();
        }
Exemplo n.º 26
0
        private void WorkQueueItemClose_CodeExecution(object sender, EventArgs e)
        {
            Success = false;

            if (WorkflowSteps == null)
            {
                WorkflowSteps = new System.Collections.Generic.List <Mercury.Server.Workflows.WorkflowStep> ();
            }


            //Server.Core.Work.WorkQueueItem workQueueItem = Application.WorkQueueItemGet (WorkQueueItemId);

            //if (workQueueItem == null) { RaiseActivityException ("Unable to retreive Work Queue Item [" + WorkQueueItemId.ToString () + "]."); }

            Server.Core.Work.WorkOutcome workOutcome = Application.WorkOutcomeGet(WorkOutcomeName);

            if (workOutcome == null)
            {
                RaiseActivityException("Unable to retreive Work Outcome [" + WorkOutcomeName.ToString() + "].");
            }


            if (!String.IsNullOrWhiteSpace(WorkflowLastStep))
            {
                WorkQueueItem.WorkflowLastStep = WorkflowLastStep;
            }

            Success = WorkQueueItem.Close(workOutcome.Id, false);

            Exception lastException = Application.LastException;

            Application.WorkQueueItemWorkflowStepsSave(WorkQueueItem.Id, WorkflowSteps);  // CLEARS APPLICATION.LASTEXCEPTION

            if (!Success)
            {
                if (lastException != null)
                {
                    RaiseActivityException(lastException.Message);
                }

                else
                {
                    RaiseActivityException("Unable to successfully close Work Queue Item, might already be marked as closed.");
                }
            }

            WorkflowStepsAdd(WorkflowCloseStepStatus, WorkOutcomeName);

            return;
        }
Exemplo n.º 27
0
        private static WorkQueueItem Create(
            string accessionNumber,
            EntityRef reportRef,
            EntityRef practitionerRef,
            EntityRef contactPointRef)
        {
            var workQueueItem = new WorkQueueItem("Mail/Fax Report");

            workQueueItem.ExtendedProperties.Add("AccessionNumber", accessionNumber);
            workQueueItem.ExtendedProperties.Add("ReportOID", reportRef.ToString(false, false));
            workQueueItem.ExtendedProperties.Add("ExternalPractitionerOID", practitionerRef.ToString(false, false));
            workQueueItem.ExtendedProperties.Add("ExternalPractitionerContactPointOID", contactPointRef.ToString(false, false));

            return(workQueueItem);
        }
Exemplo n.º 28
0
        protected override bool ShouldReschedule(WorkQueueItem item, Exception error, out DateTime retryTime)
        {
            var stage = GetStage(item);

            // a stage value of -1 signals that the merge operation is complete
            if (stage == -1)
            {
                retryTime = DateTime.MaxValue;
                return(false);
            }

            // re-schedule
            retryTime = Platform.Time + _throttleInterval;
            return(true);
        }
Exemplo n.º 29
0
        public void DoWorkCatchesExceptions()
        {
            var exception = new Exception();

            var work = new WorkQueueItem(() =>
            {
                throw exception;
            }, 1);

            var result = work.DoWork();

            Assert.That(result.Success, Is.False);
            Assert.That(result.ShouldRetry, Is.False);
            Assert.That(result.Exception, Is.EqualTo(exception));
        }
Exemplo n.º 30
0
        protected override void OnItemFailed(WorkQueueItem item, Exception error)
        {
            if (error is CannotDeleteException)
            {
                RestartItemAtStageZero(item);
                return;
            }

            if (error is TargetAlreadyDeletedException)
            {
                ConsiderItemCompletedSuccessfully(item);
                return;
            }

            base.OnItemFailed(item, error);
        }