Exemplo n.º 1
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute(RockContext rockContext, Model.WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);

            if (checkInState == null)
            {
                return(false);
            }

            var family = checkInState.CheckIn.CurrentFamily;

            if (family != null)
            {
                var  remove      = GetAttributeValue(action, "Remove").AsBoolean();
                bool ageRequired = checkInState.CheckInType == null || checkInState.CheckInType.AgeRequired;

                // get the Age Range
                var ageRangeAttributeKey  = string.Empty;
                var ageRangeAttributeGuid = GetAttributeValue(action, "GroupAgeRangeAttribute").AsGuidOrNull();
                if (ageRangeAttributeGuid.HasValue)
                {
                    var attribute = AttributeCache.Get(ageRangeAttributeGuid.Value, rockContext);
                    if (attribute != null)
                    {
                        ageRangeAttributeKey = attribute.Key;
                    }
                }

                // get the admin-selected attribute key instead of using a hardcoded key
                var birthdateRangeAttributeKey  = string.Empty;
                var birthdateRangeAttributeGuid = GetAttributeValue(action, "GroupBirthdateRangeAttribute").AsGuidOrNull();
                if (birthdateRangeAttributeGuid.HasValue)
                {
                    var attribute = AttributeCache.Get(birthdateRangeAttributeGuid.Value, rockContext);
                    if (attribute != null)
                    {
                        birthdateRangeAttributeKey = attribute.Key;
                    }
                }

                foreach (var person in family.People)
                {
                    var      ageAsDouble = person.Person.AgePrecise;
                    decimal? age         = ageAsDouble.HasValue ? Convert.ToDecimal(ageAsDouble.Value) : (decimal?)null;
                    DateTime?birthdate   = person.Person.BirthDate;

                    foreach (var groupType in person.GroupTypes.ToList())
                    {
                        foreach (var group in groupType.Groups.ToList())
                        {
                            bool?ageMatch      = null;
                            bool?birthdayMatch = null;

                            // First check to see if age matches
                            if (!string.IsNullOrWhiteSpace(ageRangeAttributeKey))
                            {
                                var    ageRange     = group.Group.GetAttributeValue(ageRangeAttributeKey).ToStringSafe();
                                var    ageRangePair = ageRange.Split(new char[] { ',' }, StringSplitOptions.None);
                                string minAgeValue  = null;
                                string maxAgeValue  = null;
                                if (ageRangePair.Length == 2)
                                {
                                    minAgeValue = ageRangePair[0];
                                    maxAgeValue = ageRangePair[1];
                                }

                                decimal?minAge = minAgeValue.AsDecimalOrNull();
                                decimal?maxAge = maxAgeValue.AsDecimalOrNull();

                                if (minAge.HasValue || maxAge.HasValue)
                                {
                                    if (age.HasValue)
                                    {
                                        if (minAge.HasValue)
                                        {
                                            int     groupMinAgePrecision = minAge.Value.GetDecimalPrecision();
                                            decimal?personAgePrecise     = age.Floor(groupMinAgePrecision);
                                            if (personAgePrecise < minAge)
                                            {
                                                ageMatch = false;
                                            }
                                        }

                                        if (maxAge.HasValue)
                                        {
                                            int     groupMaxAgePrecision = maxAge.Value.GetDecimalPrecision();
                                            decimal?personAgePrecise     = age.Floor(groupMaxAgePrecision);
                                            if (personAgePrecise > maxAge)
                                            {
                                                ageMatch = false;
                                            }
                                        }

                                        if (!ageMatch.HasValue)
                                        {
                                            ageMatch = true;
                                        }
                                    }
                                    else
                                    {
                                        if (ageRequired)
                                        {
                                            ageMatch = false;
                                        }
                                    }
                                }
                            }

                            if ((!ageMatch.HasValue || !ageMatch.Value) && !string.IsNullOrWhiteSpace(birthdateRangeAttributeKey))
                            {
                                var    birthdateRange     = group.Group.GetAttributeValue(birthdateRangeAttributeKey).ToStringSafe();
                                var    birthdateRangePair = birthdateRange.Split(new char[] { ',' }, StringSplitOptions.None);
                                string minBirthdateValue  = null;
                                string maxBirthdateValue  = null;

                                if (birthdateRangePair.Length == 2)
                                {
                                    minBirthdateValue = birthdateRangePair[0];
                                    maxBirthdateValue = birthdateRangePair[1];
                                }

                                DateTime?minBirthdate = minBirthdateValue.AsDateTime();
                                DateTime?maxBirthdate = maxBirthdateValue.AsDateTime();
                                if (minBirthdate.HasValue || maxBirthdate.HasValue)
                                {
                                    if (birthdate.HasValue)
                                    {
                                        if (minBirthdate.HasValue && birthdate.Value < minBirthdate.Value)
                                        {
                                            birthdayMatch = false;
                                        }

                                        if (maxBirthdate.HasValue && birthdate.Value > maxBirthdate.Value)
                                        {
                                            birthdayMatch = false;
                                        }

                                        if (!birthdayMatch.HasValue)
                                        {
                                            birthdayMatch = true;
                                        }
                                    }
                                    else
                                    {
                                        if (ageRequired)
                                        {
                                            birthdayMatch = false;
                                        }
                                    }
                                }
                            }

                            if ((ageMatch.HasValue || birthdayMatch.HasValue) && !((ageMatch ?? false) || (birthdayMatch ?? false)))
                            {
                                if (remove)
                                {
                                    groupType.Groups.Remove(group);
                                }
                                else
                                {
                                    group.ExcludedByFilter = true;
                                }
                            }
                        }
                    }
                }
            }

            return(true);
        }
        /// <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?  groupGuid      = null;
            Person person         = null;
            string attributeValue = string.Empty;
            Guid   groupRoleGuid  = Guid.Empty;
            string attributeKey   = string.Empty;

            // get the group attribute
            Guid groupAttributeGuid = GetAttributeValue(action, "Group").AsGuid();

            if (!groupAttributeGuid.IsEmpty())
            {
                groupGuid = action.GetWorklowAttributeValue(groupAttributeGuid).AsGuidOrNull();

                if (!groupGuid.HasValue)
                {
                    errorMessages.Add("The group could not be found!");
                }
            }

            // get person alias guid
            Guid   personAliasGuid = Guid.Empty;
            string personAttribute = GetAttributeValue(action, "Person");

            Guid guid = personAttribute.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Read(guid, rockContext);
                if (attribute != null)
                {
                    string value = action.GetWorklowAttributeValue(guid);
                    personAliasGuid = value.AsGuid();
                }

                if (personAliasGuid != Guid.Empty)
                {
                    person = new PersonAliasService(rockContext).Queryable().AsNoTracking()
                             .Where(p => p.Guid.Equals(personAliasGuid))
                             .Select(p => p.Person)
                             .FirstOrDefault();
                }
                else
                {
                    errorMessages.Add("The person could not be found in the attribute!");
                }
            }

            // get group member attribute value
            attributeValue = GetAttributeValue(action, "AttributeValue");
            guid           = attributeValue.AsGuid();
            if (guid.IsEmpty())
            {
                attributeValue = attributeValue.ResolveMergeFields(GetMergeFields(action));
            }
            else
            {
                var workflowAttributeValue = action.GetWorklowAttributeValue(guid);

                if (workflowAttributeValue != null)
                {
                    attributeValue = workflowAttributeValue;
                }
            }

            // get optional role filter
            groupRoleGuid = GetAttributeValue(action, "GroupRoleFilter").AsGuid();

            // get attribute key
            attributeKey = GetAttributeValue(action, "GroupMemberAttributeKey").Replace(" ", "");

            // set attribute
            if (groupGuid.HasValue && person != null)
            {
                var qry = new GroupMemberService(rockContext).Queryable()
                          .Where(m => m.Group.Guid == groupGuid && m.PersonId == person.Id);

                if (groupRoleGuid != Guid.Empty)
                {
                    qry = qry.Where(m => m.GroupRole.Guid == groupRoleGuid);
                }

                foreach (var groupMember in qry.ToList())
                {
                    groupMember.LoadAttributes(rockContext);
                    if (groupMember.Attributes.ContainsKey(attributeKey))
                    {
                        var attribute = groupMember.Attributes[attributeKey];
                        Rock.Attribute.Helper.SaveAttributeValue(groupMember, attribute, attributeValue, rockContext);
                    }
                    else
                    {
                        action.AddLogEntry(string.Format("The group member attribute {0} does not exist!", attributeKey));
                        break;
                    }
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
Exemplo n.º 3
0
        private void CreateControls(bool setValues)
        {
            fsAttributes.Controls.Clear();

            string validationGroup = string.Format("vgAttributeValues_{0}", this.BlockId);

            valSummaryTop.ValidationGroup = validationGroup;
            btnSave.ValidationGroup       = validationGroup;

            hfAttributeOrder.Value = AttributeList.AsDelimited("|");

            if (Person != null)
            {
                foreach (int attributeId in AttributeList)
                {
                    var    attribute      = AttributeCache.Read(attributeId);
                    string attributeValue = Person.GetAttributeValue(attribute.Key);
                    string formattedValue = string.Empty;

                    if (ViewMode != VIEW_MODE_EDIT || !attribute.IsAuthorized(Authorization.EDIT, CurrentPerson))
                    {
                        if (ViewMode == VIEW_MODE_ORDER && _canAdministrate)
                        {
                            var div = new HtmlGenericControl("div");
                            fsAttributes.Controls.Add(div);
                            div.Attributes.Add("data-attribute-id", attribute.Id.ToString());
                            div.Attributes.Add("class", "form-group");

                            var a = new HtmlGenericControl("a");
                            div.Controls.Add(a);

                            var i = new HtmlGenericControl("i");
                            a.Controls.Add(i);
                            i.Attributes.Add("class", "fa fa-bars");

                            div.Controls.Add(new LiteralControl(" " + attribute.Name));
                        }
                        else
                        {
                            if (attribute.FieldType.Class == typeof(Rock.Field.Types.ImageFieldType).FullName)
                            {
                                formattedValue = attribute.FieldType.Field.FormatValueAsHtml(fsAttributes, attribute.EntityTypeId, Person.Id, attributeValue, attribute.QualifierValues, true);
                            }
                            else
                            {
                                formattedValue = attribute.FieldType.Field.FormatValueAsHtml(fsAttributes, attribute.EntityTypeId, Person.Id, attributeValue, attribute.QualifierValues, false);
                            }

                            if (!string.IsNullOrWhiteSpace(formattedValue))
                            {
                                if (attribute.FieldType.Class == typeof(Rock.Field.Types.MatrixFieldType).FullName)
                                {
                                    fsAttributes.Controls.Add(new RockLiteral {
                                        Label = attribute.Name, Text = formattedValue, CssClass = "matrix-attribute"
                                    });
                                }
                                else
                                {
                                    fsAttributes.Controls.Add(new RockLiteral {
                                        Label = attribute.Name, Text = formattedValue
                                    });
                                }
                            }
                        }
                    }
                    else
                    {
                        attribute.AddControl(fsAttributes.Controls, attributeValue, validationGroup, setValues, true);
                    }
                }
            }

            pnlActions.Visible = (ViewMode != VIEW_MODE_VIEW);
        }
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>();
            Group  group  = null;
            Person person = null;

            //
            // Get the selected group from the configuration options.
            //
            var groupGuid = GetAttributeValue(action, "GroupExplicit").AsGuidOrNull();

            if (!groupGuid.HasValue)
            {
                var guidGroupAttribute = GetAttributeValue(action, "Group").AsGuidOrNull();
                if (guidGroupAttribute.HasValue)
                {
                    var attributeGroup = AttributeCache.Get(guidGroupAttribute.Value, rockContext);
                    if (attributeGroup != null)
                    {
                        groupGuid = action.GetWorklowAttributeValue(guidGroupAttribute.Value).AsGuidOrNull();
                    }
                }
            }

            if (groupGuid.HasValue)
            {
                group = new GroupService(rockContext).Get(groupGuid.Value);
            }

            if (group == null)
            {
                errorMessages.Add("No group was provided");
            }
            else
            {
                //
                // Get the next person to be picked.
                //
                person = GetNextPerson(action, group.Id);

                if (person == null)
                {
                    errorMessages.Add("Group contains no valid members");
                }
            }

            //
            // Set the attribute value.
            //
            if (!errorMessages.Any())
            {
                //
                // Set value of the selected attribute.
                //
                Guid selectAttributeGuid = GetAttributeValue(action, "Attribute").AsGuid();
                if (!selectAttributeGuid.IsEmpty())
                {
                    var selectedPersonAttribute = AttributeCache.Get(selectAttributeGuid, rockContext);
                    if (selectedPersonAttribute != null)
                    {
                        if (selectedPersonAttribute.FieldTypeId == FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT.AsGuid(), rockContext).Id)
                        {
                            SetWorkflowAttributeValue(action, selectAttributeGuid, person.FullName);
                        }
                        else
                        {
                            SetWorkflowAttributeValue(action, selectAttributeGuid, person.PrimaryAlias.Guid.ToString());
                        }
                    }
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
        /// <summary>
        /// Gets the group placement registrants.
        /// </summary>
        /// <param name="options">The options.</param>
        /// <param name="currentPerson">The current person.</param>
        /// <returns></returns>
        public List <GroupPlacementRegistrant> GetGroupPlacementRegistrants(GetGroupPlacementRegistrantsParameters options, Person currentPerson)
        {
            var rockContext = this.Context as RockContext;

            var registrationRegistrantService = new RegistrationRegistrantService(rockContext);
            var registrationRegistrantQuery   = registrationRegistrantService.Queryable();

            registrationRegistrantQuery = registrationRegistrantQuery
                                          .Where(a => a.Registration.RegistrationInstance.RegistrationTemplateId == options.RegistrationTemplateId);

            if (options.RegistrationInstanceId.HasValue)
            {
                registrationRegistrantQuery = registrationRegistrantQuery.Where(a => a.Registration.RegistrationInstanceId == options.RegistrationInstanceId.Value);
            }
            else if (options.RegistrationTemplateInstanceIds?.Any() == true)
            {
                registrationRegistrantQuery = registrationRegistrantQuery.Where(a => options.RegistrationTemplateInstanceIds.Contains(a.Registration.RegistrationInstanceId));
            }

            if (options.RegistrantPersonDataViewFilterId.HasValue)
            {
                var           dataFilter    = new DataViewFilterService(rockContext).Get(options.RegistrantPersonDataViewFilterId.Value);
                List <string> errorMessages = new List <string>();

                var personService   = new PersonService(rockContext);
                var paramExpression = personService.ParameterExpression;

                var personWhereExpression = dataFilter?.GetExpression(typeof(Person), personService, paramExpression, errorMessages);
                if (personWhereExpression != null)
                {
                    var personIdQry = personService.Queryable().Where(paramExpression, personWhereExpression, null).Select(x => x.Id);
                    registrationRegistrantQuery = registrationRegistrantQuery.Where(a => personIdQry.Contains(a.PersonAlias.PersonId));
                }
            }

            if (options.RegistrantId.HasValue)
            {
                registrationRegistrantQuery = registrationRegistrantQuery.Where(a => a.Id == options.RegistrantId.Value);
            }

            Block registrationInstanceGroupPlacementBlock = new BlockService(rockContext).Get(options.BlockId);

            if (registrationInstanceGroupPlacementBlock != null && currentPerson != null)
            {
                const string RegistrantAttributeFilter_RegistrationInstanceId = "RegistrantAttributeFilter_RegistrationInstanceId_{0}";
                const string RegistrantAttributeFilter_RegistrationTemplateId = "RegistrantAttributeFilter_RegistrationTemplateId_{0}";
                string       userPreferenceKey;
                if (options.RegistrationInstanceId.HasValue)
                {
                    userPreferenceKey = PersonService.GetBlockUserPreferenceKeyPrefix(options.BlockId) + string.Format(RegistrantAttributeFilter_RegistrationInstanceId, options.RegistrationInstanceId);
                }
                else
                {
                    userPreferenceKey = PersonService.GetBlockUserPreferenceKeyPrefix(options.BlockId) + string.Format(RegistrantAttributeFilter_RegistrationTemplateId, options.RegistrationTemplateId);
                }

                var        attributeFilters          = PersonService.GetUserPreference(currentPerson, userPreferenceKey).FromJsonOrNull <Dictionary <int, string> >() ?? new Dictionary <int, string>();
                var        parameterExpression       = registrationRegistrantService.ParameterExpression;
                Expression registrantWhereExpression = null;
                foreach (var attributeFilter in attributeFilters)
                {
                    var attribute             = AttributeCache.Get(attributeFilter.Key);
                    var attributeFilterValues = attributeFilter.Value.FromJsonOrNull <List <string> >();
                    var entityField           = EntityHelper.GetEntityFieldForAttribute(attribute);
                    if (entityField != null && attributeFilterValues != null)
                    {
                        var attributeWhereExpression = ExpressionHelper.GetAttributeExpression(registrationRegistrantService, parameterExpression, entityField, attributeFilterValues);
                        if (registrantWhereExpression == null)
                        {
                            registrantWhereExpression = attributeWhereExpression;
                        }
                        else
                        {
                            registrantWhereExpression = Expression.AndAlso(registrantWhereExpression, attributeWhereExpression);
                        }
                    }
                }

                if (registrantWhereExpression != null)
                {
                    registrationRegistrantQuery = registrationRegistrantQuery.Where(parameterExpression, registrantWhereExpression);
                }
            }

            var registrationTemplatePlacement = new RegistrationTemplatePlacementService(rockContext).Get(options.RegistrationTemplatePlacementId);

            if (options.FilterFeeId.HasValue)
            {
                registrationRegistrantQuery = registrationRegistrantQuery.Where(a => a.Fees.Any(f => f.RegistrationTemplateFeeId == options.FilterFeeId.Value));
            }

            if (options.FilterFeeOptionIds?.Any() == true)
            {
                registrationRegistrantQuery = registrationRegistrantQuery.Where(a => a.Fees.Any(f => f.RegistrationTemplateFeeItemId.HasValue && options.FilterFeeOptionIds.Contains(f.RegistrationTemplateFeeItemId.Value)));
            }

            // don't include registrants that are on the waiting list
            registrationRegistrantQuery = registrationRegistrantQuery.Where(a => a.OnWaitList == false);

            registrationRegistrantQuery = registrationRegistrantQuery.OrderBy(a => a.PersonAlias.Person.LastName).ThenBy(a => a.PersonAlias.Person.NickName);

            var registrationTemplatePlacementService = new RegistrationTemplatePlacementService(rockContext);
            var registrationInstanceService          = new RegistrationInstanceService(rockContext);

            // get a queryable of PersonIds for the registration template shared groups so we can determine if the registrant has been placed
            var registrationTemplatePlacementGroupsPersonIdQuery = registrationTemplatePlacementService.GetRegistrationTemplatePlacementPlacementGroups(registrationTemplatePlacement).SelectMany(a => a.Members).Select(a => a.PersonId);

            // and also get a queryable of PersonIds for the registration instance placement groups so we can determine if the registrant has been placed
            IQueryable <InstancePlacementGroupPersonId> allInstancesPlacementGroupInfoQuery = null;

            if (!options.RegistrationInstanceId.HasValue && (options.RegistrationTemplateInstanceIds == null || !options.RegistrationTemplateInstanceIds.Any()))
            {
                // if neither RegistrationInstanceId or RegistrationTemplateInstanceIds was specified, use all of the RegistrationTemplates instances
                options.RegistrationTemplateInstanceIds = new RegistrationTemplateService(rockContext).GetSelect(options.RegistrationTemplateId, s => s.Instances.Select(i => i.Id)).ToArray();
            }

            if (options.RegistrationInstanceId.HasValue)
            {
                allInstancesPlacementGroupInfoQuery =
                    registrationInstanceService.GetRegistrationInstancePlacementGroups(registrationInstanceService.Get(options.RegistrationInstanceId.Value))
                    .Where(a => a.GroupTypeId == registrationTemplatePlacement.GroupTypeId)
                    .SelectMany(a => a.Members).Select(a => a.PersonId)
                    .Select(s => new InstancePlacementGroupPersonId
                {
                    PersonId = s,
                    RegistrationInstanceId = options.RegistrationInstanceId.Value
                });
            }
            else if (options.RegistrationTemplateInstanceIds?.Any() == true)
            {
                foreach (var registrationInstanceId in options.RegistrationTemplateInstanceIds)
                {
                    var instancePlacementGroupInfoQuery = registrationInstanceService.GetRegistrationInstancePlacementGroups(registrationInstanceService.Get(registrationInstanceId))
                                                          .Where(a => a.GroupTypeId == registrationTemplatePlacement.GroupTypeId)
                                                          .SelectMany(a => a.Members).Select(a => a.PersonId)
                                                          .Select(s => new InstancePlacementGroupPersonId
                    {
                        PersonId = s,
                        RegistrationInstanceId = registrationInstanceId
                    });

                    if (allInstancesPlacementGroupInfoQuery == null)
                    {
                        allInstancesPlacementGroupInfoQuery = instancePlacementGroupInfoQuery;
                    }
                    else
                    {
                        allInstancesPlacementGroupInfoQuery = allInstancesPlacementGroupInfoQuery.Union(instancePlacementGroupInfoQuery);
                    }
                }
            }

            if (allInstancesPlacementGroupInfoQuery == null)
            {
                throw new ArgumentNullException("Registration Instance(s) must be specified");
            }

            // select in a way to avoid lazy loading
            var registrationRegistrantPlacementQuery = registrationRegistrantQuery.Select(r => new
            {
                Registrant = r,
                r.PersonAlias.Person,
                r.Registration.RegistrationInstance,

                // marked as AlreadyPlacedInGroup if the Registrant is a member of any of the registrant template placement group or the registration instance placement groups
                AlreadyPlacedInGroup =
                    registrationTemplatePlacementGroupsPersonIdQuery.Contains(r.PersonAlias.PersonId) ||
                    allInstancesPlacementGroupInfoQuery.Any(x => x.RegistrationInstanceId == r.Registration.RegistrationInstanceId && x.PersonId == r.PersonAlias.PersonId)
            });

            var registrationRegistrantPlacementList = registrationRegistrantPlacementQuery.AsNoTracking().ToList();

            var groupPlacementRegistrantList = registrationRegistrantPlacementList
                                               .Select(x => new GroupPlacementRegistrant(x.Registrant, x.Person, x.AlreadyPlacedInGroup, x.RegistrationInstance, options))
                                               .ToList();

            return(groupPlacementRegistrantList.ToList());
        }
Exemplo n.º 6
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        /// <param name="report">The report.</param>
        /// <param name="gReport">The g report.</param>
        /// <param name="currentPerson">The current person.</param>
        /// <param name="dataViewFilterOverrides">The data view filter overrides.</param>
        /// <param name="databaseTimeoutSeconds">The database timeout seconds.</param>
        /// <param name="isCommunication">if set to <c>true</c> [is communication].</param>
        /// <param name="errorMessage">The error message.</param>
        public static void BindGrid(Report report, Grid gReport, Person currentPerson, DataViewFilterOverrides dataViewFilterOverrides, int?databaseTimeoutSeconds, bool isCommunication, out string errorMessage)
        {
            errorMessage = null;
            if (report != null)
            {
                var errors = new List <string>();

                if (!report.EntityTypeId.HasValue)
                {
                    gReport.Visible = false;
                    return;
                }

                var rockContext = new RockContext();

                if (!report.IsAuthorized(Authorization.VIEW, currentPerson))
                {
                    gReport.Visible = false;
                    return;
                }

                Type entityType = EntityTypeCache.Get(report.EntityTypeId.Value, rockContext).GetEntityType();
                if (entityType == null)
                {
                    errorMessage = string.Format("Unable to determine entityType for {0}", report.EntityType);
                    return;
                }

                gReport.EntityTypeId = report.EntityTypeId;

                bool isPersonDataSet = report.EntityTypeId == EntityTypeCache.Get(typeof(Rock.Model.Person), true, rockContext).Id;

                if (isPersonDataSet)
                {
                    gReport.PersonIdField = "Id";
                    gReport.DataKeyNames  = new string[] { "Id" };
                }
                else
                {
                    gReport.PersonIdField = null;
                }

                if (report.EntityTypeId.HasValue)
                {
                    gReport.RowItemText = EntityTypeCache.Get(report.EntityTypeId.Value, rockContext).FriendlyName;
                }

                List <EntityField> entityFields = Rock.Reporting.EntityHelper.GetEntityFields(entityType, true, false);

                var selectedEntityFields = new Dictionary <int, EntityField>();
                var selectedAttributes   = new Dictionary <int, AttributeCache>();
                var selectedComponents   = new Dictionary <int, ReportField>();

                // if there is a selectField, keep it to preserve which items are checked
                var selectField = gReport.Columns.OfType <SelectField>().FirstOrDefault();
                gReport.Columns.Clear();
                int columnIndex = 0;

                if (!string.IsNullOrWhiteSpace(gReport.PersonIdField))
                {
                    // if we already had a selectField, use it (to preserve checkbox state)
                    gReport.Columns.Add(selectField ?? new SelectField());
                    columnIndex++;
                }

                var reportFieldSortExpressions = new Dictionary <Guid, string>();

                gReport.CommunicateMergeFields = new List <string>();
                gReport.CommunicationRecipientPersonIdFields = new List <string>();

                foreach (var reportField in report.ReportFields.OrderBy(a => a.ColumnOrder))
                {
                    bool mergeField     = reportField.IsCommunicationMergeField.HasValue && reportField.IsCommunicationMergeField.Value;
                    bool recipientField = reportField.IsCommunicationRecipientField.HasValue && reportField.IsCommunicationRecipientField.Value;

                    columnIndex++;
                    if (reportField.ReportFieldType == ReportFieldType.Property)
                    {
                        var entityField = entityFields.FirstOrDefault(a => a.Name == reportField.Selection);
                        if (entityField != null)
                        {
                            selectedEntityFields.Add(columnIndex, entityField);

                            BoundField boundField = entityField.GetBoundFieldType();
                            boundField.DataField      = string.Format("Entity_{0}_{1}", entityField.Name, columnIndex);
                            boundField.HeaderText     = string.IsNullOrWhiteSpace(reportField.ColumnHeaderText) ? entityField.Title : reportField.ColumnHeaderText;
                            boundField.SortExpression = boundField.DataField;
                            reportFieldSortExpressions.AddOrReplace(reportField.Guid, boundField.SortExpression);
                            boundField.Visible = reportField.ShowInGrid;
                            gReport.Columns.Add(boundField);

                            if (mergeField)
                            {
                                gReport.CommunicateMergeFields.Add($"{boundField.DataField}|{boundField.HeaderText.RemoveSpecialCharacters()}");
                            }
                            if (recipientField)
                            {
                                gReport.CommunicationRecipientPersonIdFields.Add(boundField.DataField);
                            }
                        }
                    }
                    else if (reportField.ReportFieldType == ReportFieldType.Attribute)
                    {
                        Guid?attributeGuid = reportField.Selection.AsGuidOrNull();
                        if (attributeGuid.HasValue)
                        {
                            var attribute = AttributeCache.Get(attributeGuid.Value, rockContext);
                            if (attribute != null)
                            {
                                selectedAttributes.Add(columnIndex, attribute);

                                BoundField boundField;

                                if (attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.BOOLEAN.AsGuid()))
                                {
                                    boundField = new BoolField();
                                }
                                else if (attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.DEFINED_VALUE.AsGuid()))
                                {
                                    boundField = new DefinedValueField();
                                }
                                else
                                {
                                    boundField            = new CallbackField();
                                    boundField.HtmlEncode = false;
                                    (boundField as CallbackField).OnFormatDataValue += (sender, e) => {
                                        string resultHtml = null;
                                        if (e.DataValue != null)
                                        {
                                            bool condensed = true;
                                            resultHtml = attribute.FieldType.Field.FormatValueAsHtml(gReport, e.DataValue.ToString(), attribute.QualifierValues, condensed);
                                        }

                                        e.FormattedValue = resultHtml ?? string.Empty;
                                    };
                                }

                                boundField.DataField      = string.Format("Attribute_{0}_{1}", attribute.Id, columnIndex);
                                boundField.HeaderText     = string.IsNullOrWhiteSpace(reportField.ColumnHeaderText) ? attribute.Name : reportField.ColumnHeaderText;
                                boundField.SortExpression = boundField.DataField;
                                reportFieldSortExpressions.AddOrReplace(reportField.Guid, boundField.SortExpression);

                                if (attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.INTEGER.AsGuid()) ||
                                    attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.DATE.AsGuid()) ||
                                    attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.FILTER_DATE.AsGuid()))
                                {
                                    boundField.HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
                                    boundField.ItemStyle.HorizontalAlign   = HorizontalAlign.Right;
                                }

                                boundField.Visible = reportField.ShowInGrid;

                                gReport.Columns.Add(boundField);

                                if (mergeField)
                                {
                                    gReport.CommunicateMergeFields.Add($"{boundField.DataField}|{boundField.HeaderText.RemoveSpecialCharacters()}");
                                }
                                if (recipientField)
                                {
                                    gReport.CommunicationRecipientPersonIdFields.Add(boundField.DataField);
                                }
                            }
                        }
                    }
                    else if (reportField.ReportFieldType == ReportFieldType.DataSelectComponent)
                    {
                        selectedComponents.Add(columnIndex, reportField);

                        DataSelectComponent selectComponent = DataSelectContainer.GetComponent(reportField.DataSelectComponentEntityType.Name);
                        if (selectComponent != null)
                        {
                            try
                            {
                                DataControlField columnField = selectComponent.GetGridField(entityType, reportField.Selection ?? string.Empty);
                                string           fieldId     = $"{selectComponent.ColumnPropertyName}_{columnIndex}";

                                if (columnField is BoundField)
                                {
                                    (columnField as BoundField).DataField = $"Data_{fieldId}";
                                    var  customSortProperties = selectComponent.SortProperties(reportField.Selection ?? string.Empty);
                                    bool sortReversed         = selectComponent.SortReversed(reportField.Selection ?? string.Empty);
                                    if (customSortProperties != null)
                                    {
                                        if (customSortProperties == string.Empty)
                                        {
                                            // disable sorting if customSortExpression set to string.empty
                                            columnField.SortExpression = string.Empty;
                                        }
                                        else
                                        {
                                            columnField.SortExpression = customSortProperties.Split(',').Select(a => string.Format("Sort_{0}_{1}", a, columnIndex)).ToList().AsDelimited(",");
                                        }
                                    }
                                    else
                                    {
                                        // use default sorting if customSortExpression was null
                                        columnField.SortExpression = (columnField as BoundField).DataField;
                                    }

                                    if (sortReversed == true && !string.IsNullOrWhiteSpace(columnField.SortExpression))
                                    {
                                        columnField.SortExpression = columnField.SortExpression + " DESC";
                                    }
                                }

                                columnField.HeaderText = string.IsNullOrWhiteSpace(reportField.ColumnHeaderText) ? selectComponent.ColumnHeaderText : reportField.ColumnHeaderText;
                                if (!string.IsNullOrEmpty(columnField.SortExpression))
                                {
                                    reportFieldSortExpressions.AddOrReplace(reportField.Guid, columnField.SortExpression);
                                }

                                columnField.Visible = reportField.ShowInGrid;
                                gReport.Columns.Add(columnField);

                                if (mergeField)
                                {
                                    gReport.CommunicateMergeFields.Add($"Data_{fieldId}|{columnField.HeaderText.RemoveSpecialCharacters()}");
                                }
                                if (recipientField)
                                {
                                    string fieldName = (selectComponent is IRecipientDataSelect) ? $"Recipient_{fieldId}" : $"Data_{fieldId}";
                                    gReport.CommunicationRecipientPersonIdFields.Add(fieldName);
                                }
                            }
                            catch (Exception ex)
                            {
                                ExceptionLogService.LogException(ex, HttpContext.Current);
                                errors.Add(string.Format("{0} - {1}", selectComponent, ex.Message));
                            }
                        }
                    }
                }

                // if no fields are specified, show the default fields (Previewable/All) for the EntityType
                var dataColumns = gReport.Columns.OfType <object>().Where(a => a.GetType() != typeof(SelectField));
                if (dataColumns.Count() == 0)
                {
                    // show either the Previewable Columns or all (if there are no previewable columns)
                    bool showAllColumns = !entityFields.Any(a => a.FieldKind == FieldKind.Property && a.IsPreviewable);
                    foreach (var entityField in entityFields.Where(a => a.FieldKind == FieldKind.Property))
                    {
                        columnIndex++;
                        selectedEntityFields.Add(columnIndex, entityField);

                        BoundField boundField = entityField.GetBoundFieldType();

                        boundField.DataField      = string.Format("Entity_{0}_{1}", entityField.Name, columnIndex);
                        boundField.HeaderText     = entityField.Name;
                        boundField.SortExpression = boundField.DataField;
                        boundField.Visible        = showAllColumns || entityField.IsPreviewable;
                        gReport.Columns.Add(boundField);
                    }
                }

                try
                {
                    gReport.Visible        = true;
                    gReport.ExportFilename = report.Name;
                    SortProperty sortProperty = gReport.SortProperty;
                    if (sortProperty == null)
                    {
                        var reportSort  = new SortProperty();
                        var sortColumns = new Dictionary <string, SortDirection>();
                        foreach (var reportField in report.ReportFields.Where(a => a.SortOrder.HasValue).OrderBy(a => a.SortOrder.Value))
                        {
                            if (reportFieldSortExpressions.ContainsKey(reportField.Guid))
                            {
                                var sortField = reportFieldSortExpressions[reportField.Guid];
                                if (!string.IsNullOrWhiteSpace(sortField))
                                {
                                    sortColumns.Add(sortField, reportField.SortDirection);
                                }
                            }
                        }

                        if (sortColumns.Any())
                        {
                            reportSort.Property = sortColumns.Select(a => a.Key + (a.Value == SortDirection.Descending ? " desc" : string.Empty)).ToList().AsDelimited(",");
                            sortProperty        = reportSort;
                        }
                    }

                    var qryErrors = new List <string>();
                    System.Data.Entity.DbContext reportDbContext;
                    dynamic qry = report.GetQueryable(entityType, selectedEntityFields, selectedAttributes, selectedComponents, sortProperty, dataViewFilterOverrides, databaseTimeoutSeconds ?? 180, isCommunication, out qryErrors, out reportDbContext);
                    errors.AddRange(qryErrors);

                    if (!string.IsNullOrEmpty(report.QueryHint) && reportDbContext is RockContext)
                    {
                        using (new QueryHintScope(reportDbContext as RockContext, report.QueryHint))
                        {
                            gReport.SetLinqDataSource(qry);
                        }
                    }
                    else
                    {
                        gReport.SetLinqDataSource(qry);
                    }

                    gReport.DataBind();
                }
                catch (Exception ex)
                {
                    Exception exception = ex;
                    ExceptionLogService.LogException(ex, HttpContext.Current);
                    while (exception != null)
                    {
                        if (exception is System.Data.SqlClient.SqlException)
                        {
                            // if there was a SQL Server Timeout, have the warning be a friendly message about that.
                            if ((exception as System.Data.SqlClient.SqlException).Number == -2)
                            {
                                errorMessage = "This report did not complete in a timely manner. You can try again or adjust the timeout setting of this block.";
                                return;
                            }
                            else
                            {
                                errors.Add(exception.Message);
                                exception = exception.InnerException;
                            }
                        }
                        else
                        {
                            errors.Add(exception.Message);
                            exception = exception.InnerException;
                        }
                    }
                }

                if (errors.Any())
                {
                    errorMessage = "WARNING: There was a problem with one or more of the report's data components...<br/><br/> " + errors.AsDelimited("<br/>");
                }
            }
        }
Exemplo n.º 7
0
        private void SendEmail(RockContext rockContext, WorkflowAction action)
        {
            var mergeFields = GetMergeFields(action);

            string to        = GetAttributeValue(action, "To");
            string fromValue = GetAttributeValue(action, "From");
            string subject   = GetAttributeValue(action, "Subject");
            string body      = GetAttributeValue(action, "Body");
            bool   createCommunicationRecord = GetAttributeValue(action, "SaveCommunicationHistory").AsBoolean();

            string fromEmail = string.Empty;
            string fromName  = string.Empty;
            Guid?  fromGuid  = fromValue.AsGuidOrNull();

            if (fromGuid.HasValue)
            {
                var attribute = AttributeCache.Read(fromGuid.Value, rockContext);
                if (attribute != null)
                {
                    string fromAttributeValue = action.GetWorklowAttributeValue(fromGuid.Value);
                    if (!string.IsNullOrWhiteSpace(fromAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.PersonFieldType")
                        {
                            Guid personAliasGuid = fromAttributeValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var person = new PersonAliasService(rockContext).Queryable()
                                             .Where(a => a.Guid.Equals(personAliasGuid))
                                             .Select(a => a.Person)
                                             .FirstOrDefault();
                                if (person != null && !string.IsNullOrWhiteSpace(person.Email))
                                {
                                    fromEmail = person.Email;
                                    fromName  = person.FullName;
                                }
                            }
                        }
                        else
                        {
                            fromEmail = fromAttributeValue;
                        }
                    }
                }
            }
            else
            {
                fromEmail = fromValue;
            }

            var metaData = new Dictionary <string, string>();

            metaData.Add("workflow_action_guid", action.Guid.ToString());

            Guid?guid = to.AsGuidOrNull();

            if (guid.HasValue)
            {
                var attribute = AttributeCache.Read(guid.Value, rockContext);
                if (attribute != null)
                {
                    string toValue = action.GetWorklowAttributeValue(guid.Value);
                    if (!string.IsNullOrWhiteSpace(toValue))
                    {
                        switch (attribute.FieldType.Class)
                        {
                        case "Rock.Field.Types.TextFieldType":
                        {
                            Send(toValue, fromEmail, fromName, subject, body, mergeFields, rockContext, createCommunicationRecord, metaData);
                            break;
                        }

                        case "Rock.Field.Types.PersonFieldType":
                        {
                            Guid personAliasGuid = toValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var person = new PersonAliasService(rockContext).Queryable()
                                             .Where(a => a.Guid.Equals(personAliasGuid))
                                             .Select(a => a.Person)
                                             .FirstOrDefault();
                                if (person == null)
                                {
                                    action.AddLogEntry("Invalid Recipient: Person not found", true);
                                }
                                else if (string.IsNullOrWhiteSpace(person.Email))
                                {
                                    action.AddLogEntry("Email was not sent: Recipient does not have an email address", true);
                                }
                                else if (!person.IsEmailActive)
                                {
                                    action.AddLogEntry("Email was not sent: Recipient email is not active", true);
                                }
                                else if (person.EmailPreference == EmailPreference.DoNotEmail)
                                {
                                    action.AddLogEntry("Email was not sent: Recipient has requested 'Do Not Email'", true);
                                }
                                else
                                {
                                    var personDict = new Dictionary <string, object>(mergeFields);
                                    personDict.Add("Person", person);
                                    Send(person.Email, fromEmail, fromName, subject, body, personDict, rockContext, createCommunicationRecord, metaData);
                                }
                            }
                            break;
                        }
                        }
                    }
                }
            }
            else
            {
                Send(to.ResolveMergeFields(mergeFields), fromEmail, fromName, subject, body, mergeFields, rockContext, createCommunicationRecord, metaData);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Parses the where.
        /// </summary>
        /// <param name="whereClause">The where clause.</param>
        /// <param name="type">The type.</param>
        /// <param name="service">The service.</param>
        /// <param name="parmExpression">The parm expression.</param>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="entityTypeCache">The entity type cache.</param>
        /// <returns></returns>
        private Expression ParseWhere(string whereClause, Type type, IService service, ParameterExpression parmExpression, Type entityType, EntityTypeCache entityTypeCache)
        {
            Expression returnExpression = null;

            // find locations of and/or's
            var expressionComponents = Regex.Split(whereClause, @"(\|\||&&)");

            var currentExpressionComparisonType = ExpressionComparisonType.And;

            foreach (var component in expressionComponents)
            {
                if (component == "||")
                {
                    currentExpressionComparisonType = ExpressionComparisonType.Or;
                    continue;
                }

                if (component == "&&")
                {
                    currentExpressionComparisonType = ExpressionComparisonType.And;
                    continue;
                }

                // parse the part to get the expression
                string regexPattern    = @"([a-zA-Z]+)|(==|<=|>=|<|!=|\^=|\*=|\*!|_=|_!|>|\$=|#=)|("".*""|\d+)";
                var    expressionParts = Regex.Matches(component, regexPattern)
                                         .Cast <Match>()
                                         .Select(m => m.Value)
                                         .ToList();

                if (expressionParts.Count == 3)
                {
                    var property     = expressionParts[0];
                    var operatorType = expressionParts[1];
                    var value        = expressionParts[2].Replace("\"", "");

                    List <string> selectionParms = new List <string>();
                    selectionParms.Add(PropertyComparisonConversion(operatorType).ToString());
                    selectionParms.Add(value);
                    selectionParms.Add(property);

                    Expression expression = null;

                    if (entityType.GetProperty(property) != null)
                    {
                        var entityProperty = entityType.GetProperty(property);
                        expression = ExpressionHelper.PropertyFilterExpression(selectionParms, parmExpression, property, entityProperty.PropertyType);
                    }
                    else
                    {
                        AttributeCache filterAttribute          = null;
                        Expression     attributeWhereExpression = null;

                        var attributeKey = property;

                        // We would really love to further qualify this beyond the EntityType by including the
                        // EntityTypeQualifier and EntityTypeQualifierValue but we can't easily do that so, we
                        // will do that "Just in case..." code below (because this actually happened in our Spark
                        // environment.
                        // Also, there could be multiple attributes that have the same key (due to attribute qualifiers or just simply a duplicate key)
                        var entityAttributeListForAttributeKey = AttributeCache.GetByEntity(entityTypeCache.Id)
                                                                 .SelectMany(a => a.AttributeIds)
                                                                 .Select(a => AttributeCache.Get(a))
                                                                 .Where(a => a != null && a.Key == attributeKey).ToList();


                        // Just in case this EntityType has multiple attributes with the same key, create a OR'd clause for each attribute that has this key
                        // NOTE: this could easily happen if doing an entity command against a DefinedValue, and the same attribute key is used in more than one defined type
                        foreach (var attribute in entityAttributeListForAttributeKey)
                        {
                            filterAttribute = attribute;
                            var attributeEntityField = EntityHelper.GetEntityFieldForAttribute(filterAttribute);

                            if (attributeWhereExpression == null)
                            {
                                attributeWhereExpression = ExpressionHelper.GetAttributeExpression(service, parmExpression, attributeEntityField, selectionParms);
                            }
                            else
                            {
                                attributeWhereExpression = Expression.OrElse(attributeWhereExpression, ExpressionHelper.GetAttributeExpression(service, parmExpression, attributeEntityField, selectionParms));
                            }
                        }

                        if (attributeWhereExpression != null)
                        {
                            expression = attributeWhereExpression;
                        }
                    }

                    if (returnExpression == null)
                    {
                        returnExpression = expression;
                    }
                    else
                    {
                        if (expression == null)
                        {
                            // unable to match to property or attribute, so just return what we got
                            return(returnExpression);
                        }

                        if (currentExpressionComparisonType == ExpressionComparisonType.And)
                        {
                            returnExpression = Expression.AndAlso(returnExpression, expression);
                        }
                        else
                        {
                            returnExpression = Expression.OrElse(returnExpression, expression);
                        }
                    }
                }
                else
                {
                    // error in parsing expression
                    throw new Exception("Error in Where expression");
                }
            }

            return(returnExpression);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Builds the controls for the Fields placeholder.
        /// </summary>
        /// <param name="setValues">if set to <c>true</c> [set values].</param>
        private void BuildFields(bool setValues)
        {
            phFields.Controls.Clear();

            if (TemplateState.Forms == null)
            {
                return;
            }

            foreach (var form in TemplateState.Forms.OrderBy(f => f.Order))
            {
                if (form.Fields == null)
                {
                    continue;
                }

                foreach (var field in form.Fields.OrderBy(f => f.Order))
                {
                    if (field.FieldSource == RegistrationFieldSource.RegistrantAttribute)
                    {
                        if (field.AttributeId.HasValue)
                        {
                            object fieldValue = RegistrantState.FieldValues.ContainsKey(field.Id) ? RegistrantState.FieldValues[field.Id].FieldValue : null;
                            string value      = setValues && fieldValue != null?fieldValue.ToString() : null;

                            var attribute = AttributeCache.Get(field.AttributeId.Value);

                            if ((setValues && value == null) || (value.IsNullOrWhiteSpace() && field.IsRequired == true))
                            {
                                // If the value was not set already, or if it is required and currently empty then use the default
                                // Intentionally leaving the possibility of saving an empty string as the value for non-required fields.
                                value = attribute.DefaultValue;
                            }

                            FieldVisibilityWrapper fieldVisibilityWrapper = new FieldVisibilityWrapper
                            {
                                ID = "_fieldVisibilityWrapper_attribute_" + attribute.Id.ToString(),
                                RegistrationTemplateFormFieldId = field.Id,
                                FieldVisibilityRules            = field.FieldVisibilityRules
                            };

                            fieldVisibilityWrapper.EditValueUpdated += FieldVisibilityWrapper_EditValueUpdated;

                            phFields.Controls.Add(fieldVisibilityWrapper);

                            var editControl = attribute.AddControl(fieldVisibilityWrapper.Controls, value, BlockValidationGroup, setValues, true, field.IsRequired, null, field.Attribute.Description);
                            fieldVisibilityWrapper.EditControl = editControl;

                            bool hasDependantVisibilityRule = form.Fields.Any(a => a.FieldVisibilityRules.RuleList.Any(r => r.ComparedToRegistrationTemplateFormFieldGuid == field.Guid));

                            if (hasDependantVisibilityRule && attribute.FieldType.Field.HasChangeHandler(editControl))
                            {
                                attribute.FieldType.Field.AddChangeHandler(editControl, () =>
                                {
                                    fieldVisibilityWrapper.TriggerEditValueUpdated(editControl, new FieldVisibilityWrapper.FieldEventArgs(attribute, editControl));
                                });
                            }
                        }
                    }
                }
            }

            FieldVisibilityWrapper.ApplyFieldVisibilityRules(phFields);
        }
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>();

            // get person
            int?personId = null;

            string personAttributeValue = GetAttributeValue(action, "Person");
            Guid?  guidPersonAttribute  = personAttributeValue.AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Read(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null || attributePerson.FieldType.Class != "Rock.Field.Types.PersonFieldType")
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute.Value);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        Guid personAliasGuid = attributePersonValue.AsGuid();
                        if (!personAliasGuid.IsEmpty())
                        {
                            personId = new PersonAliasService(rockContext).Queryable()
                                       .Where(a => a.Guid.Equals(personAliasGuid))
                                       .Select(a => a.PersonId)
                                       .FirstOrDefault();
                            if (personId == null)
                            {
                                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
                                return(false);
                            }
                        }
                    }
                }
            }

            if (personId == null)
            {
                errorMessages.Add("The attribute used to provide the person was invalid, or not of type 'Person'.");
                return(false);
            }

            // determine the phone type to edit
            DefinedValueCache phoneType = null;
            var phoneTypeAttributeValue = action.GetWorklowAttributeValue(GetAttributeValue(action, "PhoneTypeAttribute").AsGuid());

            if (phoneTypeAttributeValue != null)
            {
                phoneType = DefinedValueCache.Read(phoneTypeAttributeValue.AsGuid());
            }
            if (phoneType == null)
            {
                phoneType = DefinedValueCache.Read(GetAttributeValue(action, "PhoneType").AsGuid());
            }
            if (phoneType == null)
            {
                errorMessages.Add("The phone type to be updated was not selected.");
                return(false);
            }

            // get the ignore blank setting
            var ignoreBlanks = GetActionAttributeValue(action, "IgnoreBlankValues").AsBoolean(true);

            // get the new phone number value
            string phoneNumberValue     = GetAttributeValue(action, "PhoneNumber");
            Guid?  phoneNumberValueGuid = phoneNumberValue.AsGuidOrNull();

            if (phoneNumberValueGuid.HasValue)
            {
                phoneNumberValue = action.GetWorklowAttributeValue(phoneNumberValueGuid.Value);
            }
            else
            {
                phoneNumberValue = phoneNumberValue.ResolveMergeFields(GetMergeFields(action));
            }
            phoneNumberValue = PhoneNumber.CleanNumber(phoneNumberValue);

            // gets value indicating if phone number is unlisted
            string unlistedValue     = GetAttributeValue(action, "Unlisted");
            Guid?  unlistedValueGuid = unlistedValue.AsGuidOrNull();

            if (unlistedValueGuid.HasValue)
            {
                unlistedValue = action.GetWorklowAttributeValue(unlistedValueGuid.Value);
            }
            else
            {
                unlistedValue = unlistedValue.ResolveMergeFields(GetMergeFields(action));
            }
            bool?unlisted = unlistedValue.AsBooleanOrNull();

            // gets value indicating if messaging should be enabled for phone number
            string smsEnabledValue     = GetAttributeValue(action, "MessagingEnabled");
            Guid?  smsEnabledValueGuid = smsEnabledValue.AsGuidOrNull();

            if (smsEnabledValueGuid.HasValue)
            {
                smsEnabledValue = action.GetWorklowAttributeValue(smsEnabledValueGuid.Value);
            }
            else
            {
                smsEnabledValue = smsEnabledValue.ResolveMergeFields(GetMergeFields(action));
            }
            bool?smsEnabled = smsEnabledValue.AsBooleanOrNull();

            bool updated            = false;
            var  phoneNumberService = new PhoneNumberService(rockContext);
            var  phoneNumber        = phoneNumberService.Queryable()
                                      .Where(n =>
                                             n.PersonId == personId.Value &&
                                             n.NumberTypeValueId == phoneType.Id)
                                      .FirstOrDefault();
            string oldValue = string.Empty;

            if (phoneNumber == null)
            {
                phoneNumber = new PhoneNumber {
                    NumberTypeValueId = phoneType.Id, PersonId = personId.Value
                };
                phoneNumberService.Add(phoneNumber);
                updated = true;
            }
            else
            {
                oldValue = phoneNumber.NumberFormattedWithCountryCode;
            }

            if (!string.IsNullOrWhiteSpace(phoneNumberValue) || !ignoreBlanks)
            {
                updated            = updated || phoneNumber.Number != phoneNumberValue;
                phoneNumber.Number = phoneNumberValue;
            }
            if (unlisted.HasValue)
            {
                updated = updated || phoneNumber.IsUnlisted != unlisted.Value;
                phoneNumber.IsUnlisted = unlisted.Value;
            }
            if (smsEnabled.HasValue)
            {
                updated = updated || phoneNumber.IsMessagingEnabled != smsEnabled.Value;
                phoneNumber.IsMessagingEnabled = smsEnabled.Value;
            }

            if (updated)
            {
                var changes = new List <string>();
                History.EvaluateChange(
                    changes,
                    string.Format("{0} Phone", phoneType.Value),
                    oldValue,
                    phoneNumber.NumberFormattedWithCountryCode);

                if (changes.Any())
                {
                    changes.Add(string.Format("<em>(Updated by the '{0}' workflow)</em>", action.ActionTypeCache.ActivityType.WorkflowType.Name));
                    HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), personId.Value, changes, false);
                }

                rockContext.SaveChanges();

                if (action.Activity != null && action.Activity.Workflow != null)
                {
                    var workflowType = action.Activity.Workflow.WorkflowTypeCache;
                    if (workflowType != null && workflowType.LoggingLevel == WorkflowLoggingLevel.Action)
                    {
                        var person = new PersonService(rockContext).Get(personId.Value);
                        action.AddLogEntry(string.Format("Updated {0} phone for {1} to {2}.", phoneType.Value, person.FullName, phoneNumber.NumberFormattedWithCountryCode));
                    }
                }
            }

            return(true);
        }
Exemplo n.º 11
0
        /// <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)
        {
            if (RegistrantState != null)
            {
                RockContext            rockContext                        = new RockContext();
                var                    personService                      = new PersonService(rockContext);
                var                    registrantService                  = new RegistrationRegistrantService(rockContext);
                var                    registrantFeeService               = new RegistrationRegistrantFeeService(rockContext);
                var                    registrationTemplateFeeService     = new RegistrationTemplateFeeService(rockContext);
                var                    registrationTemplateFeeItemService = new RegistrationTemplateFeeItemService(rockContext);
                RegistrationRegistrant registrant = null;
                if (RegistrantState.Id > 0)
                {
                    registrant = registrantService.Get(RegistrantState.Id);
                }

                var previousRegistrantPersonIds = registrantService.Queryable().Where(a => a.RegistrationId == RegistrantState.RegistrationId)
                                                  .Where(r => r.PersonAlias != null)
                                                  .Select(r => r.PersonAlias.PersonId)
                                                  .ToList();

                bool newRegistrant     = false;
                var  registrantChanges = new History.HistoryChangeList();

                if (registrant == null)
                {
                    newRegistrant             = true;
                    registrant                = new RegistrationRegistrant();
                    registrant.RegistrationId = RegistrantState.RegistrationId;
                    registrantService.Add(registrant);
                    registrantChanges.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Record, "Registrant");
                }

                if (!registrant.PersonAliasId.Equals(ppPerson.PersonAliasId))
                {
                    string prevPerson = (registrant.PersonAlias != null && registrant.PersonAlias.Person != null) ?
                                        registrant.PersonAlias.Person.FullName : string.Empty;
                    string newPerson = ppPerson.PersonName;
                    newRegistrant = true;
                    History.EvaluateChange(registrantChanges, "Person", prevPerson, newPerson);
                }

                int?personId = ppPerson.PersonId.Value;
                registrant.PersonAliasId = ppPerson.PersonAliasId.Value;

                // Get the name of registrant for history
                string registrantName = "Unknown";
                if (ppPerson.PersonId.HasValue)
                {
                    var person = personService.Get(ppPerson.PersonId.Value);
                    if (person != null)
                    {
                        registrantName = person.FullName;
                    }
                }

                // set their status (wait list / registrant)
                registrant.OnWaitList = !tglWaitList.Checked;

                History.EvaluateChange(registrantChanges, "Cost", registrant.Cost, cbCost.Text.AsDecimal());
                registrant.Cost = cbCost.Text.AsDecimal();

                History.EvaluateChange(registrantChanges, "Discount Applies", registrant.DiscountApplies, cbDiscountApplies.Checked);
                registrant.DiscountApplies = cbDiscountApplies.Checked;

                if (!Page.IsValid)
                {
                    return;
                }

                // Remove/delete any registrant fees that are no longer in UI with quantity
                foreach (var dbFee in registrant.Fees.ToList())
                {
                    if (!RegistrantState.FeeValues.Keys.Contains(dbFee.RegistrationTemplateFeeId) ||
                        RegistrantState.FeeValues[dbFee.RegistrationTemplateFeeId] == null ||
                        !RegistrantState.FeeValues[dbFee.RegistrationTemplateFeeId]
                        .Any(f =>
                             f.RegistrationTemplateFeeItemId == dbFee.RegistrationTemplateFeeItemId &&
                             f.Quantity > 0))
                    {
                        var feeOldValue = string.Format("'{0}' Fee (Quantity:{1:N0}, Cost:{2:C2}, Option:{3}",
                                                        dbFee.RegistrationTemplateFee.Name, dbFee.Quantity, dbFee.Cost, dbFee.Option);

                        registrantChanges.AddChange(History.HistoryVerb.Delete, History.HistoryChangeType.Record, "Fee").SetOldValue(feeOldValue);
                        registrant.Fees.Remove(dbFee);
                        registrantFeeService.Delete(dbFee);
                    }
                }

                // Add/Update any of the fees from UI
                foreach (var uiFee in RegistrantState.FeeValues.Where(f => f.Value != null))
                {
                    foreach (var uiFeeOption in uiFee.Value)
                    {
                        var dbFee = registrant.Fees
                                    .Where(f =>
                                           f.RegistrationTemplateFeeId == uiFee.Key &&
                                           f.RegistrationTemplateFeeItemId == uiFeeOption.RegistrationTemplateFeeItemId)
                                    .FirstOrDefault();

                        if (dbFee == null)
                        {
                            dbFee = new RegistrationRegistrantFee();
                            dbFee.RegistrationTemplateFeeId = uiFee.Key;
                            var registrationTemplateFeeItem = registrationTemplateFeeItemService.GetNoTracking(uiFeeOption.RegistrationTemplateFeeItemId);
                            if (registrationTemplateFeeItem != null)
                            {
                                dbFee.Option = registrationTemplateFeeItem.Name;
                            }

                            dbFee.RegistrationTemplateFeeItemId = uiFeeOption.RegistrationTemplateFeeItemId;
                            registrant.Fees.Add(dbFee);
                        }

                        var templateFee = dbFee.RegistrationTemplateFee;
                        if (templateFee == null)
                        {
                            templateFee = registrationTemplateFeeService.Get(uiFee.Key);
                        }

                        string feeName = templateFee != null ? templateFee.Name : "Fee";
                        if (!string.IsNullOrWhiteSpace(uiFeeOption.FeeLabel))
                        {
                            feeName = string.Format("{0} ({1})", feeName, uiFeeOption.FeeLabel);
                        }

                        if (dbFee.Id <= 0)
                        {
                            registrantChanges.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Record, "Fee").SetNewValue(feeName);
                        }

                        History.EvaluateChange(registrantChanges, feeName + " Quantity", dbFee.Quantity, uiFeeOption.Quantity);
                        dbFee.Quantity = uiFeeOption.Quantity;

                        History.EvaluateChange(registrantChanges, feeName + " Cost", dbFee.Cost, uiFeeOption.Cost);
                        dbFee.Cost = uiFeeOption.Cost;
                    }
                }

                if (TemplateState.RequiredSignatureDocumentTemplate != null)
                {
                    var person = new PersonService(rockContext).Get(personId.Value);

                    var documentService        = new SignatureDocumentService(rockContext);
                    var binaryFileService      = new BinaryFileService(rockContext);
                    SignatureDocument document = null;

                    int?signatureDocumentId = hfSignedDocumentId.Value.AsIntegerOrNull();
                    int?binaryFileId        = fuSignedDocument.BinaryFileId;
                    if (signatureDocumentId.HasValue)
                    {
                        document = documentService.Get(signatureDocumentId.Value);
                    }

                    if (document == null && binaryFileId.HasValue)
                    {
                        var instance = new RegistrationInstanceService(rockContext).Get(RegistrationInstanceId);

                        document = new SignatureDocument();
                        document.SignatureDocumentTemplateId = TemplateState.RequiredSignatureDocumentTemplate.Id;
                        document.AppliesToPersonAliasId      = registrant.PersonAliasId.Value;
                        document.AssignedToPersonAliasId     = registrant.PersonAliasId.Value;
                        document.Name = string.Format(
                            "{0}_{1}",
                            instance != null ? instance.Name : TemplateState.Name,
                            person != null ? person.FullName.RemoveSpecialCharacters() : string.Empty);
                        document.Status         = SignatureDocumentStatus.Signed;
                        document.LastStatusDate = RockDateTime.Now;
                        documentService.Add(document);
                    }

                    if (document != null)
                    {
                        int?origBinaryFileId = document.BinaryFileId;
                        document.BinaryFileId = binaryFileId;

                        if (origBinaryFileId.HasValue && origBinaryFileId.Value != document.BinaryFileId)
                        {
                            // if a new the binaryFile was uploaded, mark the old one as Temporary so that it gets cleaned up
                            var oldBinaryFile = binaryFileService.Get(origBinaryFileId.Value);
                            if (oldBinaryFile != null && !oldBinaryFile.IsTemporary)
                            {
                                oldBinaryFile.IsTemporary = true;
                            }
                        }

                        // ensure the IsTemporary is set to false on binaryFile associated with this document
                        if (document.BinaryFileId.HasValue)
                        {
                            var binaryFile = binaryFileService.Get(document.BinaryFileId.Value);
                            if (binaryFile != null && binaryFile.IsTemporary)
                            {
                                binaryFile.IsTemporary = false;
                            }
                        }
                    }
                }

                if (!registrant.IsValid)
                {
                    // Controls will render the error messages
                    return;
                }

                // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges()
                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();

                    registrant.LoadAttributes();
                    foreach (var field in TemplateState.Forms
                             .SelectMany(f => f.Fields
                                         .Where(t =>
                                                t.FieldSource == RegistrationFieldSource.RegistrantAttribute &&
                                                t.AttributeId.HasValue)))
                    {
                        var attribute = AttributeCache.Get(field.AttributeId.Value);
                        if (attribute != null)
                        {
                            string originalValue = registrant.GetAttributeValue(attribute.Key);
                            var fieldValue       = RegistrantState.FieldValues
                                                   .Where(f => f.Key == field.Id)
                                                   .Select(f => f.Value.FieldValue)
                                                   .FirstOrDefault();
                            string newValue = fieldValue != null ? fieldValue.ToString() : string.Empty;

                            if ((originalValue ?? string.Empty).Trim() != (newValue ?? string.Empty).Trim())
                            {
                                string formattedOriginalValue = string.Empty;
                                if (!string.IsNullOrWhiteSpace(originalValue))
                                {
                                    formattedOriginalValue = attribute.FieldType.Field.FormatValue(null, originalValue, attribute.QualifierValues, false);
                                }

                                string formattedNewValue = string.Empty;
                                if (!string.IsNullOrWhiteSpace(newValue))
                                {
                                    formattedNewValue = attribute.FieldType.Field.FormatValue(null, newValue, attribute.QualifierValues, false);
                                }

                                History.EvaluateChange(registrantChanges, attribute.Name, formattedOriginalValue, formattedNewValue);
                            }

                            if (fieldValue != null)
                            {
                                registrant.SetAttributeValue(attribute.Key, fieldValue.ToString());
                            }
                        }
                    }

                    registrant.SaveAttributeValues(rockContext);
                });

                if (newRegistrant && TemplateState.GroupTypeId.HasValue && ppPerson.PersonId.HasValue)
                {
                    using (var newRockContext = new RockContext())
                    {
                        var reloadedRegistrant = new RegistrationRegistrantService(newRockContext).Get(registrant.Id);
                        if (reloadedRegistrant != null &&
                            reloadedRegistrant.Registration != null &&
                            reloadedRegistrant.Registration.Group != null &&
                            reloadedRegistrant.Registration.Group.GroupTypeId == TemplateState.GroupTypeId.Value)
                        {
                            int?groupRoleId = TemplateState.GroupMemberRoleId.HasValue ?
                                              TemplateState.GroupMemberRoleId.Value :
                                              reloadedRegistrant.Registration.Group.GroupType.DefaultGroupRoleId;
                            if (groupRoleId.HasValue)
                            {
                                var groupMemberService = new GroupMemberService(newRockContext);
                                var groupMember        = groupMemberService
                                                         .Queryable().AsNoTracking()
                                                         .Where(m =>
                                                                m.GroupId == reloadedRegistrant.Registration.Group.Id &&
                                                                m.PersonId == reloadedRegistrant.PersonId &&
                                                                m.GroupRoleId == groupRoleId.Value)
                                                         .FirstOrDefault();
                                if (groupMember == null)
                                {
                                    groupMember                   = new GroupMember();
                                    groupMember.GroupId           = reloadedRegistrant.Registration.Group.Id;
                                    groupMember.PersonId          = ppPerson.PersonId.Value;
                                    groupMember.GroupRoleId       = groupRoleId.Value;
                                    groupMember.GroupMemberStatus = TemplateState.GroupMemberStatus;
                                    groupMemberService.Add(groupMember);

                                    newRockContext.SaveChanges();

                                    registrantChanges.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Record, string.Format("Registrant to {0} group", reloadedRegistrant.Registration.Group.Name));
                                }
                                else
                                {
                                    registrantChanges.AddChange(History.HistoryVerb.Modify, History.HistoryChangeType.Record, string.Format("Registrant to existing person in {0} group", reloadedRegistrant.Registration.Group.Name));
                                }

                                if (reloadedRegistrant.GroupMemberId.HasValue && reloadedRegistrant.GroupMemberId.Value != groupMember.Id)
                                {
                                    groupMemberService.Delete(reloadedRegistrant.GroupMember);
                                    newRockContext.SaveChanges();
                                    registrantChanges.AddChange(History.HistoryVerb.Delete, History.HistoryChangeType.Record, string.Format("Registrant to previous person in {0} group", reloadedRegistrant.Registration.Group.Name));
                                }

                                // Record this to the Person's and Registrants Notes and History...

                                reloadedRegistrant.GroupMemberId = groupMember.Id;
                            }
                        }
                        if (reloadedRegistrant.Registration.FirstName.IsNotNullOrWhiteSpace() && reloadedRegistrant.Registration.LastName.IsNotNullOrWhiteSpace())
                        {
                            reloadedRegistrant.Registration.SavePersonNotesAndHistory(reloadedRegistrant.Registration.FirstName, reloadedRegistrant.Registration.LastName, this.CurrentPersonAliasId, previousRegistrantPersonIds);
                        }
                        newRockContext.SaveChanges();
                    }
                }

                HistoryService.SaveChanges(
                    rockContext,
                    typeof(Registration),
                    Rock.SystemGuid.Category.HISTORY_EVENT_REGISTRATION.AsGuid(),
                    registrant.RegistrationId,
                    registrantChanges,
                    "Registrant: " + registrantName,
                    null,
                    null);
            }

            NavigateToRegistration();
        }
Exemplo n.º 12
0
        /// <summary>
        /// Loads Rock data that's used globally by the transform
        /// </summary>
        /// <param name="lookupContext">The lookup context.</param>
        private static void LoadRockData(RockContext lookupContext = null)
        {
            lookupContext = lookupContext ?? new RockContext();

            // initialize file providers
            DatabaseProvider   = new Database();
            FileSystemProvider = new FileSystem();

            // core-specified attribute guid for setting file root path
            RootPathAttribute = AttributeCache.Get(new Guid("3CAFA34D-9208-439B-A046-CB727FB729DE"));

            // core-specified blacklist files
            FileTypeBlackList = (GlobalAttributesCache.Get().GetValue("ContentFiletypeBlacklist")
                                 ?? string.Empty).Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);

            // clean up blacklist
            FileTypeBlackList = FileTypeBlackList.Select(a => a.ToLower().TrimStart(new char[] { '.', ' ' }));
            FileTypes         = new BinaryFileTypeService(lookupContext).Queryable().AsNoTracking().ToList();

            // get all the types we'll be importing
            var binaryTypeSettings = ConfigurationManager.GetSection("binaryFileTypes") as NameValueCollection;

            // create any custom types defined in settings that don't exist yet
            foreach (var typeKey in binaryTypeSettings.AllKeys)
            {
                if (!FileTypes.Any(f => f.Name == typeKey))
                {
                    var newFileType = new BinaryFileType();
                    lookupContext.BinaryFileTypes.Add(newFileType);
                    newFileType.Name                    = typeKey;
                    newFileType.Description             = typeKey;
                    newFileType.CacheToServerFileSystem = true;

                    var typeValue = binaryTypeSettings[typeKey];
                    if (typeValue != null)
                    {
                        // #TODO: support additional storage types (like AWS?)
                        newFileType.StorageEntityTypeId = typeValue.Equals("Database") ? DatabaseStorageTypeId : FileSystemStorageTypeId;
                        newFileType.Attributes          = new Dictionary <string, AttributeCache>();
                        newFileType.AttributeValues     = new Dictionary <string, AttributeValueCache>();

                        // save changes to binary type to get an ID
                        lookupContext.SaveChanges();

                        var newRootPath = new AttributeValue()
                        {
                            AttributeId = RootPathAttribute.Id,
                            EntityId    = newFileType.Id,
                            Value       = typeValue
                        };

                        newFileType.Attributes.Add(RootPathAttribute.Key, RootPathAttribute);
                        newFileType.AttributeValues.Add(RootPathAttribute.Key, new AttributeValueCache(newRootPath));

                        // save attribute values with the current type ID
                        lookupContext.AttributeValues.Add(newRootPath);
                    }

                    lookupContext.SaveChanges();
                    FileTypes.Add(newFileType);
                }
            }

            // load attributes on file system types to get the default storage location
            foreach (var type in FileTypes)
            {
                type.LoadAttributes(lookupContext);

                if (type.StorageEntityTypeId == FileSystemStorageTypeId && binaryTypeSettings.AllKeys.Any(k => type.Name.Equals(k)))
                {
                    // override the configured storage location since we can't handle relative paths
                    type.AttributeValues["RootPath"].Value = binaryTypeSettings[type.Name];
                }
            }

            // get a list of all the imported people keys
            var personAliasList = new PersonAliasService(lookupContext).Queryable().AsNoTracking().ToList();

            ImportedPeople = personAliasList
                             .Where(pa => pa.ForeignKey != null)
                             .Select(pa =>
                                     new PersonKeys()
            {
                PersonAliasId    = pa.Id,
                PersonId         = pa.PersonId,
                PersonForeignId  = pa.ForeignId,
                PersonForeignKey = pa.ForeignKey
            }).ToList();
        }
Exemplo n.º 13
0
        private void SaveTransaction(FinancialGateway financialGateway, GatewayComponent gateway, Person person, PaymentInfo paymentInfo, FinancialTransaction transaction, RockContext rockContext)
        {
            transaction.AuthorizedPersonAliasId = person.PrimaryAliasId;
            if (RockTransactionEntry != null)
            {
                RockCheckBox cbGiveAnonymouslyControl = (( RockCheckBox )(RockTransactionEntry.FindControl("cbGiveAnonymously")));
                if (cbGiveAnonymouslyControl != null)
                {
                    transaction.ShowAsAnonymous = cbGiveAnonymouslyControl.Checked;
                }
            }
            transaction.TransactionDateTime = RockDateTime.Now;
            transaction.FinancialGatewayId  = financialGateway.Id;

            var txnType = DefinedValueCache.Read(this.GetAttributeValue("TransactionType").AsGuidOrNull() ?? Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION.AsGuid());

            transaction.TransactionTypeValueId = txnType.Id;

            transaction.Summary = paymentInfo.Comment1;

            if (transaction.FinancialPaymentDetail == null)
            {
                transaction.FinancialPaymentDetail = new FinancialPaymentDetail();
            }
            transaction.FinancialPaymentDetail.SetFromPaymentInfo(paymentInfo, gateway, rockContext);

            Guid sourceGuid = Guid.Empty;

            if (Guid.TryParse(GetAttributeValue("Source"), out sourceGuid))
            {
                var source = DefinedValueCache.Read(sourceGuid);
                if (source != null)
                {
                    transaction.SourceTypeValueId = source.Id;
                }
            }

            var transactionEntity = this.GetTransactionEntity();

            foreach (var account in GetSelectedAccounts().Where(a => a.Amount > 0))
            {
                var transactionDetail = new FinancialTransactionDetail();
                transactionDetail.Amount    = account.Amount;
                transactionDetail.AccountId = account.Id;
                if (transactionEntity != null)
                {
                    transactionDetail.EntityTypeId = transactionEntity.TypeId;
                    transactionDetail.EntityId     = transactionEntity.Id;
                }

                transaction.TransactionDetails.Add(transactionDetail);
            }

            var batchService = new FinancialBatchService(rockContext);

            // Get the batch
            var batch = batchService.Get(
                GetAttributeValue("BatchNamePrefix"),
                paymentInfo.CurrencyTypeValue,
                paymentInfo.CreditCardTypeValue,
                transaction.TransactionDateTime.Value,
                financialGateway.GetBatchTimeOffset());

            var batchChanges = new List <string>();

            if (batch.Id == 0)
            {
                batchChanges.Add("Generated the batch");
                History.EvaluateChange(batchChanges, "Batch Name", string.Empty, batch.Name);
                History.EvaluateChange(batchChanges, "Status", null, batch.Status);
                History.EvaluateChange(batchChanges, "Start Date/Time", null, batch.BatchStartDateTime);
                History.EvaluateChange(batchChanges, "End Date/Time", null, batch.BatchEndDateTime);
            }

            decimal newControlAmount = batch.ControlAmount + transaction.TotalAmount;

            History.EvaluateChange(batchChanges, "Control Amount", batch.ControlAmount.FormatAsCurrency(), newControlAmount.FormatAsCurrency());
            batch.ControlAmount = newControlAmount;

            transaction.BatchId = batch.Id;
            transaction.LoadAttributes(rockContext);

            var allowedTransactionAttributes = GetAttributeValue("AllowedTransactionAttributesFromURL").Split(',').AsGuidList().Select(x => AttributeCache.Read(x).Key);

            foreach (KeyValuePair <string, AttributeValueCache> attr in transaction.AttributeValues)
            {
                if (PageParameters().ContainsKey("Attribute_" + attr.Key) && allowedTransactionAttributes.Contains(attr.Key))
                {
                    attr.Value.Value = Server.UrlDecode(PageParameter("Attribute_" + attr.Key));
                }
            }

            batch.Transactions.Add(transaction);

            rockContext.SaveChanges();
            transaction.SaveAttributeValues();

            HistoryService.SaveChanges(
                rockContext,
                typeof(FinancialBatch),
                Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                batch.Id,
                batchChanges
                );

            SendReceipt(transaction.Id);

            TransactionCode = transaction.TransactionCode;
        }
Exemplo n.º 14
0
 private void OnDisposed(object sender, EventArgs eventArgs)
 {
     _ignoreTableSelectionChanged = true;
     if (_fidField != null)
     {
         if (_featureLayer.DataSet.DataTable.Columns.Contains(_fidField))
             _featureLayer.DataSet.DataTable.Columns.Remove(_fidField);
     }
     _selection = null;
     _selectionIndices = null;
     _selectedRows = null;
     _attributeCache = null;
     if (_featureLayer != null)
     {
         _featureLayer.SelectionChanged -= SelectedFeaturesChanged;
         _featureLayer = null;
     }
 }
Exemplo n.º 15
0
 public override bool IsExcluded <TProperty, TContainer, TValue>(TProperty property, ref TContainer container)
 {
     return(AttributeCache <TValue> .HasAttribute <NonSerializedForPersistenceAttribute>() || base.IsExcluded <TProperty, TContainer, TValue>(property, ref container));
 }
Exemplo n.º 16
0
        //Shows all rows (both selected and unselected)
        private void ShowAllRows()
        {
            _showOnlySelectedRows = false;
            if (_featureLayer.DataSet.AttributesPopulated)
            {
                _ignoreTableSelectionChanged = true;
                _ignoreSelectionChanged = true;
                dataGridView1.DataSource = _featureLayer.DataSet.DataTable;
                foreach (int row in _selectedRows)
                {
                    dataGridView1.Rows[row].Selected = true;
                }
                _ignoreTableSelectionChanged = false;
                _ignoreSelectionChanged = false;
            }
            else
            {
                _attributeCache = new AttributeCache(_featureLayer.DataSet, 16);
                dataGridView1.RowCount = _featureLayer.DrawnStates.Length;
            }

            Refresh();
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);

            CheckInGroupType lastCheckinGroupType = null;

            List <string>       labelCodes = new List <string>();
            List <int>          childGroupIds;
            List <CheckInLabel> checkInLabels = new List <CheckInLabel>();

            var    volAttributeGuid = GetAttributeValue(action, "VolunteerGroupAttribute");
            string volAttributeKey  = "";

            if (!string.IsNullOrWhiteSpace(volAttributeGuid))
            {
                volAttributeKey = AttributeCache.Get(volAttributeGuid.AsGuid()).Key;
                childGroupIds   = checkInState.Kiosk.KioskGroupTypes
                                  .SelectMany(g => g.KioskGroups)
                                  .Where(g => !g.Group.GetAttributeValue(volAttributeKey).AsBoolean())
                                  .Select(g => g.Group.Id).ToList();
            }
            else
            {
                childGroupIds = new List <int>();
            }

            if (checkInState != null)
            {
                var attendanceService = new AttendanceService(rockContext);
                var globalAttributes  = Rock.Web.Cache.GlobalAttributesCache.Get();
                var globalMergeValues = Rock.Lava.LavaHelper.GetCommonMergeFields(null);

                var groupMemberService = new GroupMemberService(rockContext);

                foreach (var family in checkInState.CheckIn.Families.Where(f => f.Selected))
                {
                    foreach (var person in family.People.Where(p => p.Selected))
                    {
                        if (person.GroupTypes.Where(gt => gt.Selected).SelectMany(gt => gt.Groups).Where(g => g.Selected && childGroupIds.Contains(g.Group.Id)).Any())
                        {
                            labelCodes.Add((person.SecurityCode) + "-" + LabelAge(person.Person));
                        }

                        if (string.IsNullOrEmpty(person.SecurityCode))
                        {
                            var lastAttendance = attendanceService.Queryable()
                                                 .Where(a => a.PersonAlias.PersonId == person.Person.Id && a.AttendanceCode != null)
                                                 .OrderByDescending(a => a.StartDateTime)
                                                 .FirstOrDefault();
                            if (lastAttendance != null)
                            {
                                person.SecurityCode = lastAttendance.AttendanceCode.Code;
                            }
                        }

                        var firstCheckinGroupType = person.GroupTypes.Where(g => g.Selected).FirstOrDefault();
                        if (firstCheckinGroupType != null)
                        {
                            List <Guid> labelGuids = new List <Guid>();

                            var mergeObjects = new Dictionary <string, object>();
                            foreach (var keyValue in globalMergeValues)
                            {
                                mergeObjects.Add(keyValue.Key, keyValue.Value);
                            }
                            mergeObjects.Add("Person", person);
                            mergeObjects.Add("GroupTypes", person.GroupTypes.Where(g => g.Selected).ToList());
                            List <Group>    mergeGroups    = new List <Group>();
                            List <Location> mergeLocations = new List <Location>();
                            List <Schedule> mergeSchedules = new List <Schedule>();

                            var sets = attendanceService
                                       .Queryable().AsNoTracking().Where(a =>
                                                                         a.PersonAlias.Person.Id == person.Person.Id &&
                                                                         a.StartDateTime >= Rock.RockDateTime.Today &&
                                                                         a.EndDateTime == null &&
                                                                         a.Occurrence.Group != null &&
                                                                         a.Occurrence.Schedule != null &&
                                                                         a.Occurrence.Location != null
                                                                         )
                                       .Select(a =>
                                               new
                            {
                                Group          = a.Occurrence.Group,
                                Location       = a.Occurrence.Location,
                                Schedule       = a.Occurrence.Schedule,
                                AttendanceGuid = a.Guid
                            }
                                               )
                                       .ToList()
                                       .OrderBy(a => a.Schedule.StartTimeOfDay);

                            //Load breakout group
                            var breakoutGroups = GetBreakoutGroups(person.Person, rockContext, action);

                            //Add in an empty object as a placeholder for our breakout group
                            mergeObjects.Add("BreakoutGroup", "");

                            //Add in GUID for QR code
                            if (sets.Any())
                            {
                                mergeObjects.Add("AttendanceGuid", sets.FirstOrDefault().AttendanceGuid.ToString());
                            }

                            foreach (var set in sets)
                            {
                                mergeGroups.Add(set.Group);
                                mergeLocations.Add(set.Location);
                                mergeSchedules.Add(set.Schedule);

                                //Add the breakout group mergefield
                                if (breakoutGroups.Any())
                                {
                                    var breakoutGroup = breakoutGroups.Where(g => g.ScheduleId == set.Schedule.Id).FirstOrDefault();
                                    if (breakoutGroup != null)
                                    {
                                        var breakoutGroupEntity = new GroupService(rockContext).Get(breakoutGroup.Id);
                                        if (breakoutGroupEntity != null)
                                        {
                                            breakoutGroupEntity.LoadAttributes();
                                            var letter = breakoutGroupEntity.GetAttributeValue("Letter");
                                            if (!string.IsNullOrWhiteSpace(letter))
                                            {
                                                mergeObjects["BreakoutGroup"] = letter;
                                            }
                                        }
                                    }
                                }
                            }
                            mergeObjects.Add("Groups", mergeGroups);
                            mergeObjects.Add("Locations", mergeLocations);
                            mergeObjects.Add("Schedules", mergeSchedules);

                            foreach (var groupType in person.GroupTypes.Where(g => g.Selected))
                            {
                                lastCheckinGroupType = groupType;

                                groupType.Labels = new List <CheckInLabel>();

                                GetGroupTypeLabels(groupType.GroupType, firstCheckinGroupType.Labels, mergeObjects, labelGuids);

                                var PrinterIPs = new Dictionary <int, string>();

                                foreach (var label in groupType.Labels)
                                {
                                    label.PrintFrom = checkInState.Kiosk.Device.PrintFrom;
                                    label.PrintTo   = checkInState.Kiosk.Device.PrintToOverride;

                                    if (label.PrintTo == PrintTo.Default)
                                    {
                                        label.PrintTo = groupType.GroupType.AttendancePrintTo;
                                    }

                                    if (label.PrintTo == PrintTo.Kiosk)
                                    {
                                        var device = checkInState.Kiosk.Device;
                                        if (device != null)
                                        {
                                            label.PrinterDeviceId = device.PrinterDeviceId;
                                        }
                                    }
                                    else if (label.PrintTo == PrintTo.Location)
                                    {
                                        // Should only be one
                                        var group = groupType.Groups.Where(g => g.Selected).FirstOrDefault();
                                        if (group != null)
                                        {
                                            var location = group.Locations.Where(l => l.Selected).FirstOrDefault();
                                            if (location != null)
                                            {
                                                var device = location.Location.PrinterDevice;
                                                if (device != null)
                                                {
                                                    label.PrinterDeviceId = device.PrinterDeviceId;
                                                }
                                            }
                                        }
                                    }

                                    if (label.PrinterDeviceId.HasValue)
                                    {
                                        if (PrinterIPs.ContainsKey(label.PrinterDeviceId.Value))
                                        {
                                            label.PrinterAddress = PrinterIPs[label.PrinterDeviceId.Value];
                                        }
                                        else
                                        {
                                            var printerDevice = new DeviceService(rockContext).Get(label.PrinterDeviceId.Value);
                                            if (printerDevice != null)
                                            {
                                                PrinterIPs.Add(printerDevice.Id, printerDevice.IPAddress);
                                                label.PrinterAddress = printerDevice.IPAddress;
                                            }
                                        }
                                    }
                                    checkInLabels.Add(label);
                                }
                            }
                        }
                    }

                    //Add in custom labels for parents
                    //This is the aggregate part
                    List <CheckInLabel> customLabels = new List <CheckInLabel>();

                    List <string> mergeCodes = (( string )GetAttributeValue(action, "MergeText")).Split(',').ToList();
                    while (labelCodes.Count > 0)
                    {
                        var mergeDict = new Dictionary <string, string>();

                        foreach (var mergeCode in mergeCodes)
                        {
                            if (labelCodes.Count > 0)
                            {
                                mergeDict.Add(mergeCode, labelCodes[0]);
                                labelCodes.RemoveAt(0);
                            }
                            else
                            {
                                mergeDict.Add(mergeCode, "");
                            }
                        }

                        mergeDict.Add("Date", Rock.RockDateTime.Today.DayOfWeek.ToString().Substring(0, 3) + " " + Rock.RockDateTime.Today.ToMonthDayString());

                        var labelCache = KioskLabel.Get(new Guid(GetAttributeValue(action, "AggregatedLabel")));
                        if (labelCache != null)
                        {
                            var checkInLabel = new CheckInLabel(labelCache, new Dictionary <string, object>());
                            checkInLabel.FileGuid = new Guid(GetAttributeValue(action, "AggregatedLabel"));

                            foreach (var keyValue in mergeDict)
                            {
                                if (checkInLabel.MergeFields.ContainsKey(keyValue.Key))
                                {
                                    checkInLabel.MergeFields[keyValue.Key] = keyValue.Value;
                                }
                                else
                                {
                                    checkInLabel.MergeFields.Add(keyValue.Key, keyValue.Value);
                                }
                            }

                            checkInLabel.PrintFrom = checkInState.Kiosk.Device.PrintFrom;
                            checkInLabel.PrintTo   = checkInState.Kiosk.Device.PrintToOverride;

                            if (checkInLabel.PrintTo == PrintTo.Default)
                            {
                                checkInLabel.PrintTo = lastCheckinGroupType.GroupType.AttendancePrintTo;
                            }

                            if (checkInLabel.PrintTo == PrintTo.Kiosk)
                            {
                                var device = checkInState.Kiosk.Device;
                                if (device != null)
                                {
                                    checkInLabel.PrinterDeviceId = device.PrinterDeviceId;
                                }
                            }
                            else if (checkInLabel.PrintTo == PrintTo.Location)
                            {
                                // Should only be one
                                var group = lastCheckinGroupType.Groups.Where(g => g.Selected).FirstOrDefault();
                                if (group != null)
                                {
                                    var location = group.Locations.Where(l => l.Selected).FirstOrDefault();
                                    if (location != null)
                                    {
                                        var device = location.Location.PrinterDevice;
                                        if (device != null)
                                        {
                                            checkInLabel.PrinterDeviceId = device.PrinterDeviceId;
                                        }
                                    }
                                }
                            }
                            if (checkInLabel.PrinterDeviceId.HasValue)
                            {
                                var printerDevice = new DeviceService(rockContext).Get(checkInLabel.PrinterDeviceId.Value);
                                checkInLabel.PrinterAddress = printerDevice.IPAddress;
                            }
                            if (lastCheckinGroupType != null)
                            {
                                lastCheckinGroupType.Labels.Add(checkInLabel);
                                checkInLabels.Add(checkInLabel);
                            }
                        }
                    }
                }

                //For mobile check-in we need to serialize this data and save it in the database.
                //This will mean that when it's time to finish checkin in
                //All we will need to do is deserialize and pass the data to the printer
                if (GetAttributeValue(action, "IsMobile").AsBoolean())
                {
                    MobileCheckinRecordService mobileCheckinRecordService = new MobileCheckinRecordService(rockContext);
                    MobileCheckinRecord        mobileCheckinRecord        = mobileCheckinRecordService.Queryable()
                                                                            .Where(r => r.Status == MobileCheckinStatus.Active)
                                                                            .Where(r => r.CreatedDateTime > Rock.RockDateTime.Today)
                                                                            .Where(r => r.UserName == checkInState.CheckIn.SearchValue)
                                                                            .FirstOrDefault();

                    if (mobileCheckinRecord == null)
                    {
                        ExceptionLogService.LogException("Mobile Check-in failed to find mobile checkin record");
                    }
                    mobileCheckinRecord.SerializedCheckInState = JsonConvert.SerializeObject(checkInLabels);

                    rockContext.SaveChanges();

                    //Freshen cache (we're going to need it soon)
                    MobileCheckinRecordCache.Update(mobileCheckinRecord.Id);
                }
                return(true);
            }
            errorMessages.Add($"Attempted to run {this.GetType().GetFriendlyTypeName()} in check-in, but the check-in state was null.");
            return(false);
        }
        /// <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)
        {
            if (Page.IsValid)
            {
                if (ViewMode == VIEW_MODE_EDIT)
                {
                    int personEntityTypeId = EntityTypeCache.Read(typeof(Person)).Id;

                    var rockContext = new RockContext();

                    var changes = new List <string>();
                    foreach (int attributeId in AttributeList)
                    {
                        var attribute = AttributeCache.Read(attributeId);

                        if (Person != null &&
                            attribute.IsAuthorized(Authorization.EDIT, CurrentPerson))
                        {
                            Control attributeControl = fsAttributes.FindControl(string.Format("attribute_field_{0}", attribute.Id));
                            if (attributeControl != null)
                            {
                                string originalValue = Person.GetAttributeValue(attribute.Key);
                                string newValue      = attribute.FieldType.Field.GetEditValue(attributeControl, attribute.QualifierValues);
                                Rock.Attribute.Helper.SaveAttributeValue(Person, attribute, newValue, rockContext);

                                // Check for changes to write to history
                                if ((originalValue ?? string.Empty).Trim() != (newValue ?? string.Empty).Trim())
                                {
                                    string formattedOriginalValue = string.Empty;
                                    if (!string.IsNullOrWhiteSpace(originalValue))
                                    {
                                        formattedOriginalValue = attribute.FieldType.Field.FormatValue(null, originalValue, attribute.QualifierValues, false);
                                    }

                                    string formattedNewValue = string.Empty;
                                    if (!string.IsNullOrWhiteSpace(newValue))
                                    {
                                        formattedNewValue = attribute.FieldType.Field.FormatValue(null, newValue, attribute.QualifierValues, false);
                                    }


                                    History.EvaluateChange(changes, attribute.Name, formattedOriginalValue, formattedNewValue, attribute.FieldType.Field.IsSensitive());
                                }
                            }
                        }
                    }

                    if (changes.Any())
                    {
                        HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                                   Person.Id, changes);
                    }
                }
                else if (ViewMode == VIEW_MODE_ORDER && _canAdministrate)
                {
                    // Split and deliminate again to remove trailing delimiter
                    var attributeOrder = hfAttributeOrder.Value.SplitDelimitedValues().ToList().AsDelimited("|");

                    SetAttributeValue("AttributeOrder", attributeOrder);
                    SaveAttributeValues();

                    BindData();
                }

                ViewMode = VIEW_MODE_VIEW;
                CreateControls(false);
            }
        }
Exemplo n.º 19
0
 public static bool HasAttribute <TType, TAttribute>()
     where TAttribute : Attribute
 {
     return(AttributeCache <TType> .HasAttribute <TAttribute>());
 }
Exemplo n.º 20
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>();

            // Determine which group to add the person to
            Group group = null;

            var guidGroupAttribute = GetAttributeValue(action, "Group").AsGuidOrNull();

            if (guidGroupAttribute.HasValue)
            {
                var attributeGroup = AttributeCache.Read(guidGroupAttribute.Value, rockContext);
                if (attributeGroup != null)
                {
                    var groupGuid = action.GetWorklowAttributeValue(guidGroupAttribute.Value).AsGuidOrNull();

                    if (groupGuid.HasValue)
                    {
                        group = new GroupService(rockContext).Get(groupGuid.Value);
                    }
                }
            }

            if (group == null)
            {
                errorMessages.Add("No group was provided");
            }

            // determine the person that will be added to the group
            Person person = null;

            // get the Attribute.Guid for this workflow's Person Attribute so that we can lookup the value
            var guidPersonAttribute = GetAttributeValue(action, "Person").AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Read(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null)
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute.Value);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        if (attributePerson.FieldType.Class == typeof(Rock.Field.Types.PersonFieldType).FullName)
                        {
                            Guid personAliasGuid = attributePersonValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                person = new PersonAliasService(rockContext).Queryable()
                                         .Where(a => a.Guid.Equals(personAliasGuid))
                                         .Select(a => a.Person)
                                         .FirstOrDefault();
                            }
                        }
                        else
                        {
                            errorMessages.Add("The attribute used to provide the person was not of type 'Person'.");
                        }
                    }
                }
            }

            if (person == null)
            {
                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
            }

            // Add Person to Group
            if (!errorMessages.Any())
            {
                var groupMemberService = new GroupMemberService(rockContext);
                var groupMember        = groupMemberService.Queryable().Where(m => m.GroupId == group.Id && m.PersonId == person.Id).FirstOrDefault();

                if (groupMember != null)
                {
                    groupMember.GroupMemberStatus = this.GetAttributeValue(action, "NewGroupMemberStatus").ConvertToEnum <GroupMemberStatus>(GroupMemberStatus.Active);
                    rockContext.SaveChanges();
                }
                else
                {
                    // the person is not in the group provided
                    errorMessages.Add("The person is not in the group provided.");
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Refresh the recipients list.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        public void RefreshCommunicationRecipientList(RockContext rockContext)
        {
            if (!ListGroupId.HasValue)
            {
                return;
            }

            var emailMediumEntityType = EntityTypeCache.Get(SystemGuid.EntityType.COMMUNICATION_MEDIUM_EMAIL.AsGuid());
            var smsMediumEntityType   = EntityTypeCache.Get(SystemGuid.EntityType.COMMUNICATION_MEDIUM_SMS.AsGuid());
            var preferredCommunicationTypeAttribute = AttributeCache.Get(SystemGuid.Attribute.GROUPMEMBER_COMMUNICATION_LIST_PREFERRED_COMMUNICATION_MEDIUM.AsGuid());
            var segmentDataViewGuids = this.Segments.SplitDelimitedValues().AsGuidList();
            var segmentDataViewIds   = new DataViewService(rockContext).GetByGuids(segmentDataViewGuids).Select(a => a.Id).ToList();

            var qryCommunicationListMembers = GetCommunicationListMembers(rockContext, ListGroupId, this.SegmentCriteria, segmentDataViewIds);

            // NOTE: If this is scheduled communication, don't include Members that were added after the scheduled FutureSendDateTime
            if (this.FutureSendDateTime.HasValue)
            {
                var memberAddedCutoffDate = this.FutureSendDateTime;
                qryCommunicationListMembers = qryCommunicationListMembers.Where(a => (a.DateTimeAdded.HasValue && a.DateTimeAdded.Value < memberAddedCutoffDate) || (a.CreatedDateTime.HasValue && a.CreatedDateTime.Value < memberAddedCutoffDate));
            }

            var communicationRecipientService = new CommunicationRecipientService(rockContext);

            var recipientsQry = GetRecipientsQry(rockContext);

            // Get all the List member which is not part of communication recipients yet
            var newMemberInList = qryCommunicationListMembers
                                  .Where(a => !recipientsQry.Any(r => r.PersonAlias.PersonId == a.PersonId))
                                  .AsNoTracking()
                                  .ToList();

            foreach (var newMember in newMemberInList)
            {
                var communicationRecipient = new CommunicationRecipient
                {
                    PersonAliasId   = newMember.Person.PrimaryAliasId.Value,
                    Status          = CommunicationRecipientStatus.Pending,
                    CommunicationId = Id
                };

                switch (CommunicationType)
                {
                case CommunicationType.Email:
                    communicationRecipient.MediumEntityTypeId = emailMediumEntityType.Id;
                    break;

                case CommunicationType.SMS:
                    communicationRecipient.MediumEntityTypeId = smsMediumEntityType.Id;
                    break;

                case CommunicationType.RecipientPreference:
                    newMember.LoadAttributes();

                    if (preferredCommunicationTypeAttribute != null)
                    {
                        var recipientPreference = ( CommunicationType? )newMember
                                                  .GetAttributeValue(preferredCommunicationTypeAttribute.Key).AsIntegerOrNull();

                        switch (recipientPreference)
                        {
                        case CommunicationType.SMS:
                            communicationRecipient.MediumEntityTypeId = smsMediumEntityType.Id;
                            break;

                        case CommunicationType.Email:
                            communicationRecipient.MediumEntityTypeId = emailMediumEntityType.Id;
                            break;

                        default:
                            communicationRecipient.MediumEntityTypeId = emailMediumEntityType.Id;
                            break;
                        }
                    }

                    break;

                default:
                    throw new Exception("Unexpected CommunicationType: " + CommunicationType.ConvertToString());
                }

                communicationRecipientService.Add(communicationRecipient);
            }

            // Get all pending communication recipents that are no longer part of the group list member, then delete them from the Recipients
            var missingMemberInList = recipientsQry.Where(a => a.Status == CommunicationRecipientStatus.Pending)
                                      .Where(a => !qryCommunicationListMembers.Any(r => r.PersonId == a.PersonAlias.PersonId))
                                      .ToList();

            foreach (var missingMember in missingMemberInList)
            {
                communicationRecipientService.Delete(missingMember);
            }

            rockContext.SaveChanges();
        }
        /// <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 mergeFields = GetMergeFields(action);

            // Get the connection request
            ConnectionRequest request  = null;
            Guid connectionRequestGuid = action.GetWorklowAttributeValue(GetAttributeValue(action, "ConnectionRequestAttribute").AsGuid()).AsGuid();

            request = new ConnectionRequestService(rockContext).Get(connectionRequestGuid);
            if (request == null)
            {
                errorMessages.Add("Invalid Connection Request Attribute or Value!");
                return(false);
            }

            // Get the activity type
            ConnectionActivityType activityType = null;
            Guid activityTypeGuid = action.GetWorklowAttributeValue(GetAttributeValue(action, "ConnectionActivityTypeAttribute").AsGuid()).AsGuid();

            activityType = new ConnectionActivityTypeService(rockContext).Get(activityTypeGuid);
            if (activityType == null)
            {
                errorMessages.Add("Invalid Connection Activity Type Attribute or Value!");
                return(false);
            }

            // Get the note
            string noteValue = GetAttributeValue(action, "Note", true);
            string note      = string.Empty;
            Guid?  noteGuid  = noteValue.AsGuidOrNull();

            if (noteGuid.HasValue)
            {
                var attribute = AttributeCache.Get(noteGuid.Value, rockContext);
                if (attribute != null)
                {
                    note = action.GetWorklowAttributeValue(noteGuid.Value);
                }
            }
            else
            {
                note = noteValue;
            }

            // Get the connector
            int? personAliasId       = null;
            Guid?personAttributeGuid = GetAttributeValue(action, "PersonAttribute").AsGuidOrNull();

            if (personAttributeGuid.HasValue)
            {
                Guid?personAliasGuid = action.GetWorklowAttributeValue(personAttributeGuid.Value).AsGuidOrNull();
                if (personAliasGuid.HasValue)
                {
                    var personAlias = new PersonAliasService(rockContext).Get(personAliasGuid.Value);
                    if (personAlias != null)
                    {
                        personAliasId = personAlias.Id;
                    }
                }
            }

            // Add the activity
            var activity = new ConnectionRequestActivity();

            activity.ConnectionRequestId      = request.Id;
            activity.ConnectionActivityTypeId = activityType.Id;
            activity.ConnectionOpportunityId  = request.ConnectionOpportunityId;
            activity.ConnectorPersonAliasId   = personAliasId;
            activity.Note = note.ResolveMergeFields(mergeFields);
            new ConnectionRequestActivityService(rockContext).Add(activity);
            rockContext.SaveChanges();

            return(true);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Job that will run quick SQL queries on a schedule.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            Guid?entryWorkflowType = dataMap.GetString("EraEntryWorkflow").AsGuidOrNull();
            Guid?exitWorkflowType  = dataMap.GetString("EraExitWorkflow").AsGuidOrNull();
            bool updateVisitDates  = dataMap.GetBooleanValue("SetVisitDates");

            int commandTimeout = dataMap.GetString("CommandTimeout").AsIntegerOrNull() ?? 3600;

            // configuration
            //

            // giving
            int exitGivingCount = 1;

            // attendance
            int exitAttendanceCountShort = 1;
            int exitAttendanceCountLong  = 8;

            // get era dataset from stored proc
            var resultContext = new RockContext();


            var eraAttribute      = AttributeCache.Get(SystemGuid.Attribute.PERSON_ERA_CURRENTLY_AN_ERA.AsGuid());
            var eraStartAttribute = AttributeCache.Get(SystemGuid.Attribute.PERSON_ERA_START_DATE.AsGuid());
            var eraEndAttribute   = AttributeCache.Get(SystemGuid.Attribute.PERSON_ERA_END_DATE.AsGuid());

            if (eraAttribute == null || eraStartAttribute == null || eraEndAttribute == null)
            {
                throw new Exception("Family analytic attributes could not be found");
            }

            resultContext.Database.CommandTimeout = commandTimeout;

            var results = resultContext.Database.SqlQuery <EraResult>("spCrm_FamilyAnalyticsEraDataset").ToList();

            int personEntityTypeId        = EntityTypeCache.Get("Rock.Model.Person").Id;
            int attributeEntityTypeId     = EntityTypeCache.Get("Rock.Model.Attribute").Id;
            int eraAttributeId            = eraAttribute.Id;
            int personAnalyticsCategoryId = CategoryCache.Get(SystemGuid.Category.HISTORY_PERSON_ANALYTICS.AsGuid()).Id;

            foreach (var result in results)
            {
                // create new rock context for each family (https://weblog.west-wind.com/posts/2014/Dec/21/Gotcha-Entity-Framework-gets-slow-in-long-Iteration-Loops)
                RockContext updateContext = new RockContext();
                updateContext.SourceOfChange          = SOURCE_OF_CHANGE;
                updateContext.Database.CommandTimeout = commandTimeout;
                var attributeValueService = new AttributeValueService(updateContext);
                var historyService        = new HistoryService(updateContext);

                // if era ensure it still meets requirements
                if (result.IsEra)
                {
                    if (result.ExitGiftCountDuration < exitGivingCount && result.ExitAttendanceCountDurationShort < exitAttendanceCountShort && result.ExitAttendanceCountDurationLong < exitAttendanceCountLong)
                    {
                        // exit era (delete attribute value from each person in family)
                        var family = new GroupService(updateContext).Queryable("Members, Members.Person").AsNoTracking().Where(m => m.Id == result.FamilyId).FirstOrDefault();

                        if (family != null)
                        {
                            foreach (var person in family.Members.Select(m => m.Person))
                            {
                                // remove the era flag
                                var eraAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                                if (eraAttributeValue != null)
                                {
                                    attributeValueService.Delete(eraAttributeValue);
                                }

                                // set end date
                                var eraEndAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraEndAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                                if (eraEndAttributeValue == null)
                                {
                                    eraEndAttributeValue             = new AttributeValue();
                                    eraEndAttributeValue.EntityId    = person.Id;
                                    eraEndAttributeValue.AttributeId = eraEndAttribute.Id;
                                    attributeValueService.Add(eraEndAttributeValue);
                                }
                                eraEndAttributeValue.Value = RockDateTime.Now.ToString();

                                // add a history record
                                if (personAnalyticsCategoryId != 0 && personEntityTypeId != 0 && attributeEntityTypeId != 0 && eraAttributeId != 0)
                                {
                                    History historyRecord = new History();
                                    historyService.Add(historyRecord);
                                    historyRecord.EntityTypeId           = personEntityTypeId;
                                    historyRecord.EntityId               = person.Id;
                                    historyRecord.CreatedDateTime        = RockDateTime.Now;
                                    historyRecord.CreatedByPersonAliasId = person.PrimaryAliasId;
                                    historyRecord.Caption = "eRA";

                                    historyRecord.Verb       = "EXITED";
                                    historyRecord.ChangeType = History.HistoryChangeType.Attribute.ConvertToString();
                                    historyRecord.ValueName  = "eRA";
                                    historyRecord.NewValue   = "Exited";

                                    historyRecord.RelatedEntityTypeId = attributeEntityTypeId;
                                    historyRecord.RelatedEntityId     = eraAttributeId;
                                    historyRecord.CategoryId          = personAnalyticsCategoryId;
                                    historyRecord.SourceOfChange      = SOURCE_OF_CHANGE;
                                }

                                updateContext.SaveChanges();
                            }

                            // launch exit workflow
                            if (exitWorkflowType.HasValue)
                            {
                                LaunchWorkflow(exitWorkflowType.Value, family);
                            }
                        }
                    }
                }
                else
                {
                    // entered era
                    var family = new GroupService(updateContext).Queryable("Members").AsNoTracking().Where(m => m.Id == result.FamilyId).FirstOrDefault();

                    if (family != null)
                    {
                        foreach (var person in family.Members.Where(m => !m.Person.IsDeceased).Select(m => m.Person))
                        {
                            // set era attribute to true
                            var eraAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                            if (eraAttributeValue == null)
                            {
                                eraAttributeValue             = new AttributeValue();
                                eraAttributeValue.EntityId    = person.Id;
                                eraAttributeValue.AttributeId = eraAttribute.Id;
                                attributeValueService.Add(eraAttributeValue);
                            }
                            eraAttributeValue.Value = bool.TrueString;

                            // add start date
                            var eraStartAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraStartAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                            if (eraStartAttributeValue == null)
                            {
                                eraStartAttributeValue             = new AttributeValue();
                                eraStartAttributeValue.EntityId    = person.Id;
                                eraStartAttributeValue.AttributeId = eraStartAttribute.Id;
                                attributeValueService.Add(eraStartAttributeValue);
                            }
                            eraStartAttributeValue.Value = RockDateTime.Now.ToString();

                            // delete end date if it exists
                            var eraEndAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraEndAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                            if (eraEndAttributeValue != null)
                            {
                                attributeValueService.Delete(eraEndAttributeValue);
                            }

                            // add a history record
                            if (personAnalyticsCategoryId != 0 && personEntityTypeId != 0 && attributeEntityTypeId != 0 && eraAttributeId != 0)
                            {
                                History historyRecord = new History();
                                historyService.Add(historyRecord);
                                historyRecord.EntityTypeId           = personEntityTypeId;
                                historyRecord.EntityId               = person.Id;
                                historyRecord.CreatedDateTime        = RockDateTime.Now;
                                historyRecord.CreatedByPersonAliasId = person.PrimaryAliasId;
                                historyRecord.Caption             = "eRA";
                                historyRecord.Verb                = "ENTERED";
                                historyRecord.ChangeType          = History.HistoryChangeType.Attribute.ConvertToString();
                                historyRecord.RelatedEntityTypeId = attributeEntityTypeId;
                                historyRecord.RelatedEntityId     = eraAttributeId;
                                historyRecord.CategoryId          = personAnalyticsCategoryId;
                                historyRecord.SourceOfChange      = SOURCE_OF_CHANGE;
                            }

                            updateContext.SaveChanges();
                        }

                        // launch entry workflow
                        if (entryWorkflowType.HasValue)
                        {
                            LaunchWorkflow(entryWorkflowType.Value, family);
                        }
                    }
                }

                // update stats
            }

            // load giving attributes
            resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsGiving");

            // load attendance attributes
            resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsAttendance");

            // process visit dates
            if (updateVisitDates)
            {
                resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsUpdateVisitDates");
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Get the next person for the action and group.
        /// </summary>
        /// <param name="action">The action that needs the next round robin person picked.</param>
        /// <param name="groupId">The identifier of the group to load the next person from.</param>
        /// <returns>A person object that represents the next person in the round robin selection process.</returns>
        private Person GetNextPerson(WorkflowAction action, int groupId)
        {
            Person person = null;

            //
            // Lock so that only one thread can do this at a time. This is to ensure that
            // we don't have two workflows processing at the same time and trying to get
            // the next person in the round robin and overwriting each others changes.
            //
            lock ( _lockObject )
            {
                var attrKey = action.ActionType.Guid.ToString();

                //
                // Load attributes if we need to.
                //
                if (action.Activity.Workflow.WorkflowType.Attributes == null)
                {
                    action.Activity.Workflow.WorkflowType.LoadAttributes();
                }

                //
                // Check if we already have an attribute.
                //
                if (!action.Activity.Workflow.WorkflowType.Attributes.ContainsKey(attrKey))
                {
                    var attribute = new Rock.Model.Attribute
                    {
                        EntityTypeId = action.Activity.Workflow.WorkflowType.TypeId,
                        Name         = string.Format("Last Round Robin Person ({0})", action.ActionType.Name),
                        Key          = attrKey,
                        FieldTypeId  = FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT.AsGuid()).Id
                    };

                    using (var newRockContext = new RockContext())
                    {
                        new AttributeService(newRockContext).Add(attribute);
                        newRockContext.SaveChanges();
                        AttributeCache.RemoveEntityAttributes();
                    }

                    action.Activity.Workflow.WorkflowType.Attributes.Add(attrKey, AttributeCache.Get(attribute));
                    var attributeValue = new AttributeValueCache
                    {
                        AttributeId = attribute.Id,
                        Value       = string.Empty
                    };
                    action.Activity.Workflow.WorkflowType.AttributeValues.Add(attrKey, attributeValue);
                }

                //
                // Get the last person selected.
                //
                var lastPersonId = action.Activity.Workflow.WorkflowType.GetAttributeValue(attrKey).AsIntegerOrNull();

                var rockContext = new RockContext();
                //
                // Get the list of group members to pick from.
                //
                var groupMemberService = new GroupMemberService(rockContext);
                var statuses           = this.GetAttributeValue(action, "GroupMemberStatus")
                                         .SplitDelimitedValues()
                                         .Select(s => ( GroupMemberStatus )Enum.Parse(typeof(GroupMemberStatus), s))
                                         .ToList();
                var groupMembers = groupMemberService.Queryable()
                                   .Where(m => m.GroupId == groupId && statuses.Contains(m.GroupMemberStatus))
                                   .DistinctBy(m => m.PersonId)
                                   .OrderBy(m => m.Person.LastName)
                                   .ThenBy(m => m.Person.FirstName)
                                   .ToList();

                //
                // Filter by the group role.
                //
                if (!string.IsNullOrWhiteSpace(GetAttributeValue(action, "GroupRole")))
                {
                    var groupRole = new GroupTypeRoleService(rockContext).Get(GetAttributeValue(action, "GroupRole").AsGuid());

                    groupMembers = groupMembers.Where(m => m.GroupRoleId == groupRole.Id).ToList();
                }

                //
                // Find the next person.
                //
                if (groupMembers.Count > 0)
                {
                    int lastMemberIndex = -1;

                    //
                    // Find the index of the last person picked.
                    //
                    if (lastPersonId.HasValue)
                    {
                        var lastMember = groupMembers
                                         .Where(m => !lastPersonId.HasValue || m.PersonId == lastPersonId)
                                         .FirstOrDefault();
                        if (lastMember != null)
                        {
                            lastMemberIndex = groupMembers.IndexOf(lastMember);
                        }
                    }

                    //
                    // Pick either the next or the first person.
                    //
                    if (lastMemberIndex < 0 || (lastMemberIndex + 1) >= groupMembers.Count)
                    {
                        person = groupMembers.First().Person;
                    }
                    else
                    {
                        person = groupMembers[lastMemberIndex + 1].Person;
                    }
                }

                //
                // Update the attribute value.
                //
                action.Activity.Workflow.WorkflowType.SetAttributeValue(attrKey, person != null ? person.Id.ToString() : string.Empty);
                action.Activity.Workflow.WorkflowType.SaveAttributeValues(rockContext);
            }

            return(person);
        }
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>();

            // Determine the group
            Group group = null;

            var guidGroupAttribute = GetAttributeValue(action, "Group").AsGuidOrNull();

            if (guidGroupAttribute.HasValue)
            {
                var attributeGroup = AttributeCache.Read(guidGroupAttribute.Value, rockContext);
                if (attributeGroup != null)
                {
                    var groupGuid = action.GetWorklowAttributeValue(guidGroupAttribute.Value).AsGuidOrNull();

                    if (groupGuid.HasValue)
                    {
                        group = new GroupService(rockContext).Get(groupGuid.Value);
                    }
                }
            }

            if (group == null)
            {
                errorMessages.Add("No group was provided");
            }

            // determine the person
            Person person = null;

            // get the Attribute.Guid for this workflow's Person Attribute so that we can lookup the value
            var guidPersonAttribute = GetAttributeValue(action, "Person").AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Read(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null)
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute.Value);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        if (attributePerson.FieldType.Class == typeof(Rock.Field.Types.PersonFieldType).FullName)
                        {
                            Guid personAliasGuid = attributePersonValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                person = new PersonAliasService(rockContext).Queryable()
                                         .Where(a => a.Guid.Equals(personAliasGuid))
                                         .Select(a => a.Person)
                                         .FirstOrDefault();
                            }
                        }
                        else
                        {
                            errorMessages.Add("The attribute used to provide the person was not of type 'Person'.");
                        }
                    }
                }
            }

            if (person == null)
            {
                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
            }

            // Add Person to Volunteer Tracking Table
            if (!errorMessages.Any())
            {
                var groupMemberService = new GroupMemberService(rockContext);
                var groupMember        = groupMemberService.Queryable().FirstOrDefault(m => m.GroupId == group.Id && m.PersonId == person.Id);

                if (groupMember != null)
                {
                    var volunteerTrackingContext   = new VolunteerTrackingContext();
                    var volunteerMembershipService = new VolunteerMembershipService(volunteerTrackingContext);
                    var oldVolunteerMembership     = volunteerMembershipService.Queryable().FirstOrDefault(v => v.GroupId == groupMember.GroupId && v.PersonId == groupMember.PersonId && v.LeftGroupDateTime == null);
                    if (oldVolunteerMembership != null)
                    {
                        oldVolunteerMembership.LeftGroupDateTime = DateTime.Now;
                    }

                    var newVolunteerMembership = new VolunteerMembership
                    {
                        GroupId             = groupMember.GroupId,
                        PersonId            = groupMember.PersonId,
                        GroupRoleId         = groupMember.GroupRoleId,
                        JoinedGroupDateTime = DateTime.Now
                    };

                    volunteerMembershipService.Add(newVolunteerMembership);

                    volunteerTrackingContext.SaveChanges();
                }
                else
                {
                    // the person is not in the group provided
                    errorMessages.Add("The person is not in the group provided.");
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Creates the child controls.
        /// </summary>
        /// <returns></returns>
        public override Control[] CreateChildControls(Type entityType, FilterField filterControl, FilterMode filterMode)
        {
            var containerControl = new DynamicControlsPanel();

            containerControl.ID       = string.Format("{0}_containerControl", filterControl.ID);
            containerControl.CssClass = "js-container-control";
            filterControl.Controls.Add(containerControl);

            // Create the field selection dropdown
            var ddlEntityField = new RockDropDownList();

            ddlEntityField.ID           = string.Format("{0}_ddlProperty", filterControl.ID);
            ddlEntityField.ClientIDMode = ClientIDMode.Predictable;
            containerControl.Controls.Add(ddlEntityField);

            // add Empty option first
            ddlEntityField.Items.Add(new ListItem());
            var rockBlock       = filterControl.RockBlock();
            var entityTypeCache = EntityTypeCache.Read(entityType, true);

            this.entityFields = EntityHelper.GetEntityFields(entityType);
            foreach (var entityField in this.entityFields.OrderBy(a => !a.IsPreviewable).ThenBy(a => a.FieldKind != FieldKind.Property).ThenBy(a => a.Title))
            {
                bool isAuthorized = true;
                bool includeField = true;
                if (entityField.FieldKind == FieldKind.Attribute && entityField.AttributeGuid.HasValue)
                {
                    if (entityType == typeof(Rock.Model.Workflow) && !string.IsNullOrWhiteSpace(entityField.AttributeEntityTypeQualifierName))
                    {
                        // Workflows can contain tons of Qualified Attributes, so let the WorkflowAttributeFilter take care of those
                        includeField = false;
                    }

                    var attribute = AttributeCache.Read(entityField.AttributeGuid.Value);
                    if (includeField && attribute != null && rockBlock != null)
                    {
                        // only show the Attribute field in the drop down if they have VIEW Auth to it
                        isAuthorized = attribute.IsAuthorized(Rock.Security.Authorization.VIEW, rockBlock.CurrentPerson);
                    }
                }

                if (isAuthorized && includeField)
                {
                    var listItem = new ListItem(entityField.Title, entityField.Name);

                    if (entityField.IsPreviewable)
                    {
                        listItem.Attributes["optiongroup"] = "Common";
                    }
                    else if (entityField.FieldKind == FieldKind.Attribute)
                    {
                        listItem.Attributes["optiongroup"] = string.Format("{0} Attributes", entityType.Name);
                    }
                    else
                    {
                        listItem.Attributes["optiongroup"] = string.Format("{0} Fields", entityType.Name);
                    }

                    ddlEntityField.Items.Add(listItem);
                }
            }

            ddlEntityField.AutoPostBack = true;

            // grab the currently selected value off of the request params since we are creating the controls after the Page Init
            var selectedValue = ddlEntityField.Page.Request.Params[ddlEntityField.UniqueID];

            if (selectedValue != null)
            {
                ddlEntityField.SelectedValue = selectedValue;
                ddlEntityField_SelectedIndexChanged(ddlEntityField, new EventArgs());
            }

            ddlEntityField.SelectedIndexChanged += ddlEntityField_SelectedIndexChanged;

            return(new Control[] { containerControl });
        }
Exemplo n.º 27
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>();

            // get person
            Person person = null;

            string personAttributeValue = GetAttributeValue(action, "Person");
            Guid?  guidPersonAttribute  = personAttributeValue.AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Get(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null || attributePerson.FieldType.Class != "Rock.Field.Types.PersonFieldType")
                {
                    string attributePersonValue = action.GetWorkflowAttributeValue(guidPersonAttribute.Value);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        Guid personAliasGuid = attributePersonValue.AsGuid();
                        if (!personAliasGuid.IsEmpty())
                        {
                            person = new PersonAliasService(rockContext).Queryable()
                                     .Where(a => a.Guid.Equals(personAliasGuid))
                                     .Select(a => a.Person)
                                     .FirstOrDefault();
                            if (person == null)
                            {
                                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
                                return(false);
                            }
                        }
                    }
                }
            }

            if (person == null)
            {
                errorMessages.Add("The attribute used to provide the person was invalid, or not of type 'Person'.");
                return(false);
            }

            // determine the location type to edit
            DefinedValueCache locationType = null;
            var locationTypeAttributeValue = action.GetWorkflowAttributeValue(GetAttributeValue(action, "LocationTypeAttribute").AsGuid());

            if (locationTypeAttributeValue != null)
            {
                locationType = DefinedValueCache.Get(locationTypeAttributeValue.AsGuid());
            }
            if (locationType == null)
            {
                locationType = DefinedValueCache.Get(GetAttributeValue(action, "LocationType").AsGuid());
            }
            if (locationType == null)
            {
                errorMessages.Add("The location type to be updated was not selected.");
                return(false);
            }

            // get the new phone number value
            Location location      = null;
            string   locationValue = GetAttributeValue(action, "Location");
            Guid?    locationGuid  = locationValue.AsGuidOrNull();

            if (!locationGuid.HasValue || locationGuid.Value.IsEmpty())
            {
                string locationAttributeValue     = GetAttributeValue(action, "LocationAttribute");
                Guid?  locationAttributeValueGuid = locationAttributeValue.AsGuidOrNull();
                if (locationAttributeValueGuid.HasValue)
                {
                    locationGuid = action.GetWorkflowAttributeValue(locationAttributeValueGuid.Value).AsGuidOrNull();
                }
            }

            if (locationGuid.HasValue)
            {
                location = new LocationService(rockContext).Get(locationGuid.Value);
            }

            if (location == null)
            {
                errorMessages.Add("The location value could not be determined.");
                return(false);
            }

            // gets value indicating if location is a mailing location
            string mailingValue     = GetAttributeValue(action, "IsMailing");
            Guid?  mailingValueGuid = mailingValue.AsGuidOrNull();

            if (mailingValueGuid.HasValue)
            {
                mailingValue = action.GetWorkflowAttributeValue(mailingValueGuid.Value);
            }
            else
            {
                mailingValue = mailingValue.ResolveMergeFields(GetMergeFields(action));
            }
            bool?mailing = mailingValue.AsBooleanOrNull();

            // gets value indicating if location is a mapped location
            string mappedValue     = GetAttributeValue(action, "IsMapped");
            Guid?  mappedValueGuid = mappedValue.AsGuidOrNull();

            if (mappedValueGuid.HasValue)
            {
                mappedValue = action.GetWorkflowAttributeValue(mappedValueGuid.Value);
            }
            else
            {
                mappedValue = mappedValue.ResolveMergeFields(GetMergeFields(action));
            }
            bool?mapped = mappedValue.AsBooleanOrNull();

            var savePreviousAddress = GetAttributeValue(action, "SavePreviousAddress").AsBoolean();

            var locationService = new LocationService(rockContext);

            locationService.Verify(location, false);

            var groupLocationService = new GroupLocationService(rockContext);

            foreach (var family in person.GetFamilies(rockContext).ToList())
            {
                bool locationUpdated = false;

                if (savePreviousAddress)
                {
                    // Get all existing addresses of the specified type
                    var groupLocations = family.GroupLocations.Where(l => l.GroupLocationTypeValueId == locationType.Id).ToList();

                    // Create a new address of the specified type, saving all existing addresses of that type as Previous Addresses
                    // Use the specified Is Mailing and Is Mapped values from the action's parameters if they are set,
                    // otherwise set them to true if any of the existing addresses of that type have those values set to true
                    GroupService.AddNewGroupAddress(rockContext, family, locationType.Guid.ToString(), location.Id, true,
                                                    $"the {action.ActionTypeCache.ActivityType.WorkflowType.Name} workflow",
                                                    mailing ?? groupLocations.Any(x => x.IsMailingLocation),
                                                    mapped ?? groupLocations.Any(x => x.IsMappedLocation));
                }
                else
                {
                    var    groupLocation = family.GroupLocations.FirstOrDefault(l => l.GroupLocationTypeValueId == locationType.Id);
                    string oldValue      = string.Empty;
                    if (groupLocation == null)
                    {
                        groupLocation         = new GroupLocation();
                        groupLocation.GroupId = family.Id;
                        groupLocation.GroupLocationTypeValueId = locationType.Id;
                        groupLocationService.Add(groupLocation);
                    }
                    else
                    {
                        oldValue = groupLocation.Location.ToString();
                    }

                    locationUpdated = oldValue != location.ToString();

                    groupLocation.Location = location;

                    if (mailing.HasValue)
                    {
                        if (((oldValue == string.Empty) ? null : groupLocation.IsMailingLocation.ToString()) != mailing.Value.ToString())
                        {
                            locationUpdated = true;
                        }
                        groupLocation.IsMailingLocation = mailing.Value;
                    }

                    if (mapped.HasValue)
                    {
                        if (((oldValue == string.Empty) ? null : groupLocation.IsMappedLocation.ToString()) != mapped.Value.ToString())
                        {
                            locationUpdated = true;
                        }
                        groupLocation.IsMappedLocation = mapped.Value;
                    }
                }

                if (locationUpdated)
                {
                    var groupChanges = new History.HistoryChangeList();
                    groupChanges.AddChange(History.HistoryVerb.Modify, History.HistoryChangeType.Record, "Location").SourceOfChange = $"{action.ActionTypeCache.ActivityType.WorkflowType.Name} workflow";

                    foreach (var fm in family.Members)
                    {
                        HistoryService.SaveChanges(
                            rockContext,
                            typeof(Person),
                            Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                            fm.PersonId,
                            groupChanges,
                            family.Name,
                            typeof(Group),
                            family.Id,
                            false,
                            null,
                            rockContext.SourceOfChange);
                    }
                }

                rockContext.SaveChanges();

                action.AddLogEntry(string.Format("Updated the {0} location for {1} (family: {2}) to {3}", locationType.Value, person.FullName, family.Name, location.ToString()));
            }

            return(true);
        }
Exemplo n.º 28
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>();

            // get person
            Person person = null;
            string personAttributeValue = GetAttributeValue(action, "Person");
            Guid   guidPersonAttribute  = personAttributeValue.AsGuid();

            if (!guidPersonAttribute.IsEmpty())
            {
                var attributePerson = AttributeCache.Get(guidPersonAttribute, rockContext);
                if (attributePerson != null)
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        if (attributePerson.FieldType.Class == "Rock.Field.Types.PersonFieldType")
                        {
                            Guid personAliasGuid = attributePersonValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                person = new PersonAliasService(rockContext).Queryable()
                                         .Where(a => a.Guid.Equals(personAliasGuid))
                                         .Select(a => a.Person)
                                         .FirstOrDefault();
                                if (person == null)
                                {
                                    errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
                                    return(false);
                                }
                            }
                        }
                        else
                        {
                            errorMessages.Add("The attribute used to provide the person was not of type 'Person'.");
                            return(false);
                        }
                    }
                }
            }

            if (person == null)
            {
                errorMessages.Add("The attribute used to provide the person was invalid, or not of type 'Person'.");
                return(false);
            }

            // get value
            string updateValue = GetAttributeValue(action, "Value");
            Guid?  valueGuid   = updateValue.AsGuidOrNull();

            if (valueGuid.HasValue)
            {
                updateValue = action.GetWorklowAttributeValue(valueGuid.Value);
            }
            else
            {
                updateValue = updateValue.ResolveMergeFields(GetMergeFields(action));
            }

            // determine the property to edit
            var propertySelected = GetAttributeValue(action, "Property");

            // get the ignore blank setting
            var ignoreBlanks = GetActionAttributeValue(action, "IgnoreBlankValues").AsBoolean();

            // update the person
            switch (propertySelected)
            {
            case "Title":
            {
                var definedValueId = GetDefinedValueId(updateValue, SystemGuid.DefinedType.PERSON_TITLE.AsGuid(), rockContext);

                if (ignoreBlanks == false || definedValueId.HasValue)
                {
                    person.TitleValueId = definedValueId;
                    rockContext.SaveChanges();
                }

                break;
            }

            case "FirstName":
            {
                if (ignoreBlanks == false || !string.IsNullOrWhiteSpace(updateValue))
                {
                    person.FirstName = updateValue;
                    rockContext.SaveChanges();
                }
                break;
            }

            case "NickName":
            {
                if (ignoreBlanks == false || !string.IsNullOrWhiteSpace(updateValue))
                {
                    person.NickName = updateValue;
                    rockContext.SaveChanges();
                }
                break;
            }

            case "MiddleName":
            {
                if (ignoreBlanks == false || !string.IsNullOrWhiteSpace(updateValue))
                {
                    person.MiddleName = updateValue;
                    rockContext.SaveChanges();
                }
                break;
            }

            case "LastName":
            {
                if (ignoreBlanks == false || !string.IsNullOrWhiteSpace(updateValue))
                {
                    person.LastName = updateValue;
                    rockContext.SaveChanges();
                }
                break;
            }

            case "Suffix":
            {
                var definedValueId = GetDefinedValueId(updateValue, SystemGuid.DefinedType.PERSON_SUFFIX.AsGuid(), rockContext);

                if (ignoreBlanks == false || definedValueId.HasValue)
                {
                    person.SuffixValueId = definedValueId;
                    rockContext.SaveChanges();
                }
                break;
            }

            case "Birthdate":
            {
                var birthdate = updateValue.AsDateTime();

                if (ignoreBlanks == false || birthdate.HasValue)
                {
                    if (birthdate.HasValue)
                    {
                        person.BirthDay   = birthdate.Value.Day;
                        person.BirthMonth = birthdate.Value.Month;
                        person.BirthYear  = birthdate.Value.Year;
                    }
                    else
                    {
                        person.BirthDay   = null;
                        person.BirthMonth = null;
                        person.BirthYear  = null;
                    }
                    rockContext.SaveChanges();
                }

                break;
            }

            case "Photo":
            {
                // could be integer of binary file or a guid

                var binaryFileId = updateValue.AsIntegerOrNull();
                if (binaryFileId.HasValue)
                {
                    person.PhotoId = binaryFileId;
                    rockContext.SaveChanges();
                }
                else
                {
                    var binaryFileGuid = updateValue.AsGuidOrNull();
                    if (binaryFileGuid.HasValue)
                    {
                        binaryFileId = new BinaryFileService(rockContext).Queryable().Where(f => f.Guid == binaryFileGuid.Value).Select(f => f.Id).FirstOrDefault();

                        if (ignoreBlanks == false || binaryFileId.HasValue)
                        {
                            person.PhotoId = binaryFileId;
                            rockContext.SaveChanges();
                        }
                    }
                }

                break;
            }

            case "Gender":
            {
                var gender = updateValue.ConvertToEnumOrNull <Gender>();
                if (ignoreBlanks == false || gender.HasValue)
                {
                    if (!gender.HasValue)
                    {
                        gender = Gender.Unknown;
                    }
                    person.Gender = gender.Value;
                    rockContext.SaveChanges();
                }
                break;
            }

            case "MaritalStatus":
            {
                var definedValueId = GetDefinedValueId(updateValue, SystemGuid.DefinedType.PERSON_MARITAL_STATUS.AsGuid(), rockContext);

                if (ignoreBlanks == false || definedValueId.HasValue)
                {
                    person.MaritalStatusValueId = definedValueId;
                    rockContext.SaveChanges();
                }

                break;
            }

            case "AnniversaryDate":
            {
                var anniversarydate = updateValue.AsDateTime();

                if (ignoreBlanks == false || anniversarydate.HasValue)
                {
                    person.AnniversaryDate = anniversarydate;
                    rockContext.SaveChanges();
                }
                break;
            }

            case "CommunicationPreference":
            {
                var communicationPreference = updateValue.ConvertToEnumOrNull <CommunicationType>();
                if (ignoreBlanks == false || communicationPreference.HasValue)
                {
                    if (!communicationPreference.HasValue)
                    {
                        communicationPreference = CommunicationType.Email;
                    }
                    person.CommunicationPreference = communicationPreference.Value;
                    rockContext.SaveChanges();
                }
                break;
            }

            case "Email":
            {
                if (ignoreBlanks == false || !string.IsNullOrWhiteSpace(updateValue))
                {
                    person.Email = updateValue;
                    rockContext.SaveChanges();
                }
                break;
            }

            case "IsEmailActive":
            {
                var updateAsBoolean = updateValue.AsBooleanOrNull();

                if (ignoreBlanks == false || updateAsBoolean.HasValue)
                {
                    if (!updateAsBoolean.HasValue)
                    {
                        updateAsBoolean = true;         // default to true
                    }
                    person.IsEmailActive = updateAsBoolean.Value;
                    rockContext.SaveChanges();
                }
                break;
            }

            case "EmailNote":
            {
                if (ignoreBlanks == false || !string.IsNullOrWhiteSpace(updateValue))
                {
                    person.EmailNote = updateValue;
                    rockContext.SaveChanges();
                }
                break;
            }

            case "EmailPreference":
            {
                var emailPreference = updateValue.ConvertToEnumOrNull <EmailPreference>();
                if (ignoreBlanks == false || emailPreference.HasValue)
                {
                    if (!emailPreference.HasValue)
                    {
                        emailPreference = EmailPreference.EmailAllowed;
                    }
                    person.EmailPreference = emailPreference.Value;
                    rockContext.SaveChanges();
                }
                break;
            }

            case "GraduationYear":
            {
                var updateAsInt = updateValue.AsIntegerOrNull();

                if (ignoreBlanks == false || updateAsInt.HasValue)
                {
                    person.GraduationYear = updateAsInt;
                    rockContext.SaveChanges();
                }

                break;
            }

            case "RecordStatus":
            {
                var definedValueId = GetDefinedValueId(updateValue, SystemGuid.DefinedType.PERSON_RECORD_STATUS.AsGuid(), rockContext);

                if (ignoreBlanks == false || definedValueId.HasValue)
                {
                    person.RecordStatusValueId = definedValueId;
                    rockContext.SaveChanges();
                }
                break;
            }

            case "RecordStatusReason":
            {
                var definedValueId = GetDefinedValueId(updateValue, SystemGuid.DefinedType.PERSON_RECORD_STATUS_REASON.AsGuid(), rockContext);

                if (ignoreBlanks == false || definedValueId.HasValue)
                {
                    person.RecordStatusReasonValueId = definedValueId;
                    rockContext.SaveChanges();
                }
                break;
            }

            case "InactiveReasonNote":
            {
                if (ignoreBlanks == false || !string.IsNullOrWhiteSpace(updateValue))
                {
                    person.InactiveReasonNote = updateValue;
                    rockContext.SaveChanges();
                }
                break;
            }

            case "ConnectionStatus":
            {
                var definedValueId = GetDefinedValueId(updateValue, SystemGuid.DefinedType.PERSON_CONNECTION_STATUS.AsGuid(), rockContext);

                if (ignoreBlanks == false || definedValueId.HasValue)
                {
                    person.ConnectionStatusValueId = definedValueId;
                    rockContext.SaveChanges();
                }
                break;
            }

            case "IsDeceased":
            {
                var updateAsBoolean = updateValue.AsBooleanOrNull();

                if (ignoreBlanks == false || updateAsBoolean.HasValue)
                {
                    if (!updateAsBoolean.HasValue)
                    {
                        updateAsBoolean = false;         // default to false
                    }
                    person.IsDeceased = updateAsBoolean.Value;
                    rockContext.SaveChanges();
                }
                break;
            }

            case "SystemNote":
            {
                if (ignoreBlanks == false || !string.IsNullOrWhiteSpace(updateValue))
                {
                    person.SystemNote = updateValue;
                    rockContext.SaveChanges();
                }
                break;
            }
            }


            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
Exemplo n.º 29
0
 /// <summary>
 /// Abstract method for sending a background request. Derived classes should implement
 /// this method to initiate a background request. Because requests will be made through a
 /// workflow, the workflow is passed to this method. It is up to the derived class to
 /// evaluate/update any workflow attributes it needs
 /// </summary>
 /// <param name="rockContext">The rock context.</param>
 /// <param name="workflow">The Workflow initiating the request.</param>
 /// <param name="personAttribute">The person attribute.</param>
 /// <param name="ssnAttribute">The SSN attribute.</param>
 /// <param name="requestTypeAttribute">The request type attribute.</param>
 /// <param name="billingCodeAttribute">The billing code attribute.</param>
 /// <param name="errorMessages">The error messages.</param>
 /// <returns>
 /// True/False value of whether the request was successfully sent or not
 /// </returns>
 public abstract bool SendRequest(RockContext rockContext, Rock.Model.Workflow workflow,
                                  AttributeCache personAttribute, AttributeCache ssnAttribute, AttributeCache requestTypeAttribute,
                                  AttributeCache billingCodeAttribute, out List <string> errorMessages);
Exemplo n.º 30
0
        //Limits the displayed rows only to rows which are selected
        private void ShowOnlySelectedRows()
        {
            if (_featureLayer.DataSet.AttributesPopulated)
            {
                int numRows = _featureLayer.DataSet.DataTable.Rows.Count;
                dataGridView1.SuspendLayout();
                _selection = new DataTable();
                _selection.Columns.AddRange(_featureLayer.DataSet.GetColumns());

                if (!_selection.Columns.Contains(_fidField))
                {
                    _selection.Columns.Add(_fidField, typeof(int));
                }
                if (_selectionIndices == null) _selectionIndices = new List<int>();
                _selectionIndices.Clear();
                for (int row = 0; row < numRows; row++)
                {
                    if (!_featureLayer.DrawnStates[row].Selected) continue;
                    DataRow dr = _selection.NewRow();
                    dr.ItemArray = _featureLayer.DataSet.DataTable.Rows[row].ItemArray;
                    _selection.Rows.Add(dr);
                    _selectionIndices.Add(row);
                }
                dataGridView1.DataSource = _selection;
                dataGridView1.SelectAll();
                dataGridView1.ResumeLayout();
            }
            else
            {
                _attributeCache = new AttributeCache(_featureLayer.Selection, 16);
                dataGridView1.Rows.Clear(); // without this setting rowCount takes a looooong time
                dataGridView1.RowCount = _featureLayer.Selection.Count;
            }
            _showOnlySelectedRows = true;
            Refresh();
        }
Exemplo n.º 31
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            AttributeMatrixService attributeMatrixService = new AttributeMatrixService(rockContext);

            errorMessages = new List <string>();

            // Get all the attribute values
            var sourceMatrixAttributeGuid = action.GetWorkflowAttributeValue(GetActionAttributeValue(action, "SourceAttributeMatrix").AsGuid()).AsGuidOrNull();
            var targetMatrixAttributeGuid = action.GetWorkflowAttributeValue(GetActionAttributeValue(action, "TargetAttributeMatrix").AsGuid()).AsGuidOrNull();

            if (sourceMatrixAttributeGuid.HasValue)
            {
                // Load the source matrix
                AttributeMatrix sourceMatrix = attributeMatrixService.Get(sourceMatrixAttributeGuid.Value);
                AttributeMatrix targetMatrix = null;

                if (targetMatrixAttributeGuid.HasValue)
                {
                    // Just delete all the existing items and add new items from the source attribute
                    targetMatrix = attributeMatrixService.Get(targetMatrixAttributeGuid.Value);
                    targetMatrix.AttributeMatrixItems.Clear();
                }
                else
                {
                    targetMatrix = new AttributeMatrix();
                    targetMatrix.AttributeMatrixItems      = new List <AttributeMatrixItem>();
                    targetMatrix.AttributeMatrixTemplateId = sourceMatrix.AttributeMatrixTemplateId;
                    attributeMatrixService.Add(targetMatrix);
                }

                // Now copy all the items from the source to the target
                foreach (var sourceItem in sourceMatrix.AttributeMatrixItems)
                {
                    var targetItem = new AttributeMatrixItem();
                    sourceItem.LoadAttributes();
                    targetItem.AttributeMatrix = targetMatrix;
                    targetItem.LoadAttributes();
                    foreach (var attribute in sourceItem.AttributeValues)
                    {
                        targetItem.SetAttributeValue(attribute.Key, attribute.Value.Value);
                    }
                    targetMatrix.AttributeMatrixItems.Add(targetItem);
                    rockContext.SaveChanges(true);
                    targetItem.SaveAttributeValues(rockContext);
                }


                // Now store the target attribute
                var targetAttribute = AttributeCache.Get(GetActionAttributeValue(action, "TargetAttributeMatrix").AsGuid(), rockContext);
                if (targetAttribute.EntityTypeId == new Rock.Model.Workflow().TypeId)
                {
                    action.Activity.Workflow.SetAttributeValue(targetAttribute.Key, targetMatrix.Guid.ToString());
                }
                else if (targetAttribute.EntityTypeId == new WorkflowActivity().TypeId)
                {
                    action.Activity.SetAttributeValue(targetAttribute.Key, targetMatrix.Guid.ToString());
                }
            }

            return(true);
        }
Exemplo n.º 32
0
        private void FeatureLayerSetup()
        {
            if (_featureLayer == null) return;
            if (_featureLayer.DataSet.NumRows() < 10000 && !_featureLayer.DataSet.AttributesPopulated)
            {
                _featureLayer.DataSet.FillAttributes();
            }

            if (_featureLayer.DataSet.AttributesPopulated)
            {
                dataGridView1.VirtualMode = false;
                dataGridView1.AllowUserToOrderColumns = true;
                dataGridView1.DataSource = _featureLayer.DataSet.DataTable;
                if (_virtualHooked)
                {
                    dataGridView1.CellValueNeeded -= DataGridView1CellValueNeeded;
                    dataGridView1.CellValuePushed -= dataGridView1_CellValuePushed;
                    dataGridView1.RowValidated -= dataGridView1_RowValidated;
                }
                AddFid(_featureLayer.DataSet.DataTable);
            }
            else
            {
                dataGridView1.VirtualMode = true;
                dataGridView1.AllowUserToOrderColumns = false;
                if (!_virtualHooked)
                {
                    dataGridView1.CellValueNeeded += DataGridView1CellValueNeeded;
                    dataGridView1.CellValuePushed += dataGridView1_CellValuePushed;
                    dataGridView1.RowValidated += dataGridView1_RowValidated;
                    _virtualHooked = true;
                }
                _attributeCache = new AttributeCache(FeatureLayer.DataSet, 16);                
                foreach (var field in _featureLayer.DataSet.GetColumns())
                {
                    dataGridView1.Columns.Add(field.ColumnName, field.ColumnName);
                }
                dataGridView1.RowCount = _featureLayer.DataSet.NumRows();
            }
            _featureLayer.SelectionChanged += SelectedFeaturesChanged;
        }
Exemplo n.º 33
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?  groupGuid = null;
            Person person    = null;
            Group  group     = null;
            string noteValue = string.Empty;

            // get the group attribute
            Guid groupAttributeGuid = GetAttributeValue(action, "Group").AsGuid();

            if (!groupAttributeGuid.IsEmpty())
            {
                groupGuid = action.GetWorkflowAttributeValue(groupAttributeGuid).AsGuidOrNull();

                if (groupGuid.HasValue)
                {
                    group = new GroupService(rockContext).Get(groupGuid.Value);

                    if (group == null)
                    {
                        errorMessages.Add("The group provided does not exist.");
                    }
                }
                else
                {
                    errorMessages.Add("Invalid group provided.");
                }
            }

            // get person alias guid
            Guid   personAliasGuid = Guid.Empty;
            string personAttribute = GetAttributeValue(action, "Person");

            Guid guid = personAttribute.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Get(guid, rockContext);
                if (attribute != null)
                {
                    string value = action.GetWorkflowAttributeValue(guid);
                    personAliasGuid = value.AsGuid();
                }

                if (personAliasGuid != Guid.Empty)
                {
                    person = new PersonAliasService(rockContext).Queryable()
                             .Where(p => p.Guid.Equals(personAliasGuid))
                             .Select(p => p.Person)
                             .FirstOrDefault();

                    if (person == null)
                    {
                        errorMessages.Add("The person could not be found.");
                    }
                }
                else
                {
                    errorMessages.Add("Invalid person provided.");
                }
            }

            // get group member note
            noteValue = GetAttributeValue(action, "Note");
            guid      = noteValue.AsGuid();
            if (guid.IsEmpty())
            {
                noteValue = noteValue.ResolveMergeFields(GetMergeFields(action));
            }
            else
            {
                var workflowAttributeValue = action.GetWorkflowAttributeValue(guid);

                if (workflowAttributeValue != null)
                {
                    noteValue = workflowAttributeValue;
                }
            }

            // set note
            if (group != null && person != null)
            {
                var groupMembers = new GroupMemberService(rockContext).Queryable()
                                   .Where(m => m.Group.Guid == groupGuid && m.PersonId == person.Id).ToList();

                if (groupMembers.Count() > 0)
                {
                    foreach (var groupMember in groupMembers)
                    {
                        groupMember.Note = noteValue;
                        rockContext.SaveChanges();
                    }
                }
                else
                {
                    errorMessages.Add(string.Format("{0} is not a member of the group {1}.", person.FullName, group.Name));
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
Exemplo n.º 34
0
        /// <summary>
        /// Returns
        /// </summary>
        private static bool SufficientValues(string fieldName, IAttributeSource source, int numValues)
        {
            ArrayList lst = new ArrayList();
            AttributeCache ac = new AttributeCache(source, numValues);

            foreach (Dictionary<string, object> dr in ac)
            {
                object val = dr[fieldName] ?? "[NULL]";
                if (val.ToString() == string.Empty) val = "[NULL]";
                if (lst.Contains(val)) continue;
                lst.Add(val);
                if (lst.Count > numValues) return true;
            }
            return false;
        }
Exemplo n.º 35
0
        /// <summary>
        /// Renders the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="result">The result.</param>
        /// <exception cref="System.Exception">Your Lava command must contain at least one valid filter. If you configured a filter it's possible that the property or attribute you provided does not exist.</exception>
        public override void Render(Context context, TextWriter result)
        {
            // first ensure that entity commands are allowed in the context
            if (!this.IsAuthorized(context))
            {
                result.Write(string.Format(RockLavaBlockBase.NotAuthorizedMessage, this.Name));
                base.Render(context, result);
                return;
            }

            bool hasFilter = false;

            // get a service for the entity based off it's friendly name
            var entityTypes = EntityTypeCache.All();

            var model = string.Empty;

            if (_entityName == "business")
            {
                model = "Rock.Model.Person";
            }
            else
            {
                model = "Rock.Model." + _entityName;
            }

            // Check first to see if this is a core model
            var entityTypeCache = entityTypes.Where(e => String.Equals(e.Name, model, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

            // If not, look for first plug-in model that has same friendly name
            if (entityTypeCache == null)
            {
                entityTypeCache = entityTypes
                                  .Where(e =>
                                         e.IsEntity &&
                                         !e.Name.StartsWith("Rock.Model") &&
                                         e.FriendlyName != null &&
                                         e.FriendlyName.RemoveSpaces().ToLower() == _entityName)
                                  .OrderBy(e => e.Id)
                                  .FirstOrDefault();
            }

            // If still null check to see if this was a duplicate class and full class name was used as entity name
            if (entityTypeCache == null)
            {
                model           = _entityName.Replace('_', '.');
                entityTypeCache = entityTypes.Where(e => String.Equals(e.Name, model, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            }

            if (entityTypeCache != null)
            {
                Type entityType = entityTypeCache.GetEntityType();
                if (entityType != null)
                {
                    // Get the database context
                    var dbContext = Reflection.GetDbContextForEntityType(entityType);    // TODO why not use RockContext here?

                    // Create an instance of the entity's service
                    IService serviceInstance = Reflection.GetServiceForEntityType(entityType, dbContext);

                    ParameterExpression paramExpression = Expression.Parameter(entityType, "x");
                    Expression          queryExpression = null; // the base expression we'll use to build our query from

                    // Parse markup
                    var parms = ParseMarkup(_markup, context);

                    if (parms.Any(p => p.Key == "id"))
                    {
                        string propertyName = "Id";

                        List <string> selectionParms = new List <string>();
                        selectionParms.Add(PropertyComparisonConversion("==").ToString());
                        selectionParms.Add(parms["id"].ToString());
                        selectionParms.Add(propertyName);

                        var entityProperty = entityType.GetProperty(propertyName);
                        queryExpression = ExpressionHelper.PropertyFilterExpression(selectionParms, paramExpression, propertyName, entityProperty.PropertyType);

                        hasFilter = true;
                    }
                    else
                    {
                        // where clause expression
                        if (parms.Any(p => p.Key == "where"))
                        {
                            queryExpression = ParseWhere(parms["where"], entityType, serviceInstance, paramExpression, entityType, entityTypeCache);

                            if (queryExpression != null)
                            {
                                hasFilter = true;
                            }
                        }

                        // DataView expression
                        if (parms.Any(p => p.Key == "dataview"))
                        {
                            var dataViewId = parms["dataview"].AsIntegerOrNull();

                            if (dataViewId.HasValue)
                            {
                                var dataViewExpression = GetDataViewExpression(dataViewId.Value, serviceInstance, paramExpression, entityTypeCache);

                                if (queryExpression == null)
                                {
                                    queryExpression = dataViewExpression;
                                    hasFilter       = true;
                                }
                                else
                                {
                                    queryExpression = Expression.AndAlso(queryExpression, dataViewExpression);
                                }
                            }
                        }

                        // process dynamic filter expressions (from the query string)
                        if (parms.Any(p => p.Key == "dynamicparameters"))
                        {
                            var dynamicFilters = parms["dynamicparameters"].Split(',')
                                                 .Select(x => x.Trim())
                                                 .Where(x => !string.IsNullOrWhiteSpace(x))
                                                 .ToList();

                            foreach (var dynamicFilter in dynamicFilters)
                            {
                                var dynamicFilterValue      = HttpContext.Current.Request[dynamicFilter];
                                var dynamicFilterExpression = GetDynamicFilterExpression(dynamicFilter, dynamicFilterValue, entityType, serviceInstance, paramExpression);
                                if (dynamicFilterExpression != null)
                                {
                                    if (queryExpression == null)
                                    {
                                        queryExpression = dynamicFilterExpression;
                                        hasFilter       = true;
                                    }
                                    else
                                    {
                                        queryExpression = Expression.AndAlso(queryExpression, dynamicFilterExpression);
                                    }
                                }
                            }
                        }
                    }

                    // Make the query from the expression
                    MethodInfo getMethod = serviceInstance.GetType().GetMethod("GetNoTracking", new Type[] { typeof(ParameterExpression), typeof(Expression), typeof(Rock.Web.UI.Controls.SortProperty), typeof(int?) });
                    if (getMethod != null)
                    {
                        // get a listing of ids and build it into the query expression
                        if (parms.Any(p => p.Key == "ids"))
                        {
                            List <int>         value = parms["ids"].ToString().Split(',').Select(int.Parse).ToList();
                            MemberExpression   propertyExpression = Expression.Property(paramExpression, "Id");
                            ConstantExpression constantExpression = Expression.Constant(value, typeof(List <int>));
                            Expression         containsExpression = Expression.Call(constantExpression, typeof(List <int>).GetMethod("Contains", new Type[] { typeof(int) }), propertyExpression);
                            if (queryExpression != null)
                            {
                                queryExpression = Expression.AndAlso(queryExpression, containsExpression);
                            }
                            else
                            {
                                queryExpression = containsExpression;
                            }

                            hasFilter = true;
                        }

                        var getResult   = getMethod.Invoke(serviceInstance, new object[] { paramExpression, queryExpression, null, null });
                        var queryResult = getResult as IQueryable <IEntity>;

                        // process entity specific filters
                        switch (_entityName)
                        {
                        case "person":
                        {
                            queryResult = PersonFilters((IQueryable <Person>)queryResult, parms);
                            break;
                        }

                        case "business":
                        {
                            queryResult = BusinessFilters((IQueryable <Person>)queryResult, parms);
                            break;
                        }
                        }

                        // if there was a dynamic expression add it now
                        if (parms.Any(p => p.Key == "expression"))
                        {
                            queryResult = queryResult.Where(parms["expression"]);
                            hasFilter   = true;
                        }

                        var queryResultExpression = queryResult.Expression;

                        // add sort expressions
                        if (parms.Any(p => p.Key == "sort"))
                        {
                            string orderByMethod = "OrderBy";

                            foreach (var column in parms["sort"].Split(',').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToList())
                            {
                                string propertyName;
                                var    direction = SortDirection.Ascending;

                                if (column.EndsWith(" desc", StringComparison.OrdinalIgnoreCase))
                                {
                                    direction    = SortDirection.Descending;
                                    propertyName = column.Left(column.Length - 5);
                                }
                                else
                                {
                                    propertyName = column;
                                }

                                string methodName = direction == SortDirection.Descending ? orderByMethod + "Descending" : orderByMethod;

                                if (entityType.GetProperty(propertyName) != null)
                                {
                                    // sorting a entity property
                                    var memberExpression          = Expression.Property(paramExpression, propertyName);
                                    LambdaExpression sortSelector = Expression.Lambda(memberExpression, paramExpression);
                                    queryResultExpression = Expression.Call(typeof(Queryable), methodName, new Type[] { queryResult.ElementType, sortSelector.ReturnType }, queryResultExpression, sortSelector);
                                }
                                else
                                {
                                    // sorting on an attribute

                                    // get attribute id
                                    int?attributeId = null;
                                    foreach (var id in AttributeCache.GetByEntity(entityTypeCache.Id).SelectMany(a => a.AttributeIds))
                                    {
                                        var attribute = AttributeCache.Get(id);
                                        if (attribute.Key == propertyName)
                                        {
                                            attributeId = id;
                                            break;
                                        }
                                    }

                                    if (attributeId.HasValue)
                                    {
                                        // get AttributeValue queryable and parameter
                                        if (dbContext is RockContext)
                                        {
                                            var attributeValues = new AttributeValueService(dbContext as RockContext).Queryable();
                                            ParameterExpression attributeValueParameter = Expression.Parameter(typeof(AttributeValue), "v");
                                            MemberExpression    idExpression            = Expression.Property(paramExpression, "Id");
                                            var attributeExpression = Attribute.Helper.GetAttributeValueExpression(attributeValues, attributeValueParameter, idExpression, attributeId.Value);

                                            LambdaExpression sortSelector = Expression.Lambda(attributeExpression, paramExpression);
                                            queryResultExpression = Expression.Call(typeof(Queryable), methodName, new Type[] { queryResult.ElementType, sortSelector.ReturnType }, queryResultExpression, sortSelector);
                                        }
                                        else
                                        {
                                            throw new Exception(string.Format("The database context for type {0} does not support RockContext attribute value queries.", entityTypeCache.FriendlyName));
                                        }
                                    }
                                }

                                orderByMethod = "ThenBy";
                            }
                        }

                        // check to ensure we had some form of filter (otherwise we'll return all results in the table)
                        if (!hasFilter)
                        {
                            throw new Exception("Your Lava command must contain at least one valid filter. If you configured a filter it's possible that the property or attribute you provided does not exist.");
                        }

                        // reassemble the queryable with the sort expressions
                        queryResult = queryResult.Provider.CreateQuery(queryResultExpression) as IQueryable <IEntity>;

                        if (parms.GetValueOrNull("count").AsBoolean())
                        {
                            int countResult = queryResult.Count();
                            context.Scopes.Last()["count"] = countResult;
                        }
                        else
                        {
                            // Run security check on each result if enabled and entity is not a person (we do not check security on people)
                            if (parms["securityenabled"].AsBoolean() && _entityName != "person")
                            {
                                var items        = queryResult.ToList();
                                var itemsSecured = new List <IEntity>();

                                Person person = GetCurrentPerson(context);

                                foreach (IEntity item in items)
                                {
                                    ISecured itemSecured = item as ISecured;
                                    if (itemSecured == null || itemSecured.IsAuthorized(Authorization.VIEW, person))
                                    {
                                        itemsSecured.Add(item);
                                    }
                                }

                                queryResult = itemsSecured.AsQueryable();
                            }

                            // offset
                            if (parms.Any(p => p.Key == "offset"))
                            {
                                queryResult = queryResult.Skip(parms["offset"].AsInteger());
                            }

                            // limit, default to 1000
                            if (parms.Any(p => p.Key == "limit"))
                            {
                                queryResult = queryResult.Take(parms["limit"].AsInteger());
                            }
                            else
                            {
                                queryResult = queryResult.Take(1000);
                            }

                            var resultList = queryResult.ToList();

                            // if there is only one item to return set an alternative non-array based variable
                            if (resultList.Count == 1)
                            {
                                context.Scopes.Last()[_entityName] = resultList.FirstOrDefault();
                            }

                            context.Scopes.Last()[parms["iterator"]] = resultList;
                        }
                    }
                }
            }
            else
            {
                result.Write(string.Format("Could not find a model for {0}.", _entityName));
                base.Render(context, result);
            }

            base.Render(context, result);
        }