Exemplo n.º 1
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            string activityTypeId = GetAttributeValue(action, "ActivityType");

            if (String.IsNullOrWhiteSpace(activityTypeId))
            {
                action.AddLogEntry("Invalid Activity Type Property");
                return(false);
            }

            var workflow = action.Activity.Workflow;

            var activityType = workflow.WorkflowType.ActivityTypes
                               .Where(a => a.Id.ToString() == activityTypeId).FirstOrDefault();

            if (activityType != null)
            {
                WorkflowActivity.Activate(activityType, workflow);
                action.AddLogEntry(string.Format("Activated new '{0}' activity", activityType.ToString()));
                return(true);
            }

            action.AddLogEntry(string.Format("Could Not activate new '{0}' activity!", activityType.ToString()));
            return(false);
        }
Exemplo n.º 2
0
        public async Task <ActivityContext> ExecuteAsync(WorkflowActivity activity, ActivityContext context)
        {
            await activity.ExecuteAsync(context);

            //TODO: add execution of output mapping between activity and context
            return(context);
        }
Exemplo n.º 3
0
        private bool activateActivity(RockContext rockContext, WorkflowAction action, string activityAttributeName)
        {
            Guid guid = GetAttributeValue(action, activityAttributeName).AsGuid();

            if (guid.IsEmpty())
            {
                // No activity.  Just be done.
                return(true);
            }

            var workflow = action.Activity.Workflow;

            var activityType = new WorkflowActivityTypeService(rockContext).Queryable()
                               .Where(a => a.Guid.Equals(guid)).FirstOrDefault();

            if (activityType == null)
            {
                action.AddLogEntry("Invalid Activity Property", true);
                return(false);
            }

            WorkflowActivity.Activate(activityType, workflow);
            action.AddLogEntry(string.Format("Activated new '{0}' activity", activityType.ToString()));

            return(true);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();


            var ActivityToActivate = GetAttributeValue(action, "ActivityId", true).ResolveMergeFields(GetMergeFields(action)).AsIntegerOrNull();

            if (!ActivityToActivate.HasValue)
            {
                action.AddLogEntry("Invalid Activity Property", true);
                return(false);
            }

            WorkflowActivity activity = action.Activity.Workflow.Activities.Where(a => a.Id == ActivityToActivate).FirstOrDefault();

            activity.CompletedDateTime = null;
            action.AddLogEntry("Marked activity incomplete");

            foreach (var a in activity.Actions)
            {
                a.CompletedDateTime = null;
            }

            action.AddLogEntry(string.Format("Activated all actions for '{0}' activity.", action.ActionTypeCache.Name));



            return(true);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            Guid guid = GetAttributeValue(action, "Activity").AsGuid();

            if (guid.IsEmpty())
            {
                action.AddLogEntry("Invalid Activity Property", true);
                return(false);
            }

            var workflow = action.Activity.Workflow;

            var activityType = WorkflowActivityTypeCache.Read(guid);

            if (activityType == null)
            {
                action.AddLogEntry("Invalid Activity Property", true);
                return(false);
            }

            WorkflowActivity.Activate(activityType, workflow);
            action.AddLogEntry(string.Format("Activated new '{0}' activity", activityType.ToString()));

            return(true);
        }
Exemplo n.º 6
0
        protected void ddlActivateNewActivity_SelectedIndexChanged(object sender, EventArgs e)
        {
            ParseControls();

            int?activityTypeId = ddlActivateNewActivity.SelectedValueAsId();

            if (activityTypeId.HasValue)
            {
                var activityType = new WorkflowActivityTypeService(new RockContext()).Get(activityTypeId.Value);
                if (activityType != null)
                {
                    var activity = WorkflowActivity.Activate(activityType, Workflow);
                    activity.ActivityTypeId = activity.ActivityType.Id;
                    activity.Guid           = Guid.NewGuid();

                    foreach (var action in activity.Actions)
                    {
                        action.ActionTypeId = action.ActionType.Id;
                        action.Guid         = Guid.NewGuid();
                    }

                    Workflow.AddLogEntry(string.Format("Manually Activated new '{0}' activity", activityType.ToString()));

                    ExpandedActivities.Add(activity.Guid);

                    BuildControls(true, activity.Guid);
                }
            }

            ddlActivateNewActivity.SelectedIndex = 0;
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var  itemListValue       = GetAttributeValue(action, "ItemList");
            Guid itemListValueAsGuid = itemListValue.AsGuid();

            if (!itemListValueAsGuid.IsEmpty())
            {
                var workflowAttributeValue = action.GetWorklowAttributeValue(itemListValueAsGuid);
                if (workflowAttributeValue != null)
                {
                    itemListValue = workflowAttributeValue;
                }
            }
            else
            {
                itemListValue = itemListValue.ResolveMergeFields(GetMergeFields(action));
            }

            if (string.IsNullOrWhiteSpace(itemListValue))
            {
                action.AddLogEntry("List is empty, not activating any activities.", true);
                return(true);
            }


            Guid guid = GetAttributeValue(action, "Activity").AsGuid();

            if (guid.IsEmpty())
            {
                action.AddLogEntry("Invalid Activity Property", true);
                return(false);
            }

            var workflow = action.Activity.Workflow;

            var activityTypeCache = WorkflowActivityTypeCache.Get(guid);

            if (activityTypeCache == null)
            {
                action.AddLogEntry("Invalid Activity Property", true);
                return(false);
            }

            string activityAttributeKey    = GetAttributeValue(action, "ActivityAttributeKey");
            bool   hasActivityAttributeKey = !string.IsNullOrWhiteSpace(activityAttributeKey);

            foreach (var item in itemListValue.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var activity = WorkflowActivity.Activate(activityTypeCache, workflow);
                if (hasActivityAttributeKey)
                {
                    activity.SetAttributeValue(activityAttributeKey, item);
                }
                action.AddLogEntry(string.Format("Activated new '{0}' activity", activityTypeCache.ToString()));
            }

            return(true);
        }
Exemplo n.º 8
0
        private bool activateActivity(RockContext rockContext, WorkflowAction action, string activityAttributeName)
        {
            Guid guid = GetAttributeValue(action, activityAttributeName).AsGuid();

            if (guid.IsEmpty())
            {
                // No activity.  Just be done.
                return(true);
            }

            var workflow = action.Activity.Workflow;

            var activityType = WorkflowActivityTypeCache.Get(guid);

            if (activityType == null)
            {
                action.AddLogEntry("Invalid Activity Property", true);
                return(false);
            }

            WorkflowActivity.Activate(activityType, workflow);
            action.AddLogEntry(string.Format("Activated new '{0}' activity", activityType.ToString()));

            return(true);
        }
Exemplo n.º 9
0
 //设置变量集合
 private void SetVariablesForActivity(System.Collections.ObjectModel.Collection <System.Activities.Variable> variables
                                      , WorkflowActivity activity)
 {
     foreach (var variable in variables)
     {
         //判断变量名称是否合法
         if (Regex.IsMatch(variable.Name, @"[a-zA-Z][a-zA-Z_0-9]*"))
         {
             if (variable.GetType().IsGenericType)
             {
                 var dataType = variable.GetType().GetGenericArguments()[0];
                 if (dataType == typeof(String))
                 {
                     activity.Variables.Add(new Taobao.Activities.Variable <String>(variable.Name));
                 }
                 else if (dataType == typeof(Int32))
                 {
                     activity.Variables.Add(new Taobao.Activities.Variable <Int32>(variable.Name));
                 }
                 else if (dataType == typeof(Int64))
                 {
                     activity.Variables.Add(new Taobao.Activities.Variable <Int64>(variable.Name));
                 }
             }
         }
     }
 }
Exemplo n.º 10
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            Guid guid = GetAttributeValue(action, "Activity").AsGuid();

            if (guid.IsEmpty())
            {
                action.AddLogEntry("Invalid Activity Property", true);
                return(false);
            }

            var workflow = action.Activity.Workflow;

            var activityType = new WorkflowActivityTypeService(rockContext).Queryable()
                               .Where(a => a.Guid.Equals(guid)).FirstOrDefault();

            if (activityType == null)
            {
                action.AddLogEntry("Invalid Activity Property", true);
                return(false);
            }

            WorkflowActivity.Activate(activityType, workflow);
            action.AddLogEntry(string.Format("Activated new '{0}' activity", activityType.ToString()));

            return(true);
        }
Exemplo n.º 11
0
        private FlowStep GetNextFlowStep(WorkflowActivity workflow, FlowStep step)
        {
            var flowSwitch = step.Next as FlowSwitch <string>;

            return(flowSwitch.Cases.Count > 0
                ? flowSwitch.Cases.First().Value as FlowStep
                : flowSwitch.Default as FlowStep);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Activates and processes a workflow activity.  If the workflow has not yet been activated, it will
        /// also be activated
        /// </summary>
        /// <param name="activityName">Name of the activity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        protected bool ProcessActivity(string activityName, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            Guid?guid = GetAttributeValue("WorkflowType").AsGuidOrNull();

            if (guid.HasValue)
            {
                using (var rockContext = new RockContext())
                {
                    var workflowTypeService = new WorkflowTypeService(rockContext);
                    var workflowService     = new WorkflowService(rockContext);

                    var workflowType = workflowTypeService.Queryable("ActivityTypes")
                                       .Where(w => w.Guid.Equals(guid.Value))
                                       .FirstOrDefault();

                    if (workflowType != null)
                    {
                        if (CurrentWorkflow == null)
                        {
                            CurrentWorkflow = Rock.Model.Workflow.Activate(workflowType, CurrentCheckInState.Kiosk.Device.Name, rockContext);

                            if (Request["Override"] != null)
                            {
                                if (Request["Override"].ToString() == "True")
                                {
                                    CurrentWorkflow.SetAttributeValue("Override", "True");
                                }
                            }
                        }

                        var activityType = workflowType.ActivityTypes.Where(a => a.Name == activityName).FirstOrDefault();
                        if (activityType != null)
                        {
                            WorkflowActivity.Activate(activityType, CurrentWorkflow, rockContext);
                            if (workflowService.Process(CurrentWorkflow, CurrentCheckInState, out errorMessages))
                            {
                                // Keep workflow active for continued processing
                                CurrentWorkflow.CompletedDateTime = null;

                                return(true);
                            }
                        }
                        else
                        {
                            errorMessages.Add(string.Format("Workflow type does not have a '{0}' activity type", activityName));
                        }
                    }
                    else
                    {
                        errorMessages.Add("Invalid Workflow Type");
                    }
                }
            }

            return(false);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Default implementation for the Workflow's Process method.
        ///     Get the current state
        ///     Invoke the corresponding action (with the data object passed in)
        ///     Add any results to the Item's SuggestionsList
        ///     Move to the next state and terminate the workflow if it is at the end
        /// </summary>
        /// <param name="instance">Workflow instance</param>
        /// <param name="entity">Entity to process</param>
        /// <param name="data">Extra data to pass to Activity</param>
        /// <returns>true if completed, false if not</returns>
        protected virtual WorkflowActivity.Status Process(WorkflowInstance instance, ServerEntity entity, object data)
        {
            try
            {
                // get current state and corresponding activity
                TraceLog.TraceInfo(String.Format("Workflow {0} entering state {1}", instance.WorkflowType, instance.State));
                WorkflowState state = States.Single(s => s.Name == instance.State);
                //var activity = PrepareActivity(instance, state.Activity, UserContext, SuggestionsContext);

                WorkflowActivity activity = null;
                if (state.Activity != null)
                {
                    activity = WorkflowActivity.CreateActivity(state.Activity);
                }
                else if (state.ActivityDefinition != null)
                {
                    activity = WorkflowActivity.CreateActivity(state.ActivityDefinition, instance);
                }

                if (activity == null)
                {
                    TraceLog.TraceError("Could not find or prepare Activity");
                    return(WorkflowActivity.Status.Error);
                }
                else
                {
                    activity.UserContext        = UserContext;
                    activity.SuggestionsContext = SuggestionsContext;
                }

                // invoke the activity
                TraceLog.TraceInfo(String.Format("Workflow {0} invoking activity {1}", instance.WorkflowType, activity.Name));
                var status = activity.Function.Invoke(instance, entity, data);
                TraceLog.TraceInfo(String.Format("Workflow {0}: activity {1} returned status {2}", instance.WorkflowType, activity.Name, status.ToString()));
                instance.LastModified = DateTime.Now;

                // if the activity completed, advance the workflow state
                if (status == WorkflowActivity.Status.Complete)
                {
                    // store next state and terminate the workflow if next state is null
                    instance.State = state.NextState;
                    if (instance.State == null)
                    {
                        status = WorkflowActivity.Status.WorkflowDone;
                        TraceLog.TraceInfo(String.Format("Workflow {0} is done", instance.WorkflowType));
                    }
                }
                SuggestionsContext.SaveChanges();

                return(status);
            }
            catch (Exception ex)
            {
                TraceLog.TraceException("Process failed", ex);
                return(WorkflowActivity.Status.Error);
            }
        }
        private WorkflowAccount GetRequestorUsername(WorkflowActivity src, IQueryable <WorkflowProperty> properties)
        {
            WorkflowProperty workflowProperty = properties.FirstOrDefault(x => x.Name == WorkflowPropertyHelper.DSW_PROPERTY_PROPOSER_USER);

            return(workflowProperty == null
                ? new WorkflowAccount {
                AccountName = src.RegistrationUser
            }
                : JsonConvert.DeserializeObject <WorkflowAccount>(workflowProperty.ValueString));
        }
Exemplo n.º 15
0
        public virtual void Initial(string operatorId)
        {
            if (this.WorkflowActivity == null)
            {
                this.WorkflowActivity = new List <WorkflowActivity>();
            }
            WorkflowActivity activity = new WorkflowActivity(this.Id, "PurchaseOrder", "PO-010", operatorId, null);

            this.WorkflowActivity.Add(activity);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            Guid guid = GetAttributeValue(action, "Activity").AsGuid();

            if (guid.IsEmpty())
            {
                action.AddLogEntry("Invalid Activity Property", true);
                return(false);
            }

            var workflow = action.Activity.Workflow;

            var activityType = WorkflowActivityTypeCache.Get(guid);

            if (activityType == null)
            {
                action.AddLogEntry("Invalid Activity Property", true);
                return(false);
            }

            Dictionary <string, string> keyValues = null;
            var attributeValues = GetAttributeValue(action, "AttributeValues");

            if (!string.IsNullOrWhiteSpace(attributeValues))
            {
                keyValues = attributeValues.AsDictionaryOrNull();
            }
            keyValues = keyValues ?? new Dictionary <string, string>();

            var activity = WorkflowActivity.Activate(activityType, workflow);

            activity.LoadAttributes(rockContext);

            foreach (var keyPair in keyValues)
            {
                //
                // Does the key exist as an attribute in the destination activity?
                //
                if (activity.Attributes.ContainsKey(keyPair.Key))
                {
                    var value = keyPair.Value.ResolveMergeFields(GetMergeFields(action));
                    activity.SetAttributeValue(keyPair.Key, value);
                }
                else
                {
                    errorMessages.Add(string.Format("'{0}' is not an attribute key in the activated activity: '{1}'", keyPair.Value, activityType.Name));
                }
            }

            action.AddLogEntry(string.Format("Activated new '{0}' activity", activityType.ToString()));

            return(true);
        }
Exemplo n.º 17
0
        public virtual void Apply(string operatorId)
        {
            this.StatuId = "PO-020";
            WorkflowActivity beforActivity = this.WorkflowActivity.Where(s => s.EndTime == null).Last();

            beforActivity.EndTime = DateTime.Now;

            WorkflowActivity activity = new WorkflowActivity(this.Id, "PurchaseOrder", "PO-020", operatorId, beforActivity);

            this.WorkflowActivity.Add(activity);
        }
        public HttpResponseMessage Family(string param)
        {
            try
            {
                var Session = HttpContext.Current.Session;

                CurrentKioskId = ( int )Session["CheckInKioskId"];
                Guid       blockGuid           = ( Guid )Session["BlockGuid"];
                List <int> CheckInGroupTypeIds = (List <int>)Session["CheckInGroupTypeIds"];
                CurrentCheckInState = new CheckInState(CurrentKioskId, null, CheckInGroupTypeIds);
                CurrentCheckInState.CheckIn.UserEnteredSearch   = true;
                CurrentCheckInState.CheckIn.ConfirmSingleFamily = true;
                CurrentCheckInState.CheckIn.SearchType          = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_PHONE_NUMBER);
                CurrentCheckInState.CheckIn.SearchValue         = param;

                var    rockContext      = new Rock.Data.RockContext();
                var    block            = BlockCache.Read(blockGuid, rockContext);
                string workflowActivity = block.GetAttributeValue("WorkflowActivity");
                Guid?  workflowGuid     = block.GetAttributeValue("WorkflowType").AsGuidOrNull();

                List <string> errors;
                var           workflowTypeService = new WorkflowTypeService(rockContext);
                var           workflowService     = new WorkflowService(rockContext);
                var           workflowType        = workflowTypeService.Queryable("ActivityTypes")
                                                    .Where(w => w.Guid.Equals(workflowGuid.Value))
                                                    .FirstOrDefault();
                var CurrentWorkflow = Rock.Model.Workflow.Activate(workflowType, CurrentCheckInState.Kiosk.Device.Name, rockContext);

                var activityType = workflowType.ActivityTypes.Where(a => a.Name == workflowActivity).FirstOrDefault();
                if (activityType != null)
                {
                    WorkflowActivity.Activate(activityType, CurrentWorkflow, rockContext);
                    if (workflowService.Process(CurrentWorkflow, CurrentCheckInState, out errors))
                    {
                        // Keep workflow active for continued processing
                        CurrentWorkflow.CompletedDateTime = null;
                        SaveState(Session);
                        List <CheckInFamily> families = CurrentCheckInState.CheckIn.Families;
                        families = families.OrderBy(f => f.Caption).ToList();
                        return(ControllerContext.Request.CreateResponse(HttpStatusCode.OK, families));
                    }
                }
                else
                {
                    return(ControllerContext.Request.CreateResponse(HttpStatusCode.InternalServerError, string.Format("Workflow type does not have a '{0}' activity type", workflowActivity)));
                }
                return(ControllerContext.Request.CreateResponse(HttpStatusCode.InternalServerError, String.Join("\n", errors)));
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, HttpContext.Current);
                return(ControllerContext.Request.CreateResponse(HttpStatusCode.Forbidden, "Forbidden"));
            }
        }
        /// <summary>
        /// 获取当前状态
        /// </summary>
        /// <param name="linkObjectId"></param>
        /// <returns></returns>
        public WorkflowActivity GetCurrentActivity(string objectId)
        {
            WorkflowActivity activity = null;
            Query            query    = new Query();

            query.Add(Criterion.Create <WorkflowActivity>(a => a.Id, objectId, CriteriaOperator.Equal));
            query.Add(Criterion.Create <WorkflowActivity>(a => a.EndTime, null, CriteriaOperator.IsNull));

            activity = this._workflowActivityRepository.FindBy(query).FirstOrDefault();
            return(activity);
        }
Exemplo n.º 20
0
        public static WorkflowActivity GetLastWorkflowActivityByDoumentUnitId(this IRepository <WorkflowActivity> repository, Guid DocumentUnitId, string account, bool optimization = true)
        {
            WorkflowActivity workflowActivity = repository
                                                .Query(x => x.DocumentUnitReferenced.UniqueId == DocumentUnitId &&
                                                       (x.Status == WorkflowStatus.Done) &&
                                                       x.WorkflowAuthorizations.Any(y => y.Account.ToLower() == account.ToLower()), optimization: optimization)
                                                .Include(x => x.DocumentUnitReferenced.Category)
                                                .OrderBy(o => o.OrderByDescending(c => c.LastChangedDate))
                                                .Top(1).FirstOrDefault();

            return(workflowActivity);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var workflowActivityGuid = action.GetWorklowAttributeValue(GetAttributeValue(action, "Activity").AsGuid()).AsGuid();

            if (workflowActivityGuid.IsEmpty())
            {
                action.AddLogEntry("Invalid Activity Property", true);
                return(false);
            }

            var attributeKey   = GetAttributeValue(action, "WorkflowAttributeKey", true);
            var attributeValue = GetAttributeValue(action, "WorkflowAttributeValue", true);

            if (string.IsNullOrWhiteSpace(attributeKey) || string.IsNullOrWhiteSpace(attributeValue))
            {
                action.AddLogEntry("Invalid Workflow Property", true);
                return(false);
            }

            var activityType = new WorkflowActivityTypeService(rockContext).Queryable()
                               .Where(a => a.Guid.Equals(workflowActivityGuid)).FirstOrDefault();

            if (activityType == null)
            {
                action.AddLogEntry("Invalid Activity Property", true);
                return(false);
            }

            var entityType = EntityTypeCache.Read(typeof(Rock.Model.Workflow));

            var workflowIds = new AttributeValueService(rockContext)
                              .Queryable()
                              .AsNoTracking()
                              .Where(a => a.Attribute.Key == attributeKey && a.Value == attributeValue && a.Attribute.EntityTypeId == entityType.Id)
                              .Select(a => a.EntityId);

            var workflows = new WorkflowService(rockContext)
                            .Queryable()
                            //.AsNoTracking()
                            .Where(w => w.WorkflowType.ActivityTypes.Any(a => a.Guid == activityType.Guid) && workflowIds.Contains(w.Id))
                            .ToList();

            foreach (var workflow in workflows)
            {
                WorkflowActivity.Activate(activityType, workflow);
                action.AddLogEntry(string.Format("Activated new '{0}' activity in {1} {2}", activityType.ToString(), workflow.TypeName, workflow.WorkflowId));
            }


            return(true);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Gets or sets the workflow activity.
        /// </summary>
        /// <param name="activity">The activity.</param>
        /// <param name="expandInvalid">if set to <c>true</c> [expand invalid].</param>
        /// <value>
        /// The workflow activity.
        /// </value>
        public void GetWorkflowActivity(WorkflowActivity activity, bool expandInvalid)
        {
            EnsureChildControls();

            if (!activity.CompletedDateTime.HasValue && _cbActivityIsComplete.Checked)
            {
                activity.CompletedDateTime = RockDateTime.Now;
            }
            else if (activity.CompletedDateTime.HasValue && !_cbActivityIsComplete.Checked)
            {
                activity.CompletedDateTime = null;
            }

            if (_ppAssignedToPerson.SelectedValue.HasValue)
            {
                activity.AssignedPersonAliasId = _ppAssignedToPerson.PersonAliasId;
            }
            else
            {
                activity.AssignedPersonAliasId = null;
            }


            if (_gpAssignedToGroup.SelectedValueAsInt().HasValue)
            {
                activity.AssignedGroupId = _gpAssignedToGroup.SelectedValueAsInt();
            }
            else if (_ddlAssignedToRole.SelectedValueAsInt().HasValue)
            {
                activity.AssignedGroupId = _ddlAssignedToRole.SelectedValueAsInt();
            }
            else
            {
                activity.AssignedGroupId = null;
            }

            Attribute.Helper.GetEditValues(_phAttributes, activity);

            foreach (WorkflowActionEditor actionEditor in this.Controls.OfType <WorkflowActionEditor>())
            {
                var action = activity.Actions.Where(a => a.Guid.Equals(actionEditor.ActionGuid)).FirstOrDefault();
                if (action != null)
                {
                    actionEditor.GetWorkflowAction(action);
                }
            }

            if (expandInvalid && !Expanded && !activity.IsValid)
            {
                Expanded = true;
            }
        }
Exemplo n.º 23
0
        protected void bntMerge_Click(object sender, EventArgs e)
        {
            PDFWorkflowObject pdfWorkflowObject = new PDFWorkflowObject();

            pdfWorkflowObject.LavaInput = ceLava.Text;

            pdfWorkflowObject.MergeObjects = new Dictionary <string, object>();
            if (cbCurrentPerson.Checked)
            {
                pdfWorkflowObject.MergeObjects.Add("CurrentPerson", CurrentPerson);
            }
            if (cbGlobal.Checked)
            {
                pdfWorkflowObject.MergeObjects.Add("GlobalAttributes", GlobalAttributesCache.Read());
            }


            Guid workflowTypeGuid = Guid.NewGuid();

            if (Guid.TryParse(GetAttributeValue("WorkflowType"), out workflowTypeGuid))
            {
                var workflowRockContext = new RockContext();
                var workflowTypeService = new WorkflowTypeService(workflowRockContext);
                var workflowType        = workflowTypeService.Get(workflowTypeGuid);
                if (workflowType != null)
                {
                    var workflow = Workflow.Activate(workflowType, "PDFLavaWorkflow");

                    List <string> workflowErrors;
                    var           workflowService  = new WorkflowService(workflowRockContext);
                    var           workflowActivity = GetAttributeValue("WorkflowActivity");
                    var           activityType     = workflowType.ActivityTypes.Where(a => a.Name == workflowActivity).FirstOrDefault();
                    if (activityType != null)
                    {
                        WorkflowActivity.Activate(activityType, workflow, workflowRockContext);
                        if (workflowService.Process(workflow, pdfWorkflowObject, out workflowErrors))
                        {
                            //success
                        }
                    }
                }
            }

            RockContext       rockContext       = new RockContext();
            BinaryFileService binaryFileService = new BinaryFileService(rockContext);

            pdfWorkflowObject.RenderedPDF.FileName = "LavaGeneratedPDF.pdf";
            binaryFileService.Add(pdfWorkflowObject.RenderedPDF);
            rockContext.SaveChanges();

            Response.Redirect(pdfWorkflowObject.RenderedPDF.Path);
        }
Exemplo n.º 24
0
        protected override async Task ProcessItem(string itemId, CancellationToken cancellationToken)
        {
            try
            {
                var workflow = await FetchWorkflow(itemId);

                WorkflowActivity.Enrich(workflow, "index");
                await _searchIndex.IndexWorkflow(workflow);

                lock (_errorCounts)
                {
                    _errorCounts.Remove(itemId);
                }
            }
            catch (Exception e)
            {
                Logger.LogWarning(default(EventId), $"Error indexing workfow - {itemId} - {e.Message}");
                var errCount = 0;
                lock (_errorCounts)
                {
                    if (!_errorCounts.ContainsKey(itemId))
                    {
                        _errorCounts.Add(itemId, 0);
                    }

                    _errorCounts[itemId]++;
                    errCount = _errorCounts[itemId];
                }

                if (errCount < 5)
                {
                    await QueueProvider.QueueWork(itemId, Queue);

                    return;
                }
                if (errCount < 20)
                {
                    await Task.Delay(TimeSpan.FromSeconds(10));

                    await QueueProvider.QueueWork(itemId, Queue);

                    return;
                }

                lock (_errorCounts)
                {
                    _errorCounts.Remove(itemId);
                }

                Logger.LogError(default(EventId), e, $"Unable to index workfow - {itemId} - {e.Message}");
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var workflowActivityGuid = action.GetWorklowAttributeValue(GetAttributeValue(action, "Activity").AsGuid()).AsGuid();

            if (workflowActivityGuid.IsEmpty())
            {
                action.AddLogEntry("Invalid Activity Property", true);
                return(false);
            }

            var reference = GetAttributeValue(action, "WorkflowReference", true);

            Rock.Model.Workflow workflow = null;
            if (reference.AsGuidOrNull() != null)
            {
                var referenceGuid = reference.AsGuid();
                workflow = new WorkflowService(rockContext).Queryable()
                           .Where(w => w.Guid == referenceGuid)
                           .FirstOrDefault();
            }
            else if (reference.AsIntegerOrNull() != null)
            {
                var referenceInt = reference.AsInteger();
                workflow = new WorkflowService(rockContext).Queryable()
                           .Where(w => w.Id == referenceInt)
                           .FirstOrDefault();
            }
            else
            {
                action.AddLogEntry("Invalid Workflow Property", true);
                return(false);
            }

            var activityType = new WorkflowActivityTypeService(rockContext).Queryable()
                               .Where(a => a.Guid.Equals(workflowActivityGuid)).FirstOrDefault();

            if (activityType == null)
            {
                action.AddLogEntry("Invalid Activity Property", true);
                return(false);
            }

            WorkflowActivity.Activate(activityType, workflow);
            action.AddLogEntry(string.Format("Activated new '{0}' activity", activityType.ToString()));

            return(true);
        }
Exemplo n.º 26
0
        protected void bntMerge_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();
            //Get the mergefields and pdf
            BinaryFileService           binaryFileService = new BinaryFileService(rockContext);
            Dictionary <string, object> mergeFields       = GetMergeFields();
            BinaryFile pdf = binaryFileService.Get(int.Parse(fpSelectedFile.SelectedValue));

            //Create the object we will need to pass to the workflow
            if (pdf != null && mergeFields.Count > 0)
            {
                var pdfEntity = new PDFWorkflowObject();
                pdfEntity.PDF          = pdf;
                pdfEntity.MergeObjects = mergeFields;

                Guid workflowTypeGuid = Guid.NewGuid();
                if (Guid.TryParse(GetAttributeValue("WorkflowType"), out workflowTypeGuid))
                {
                    var workflowRockContext = new RockContext();
                    var workflowTypeService = new WorkflowTypeService(workflowRockContext);
                    var workflowType        = workflowTypeService.Get(workflowTypeGuid);
                    if (workflowType != null)
                    {
                        var workflow = Workflow.Activate(workflowType, pdf.FileName);

                        List <string> workflowErrors;
                        var           workflowService  = new WorkflowService(workflowRockContext);
                        var           workflowActivity = GetAttributeValue("WorkflowActivity");
                        var           activityType     = workflowType.ActivityTypes.Where(a => a.Name == workflowActivity).FirstOrDefault();
                        if (activityType != null)
                        {
                            WorkflowActivity.Activate(activityType, workflow, workflowRockContext);
                            if (workflowService.Process(workflow, pdfEntity, out workflowErrors))
                            {
                                //success
                            }
                        }
                    }
                }

                var mergedPDF = pdfEntity.PDF;
                //mergedPDF.Guid = Guid.NewGuid();
                binaryFileService.Add(mergedPDF);
                rockContext.SaveChanges();

                Response.Redirect(mergedPDF.Path);
            }
        }
        public void InsertNewActivity(AddWorkflowActivityRequest request)
        {
            //插入新活动前,先保存当前所处活动
            WorkflowActivity activityBeforUpdate = GetCurrentActivity(request.ObjectId);

            WorkflowActivity activity = new WorkflowActivity(request.ObjectId, request.ObjectTypeId, request.WorkflowNodeId, request.CreateUserId, activityBeforUpdate);

            this._workflowActivityRepository.Save(activity);

            if (activityBeforUpdate != null)
            {
                activityBeforUpdate.EndTime = DateTime.Now;
                this._workflowActivityRepository.Save(activityBeforUpdate);
            }
            this._uow.Commit();
        }
Exemplo n.º 28
0
        public virtual void Reject(string operatorId)
        {
            this.StatuId = "PO-040";
            WorkflowActivity beforActivity      = new WorkflowActivity();
            IEnumerable <WorkflowActivity> list = this.WorkflowActivity.Where(s => s.EndTime == null);

            if (list.Count() > 0)
            {
                beforActivity         = list.Last();
                beforActivity.EndTime = DateTime.Now;
            }

            WorkflowActivity activity = new WorkflowActivity(this.Id, "PurchaseOrder", "PO-040", operatorId, beforActivity);

            this.WorkflowActivity.Add(activity);
        }
Exemplo n.º 29
0
        public Task <ActivityContext> ExecuteSingle(WorkflowActivity activity, ActivityContext context)
        {
            //TODO: consider different grain allocation strategy
            //perhaps it should be created from hashcode of activity implementation or something
            var worker = GrainFactory.GetGrain <IWorkerGrain>(Guid.NewGuid());

            try
            {
                return(worker.ExecuteAsync(activity, context));
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Unhandled exception thrown while running activity of type = {activity.GetType().FullName}");
            }

            return(Task.FromResult <ActivityContext>(null));
        }
Exemplo n.º 30
0
        private async Task PollCommands()
        {
            var activity = WorkflowActivity.StartPoll("commands");

            try
            {
                if (!_persistenceStore.SupportsScheduledCommands)
                {
                    return;
                }

                if (await _lockProvider.AcquireLock("poll-commands", new CancellationToken()))
                {
                    try
                    {
                        _logger.LogDebug("Polling for scheduled commands");
                        await _persistenceStore.ProcessCommands(new DateTimeOffset(_dateTimeProvider.UtcNow), async (command) =>
                        {
                            switch (command.CommandName)
                            {
                            case ScheduledCommand.ProcessWorkflow:
                                await _queueProvider.QueueWork(command.Data, QueueType.Workflow);
                                break;

                            case ScheduledCommand.ProcessEvent:
                                await _queueProvider.QueueWork(command.Data, QueueType.Event);
                                break;
                            }
                        });
                    }
                    finally
                    {
                        await _lockProvider.ReleaseLock("poll-commands");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                activity?.RecordException(ex);
            }
            finally
            {
                activity?.Dispose();
            }
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            var service = new WorkflowService( rockContext );

            ParseControls( rockContext, true );

            Workflow dbWorkflow = null;

            if ( Workflow != null )
            {
                dbWorkflow = service.Get( Workflow.Id );

                if ( dbWorkflow != null )
                {
                    if ( !dbWorkflow.CompletedDateTime.HasValue && Workflow.CompletedDateTime.HasValue )
                    {
                        dbWorkflow.AddLogEntry( "Workflow Manually Completed." );
                        dbWorkflow.CompletedDateTime = Workflow.CompletedDateTime;
                    }
                    else if ( dbWorkflow.CompletedDateTime.HasValue && !Workflow.CompletedDateTime.HasValue )
                    {
                        dbWorkflow.AddLogEntry( "Workflow Manually Re-Activated." );
                        dbWorkflow.CompletedDateTime = null;
                    }

                    if ( dbWorkflow.Name.Trim() != Workflow.Name.Trim() )
                    {
                        dbWorkflow.AddLogEntry( string.Format( "Workflow name manually changed from '{0}' to '{0}'.", dbWorkflow.Name, tbName.Text ) );
                        dbWorkflow.Name = Workflow.Name;
                    }

                    if ( dbWorkflow.Status.Trim() != Workflow.Status.Trim() )
                    {
                        dbWorkflow.AddLogEntry( string.Format( "Workflow status manually changed from '{0}' to '{0}'.", dbWorkflow.Status, tbStatus.Text ) );
                        dbWorkflow.Status = Workflow.Status;
                    }

                    if ( !dbWorkflow.InitiatorPersonAliasId.Equals(Workflow.InitiatorPersonAliasId))
                    {
                        dbWorkflow.AddLogEntry( string.Format( "Workflow status manually changed from '{0}' to '{0}'.",
                            dbWorkflow.InitiatorPersonAlias != null ? dbWorkflow.InitiatorPersonAlias.Person.FullName : "",
                            Workflow.InitiatorPersonAlias != null ? Workflow.InitiatorPersonAlias.Person.FullName : "" ) );
                        dbWorkflow.InitiatorPersonAlias = Workflow.InitiatorPersonAlias;
                        dbWorkflow.InitiatorPersonAliasId = Workflow.InitiatorPersonAliasId;
                    }

                    if ( !Page.IsValid || !dbWorkflow.IsValid )
                    {
                        return;
                    }

                    foreach ( var activity in Workflow.Activities )
                    {
                        if ( !activity.IsValid )
                        {
                            return;
                        }
                        foreach ( var action in activity.Actions )
                        {
                            if ( !action.IsValid )
                            {
                                return;
                            }
                        }
                    }

                    rockContext.WrapTransaction( () =>
                    {
                        rockContext.SaveChanges();

                        dbWorkflow.LoadAttributes( rockContext );
                        foreach ( var attributeValue in Workflow.AttributeValues )
                        {
                            dbWorkflow.SetAttributeValue( attributeValue.Key, Workflow.GetAttributeValue( attributeValue.Key ) );
                        }
                        dbWorkflow.SaveAttributeValues( rockContext );

                        WorkflowActivityService workflowActivityService = new WorkflowActivityService( rockContext );
                        WorkflowActionService workflowActionService = new WorkflowActionService( rockContext );

                        var activitiesInUi = new List<Guid>();
                        var actionsInUI = new List<Guid>();
                        foreach ( var activity in Workflow.Activities )
                        {
                            activitiesInUi.Add( activity.Guid );
                            foreach ( var action in activity.Actions )
                            {
                                actionsInUI.Add( action.Guid );
                            }
                        }

                        // delete WorkflowActions that were removed in the UI
                        foreach ( var action in workflowActionService.Queryable()
                            .Where( a =>
                                a.Activity.WorkflowId.Equals( dbWorkflow.Id ) &&
                                !actionsInUI.Contains( a.Guid ) ) )
                        {
                            workflowActionService.Delete( action );
                        }

                        // delete WorkflowActivities that aren't assigned in the UI anymore
                        foreach ( var activity in workflowActivityService.Queryable()
                            .Where( a =>
                                a.WorkflowId.Equals( dbWorkflow.Id ) &&
                                !activitiesInUi.Contains( a.Guid ) ) )
                        {
                            workflowActivityService.Delete( activity );
                        }

                        rockContext.SaveChanges();

                        // add or update WorkflowActivities(and Actions) that are assigned in the UI
                        foreach ( var editorWorkflowActivity in Workflow.Activities )
                        {
                            // Add or Update the activity type
                            WorkflowActivity workflowActivity = dbWorkflow.Activities.FirstOrDefault( a => a.Guid.Equals( editorWorkflowActivity.Guid ) );
                            if ( workflowActivity == null )
                            {
                                workflowActivity = new WorkflowActivity();
                                workflowActivity.ActivityTypeId = editorWorkflowActivity.ActivityTypeId;
                                dbWorkflow.Activities.Add( workflowActivity );
                            }

                            workflowActivity.AssignedPersonAliasId = editorWorkflowActivity.AssignedPersonAliasId;
                            workflowActivity.AssignedGroupId = editorWorkflowActivity.AssignedGroupId;
                            workflowActivity.ActivatedDateTime = editorWorkflowActivity.ActivatedDateTime;
                            workflowActivity.LastProcessedDateTime = editorWorkflowActivity.LastProcessedDateTime;

                            if ( !workflowActivity.CompletedDateTime.HasValue && editorWorkflowActivity.CompletedDateTime.HasValue )
                            {
                                workflowActivity.AddLogEntry( "Activity Manually Completed." );
                                workflowActivity.CompletedDateTime = RockDateTime.Now;
                            }
                            if ( workflowActivity.CompletedDateTime.HasValue && !editorWorkflowActivity.CompletedDateTime.HasValue )
                            {
                                workflowActivity.AddLogEntry( "Activity Manually Re-Activated." );
                                workflowActivity.CompletedDateTime = null;
                            }

                            // Save Activity Type
                            rockContext.SaveChanges();

                            // Save ActivityType Attributes
                            workflowActivity.LoadAttributes( rockContext );
                            foreach ( var attributeValue in editorWorkflowActivity.AttributeValues )
                            {
                                workflowActivity.SetAttributeValue( attributeValue.Key, editorWorkflowActivity.GetAttributeValue( attributeValue.Key ) );
                            }
                            workflowActivity.SaveAttributeValues( rockContext );

                            foreach ( var editorWorkflowAction in editorWorkflowActivity.Actions )
                            {
                                WorkflowAction workflowAction = workflowActivity.Actions.FirstOrDefault( a => a.Guid.Equals( editorWorkflowAction.Guid ) );
                                if ( workflowAction == null )
                                {
                                    // New action
                                    workflowAction = new WorkflowAction();
                                    workflowAction.ActionTypeId = editorWorkflowAction.ActionTypeId;
                                    workflowActivity.Actions.Add( workflowAction );
                                }

                                workflowAction.LastProcessedDateTime = editorWorkflowAction.LastProcessedDateTime;
                                workflowAction.FormAction = editorWorkflowAction.FormAction;

                                if ( !workflowAction.CompletedDateTime.HasValue && editorWorkflowAction.CompletedDateTime.HasValue )
                                {
                                    workflowAction.AddLogEntry( "Action Manually Completed." );
                                    workflowAction.CompletedDateTime = RockDateTime.Now;
                                }
                                if ( workflowAction.CompletedDateTime.HasValue && !editorWorkflowAction.CompletedDateTime.HasValue )
                                {
                                    workflowAction.AddLogEntry( "Action Manually Re-Activated." );
                                    workflowAction.CompletedDateTime = null;
                                }
                            }

                            // Save action updates
                            rockContext.SaveChanges();

                        }

                    } );

                }

                Workflow = service
                    .Queryable("WorkflowType,Activities.ActivityType,Activities.Actions.ActionType")
                    .FirstOrDefault( w => w.Id == Workflow.Id );

                var errorMessages = new List<string>();
                service.Process( Workflow, out errorMessages );

            }

            ShowReadonlyDetails();
        }
Exemplo n.º 32
0
        private bool HydrateObjects()
        {
            LoadWorkflowType();

            // Set the note type if this is first request
            if ( !Page.IsPostBack )
            {
                var entityType = EntityTypeCache.Read( typeof( Rock.Model.Workflow ) );
                var noteTypes = NoteTypeCache.GetByEntity( entityType.Id, string.Empty, string.Empty );
                ncWorkflowNotes.NoteTypes = noteTypes;
            }

            if ( _workflowType == null )
            {
                ShowNotes( false );
                ShowMessage( NotificationBoxType.Danger, "Configuration Error", "Workflow type was not configured or specified correctly." );
                return false;
            }

            if ( !_workflowType.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
            {
                ShowNotes( false );
                ShowMessage( NotificationBoxType.Warning, "Sorry", "You are not authorized to view this type of workflow." );
                return false;
            }

            // If operating against an existing workflow, get the workflow and load attributes
            if ( !WorkflowId.HasValue )
            {
                WorkflowId = PageParameter( "WorkflowId" ).AsIntegerOrNull();
                if ( !WorkflowId.HasValue )
                {
                    Guid guid = PageParameter( "WorkflowGuid" ).AsGuid();
                    if ( !guid.IsEmpty() )
                    {
                        _workflow = _workflowService.Queryable()
                            .Where( w => w.Guid.Equals( guid ) && w.WorkflowTypeId == _workflowType.Id )
                            .FirstOrDefault();
                        if ( _workflow != null )
                        {
                            WorkflowId = _workflow.Id;
                        }
                    }
                }
            }

            if ( WorkflowId.HasValue )
            {
                if ( _workflow == null )
                {
                    _workflow = _workflowService.Queryable()
                        .Where( w => w.Id == WorkflowId.Value && w.WorkflowTypeId == _workflowType.Id )
                        .FirstOrDefault();
                }
                if ( _workflow != null )
                {
                    _workflow.LoadAttributes();
                    foreach ( var activity in _workflow.Activities )
                    {
                        activity.LoadAttributes();
                    }
                }

            }

            // If an existing workflow was not specified, activate a new instance of workflow and start processing
            if ( _workflow == null )
            {
                string workflowName = PageParameter( "WorkflowName" );
                if ( string.IsNullOrWhiteSpace(workflowName))
                {
                    workflowName = "New " + _workflowType.WorkTerm;
                }

                _workflow = Rock.Model.Workflow.Activate( _workflowType, workflowName);
                if ( _workflow != null )
                {
                    // If a PersonId or GroupId parameter was included, load the corresponding
                    // object and pass that to the actions for processing
                    object entity = null;
                    int? personId = PageParameter( "PersonId" ).AsIntegerOrNull();
                    if ( personId.HasValue )
                    {
                        entity = new PersonService( _rockContext ).Get( personId.Value );
                    }
                    else
                    {
                        int? groupId = PageParameter( "GroupId" ).AsIntegerOrNull();
                        if ( groupId.HasValue )
                        {
                            entity = new GroupService( _rockContext ).Get( groupId.Value );
                        }
                    }

                    // Loop through all the query string parameters and try to set any workflow
                    // attributes that might have the same key
                    foreach ( string key in Request.QueryString.AllKeys )
                    {
                        _workflow.SetAttributeValue( key, Request.QueryString[key] );
                    }

                    List<string> errorMessages;
                    if ( !_workflowService.Process( _workflow, entity, out errorMessages ) )
                    {
                        ShowNotes( false );
                        ShowMessage( NotificationBoxType.Danger, "Workflow Processing Error(s):",
                            "<ul><li>" + errorMessages.AsDelimited( "</li><li>" ) + "</li></ul>" );
                        return false;
                    }
                    if ( _workflow.Id != 0 )
                    {
                        WorkflowId = _workflow.Id;
                    }
                }
            }

            if ( _workflow == null )
            {
                ShowNotes( false );
                ShowMessage( NotificationBoxType.Danger, "Workflow Activation Error", "Workflow could not be activated." );
                return false;
            }

            if ( _workflow.IsActive )
            {
                if ( ActionTypeId.HasValue )
                {
                    foreach ( var activity in _workflow.ActiveActivities )
                    {
                        _action = activity.Actions.Where( a => a.ActionTypeId == ActionTypeId.Value ).FirstOrDefault();
                        if ( _action != null )
                        {
                            _activity = activity;
                            _activity.LoadAttributes();

                            _actionType = _action.ActionType;
                            ActionTypeId = _actionType.Id;
                            return true;
                        }
                    }
                }

                var canEdit = UserCanEdit || _workflow.IsAuthorized( Authorization.EDIT, CurrentPerson );

                // Find first active action form
                int personId = CurrentPerson != null ? CurrentPerson.Id : 0;
                foreach ( var activity in _workflow.Activities
                    .Where( a =>
                        a.IsActive &&
                        (
                            ( canEdit ) ||
                            ( !a.AssignedGroupId.HasValue && !a.AssignedPersonAliasId.HasValue ) ||
                            ( a.AssignedPersonAlias != null && a.AssignedPersonAlias.PersonId == personId ) ||
                            ( a.AssignedGroup != null && a.AssignedGroup.Members.Any( m => m.PersonId == personId ) )
                        )
                    )
                    .OrderBy( a => a.ActivityType.Order ) )
                {
                    if ( canEdit || ( activity.ActivityType.IsAuthorized( Authorization.VIEW, CurrentPerson ) ) )
                    {
                        foreach ( var action in activity.ActiveActions )
                        {
                            if ( action.ActionType.WorkflowForm != null && action.IsCriteriaValid )
                            {
                                _activity = activity;
                                _activity.LoadAttributes();

                                _action = action;
                                _actionType = _action.ActionType;
                                ActionTypeId = _actionType.Id;
                                return true;
                            }
                        }
                    }
                }
            }

            ShowNotes( false );
            ShowMessage( NotificationBoxType.Warning, string.Empty, "The selected workflow is not in a state that requires you to enter information." );
            return false;
        }
Exemplo n.º 33
0
        private void CompleteFormAction( string formAction )
        {
            if ( !string.IsNullOrWhiteSpace( formAction ) &&
                _workflow != null &&
                _actionType != null &&
                _actionType.WorkflowForm != null &&
                _activity != null &&
                _action != null )
            {
                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( this.RockPage, this.CurrentPerson );
                mergeFields.Add( "Action", _action );
                mergeFields.Add( "Activity", _activity );
                mergeFields.Add( "Workflow", _workflow );

                Guid activityTypeGuid = Guid.Empty;
                string responseText = "Your information has been submitted successfully.";

                foreach ( var action in _actionType.WorkflowForm.Actions.Split( new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries ) )
                {
                    var actionDetails = action.Split( new char[] { '^' } );
                    if ( actionDetails.Length > 0 && actionDetails[0] == formAction )
                    {
                        if ( actionDetails.Length > 2 )
                        {
                            activityTypeGuid = actionDetails[2].AsGuid();
                        }

                        if ( actionDetails.Length > 3 && !string.IsNullOrWhiteSpace( actionDetails[3] ) )
                        {
                            responseText = actionDetails[3].ResolveMergeFields( mergeFields );
                        }
                        break;
                    }
                }

                _action.MarkComplete();
                _action.FormAction = formAction;
                _action.AddLogEntry( "Form Action Selected: " + _action.FormAction );

                if (_action.ActionType.IsActivityCompletedOnSuccess)
                {
                    _action.Activity.MarkComplete();
                }

                if ( _actionType.WorkflowForm.ActionAttributeGuid.HasValue )
                {
                    var attribute = AttributeCache.Read( _actionType.WorkflowForm.ActionAttributeGuid.Value );
                    if ( attribute != null )
                    {
                        IHasAttributes item = null;
                        if ( attribute.EntityTypeId == _workflow.TypeId )
                        {
                            item = _workflow;
                        }
                        else if ( attribute.EntityTypeId == _activity.TypeId )
                        {
                            item = _activity;
                        }

                        if ( item != null )
                        {
                            item.SetAttributeValue( attribute.Key, formAction );
                        }
                    }
                }

                if ( !activityTypeGuid.IsEmpty() )
                {
                    var activityType = _workflowType.ActivityTypes.Where( a => a.Guid.Equals( activityTypeGuid ) ).FirstOrDefault();
                    if ( activityType != null )
                    {
                        WorkflowActivity.Activate( activityType, _workflow );
                    }
                }

                List<string> errorMessages;
                if ( _workflowService.Process( _workflow, out errorMessages ) )
                {
                    int? previousActionId = null;

                    if ( _action != null )
                    {
                        previousActionId = _action.Id;
                    }

                    ActionTypeId = null;
                    _action = null;
                    _actionType = null;
                    _activity = null;

                    if ( HydrateObjects() && _action != null && _action.Id != previousActionId )
                    {
                        BuildForm( true );
                    }
                    else
                    {
                        ShowMessage( NotificationBoxType.Success, string.Empty, responseText, ( _action == null || _action.Id != previousActionId ) );
                    }
                }
                else
                {
                    ShowMessage( NotificationBoxType.Danger, "Workflow Processing Error(s):",
                        "<ul><li>" + errorMessages.AsDelimited( "</li><li>", null, true ) + "</li></ul>" );
                }
                if ( _workflow.Id != 0 )
                {
                    WorkflowId = _workflow.Id;
                }
            }
        }
Exemplo n.º 34
0
        private void CompleteFormAction( string formAction )
        {
            if ( !string.IsNullOrWhiteSpace( formAction ) &&
                _workflow != null &&
                _actionType != null &&
                _actionType.WorkflowForm != null &&
                _activity != null &&
                _action != null )
            {

                Guid activityTypeGuid = Guid.Empty;
                string responseText = "Your information has been submitted succesfully.";

                foreach ( var action in _actionType.WorkflowForm.Actions.Split( new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries ) )
                {
                    var actionDetails = action.Split( new char[] { '^' } );
                    if ( actionDetails.Length > 0 && actionDetails[0] == formAction )
                    {
                        if ( actionDetails.Length > 2 )
                        {
                            activityTypeGuid = actionDetails[2].AsGuid();
                        }

                        if ( actionDetails.Length > 3 && !string.IsNullOrWhiteSpace( actionDetails[3] ) )
                        {
                            responseText = actionDetails[3];
                        }
                        break;
                    }
                }

                _action.MarkComplete();
                _action.FormAction = formAction;
                _action.AddLogEntry( "Form Action Selected: " + _action.FormAction );

                if ( _actionType.WorkflowForm.ActionAttributeGuid.HasValue )
                {
                    var attribute = AttributeCache.Read( _actionType.WorkflowForm.ActionAttributeGuid.Value );
                    if ( attribute != null )
                    {
                        IHasAttributes item = null;
                        if ( attribute.EntityTypeId == _workflow.TypeId )
                        {
                            item = _workflow;
                        }
                        else if ( attribute.EntityTypeId == _activity.TypeId )
                        {
                            item = _activity;
                        }

                        if ( item != null )
                        {
                            item.SetAttributeValue( attribute.Key, formAction );
                        }
                    }
                }

                // save current activity form's actions (to formulate response if needed).
                var mergeFields = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields( null );
                mergeFields.Add( "Action", _action );
                mergeFields.Add( "Activity", _activity );
                mergeFields.Add( "Workflow", _workflow );

                if ( !activityTypeGuid.IsEmpty() )
                {
                    var activityType = _workflowType.ActivityTypes.Where( a => a.Guid.Equals( activityTypeGuid ) ).FirstOrDefault();
                    if ( activityType != null )
                    {
                        WorkflowActivity.Activate( activityType, _workflow );
                    }
                }

                List<string> errorMessages;
                if ( _workflow.Process( _rockContext, out errorMessages ) )
                {
                    if ( _workflow.IsPersisted || _workflowType.IsPersisted )
                    {
                        if ( _workflow.Id == 0 )
                        {
                            _workflowService.Add( _workflow );
                        }

                        RockTransactionScope.WrapTransaction( () =>
                        {
                            _rockContext.SaveChanges();
                            _workflow.SaveAttributeValues( _rockContext );
                            foreach ( var activity in _workflow.Activities )
                            {
                                activity.SaveAttributeValues( _rockContext );
                            }
                        } );

                        WorkflowId = _workflow.Id;
                    }

                    int? previousActivityId = null;
                    if ( _activity != null )
                    {
                        previousActivityId = _activity.Id;
                    }

                    ActionTypeId = null;
                    _action = null;
                    _actionType = null;
                    _activity = null;

                    if ( HydrateObjects() && _activity.Id != previousActivityId )
                    {
                        BuildForm( true );
                    }
                    else
                    {
                        ShowMessage( NotificationBoxType.Success, string.Empty, responseText, ( _activity == null || _activity.Id != previousActivityId ) );
                    }
                }
                else
                {
                    ShowMessage( NotificationBoxType.Danger, "Workflow Processing Error(s):", errorMessages.AsDelimited( "<br/>" ) );
                }
            }
        }
Exemplo n.º 35
0
        private bool HydrateObjects()
        {
            LoadWorkflowType();

            if ( _workflowType == null )
            {
                ShowMessage( NotificationBoxType.Danger, "Configuration Error", "Workflow type was not configured or specified correctly." );
                return false;
            }

            if ( !_workflowType.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
            {
                ShowMessage( NotificationBoxType.Warning, "Sorry", "You are not authorized to view this type of workflow." );
                return false;
            }

            // If operating against an existing workflow, get the workflow and load attributes
            if ( !WorkflowId.HasValue )
            {
                WorkflowId = PageParameter( "WorkflowId" ).AsIntegerOrNull();
                if ( !WorkflowId.HasValue )
                {
                    Guid guid = PageParameter( "WorkflowGuid" ).AsGuid();
                    if ( !guid.IsEmpty() )
                    {
                        _workflow = _workflowService.Queryable()
                            .Where( w => w.Guid.Equals( guid ) && w.WorkflowTypeId == _workflowType.Id )
                            .FirstOrDefault();
                        if ( _workflow != null )
                        {
                            WorkflowId = _workflow.Id;
                        }
                    }
                }
            }

            if ( WorkflowId.HasValue )
            {
                if ( _workflow == null )
                {
                    _workflow = _workflowService.Queryable()
                        .Where( w => w.Id == WorkflowId.Value && w.WorkflowTypeId == _workflowType.Id )
                        .FirstOrDefault();
                }
                if ( _workflow != null )
                {
                    _workflow.LoadAttributes();
                    foreach ( var activity in _workflow.Activities )
                    {
                        activity.LoadAttributes();
                    }
                }

            }

            // If an existing workflow was not specified, activate a new instance of workflow and start processing
            if ( _workflow == null )
            {
                _workflow = Rock.Model.Workflow.Activate( _workflowType, "Workflow" );

                List<string> errorMessages;
                if ( _workflow.Process( _rockContext, out errorMessages ) )
                {
                    // If the workflow type is persisted, save the workflow
                    if ( _workflow.IsPersisted || _workflowType.IsPersisted )
                    {
                        _workflowService.Add( _workflow );

                        RockTransactionScope.WrapTransaction( () =>
                        {
                            _rockContext.SaveChanges();
                            _workflow.SaveAttributeValues( _rockContext );
                            foreach ( var activity in _workflow.Activities )
                            {
                                activity.SaveAttributeValues( _rockContext );
                            }
                        } );

                        WorkflowId = _workflow.Id;
                    }
                }
            }

            if ( _workflow == null )
            {
                ShowMessage( NotificationBoxType.Danger, "Workflow Activation Error", "Workflow could not be activated." );
                return false;
            }

            if ( _workflow.IsActive )
            {
                if ( ActionTypeId.HasValue )
                {
                    foreach ( var activity in _workflow.ActiveActivities )
                    {
                        _action = activity.Actions.Where( a => a.ActionTypeId == ActionTypeId.Value ).FirstOrDefault();
                        if ( _action != null )
                        {
                            _activity = activity;
                            _activity.LoadAttributes();

                            _actionType = _action.ActionType;
                            ActionTypeId = _actionType.Id;
                            return true;
                        }
                    }
                }

                var canEdit = IsUserAuthorized( Authorization.EDIT );

                // Find first active action form
                int personId = CurrentPerson != null ? CurrentPerson.Id : 0;
                foreach ( var activity in _workflow.Activities
                    .Where( a =>
                        a.IsActive &&
                        (
                            ( !a.AssignedGroupId.HasValue && !a.AssignedPersonAliasId.HasValue ) ||
                            ( a.AssignedPersonAlias != null && a.AssignedPersonAlias.PersonId == personId ) ||
                            ( a.AssignedGroup != null && a.AssignedGroup.Members.Any( m => m.PersonId == personId ) )
                        )
                    )
                    .OrderBy( a => a.ActivityType.Order ) )
                {
                    if ( canEdit || ( activity.ActivityType.IsAuthorized( Authorization.VIEW, CurrentPerson ) ) )
                    {
                        foreach ( var action in activity.ActiveActions )
                        {
                            if ( action.ActionType.WorkflowForm != null )
                            {
                                _activity = activity;
                                _activity.LoadAttributes();

                                _action = action;
                                _actionType = _action.ActionType;
                                ActionTypeId = _actionType.Id;
                                return true;
                            }
                        }
                    }
                }
            }

            ShowMessage( NotificationBoxType.Warning, string.Empty, "The selected workflow is not in a state that requires you to enter information." );
            return false;

        }
Exemplo n.º 36
0
        /// <summary>
        /// Gets or sets the workflow activity.
        /// </summary>
        /// <param name="activity">The activity.</param>
        /// <param name="expandInvalid">if set to <c>true</c> [expand invalid].</param>
        /// <value>
        /// The workflow activity.
        /// </value>
        public void GetWorkflowActivity( WorkflowActivity activity, bool expandInvalid )
        {
            EnsureChildControls();

            if ( !activity.CompletedDateTime.HasValue && _cbActivityIsComplete.Checked )
            {
                activity.CompletedDateTime = RockDateTime.Now;
            }
            else if ( activity.CompletedDateTime.HasValue && !_cbActivityIsComplete.Checked )
            {
                activity.CompletedDateTime = null;
            }

            if (_ppAssignedToPerson.SelectedValue.HasValue)
            {
                activity.AssignedPersonAliasId = _ppAssignedToPerson.SelectedValue;
            } 
            else if (_gpAssignedToGroup.SelectedValueAsInt().HasValue)
            {
                activity.AssignedGroupId = _gpAssignedToGroup.SelectedValueAsInt();
            }
            else if (_ddlAssignedToRole.SelectedValueAsInt().HasValue)
            {
                activity.AssignedGroupId = _ddlAssignedToRole.SelectedValueAsInt();
            }

            Attribute.Helper.GetEditValues( _phAttributes, activity );

            foreach ( WorkflowActionEditor actionEditor in this.Controls.OfType<WorkflowActionEditor>() )
            {
                var action = activity.Actions.Where( a => a.Guid.Equals(actionEditor.ActionGuid)).FirstOrDefault();
                if (action != null)
                {
                    actionEditor.GetWorkflowAction( action );
                }
            }

            if (expandInvalid && !Expanded && !activity.IsValid)
            {
                Expanded = true;
            }
        }
Exemplo n.º 37
0
        /// <summary>
        /// Sets the workflow activity.
        /// </summary>
        /// <param name="activity">The value.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="setValues">if set to <c>true</c> [set values].</param>
        public void SetWorkflowActivity( WorkflowActivity activity, RockContext rockContext, bool setValues = false )
        {
            EnsureChildControls();

            _hfActivityGuid.Value = activity.Guid.ToString();

            _lblActivityTypeName.Text = activity.ActivityType.Name;
            _lblActivityTypeDescription.Text = activity.ActivityType.Description;

            if ( activity.CompletedDateTime.HasValue )
            {
                _lblStatus.Visible = true;
                _lblStatus.Text = "<span class='label label-default'>Completed</span>";
            }
            else if (activity.ActivatedDateTime.HasValue)
            {
                _lblStatus.Visible = true;
                _lblStatus.Text = "<span class='label label-success'>Active</span>";
            }
            else
            {
                _lblStatus.Visible = false;
                _lblStatus.Text = string.Empty;
            }

            _cbActivityIsComplete.Checked = activity.CompletedDateTime.HasValue;

            if ( activity.AssignedPersonAliasId.HasValue )
            {
                var person =  new PersonAliasService( rockContext).Queryable()
                    .Where( a => a.Id == activity.AssignedPersonAliasId.Value )
                    .Select( a => a.Person )
                    .FirstOrDefault();
                if ( person != null )
                {
                    _ppAssignedToPerson.SetValue( person );
                    _lAssignedToPerson.Text = person.FullName;
                }
            }

            if ( activity.AssignedGroupId.HasValue )
            {
                var group = new GroupService( rockContext ).Get( activity.AssignedGroupId.Value );
                if ( group != null )
                {
                    if ( group.IsSecurityRole )
                    {
                        _ddlAssignedToRole.SetValue( group.Id );
                        _gpAssignedToGroup.SetValue( null );
                        _lAssignedToRole.Text = group.Name;
                    }
                    else
                    {
                        _ddlAssignedToRole.SelectedIndex = -1;
                        _gpAssignedToGroup.SetValue( group );
                        _lAssignedToGroup.Text = group.Name;
                    }
                }
            }

            var sbState = new StringBuilder();
            if ( activity.ActivatedDateTime.HasValue )
            {
                sbState.AppendFormat( "<strong>Activated:</strong> {0} {1} ({2})<br/>",
                    activity.ActivatedDateTime.Value.ToShortDateString(),
                    activity.ActivatedDateTime.Value.ToShortTimeString(),
                    activity.ActivatedDateTime.Value.ToRelativeDateString() );
            }
            if ( activity.CompletedDateTime.HasValue )
            {
                sbState.AppendFormat( "<strong>Completed:</strong> {0} {1} ({2})",
                    activity.CompletedDateTime.Value.ToShortDateString(),
                    activity.CompletedDateTime.Value.ToShortTimeString(),
                    activity.CompletedDateTime.Value.ToRelativeDateString() );
            }
            _lState.Text = sbState.ToString();

            _phAttributes.Controls.Clear();
            if ( CanEdit )
            {
                Rock.Attribute.Helper.AddEditControls( activity, _phAttributes, setValues, ValidationGroup );
            }
            else
            {
                Rock.Attribute.Helper.AddDisplayControls( activity, _phAttributes );
            }
        }
Exemplo n.º 38
0
        /// <summary>
        /// Sets the workflow activity.
        /// </summary>
        /// <param name="activity">The value.</param>
        /// <param name="setValues">if set to <c>true</c> [set values].</param>
        public void SetWorkflowActivity( WorkflowActivity activity, bool setValues = false )
        {
            EnsureChildControls();

            _hfActivityGuid.Value = activity.Guid.ToString();

            _lblActivityTypeName.Text = activity.ActivityType.Name;
            _lblActivityTypeDescription.Text = activity.ActivityType.Description;

            if ( activity.CompletedDateTime.HasValue )
            {
                _lblStatus.Visible = true;
                _lblStatus.Text = "<span class='label label-danger'>Completed</span>";
            }
            else if (activity.ActivatedDateTime.HasValue)
            {
                _lblStatus.Visible = true;
                _lblStatus.Text = "<span class='label label-success'>Active</span>";
            }
            else
            {
                _lblStatus.Visible = false;
                _lblStatus.Text = string.Empty;
            }

            _cbActivityIsComplete.Checked = activity.CompletedDateTime.HasValue;

            if (activity.AssignedPersonAlias != null && activity.AssignedPersonAlias.Person != null)
            {
                _ppAssignedToPerson.SetValue( activity.AssignedPersonAlias.Person );
            }
            else if ( activity.AssignedGroup != null)
            {
                if (activity.AssignedGroup.IsSecurityRole )
                {
                    _ddlAssignedToRole.SetValue( activity.AssignedGroup.Id );
                }
                else
                {
                    _gpAssignedToGroup.SetValue( activity.AssignedGroup );
                }
            }

            var sbState = new StringBuilder();
            if ( activity.ActivatedDateTime.HasValue )
            {
                sbState.AppendFormat( "<strong>Activated:</strong> {0} {1} ({2})<br/>",
                    activity.ActivatedDateTime.Value.ToShortDateString(),
                    activity.ActivatedDateTime.Value.ToShortTimeString(),
                    activity.ActivatedDateTime.Value.ToRelativeDateString() );
            }
            if ( activity.CompletedDateTime.HasValue )
            {
                sbState.AppendFormat( "<strong>Completed:</strong> {0} {1} ({2})",
                    activity.CompletedDateTime.Value.ToShortDateString(),
                    activity.CompletedDateTime.Value.ToShortTimeString(),
                    activity.CompletedDateTime.Value.ToRelativeDateString() );
            }
            _lState.Text = sbState.ToString();

            _phAttributes.Controls.Clear();
            Rock.Attribute.Helper.AddEditControls( activity, _phAttributes, setValues, ValidationGroup );
        }
        private List<WorkflowAction> GetWorkflows()
        {
            var actions = new List<WorkflowAction>();

            if ( CurrentPerson != null )
            {
                using ( var rockContext = new RockContext() )
                {
                    var categoryIds = GetCategories( rockContext );

                    var qry = new WorkflowService( rockContext ).Queryable()
                        .Where( w =>
                            w.ActivatedDateTime.HasValue &&
                            !w.CompletedDateTime.HasValue &&
                            w.InitiatorPersonAlias.PersonId == CurrentPerson.Id );

                    if ( categoryIds.Any() )
                    {
                        qry = qry
                            .Where( w =>
                                w.WorkflowType.CategoryId.HasValue &&
                                categoryIds.Contains( w.WorkflowType.CategoryId.Value ) );
                    }

                    foreach ( var workflow in qry.OrderBy( w => w.ActivatedDateTime ) )
                    {
                        var activity = new WorkflowActivity();
                        activity.Workflow = workflow;

                        var action = new WorkflowAction();
                        action.Activity = activity;

                        actions.Add( action );
                    }
                }
            }

            return actions;
        }