Exemplo n.º 1
0
        /// <summary>
        /// Runs when the activity is run by the workflow.
        /// </summary>
        /// <param name="context">The run state.</param>
        /// <param name="inputs">The inputs.</param>
        void IRunNowActivity.OnRunNow(IRunState context, ActivityInputs inputs)
        {
            var text           = GetArgumentValue <string>(inputs, "inLogActivityMessage");
            var refencedObject = GetArgumentEntity <UserResource>(inputs, "inLogActivityObject");

            IEntity logEntry;

            if (refencedObject != null)
            {
                logEntry = new LogActivityResourceLogEntry
                {
                    ObjectReferencedInLog = refencedObject,
                    ReferencedObjectName  = refencedObject.Name
                };
            }
            else
            {
                logEntry = new LogActivityLogEntry();
            }

            logEntry.SetField(WorkflowRunLogEntry.Name_Field, ActivityInstance.Name);
            logEntry.SetField(WorkflowRunLogEntry.Description_Field, text);

            context.Log(logEntry);

            // Provide some context information to the log message
            EventLog.Application.WriteInformation(string.Format("Log | {1} | Message: {2}", DateTime.UtcNow.Ticks, context.GetSafeWorkflowDescription(), text));
        }
        void IRunNowActivity.OnRunNow(IRunState context, ActivityInputs inputs)
        {
            var res = (IEntity)inputs[GetArgumentKey("updateFieldActivityResourceArgument")];

            IEntity entityToUpdate = null;

            try
            {
                if (res != null)
                {
                    entityToUpdate = res.AsWritable();
                }
            }
            catch
            {
                // ignore
            }

            if (entityToUpdate == null)
            {
                throw new WorkflowRunException_Internal("Input resource argument must be a resource", null);
            }

            var activityAs = ActivityInstance.Cast <EntityWithArgsAndExits>();

            Action <IEntity> updateAction = (e) => UpdateArgsHelper.UpdateEntityFromArgs(activityAs, inputs, e);

            PerformUpdate(entityToUpdate, updateAction);
        }
        bool IResumableActivity.OnStart(IRunState context, ActivityInputs inputs)
        {
            Workflow workflowToProxy;

            using (CustomContext.SetContext(context.EffectiveSecurityContext))
            {
                workflowToProxy = ActivityInstance.As <WorkflowProxy>().WorkflowToProxy;
            }
            var wfArgs = workflowToProxy.As <WfActivity>().GetInputArguments().Select(arg => arg.Name);

            // copy across matching arguments. Arguments that are supplied that are not used are ignored.
            var matchingInputs = inputs.Where(kvp => wfArgs.Contains(kvp.Key.Name)).ToDictionary(kvp => kvp.Key.Name, kvp => kvp.Value);

            if (inputs.Count != matchingInputs.Count)    // We have some mismatched parameters
            {
                var expected = String.Join(", ", wfArgs);
                var actual   = String.Join(", ", inputs.Select(i => i.Key.Name));
                throw new WorkflowRunException($"Mismatched inputs to workflow. (Have the proxied workflows inputs changed?)\n   Expected: {expected}\n   Actual: {actual}");
            }

            context.WorkflowInvoker.PostEvent(new ChildWorkflowStartEvent(workflowToProxy, matchingInputs, context.WorkflowRun));

            // note, we always rely on the resume for handling the completion.
            return(false);
        }
        /// <summary>
        /// Get a list of entities.
        /// </summary>
        /// <typeparam name="T">The entity type.</typeparam>
        /// <param name="inputs">The input arguments.</param>
        /// <param name="paramAlias">The parameter alias.</param>
        /// <returns>The list of entities.</returns>
        protected IEnumerable <T> GetArgumentEntityList <T>(ActivityInputs inputs, string paramAlias) where T : class, IEntity
        {
            var obj = GetArgumentValue_imp(inputs, paramAlias);

            if (obj == null)
            {
                return(Enumerable.Empty <T>());
            }

            var list = obj as IEnumerable <T>;

            if (list != null)
            {
                return(list);
            }

            var list2 = obj as IEnumerable <IEntity>;

            if (list2 != null)
            {
                return(list2.Select(m => m.Cast <T>()));
            }

            return(GetArgumentEntity <T>(inputs, paramAlias).ToEnumerable());
        }
Exemplo n.º 5
0
        /// <summary>
        /// Runs when the activity is run by the workflow.
        /// </summary>
        /// <param name="context">The run state.</param>
        /// <param name="inputs">The inputs.</param>
        void IRunNowActivity.OnRunNow(IRunState context, ActivityInputs inputs)
        {
            using (Profiler.Measure("ExportToImplementation.OnRunNow"))
            {
                var name   = GetArgumentValue <string>(inputs, "inExportToName");
                var report = GetArgumentEntity <Report>(inputs, "inExportToReport");
                var format = GetArgumentEntity <ExportFileTypeEnum>(inputs, "inExportToFormat");

                if (String.IsNullOrWhiteSpace(name))
                {
                    name = GenerateName(report.Name);
                }

                var description = string.Format(DescriptionFormat, report.Name ?? "[Unnamed]", DateTime.Now.ToShortTimeString());

                Document generatedDoc;

                using (CustomContext.SetContext(context.EffectiveSecurityContext))
                {
                    var timeZone = RequestContext.GetContext().TimeZone ?? TimeZoneHelper.SydneyTimeZoneName;

                    generatedDoc = ExportTo(report, name, description, timeZone, ToExportFormat(format));
                }

                context.SetArgValue(ActivityInstance, GetArgumentKey("core:outExportToDoc"), generatedDoc);
            }
        }
Exemplo n.º 6
0
        void IRunNowActivity.OnRunNow(IRunState context, ActivityInputs inputs)
        {
            var ResourceTypeToCreateKey = GetArgumentKey("createActivityResourceArgument");
            var CreatedResourceKey      = GetArgumentKey("createActivityCreatedResource");

            IEntity newEntity = null;

            var resTypeRef = (IEntity)inputs[ResourceTypeToCreateKey];
            var resType    = resTypeRef?.As <EntityType>();

            if (resType == null)
            {
                throw new WorkflowRunException_Internal("Input resource argument must be a type.", null);
            }

            var activityAs = ActivityInstance.Cast <EntityWithArgsAndExits>();
            Action <IEntity> updateAction = (e) => UpdateArgsHelper.UpdateEntityFromArgs(activityAs, inputs, e);


            DatabaseContext.RunWithRetry(() =>
            {
                newEntity = PerformCreate(resType, updateAction);
            });

            context.SetArgValue(ActivityInstance, CreatedResourceKey, newEntity);
        }
        void IRunNowActivity.OnRunNow(IRunState context, ActivityInputs inputs)
        {
            _activityInputs = inputs;
            try
            {
                if (string.IsNullOrEmpty(TenantEmailSetting.SmtpServer))
                {
                    throw new Exception("smtpServer has not been specified.");
                }

                var sendEmailRecipientsType = GetArgumentValue <Resource>(inputs, "core:sendEmailRecipientsType");

                var sentEmailMessages = new List <SentEmailMessage>();
                if (string.IsNullOrEmpty(sendEmailRecipientsType?.Alias) || (sendEmailRecipientsType?.Alias == "core:sendEmailActivityRecipientsAddress"))
                {
                    sentEmailMessages.Add(GenerateEmailToRecipientsExpression());
                }
                else
                {
                    var sendEmailDistributionType = GetArgumentValue <Resource>(inputs, "core:sendEmailDistributionType");
                    if (string.IsNullOrEmpty(sendEmailDistributionType?.Alias) || (sendEmailDistributionType?.Alias == "core:sendEmailActivityGroupDistribution"))
                    {
                        sentEmailMessages.Add(GenerateGroupEmailsToRecipientsList());
                    }
                    else
                    {
                        sentEmailMessages.AddRange(GenerateIndividualEmailsToRecipientsList());
                    }
                }

                var mailMessages = new List <MailMessage>();
                sentEmailMessages.RemoveAll(msg => string.IsNullOrEmpty(msg.EmTo) && string.IsNullOrEmpty(msg.EmCC) && string.IsNullOrEmpty(msg.EmBCC));
                sentEmailMessages.RemoveAll(msg => string.IsNullOrEmpty(msg.EmSubject));
                sentEmailMessages.ForEach(msg =>
                {
                    msg.EmSentDate = DateTime.UtcNow;
                    msg.Save();
                    mailMessages.Add(msg.ToMailMessage());
                });

                RecordInfoToUserLog(context, $"Sending {sentEmailMessages.Count} emails");

                if (sentEmailMessages.Count == 0)
                {
                    context.ExitPointId = Entity.GetId("core:sendEmailSucceededSend");
                    return;
                }

                EmailSender.SendMessages(mailMessages);

                context.SetArgValue(ActivityInstance, GetArgumentKey("core:outSentEmailMessages"), sentEmailMessages);
                context.ExitPointId = Entity.GetId("core:sendEmailSucceededSend");
            }
            catch (Exception ex)
            {
                RecordErrorToUserLog(context, ex);
                context.ExitPointId = Entity.GetId("core:sendEmailFailedSend");
            }
        }
Exemplo n.º 8
0
        void IRunNowActivity.OnRunNow(IRunState context, ActivityInputs inputs)
        {
            var activityAs    = ActivityInstance.Cast <AssignToVariable>();
            var valueArgument = Entity.Get <ActivityArgument>("assignValueArgument", Resource.Name_Field);
            var targetVar     = activityAs.TargetVariable;

            context.SetArgValue(targetVar, inputs[valueArgument]);
        }
Exemplo n.º 9
0
        void IRunNowActivity.OnRunNow(IRunState context, ActivityInputs inputs)
        {
            var haveStarted         = GetArgumentKey("forEachHaveStarted");
            var foreachList         = GetArgumentKey("forEachResourceList");
            var resourceListKey     = GetArgumentKey("foreachList");
            var selectedResourceKey = GetArgumentKey("foreachSelectedResource");


            IEnumerable <IEntity> resourceList;


            if (!(context.GetArgValue <bool?>(ActivityInstance, haveStarted) ?? false))
            {
                context.SetArgValue(ActivityInstance, haveStarted, true);

                //
                // it's the first time into the loop
                //
                object listObj;
                if (inputs.TryGetValue(resourceListKey, out listObj))
                {
                    if (listObj == null)
                    {
                        throw new ApplicationException("The [List] argument is null. This should never happen.");
                    }

                    resourceList = (IEnumerable <IEntity>)listObj;
                }
                else
                {
                    throw new ApplicationException("The [List] is missing from the input arguments. This should never happen.");
                }
            }
            else
            {
                resourceList = context.GetArgValue <IEnumerable <IEntity> >(ActivityInstance, foreachList);
            }

            var selectedResourceRef = resourceList.FirstOrDefault();


            if (selectedResourceRef != null)
            {
                context.SetArgValue(ActivityInstance, selectedResourceKey, selectedResourceRef);
                resourceList = resourceList.Skip(1);
                context.SetArgValue(ActivityInstance, foreachList, resourceList);
                context.ExitPointId = Entity.GetId(LoopExitPointAlias);
            }
            else
            {
                // We have finished
                context.SetArgValue(ActivityInstance, haveStarted, false);
                context.SetArgValue(ActivityInstance, foreachList, null);
                context.ExitPointId = Entity.GetId("core", "foreachCompletedExitPoint");
            }
        }
Exemplo n.º 10
0
        //private const string ClonedNameFormat = "{0} (clone)";

        void IRunNowActivity.OnRunNow(IRunState context, ActivityInputs inputs)
        {
            using (Profiler.MeasureAndSuppress("CloneImplementation.OnRunNow"))
            {
                var resourceKey   = GetArgumentKey("resourceToCloneArgument");
                var definitionKey = GetArgumentKey("newDefinitionCloneArgument");
                var clonedKey     = GetArgumentKey("clonedResourceArgument");

                var resId    = (IEntity)inputs[resourceKey];
                var resource = resId.As <Resource>();

                IEntity clone = null;

                EntityType cloneType = null;


                object definitionObj;
                if (inputs.TryGetValue(definitionKey, out definitionObj))
                {
                    if (definitionObj != null)
                    {
                        cloneType = ((IEntity)definitionObj).As <EntityType>();
                    }
                }

                try
                {
                    using (CustomContext.SetContext(context.EffectiveSecurityContext))
                    {
                        using (var ctx = DatabaseContext.GetContext(true))
                        {
                            var activityAs = ActivityInstance.Cast <EntityWithArgsAndExits>();

                            Action <IEntity> updateAction = c => UpdateArgsHelper.UpdateEntityFromArgs(activityAs, inputs, c);

                            clone = CreateClone(resource, cloneType, updateAction);

                            clone.Save();

                            ctx.CommitTransaction();
                        }
                    };
                }
                catch (DuplicateKeyException ex)
                {
                    throw new WorkflowRunException("The Clone item failed during saving: " + ex.Message, ex);
                }
                catch (ValidationException ex)
                {
                    throw new WorkflowRunException("The Cloned item failed validation during saving: " + ex.Message, ex);
                }

                context.SetArgValue(ActivityInstance, clonedKey, clone);
            }
        }
        /// <summary>
        /// Give the argument alias, return the input, throw an exception if the input is undefined
        /// </summary>
        protected T GetArgumentValueStruct <T>(ActivityInputs input, string paramAlias) where T : struct
        {
            object o = GetArgumentValue_imp(input, paramAlias);

            if (o == null)
            {
                return(default(T));
            }

            return((T)o);
        }
        /// <summary>
        /// Start the activity running
        /// </summary>
        /// <returns>True if the activity has completed, false if it is paused. Along with a sequence number of if it is paused</returns>
        public override bool OnStart(IRunState context, ActivityInputs inputs)
        {
            var survey       = GetArgumentEntity <UserSurvey>(inputs, "inLaunchPersonSurvey");
            var recipients   = GetArgumentEntityList <Person>(inputs, "inLaunchPersonRecipients").ToList();
            var targetObject = GetArgumentEntity <UserResource>(inputs, "inLaunchPersonTarget");
            var taskName     = GetArgumentValue <string>(inputs, "inLaunchPersonTaskName");
            var dueInDays    = GetArgumentValue(inputs, "inLaunchPersonDueDays", 0m);
            var pause        = GetArgumentValue(inputs, "inLaunchPersonPause", false);

            // ensure that there is at least one recipient
            if (recipients.Count <= 0)
            {
                throw new WorkflowRunException("The recipients list for the Survey was empty.");
            }

            var campaign = Entity.Create <SurveyPersonCampaign>();

            campaign.Name = $"Person Campaign ({survey.Name})";
            campaign.SurveyForCampaign = survey;
            campaign.CampaignPersonRecipients.AddRange(recipients);
            if (dueInDays > 0)
            {
                campaign.SurveyClosesOn = DateTime.UtcNow.AddDays(decimal.ToDouble(dueInDays));
            }

            var tasks = campaign.Launch(campaign.SurveyClosesOn, targetObject, taskName).ToList();

            if (pause)
            {
                foreach (var task in tasks)
                {
                    // this will do the save for us.
                    context.SetUserTask(task.Cast <BaseUserTask>());
                }
            }
            else
            {
                Entity.Save(tasks);
            }

            var responses = tasks.Select(t => t.UserSurveyTaskSurveyResponse);

            context.SetArgValue(ActivityInstance, GetArgumentKey("core:outLaunchPersonResponses"), responses);

            // Deal with time-outs. Time-outs can only occur if there is due date and we are pausing.
            if (pause)
            {
                SetTimeoutIfNeeded(context, dueInDays);
            }

            // Note that there is no need to set an exit point if we are not pausing as the default exit point will be used.
            return(!pause);
        }
        /// <summary>
        /// Runs the activity.
        /// </summary>
        /// <param name="context">The run context.</param>
        /// <param name="inputs">The input parameters.</param>
        public void OnRunNow(IRunState context, ActivityInputs inputs)
        {
            var campaign = GetArgumentEntity <SurveyCampaign>(inputs, "inStartSurveyCampaign");

            var tasks = campaign.Launch().ToList();

            Entity.Save(tasks);

            var responses = tasks.Select(t => t.UserSurveyTaskSurveyResponse);

            context.SetArgValue(ActivityInstance, GetArgumentKey("core:outStartSurveyResponses"), responses);
        }
        /// <summary>
        /// Start the activity running
        /// </summary>
        /// <returns>True if the activity has completed, false if it is paused. Along with a sequence number of if it is paused</returns>
        public override bool OnStart(IRunState context, ActivityInputs inputs)
        {
            var assignedTo         = GetArgumentEntity <Person>(inputs, "inPromptUserForPerson");
            var promptMessage      = GetArgumentValue <string>(inputs, "inPromptUserMessage");
            var activityInstanceAs = ActivityInstance.Cast <PromptUserActivity>();

            var userTask = new PromptUserTask
            {
                Name                   = ActivityInstance.Name ?? "User input required",
                AssignedToUser         = assignedTo,
                TaskStatus_Enum        = TaskStatusEnum_Enumeration.TaskStatusNotStarted,
                UserTaskDueOn          = DateTime.UtcNow, // dueDate
                KeepAfterCompletion    = false,           // keepTask
                WaitForNextTask        = true,            // waitForNext
                PromptForTaskMessage   = promptMessage,
                PromptForTaskArguments = new EntityCollection <ActivityPrompt>(activityInstanceAs.PromptForArguments)
            };

            // move current state information on to the task for pre-population of any arguments for prompt
            var argValues = context.GetArgValues().ToList();

            foreach (var arg in activityInstanceAs.PromptForArguments)
            {
                var argValue = argValues.FirstOrDefault(a => a.Item2.Id == arg.ActivityPromptArgument.Id);
                if (argValue != null)
                {
                    var valueArg = ActivityArgumentHelper.ConvertArgInstValue(argValue.Item1, argValue.Item2, argValue.Item3);
                    userTask.PromptForTaskStateInfo.Add(new StateInfoEntry
                    {
                        Name = valueArg.Name,
                        StateInfoActivity = ActivityInstance,
                        StateInfoArgument = argValue.Item2,
                        StateInfoValue    = valueArg
                    });

                    continue;
                }

                var emptyArg = ActivityArgumentHelper.ConvertArgInstValue(ActivityInstance, arg.ActivityPromptArgument, null);
                userTask.PromptForTaskStateInfo.Add(new StateInfoEntry
                {
                    Name = emptyArg.Name,
                    StateInfoActivity = ActivityInstance,
                    StateInfoArgument = arg.ActivityPromptArgument,
                    StateInfoValue    = emptyArg
                });
            }

            context.SetUserTask(userTask.Cast <BaseUserTask>());

            return(false);
        }
        /// <summary>
        /// Give the argument alias, return the input, throw an exception if the input is undefined
        /// </summary>
        protected T GetArgumentEntity <T>(ActivityInputs input, string paramAlias) where T : class, IEntity
        {
            var o = (IEntity)GetArgumentValue_imp(input, paramAlias);

            if (o == null)
            {
                return(default(T));
            }
            else
            {
                return(o.Cast <T>());
            }
        }
Exemplo n.º 16
0
        ///// <summary>
        ///// Update all the output arguments
        ///// </summary>
        //void UpdateWfOutputs(IRunState context, Dictionary<WfExpression, object> resolvedExpressions)
        //{
        //    UpdateWorkflowArguments(context, resolvedExpressions);
        //}

        /// <summary>
        /// Create an input dictionary using the applicable values in the ArgumentValueStore
        /// </summary>
        ActivityInputs CreateInputDictionaryForNextStep(IRunState context, WfActivity nextActivity, Dictionary <WfExpression, object> evaluatedExpressions)
        {
            var result = new ActivityInputs();

            // add expressions
            foreach (var kvp in evaluatedExpressions)
            {
                var arg = kvp.Key.ArgumentToPopulate;
                result.Add(arg, kvp.Value);
            }

            return(result);
        }
Exemplo n.º 17
0
        bool IResumableActivity.OnStart(IRunState context, ActivityInputs inputs)
        {
            bool hasCompleted = true;

            MapInitialInput(context, inputs);

            var nextActivity = _activityInstanceAsWf.FirstActivity;

            ScheduleNextStep(context, nextActivity);

            hasCompleted = context.WorkflowInvoker.RunTillCompletion(context);

            return(hasCompleted);
        }
Exemplo n.º 18
0
        void IRunNowActivity.OnRunNow(IRunState context, ActivityInputs inputs)
        {
            var ResourceToUpdateKey = GetArgumentKey("setChoiceActivityResourceArgument");
            var ValueKey            = GetArgumentKey("setChoiceActivityValueArgument");
            var FieldKey            = GetArgumentKey("setChoiceActivityFieldArgument");
            var replaceExistingKey  = GetArgumentKey("setChoiceActivityReplaceExisting");

            var choiceToUpdateRef = (IEntity)inputs[FieldKey];
            var resId             = (IEntity)inputs[ResourceToUpdateKey];
            var valueId           = (IEntity)inputs[ValueKey];

            bool replaceExisting = false;

            object replaceExistingObj;

            if (inputs.TryGetValue(replaceExistingKey, out replaceExistingObj))
            {
                replaceExisting = (bool?)replaceExistingObj ?? false;
            }

            var relationship = choiceToUpdateRef.As <Relationship>();

            SecurityBypassContext.RunAsUser(() =>
            {
                var resource = resId.AsWritable();    // Does not have to be a writeable copy because we are only manipulating relationships.

                var cardinality = relationship.Cardinality_Enum ?? CardinalityEnum_Enumeration.ManyToMany;

                replaceExisting =
                    replaceExisting
                    ||
                    cardinality == CardinalityEnum_Enumeration.OneToOne
                    ||
                    cardinality == CardinalityEnum_Enumeration.ManyToOne;


                var relCollection = resource.GetRelationships(choiceToUpdateRef, Direction.Forward);        // you can't have a reverse choice field.

                if (replaceExisting)
                {
                    relCollection.Clear();
                }

                relCollection.Add(valueId);

                resource.Save();
            });
        }
        void IRunNowActivity.OnRunNow(IRunState context, ActivityInputs inputs)
        {
            var resource = GetArgumentEntity <Resource>(inputs, "core:createLinkResourceArgument");

            if (resource == null)
            {
                throw new WorkflowRunException("The 'Resource' argument is empty. It must have a value.");
            }

            string Url = NavigationHelper.GetResourceViewUrl(resource.Id).ToString();

            string anchor = string.Format("<a href='{0}'>{1}</a>", Url, XmlHelper.EscapeXmlText(resource.Name ?? "[Unnamed]"));

            context.SetArgValue(ActivityInstance, GetArgumentKey("core:createLinkUrlOutput"), Url);
            context.SetArgValue(ActivityInstance, GetArgumentKey("core:createLinkAnchorOutput"), anchor);
        }
        /// <summary>
        /// Give the argument alias, return the input or the default
        /// </summary>
        protected T GetArgumentValue <T>(ActivityInputs input, string paramAlias, T defaultValue)
        {
            object o;

            if (input.TryGetValue(GetArgumentKey(paramAlias), out o))
            {
                if (o == null)
                {
                    return(defaultValue);
                }
                return((T)o);
            }
            else
            {
                return(defaultValue);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Switch on the provided value
        /// </summary>

        void IRunNowActivity.OnRunNow(IRunState context, ActivityInputs inputs)
        {
            var valuetoSwitchOnKey = GetArgumentKey("switchActivityDecisionArgument");

            var result = (string)inputs[valuetoSwitchOnKey];

            var activityAs = ActivityInstance.Cast <EntityWithArgsAndExits>();

            var selectedExitPoint = activityAs.ExitPoints.FirstOrDefault(ep => ep.Name == result);

            if (selectedExitPoint == null)
            {
                selectedExitPoint = Entity.Get <ExitPoint>("switchActivityOtherwiseExitPoint");
            }

            context.ExitPointId = selectedExitPoint;
        }
        /// <summary>
        /// Execute an activity, return true if it completed. Fase if bookmarked
        /// </summary>
        /// <returns>True if the activity completed.</returns>
        public virtual bool Execute(IRunState runState, ActivityInputs inputs)
        {
            using (Profiler.Measure("ActivityImplementationBase.Execute " + GetType().Name))
            {
                bool hasCompleted = true;

                if (ActivityInstance == null)
                {
                    throw new Exception("IEdc activities need to be initalized before being executed.");
                }

                var thisAsRunNow = this as IRunNowActivity;

                if (thisAsRunNow != null)
                {
                    //
                    // Run Now
                    //
                    thisAsRunNow.OnRunNow(runState, inputs);

                    hasCompleted = true;
                }
                else
                {
                    //
                    // Resumable
                    //
                    var thisAsResumable = this as IResumableActivity;

                    if (thisAsResumable == null)
                    {
                        throw new ApplicationException("We have a non resumable non num now activity. This should never occur.");
                    }

                    hasCompleted = thisAsResumable.OnStart(runState, inputs);
                }

                if (hasCompleted && runState.ExitPointId == null)
                {
                    runState.ExitPointId = ActivityInstance.GetDefaultExitPoint();
                }

                return(hasCompleted);
            }
        }
Exemplo n.º 23
0
        void IRunNowActivity.OnRunNow(IRunState context, ActivityInputs inputs)
        {
            var typeRefKey   = GetArgumentKey("getResourcesResourceType");
            var reportRefKey = GetArgumentKey("getResourcesReport");
            var listKey      = GetArgumentKey("getResourcesList");
            var firstKey     = GetArgumentKey("getResourcesFirst");
            var countKey     = GetArgumentKey("getResourcesCount");

            object     o;
            EntityType resourceType = null;
            IEntity    reportRef    = null;

            if (inputs.TryGetValue(typeRefKey, out o))
            {
                if (o != null)
                {
                    resourceType = ((IEntity)o).As <EntityType>();
                }
            }

            if (inputs.TryGetValue(reportRefKey, out o))
            {
                if (o != null)
                {
                    reportRef = (IEntity)o;
                }
            }

            if (resourceType == null && reportRef == null)
            {
                throw new WorkflowRunException("Get Resources must have one of either the Type or Report parameters specified.");
            }


            IEnumerable <IEntity> list = null;

            SecurityBypassContext.RunAsUser(() =>
            {
                list = reportRef != null ? GetListFromReport(context, reportRef) : GetListFromType(resourceType);
            });

            context.SetArgValue(ActivityInstance, listKey, list);
            context.SetArgValue(ActivityInstance, firstKey, list.FirstOrDefault());
            context.SetArgValue(ActivityInstance, countKey, list.Count());
        }
Exemplo n.º 24
0
        void IRunNowActivity.OnRunNow(IRunState context, ActivityInputs inputs)
        {
            var resourceToDeleteKey = GetArgumentKey("deleteActivityResourceArgument");

            var res = (IEntity)inputs[resourceToDeleteKey];

            if (res == null)
            {
                throw new WorkflowRunException_Internal("No record provided.", null);
            }

            SecurityBypassContext.RunAsUser(() =>
            {
                Entity.Delete(res.Id);
            });

            context.RemoveReference(res.Id);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Run activity using its own context. The activity can not have any pending actions when it completes)
        /// </summary>
        /// <returns>True if the run completed.</returns>
        bool ProcessWorkflow(Workflow wf, IRunState runState, IWorkflowEvent wfEvent)
        {
            var activityInst = wf.Cast <WfActivity>();
            var activityImp  = activityInst.CreateWindowsActivity();

            var metadata = runState.Metadata;
            var invoker  = runState.WorkflowInvoker;

            if (!metadata.HasViolations)
            {
                var startEvent = wfEvent as WorkflowStartEvent;

                if (startEvent != null)
                {
                    var inputArgs = activityInst.GetInputArguments();
                    var inputs    = new ActivityInputs(inputArgs, startEvent.Arguments);

                    invoker.ScheduleActivity(runState, activityImp, inputs, null, null);
                }
                else
                {
                    invoker.ScheduleResume(runState, activityImp, wfEvent, null, null);
                }

                try
                {
                    var result = RunTillCompletion(invoker, runState);
                    return(result);
                }
                catch (PlatformSecurityException ex)
                {
                    throw new WorkflowRunException(ex.Message, ex);
                }
                catch (WorkflowRunException_Internal ex)
                {
                    throw new WorkflowRunException(ex.Message, ex.InnerException);
                }
            }

            var act = GetActivityForError(runState, activityInst);

            throw new WorkflowValidationException(runState.WorkflowRunId, act.ContainingWorkflow, act, metadata.ValidationMessages);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Use to pass the result of the expression evaluation
        /// </summary>

        void IRunNowActivity.OnRunNow(IRunState context, ActivityInputs inputs)
        {
            var decisionArgumentKey = GetArgumentKey("decisionActivityDecisionArgument");

            var result = (bool)inputs[decisionArgumentKey];

            EntityRef exitPoint;

            if (result)
            {
                exitPoint = new EntityRef("core", "decisionActivityYesExitPoint");
            }
            else
            {
                exitPoint = new EntityRef("core", "decisionActivityNoExitPoint");
            }

            context.ExitPointId = exitPoint;
        }
Exemplo n.º 27
0
        private const decimal DefaultTimeOutMins = 0;     // no time out


        public override bool OnStart(IRunState context, ActivityInputs inputs)
        {
            var users = GetArgumentEntityList(inputs, "inPeople");

            var message           = GetArgumentValue <String>(inputs, "inMessage");
            var waitForReplies    = GetArgumentValueStruct <bool>(inputs, "inWaitForReplies");
            var timeoutDays       = GetArgumentValue <decimal>(inputs, "inNotifyTimeOut", 0);
            var acceptRepliesDays = GetArgumentValue <decimal>(inputs, "inAcceptRepliesFor", 1);

            var linkToRecord = GetArgumentEntity <UserResource>(inputs, "inLinkToRecord");

            if (!Factory.Current.Resolve <INotifier>().IsConfigured)
            {
                throw new WorkflowRunException("No tenant notifier has been configured in tenant general settings.");
            }

            //
            // Notification needs to be created first to ensure that a fast response will not be processed before the notification is created
            //
            var effectiveUser = Entity.Get <UserAccount>(context.EffectiveSecurityContext.Identity.Id);

            var notification = Entity.Create <Notification>();

            notification.NMessage            = message;
            notification.SecurityOwner       = effectiveUser;           // The workflow runner can delete and update the notification and the send and replies.
            notification.NRelatedRecord      = linkToRecord;
            notification.NAcceptRepliesUntil = DateTime.UtcNow.AddDays(Convert.ToDouble(acceptRepliesDays));

            CopyReplyMap(context, notification);

            notification.Save();

            context.SetArgValue(ActivityInstance, GetArgumentKey("core:outNotificationRecord"), notification);

            if (waitForReplies)
            {
                SetTimeoutIfNeeded(context, timeoutDays);    // Note that there is no timeout exit.
            }

            SendMessagesInBackground(context, notification.Id, users.Select(u => u.Id).ToList(), waitForReplies);

            return(false);
        }
        /// <summary>
        /// Give the argument alias, return the input, throw an exception if the input is undefined
        /// </summary>
        private object GetArgumentValue_imp(ActivityInputs input, string paramAlias)
        {
            object o;

            if (input.TryGetValue(GetArgumentKey(paramAlias), out o))
            {
                return(o);
            }
            else
            {
                var arg = Entity.Get <ActivityArgument>(paramAlias, ActivityArgument.Name_Field, ActivityArgument.ArgumentIsMandatory_Field);

                if (arg.ArgumentIsMandatory ?? false)
                {
                    throw new ApplicationException(string.Format("Mandatory argument '{0}' is missing. This error should have been caught earlier in the code. This should never occur.", arg.Name));
                }

                return(null);
            }
        }
        /// <summary>
        /// Runs when the activity is run by the workflow.
        /// </summary>
        /// <param name="context">The run state.</param>
        /// <param name="inputs">The inputs.</param>
        void IRunNowActivity.OnRunNow(IRunState context, ActivityInputs inputs)
        {
            using (Profiler.Measure("GenerateDocImplementation.OnRunNow"))
            {
                var inGenerateDocTemplateKey = GetArgumentKey("inGenerateDocTemplate");
                var inGenerateDocNameKey     = GetArgumentKey("inGenerateDocName");
                var inGenerateDocSourceKey   = GetArgumentKey("inGenerateDocSource");

                var reportTemplate = ((IEntity)inputs[inGenerateDocTemplateKey]).As <ReportTemplate>();

                var name = inputs.ContainsKey(inGenerateDocNameKey) ? (string)inputs[inGenerateDocNameKey] : null;

                if (String.IsNullOrWhiteSpace(name))
                {
                    name = GenerateName(reportTemplate.Name);
                }

                var description = string.Format(DescriptionFormat, reportTemplate.Name ?? "[Unnamed]", DateTime.Now.ToShortTimeString());

                var sourceResource = inputs.ContainsKey(inGenerateDocSourceKey) ? ((IEntity)inputs[inGenerateDocSourceKey]) : null;

                Document generatedDoc;

                using (CustomContext.SetContext(context.EffectiveSecurityContext))
                {
                    var timeZone     = RequestContext.GetContext().TimeZone ?? TimeZoneHelper.SydneyTimeZoneName;
                    var templateFile = reportTemplate.ReportTemplateUsesDocument;

                    try
                    {
                        generatedDoc = GenerateDoc(templateFile, sourceResource, name, description, timeZone);
                    }
                    catch (DocGenException ex)
                    {
                        throw new WorkflowRunException(ex.Message);
                    }
                }

                context.SetArgValue(ActivityInstance, GetArgumentKey("core:outGenerateDocDoc"), generatedDoc);
            }
        }
        /// <summary>
        /// Get a list of entities. IF there is only one entity present, turn it into a list.
        /// If there isn't anything present, return an empty list.
        /// </summary>
        protected IEnumerable <IEntity> GetArgumentEntityList(ActivityInputs input, string paramAlias)
        {
            var o = GetArgumentValue_imp(input, paramAlias);

            if (o == null)
            {
                return(Enumerable.Empty <IEntity>());
            }

            var l = o as IEnumerable <IEntity>;

            if (l != null)
            {
                return(l);
            }
            else
            {
                // If it is a single entity, turn it into a list
                return(GetArgumentEntity <IEntity>(input, paramAlias).ToEnumerable());
            }
        }