示例#1
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)
        {
            using (new UnitOfWorkScope())
            {
                RockTransactionScope.WrapTransaction(() =>
                {
                    var attributeService           = new AttributeService();
                    Rock.Model.Attribute attribute = null;

                    // remove old qualifier values in case they changed
                    if (edtAttribute.AttributeId.HasValue)
                    {
                        AttributeQualifierService attributeQualifierService = new AttributeQualifierService();
                        foreach (var oldQualifier in attributeQualifierService.GetByAttributeId(edtAttribute.AttributeId.Value).ToList())
                        {
                            attributeQualifierService.Delete(oldQualifier, CurrentPersonId);
                            attributeQualifierService.Save(oldQualifier, CurrentPersonId);
                        }
                        attribute = attributeService.Get(edtAttribute.AttributeId.Value);
                    }

                    if (attribute == null)
                    {
                        attribute = new Rock.Model.Attribute();
                        attributeService.Add(attribute, CurrentPersonId);
                    }

                    if (_configuredType)
                    {
                        attribute.EntityTypeId = _entityTypeId;
                        attribute.EntityTypeQualifierColumn = _entityQualifierColumn;
                        attribute.EntityTypeQualifierValue  = _entityQualifierValue;
                    }
                    else
                    {
                        attribute.EntityTypeId = ddlAttrEntityType.SelectedValueAsInt();
                        attribute.EntityTypeQualifierColumn = tbAttrQualifierField.Text;
                        attribute.EntityTypeQualifierValue  = tbAttrQualifierValue.Text;
                    }

                    edtAttribute.GetAttributeProperties(attribute);

                    // Controls will show warnings
                    if (!attribute.IsValid)
                    {
                        return;
                    }

                    Rock.Web.Cache.AttributeCache.Flush(attribute.Id);
                    attributeService.Save(attribute, CurrentPersonId);
                });
            }

            BindGrid();

            pnlDetails.Visible = false;
            pnlList.Visible    = true;
        }
        /// <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)
        {
            Group group;
            bool  wasSecurityRole = false;

            using (new UnitOfWorkScope())
            {
                GroupService     groupService     = new GroupService();
                AttributeService attributeService = new AttributeService();

                int groupId = int.Parse(hfGroupId.Value);

                if (groupId == 0)
                {
                    group          = new Group();
                    group.IsSystem = false;
                    group.Name     = string.Empty;
                }
                else
                {
                    group           = groupService.Get(groupId);
                    wasSecurityRole = group.IsSecurityRole;
                }

                if ((ddlGroupType.SelectedValueAsInt() ?? 0) == 0)
                {
                    ddlGroupType.ShowErrorMessage(Rock.Constants.WarningMessage.CannotBeBlank(GroupType.FriendlyTypeName));
                    return;
                }

                group.Name           = tbName.Text;
                group.Description    = tbDescription.Text;
                group.CampusId       = ddlCampus.SelectedValue.Equals(None.IdValue) ? (int?)null : int.Parse(ddlCampus.SelectedValue);
                group.GroupTypeId    = int.Parse(ddlGroupType.SelectedValue);
                group.ParentGroupId  = gpParentGroup.SelectedValue.Equals(None.IdValue) ? (int?)null : int.Parse(gpParentGroup.SelectedValue);
                group.IsSecurityRole = cbIsSecurityRole.Checked;
                group.IsActive       = cbIsActive.Checked;

                if (group.ParentGroupId == group.Id)
                {
                    gpParentGroup.ShowErrorMessage("Group cannot be a Parent Group of itself.");
                    return;
                }

                group.LoadAttributes();

                Rock.Attribute.Helper.GetEditValues(phGroupAttributes, group);

                if (!Page.IsValid)
                {
                    return;
                }

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

                RockTransactionScope.WrapTransaction(() =>
                {
                    if (group.Id.Equals(0))
                    {
                        groupService.Add(group, CurrentPersonId);
                    }

                    groupService.Save(group, CurrentPersonId);
                    Rock.Attribute.Helper.SaveAttributeValues(group, CurrentPersonId);

                    /* Take care of Group Member Attributes */

                    // delete GroupMemberAttributes that are no longer configured in the UI
                    string qualifierValue        = group.Id.ToString();
                    var groupMemberAttributesQry = attributeService.GetByEntityTypeId(new GroupMember().TypeId).AsQueryable()
                                                   .Where(a => a.EntityTypeQualifierColumn.Equals("GroupId", StringComparison.OrdinalIgnoreCase) &&
                                                          a.EntityTypeQualifierValue.Equals(qualifierValue));

                    var deletedGroupMemberAttributes = from attr in groupMemberAttributesQry
                                                       where !(from d in GroupMemberAttributesState
                                                               select d.Guid).Contains(attr.Guid)
                                                       select attr;

                    deletedGroupMemberAttributes.ToList().ForEach(a =>
                    {
                        var attr = attributeService.Get(a.Guid);
                        Rock.Web.Cache.AttributeCache.Flush(attr.Id);
                        attributeService.Delete(attr, CurrentPersonId);
                        attributeService.Save(attr, CurrentPersonId);
                    });

                    // add/update the GroupMemberAttributes that are assigned in the UI
                    foreach (var attributeState in GroupMemberAttributesState)
                    {
                        // remove old qualifiers in case they changed
                        var qualifierService = new AttributeQualifierService();
                        foreach (var oldQualifier in qualifierService.GetByAttributeId(attributeState.Id).ToList())
                        {
                            qualifierService.Delete(oldQualifier, CurrentPersonId);
                            qualifierService.Save(oldQualifier, CurrentPersonId);
                        }

                        Attribute attribute = groupMemberAttributesQry.FirstOrDefault(a => a.Guid.Equals(attributeState.Guid));
                        if (attribute == null)
                        {
                            attribute = attributeState.Clone() as Rock.Model.Attribute;
                            attributeService.Add(attribute, CurrentPersonId);
                        }
                        else
                        {
                            attributeState.Id = attribute.Id;
                            attribute.FromDictionary(attributeState.ToDictionary());

                            foreach (var qualifier in attributeState.AttributeQualifiers)
                            {
                                attribute.AttributeQualifiers.Add(qualifier.Clone() as AttributeQualifier);
                            }
                        }

                        attribute.EntityTypeQualifierColumn = "GroupId";
                        attribute.EntityTypeQualifierValue  = group.Id.ToString();
                        attribute.EntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(GroupMember)).Id;
                        Rock.Web.Cache.AttributeCache.Flush(attribute.Id);
                        attributeService.Save(attribute, CurrentPersonId);
                    }
                });
            }

            if (group != null && wasSecurityRole)
            {
                if (!group.IsSecurityRole)
                {
                    // if this group was a SecurityRole, but no longer is, flush
                    Rock.Security.Role.Flush(group.Id);
                    Rock.Security.Authorization.Flush();
                }
            }
            else
            {
                if (group.IsSecurityRole)
                {
                    // new security role, flush
                    Rock.Security.Authorization.Flush();
                }
            }

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

            qryParams["groupId"] = group.Id.ToString();

            NavigateToPage(this.CurrentPage.Guid, qryParams);
        }
示例#3
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)
        {
            using (new UnitOfWorkScope())
            {
                BinaryFileType        binaryFileType;
                BinaryFileTypeService binaryFileTypeService = new BinaryFileTypeService();
                AttributeService      attributeService      = new AttributeService();

                int binaryFileTypeId = int.Parse(hfBinaryFileTypeId.Value);

                if (binaryFileTypeId == 0)
                {
                    binaryFileType = new BinaryFileType();
                    binaryFileTypeService.Add(binaryFileType, CurrentPersonId);
                }
                else
                {
                    binaryFileType = binaryFileTypeService.Get(binaryFileTypeId);
                }

                binaryFileType.Name            = tbName.Text;
                binaryFileType.Description     = tbDescription.Text;
                binaryFileType.IconCssClass    = tbIconCssClass.Text;
                binaryFileType.IconSmallFileId = imgIconSmall.ImageId;
                binaryFileType.IconLargeFileId = imgIconLarge.ImageId;

                if (!string.IsNullOrWhiteSpace(cpStorageType.SelectedValue))
                {
                    var entityTypeService = new EntityTypeService();
                    var storageEntityType = entityTypeService.Get(new Guid(cpStorageType.SelectedValue));

                    if (storageEntityType != null)
                    {
                        binaryFileType.StorageEntityTypeId = storageEntityType.Id;
                    }
                }

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

                RockTransactionScope.WrapTransaction(() =>
                {
                    binaryFileTypeService.Save(binaryFileType, CurrentPersonId);

                    // get it back to make sure we have a good Id for it for the Attributes
                    binaryFileType = binaryFileTypeService.Get(binaryFileType.Guid);

                    /* Take care of Binary File Attributes */

                    // delete BinaryFileAttributes that are no longer configured in the UI
                    string qualifierValue       = binaryFileType.Id.ToString();
                    var BinaryFileAttributesQry = attributeService.GetByEntityTypeId(new BinaryFile().TypeId).AsQueryable()
                                                  .Where(a => a.EntityTypeQualifierColumn.Equals("BinaryFileTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                         a.EntityTypeQualifierValue.Equals(qualifierValue));

                    var deletedBinaryFileAttributes = from attr in BinaryFileAttributesQry
                                                      where !(from d in BinaryFileAttributesState
                                                              select d.Guid).Contains(attr.Guid)
                                                      select attr;

                    deletedBinaryFileAttributes.ToList().ForEach(a =>
                    {
                        var attr = attributeService.Get(a.Guid);
                        Rock.Web.Cache.AttributeCache.Flush(attr.Id);
                        attributeService.Delete(attr, CurrentPersonId);
                        attributeService.Save(attr, CurrentPersonId);
                    });

                    // add/update the BinaryFileAttributes that are assigned in the UI
                    foreach (var attributeState in BinaryFileAttributesState)
                    {
                        // remove old qualifiers in case they changed
                        var qualifierService = new AttributeQualifierService();
                        foreach (var oldQualifier in qualifierService.GetByAttributeId(attributeState.Id).ToList())
                        {
                            qualifierService.Delete(oldQualifier, CurrentPersonId);
                            qualifierService.Save(oldQualifier, CurrentPersonId);
                        }

                        Attribute attribute = BinaryFileAttributesQry.FirstOrDefault(a => a.Guid.Equals(attributeState.Guid));
                        if (attribute == null)
                        {
                            attribute = attributeState.Clone() as Rock.Model.Attribute;
                            attributeService.Add(attribute, CurrentPersonId);
                        }
                        else
                        {
                            attributeState.Id = attribute.Id;
                            attribute.FromDictionary(attributeState.ToDictionary());

                            foreach (var qualifier in attributeState.AttributeQualifiers)
                            {
                                attribute.AttributeQualifiers.Add(qualifier.Clone() as AttributeQualifier);
                            }
                        }

                        attribute.EntityTypeQualifierColumn = "BinaryFileTypeId";
                        attribute.EntityTypeQualifierValue  = binaryFileType.Id.ToString();
                        attribute.EntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(BinaryFile)).Id;
                        Rock.Web.Cache.AttributeCache.Flush(attribute.Id);
                        attributeService.Save(attribute, CurrentPersonId);
                    }
                });
            }

            NavigateToParentPage();
        }
示例#4
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)
        {
            using (new UnitOfWorkScope())
            {
                GroupType        groupType;
                GroupTypeService groupTypeService = new GroupTypeService();
                AttributeService attributeService = new AttributeService();

                int groupTypeId = int.Parse(hfGroupTypeId.Value);

                if (groupTypeId == 0)
                {
                    groupType = new GroupType();
                    groupTypeService.Add(groupType, CurrentPersonId);
                }
                else
                {
                    groupType = groupTypeService.Get(groupTypeId);
                }

                groupType.Name = tbName.Text;

                groupType.Description             = tbDescription.Text;
                groupType.GroupTerm               = tbGroupTerm.Text;
                groupType.GroupMemberTerm         = tbGroupMemberTerm.Text;
                groupType.DefaultGroupRoleId      = ddlDefaultGroupRole.SelectedValueAsInt();
                groupType.ShowInGroupList         = cbShowInGroupList.Checked;
                groupType.ShowInNavigation        = cbShowInNavigation.Checked;
                groupType.IconCssClass            = tbIconCssClass.Text;
                groupType.IconSmallFileId         = imgIconSmall.BinaryFileId;
                groupType.IconLargeFileId         = imgIconLarge.BinaryFileId;
                groupType.TakesAttendance         = cbTakesAttendance.Checked;
                groupType.AttendanceRule          = ddlAttendanceRule.SelectedValueAsEnum <AttendanceRule>();
                groupType.AttendancePrintTo       = ddlAttendancePrintTo.SelectedValueAsEnum <PrintTo>();
                groupType.LocationSelectionMode   = ddlLocationSelectionMode.SelectedValueAsEnum <LocationPickerMode>();
                groupType.GroupTypePurposeValueId = ddlGroupTypePurpose.SelectedValueAsInt();
                groupType.AllowMultipleLocations  = cbAllowMultipleLocations.Checked;
                groupType.InheritedGroupTypeId    = gtpInheritedGroupType.SelectedGroupTypeId;

                groupType.ChildGroupTypes = new List <GroupType>();
                groupType.ChildGroupTypes.Clear();
                foreach (var item in ChildGroupTypesDictionary)
                {
                    var childGroupType = groupTypeService.Get(item.Key);
                    if (childGroupType != null)
                    {
                        groupType.ChildGroupTypes.Add(childGroupType);
                    }
                }

                DefinedValueService definedValueService = new DefinedValueService();

                groupType.LocationTypes = new List <GroupTypeLocationType>();
                groupType.LocationTypes.Clear();
                foreach (var item in LocationTypesDictionary)
                {
                    var locationType = definedValueService.Get(item.Key);
                    if (locationType != null)
                    {
                        groupType.LocationTypes.Add(new GroupTypeLocationType {
                            LocationTypeValueId = locationType.Id
                        });
                    }
                }

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

                RockTransactionScope.WrapTransaction(() =>
                {
                    groupTypeService.Save(groupType, CurrentPersonId);

                    // get it back to make sure we have a good Id for it for the Attributes
                    groupType = groupTypeService.Get(groupType.Guid);

                    /* Take care of Group Type Attributes */

                    // delete GroupTypeAttributes that are no longer configured in the UI
                    var groupTypeAttributesQry = attributeService.Get(new GroupType().TypeId, "Id", groupType.Id.ToString());
                    var selectedAttributes     = GroupTypeAttributesState.Select(a => a.Guid);
                    foreach (var attr in groupTypeAttributesQry.Where(a => !selectedAttributes.Contains(a.Guid)))
                    {
                        Rock.Web.Cache.AttributeCache.Flush(attr.Id);
                        attributeService.Delete(attr, CurrentPersonId);
                        attributeService.Save(attr, CurrentPersonId);
                    }

                    string qualifierValue = groupType.Id.ToString();

                    // add/update the GroupTypeAttributes that are assigned in the UI
                    foreach (var attributeState in GroupTypeAttributesState
                             .Where(a =>
                                    a.EntityTypeQualifierValue == null ||
                                    a.EntityTypeQualifierValue.Trim() == string.Empty ||
                                    a.EntityTypeQualifierValue.Equals(qualifierValue)))
                    {
                        // remove old qualifiers in case they changed
                        var qualifierService = new AttributeQualifierService();
                        foreach (var oldQualifier in qualifierService.GetByAttributeId(attributeState.Id).ToList())
                        {
                            qualifierService.Delete(oldQualifier, CurrentPersonId);
                            qualifierService.Save(oldQualifier, CurrentPersonId);
                        }

                        Attribute attribute = groupTypeAttributesQry.FirstOrDefault(a => a.Guid.Equals(attributeState.Guid));
                        if (attribute == null)
                        {
                            attribute = attributeState.Clone() as Rock.Model.Attribute;
                            attributeService.Add(attribute, CurrentPersonId);
                        }
                        else
                        {
                            attributeState.Id = attribute.Id;
                            attribute.FromDictionary(attributeState.ToDictionary());

                            foreach (var qualifier in attributeState.AttributeQualifiers)
                            {
                                attribute.AttributeQualifiers.Add(qualifier.Clone() as AttributeQualifier);
                            }
                        }

                        attribute.EntityTypeQualifierColumn = "Id";
                        attribute.EntityTypeQualifierValue  = qualifierValue;
                        attribute.EntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(GroupType)).Id;
                        Rock.Web.Cache.AttributeCache.Flush(attribute.Id);
                        attributeService.Save(attribute, CurrentPersonId);
                    }

                    /* Take care of Group Attributes */

                    // delete GroupAttributes that are no longer configured in the UI
                    var groupAttributesQry = attributeService.Get(new Group().TypeId, "GroupTypeId", groupType.Id.ToString());
                    selectedAttributes     = GroupAttributesState.Select(a => a.Guid);
                    foreach (var attr in groupAttributesQry.Where(a => !selectedAttributes.Contains(a.Guid)))
                    {
                        Rock.Web.Cache.AttributeCache.Flush(attr.Id);
                        attributeService.Delete(attr, CurrentPersonId);
                        attributeService.Save(attr, CurrentPersonId);
                    }

                    // add/update the GroupAttributes that are assigned in the UI
                    foreach (var attributeState in GroupAttributesState
                             .Where(a =>
                                    a.EntityTypeQualifierValue == null ||
                                    a.EntityTypeQualifierValue.Trim() == string.Empty ||
                                    a.EntityTypeQualifierValue.Equals(qualifierValue)))
                    {
                        // remove old qualifiers in case they changed
                        var qualifierService = new AttributeQualifierService();
                        foreach (var oldQualifier in qualifierService.GetByAttributeId(attributeState.Id).ToList())
                        {
                            qualifierService.Delete(oldQualifier, CurrentPersonId);
                            qualifierService.Save(oldQualifier, CurrentPersonId);
                        }

                        Attribute attribute = groupAttributesQry.FirstOrDefault(a => a.Guid.Equals(attributeState.Guid));
                        if (attribute == null)
                        {
                            attribute = attributeState.Clone() as Rock.Model.Attribute;
                            attributeService.Add(attribute, CurrentPersonId);
                        }
                        else
                        {
                            attributeState.Id = attribute.Id;
                            attribute.FromDictionary(attributeState.ToDictionary());

                            foreach (var qualifier in attributeState.AttributeQualifiers)
                            {
                                attribute.AttributeQualifiers.Add(qualifier.Clone() as AttributeQualifier);
                            }
                        }

                        attribute.EntityTypeQualifierColumn = "GroupTypeId";
                        attribute.EntityTypeQualifierValue  = qualifierValue;
                        attribute.EntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(Group)).Id;
                        Rock.Web.Cache.AttributeCache.Flush(attribute.Id);
                        attributeService.Save(attribute, CurrentPersonId);
                    }
                });
            }
            NavigateToParentPage();
        }
示例#5
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)
        {
            using (new UnitOfWorkScope())
            {
                var attributeService          = new AttributeService();
                var attributeQualifierService = new AttributeQualifierService();

                Rock.Model.Attribute attribute;

                int attributeId = 0;
                if (hfId.Value != string.Empty && !int.TryParse(hfId.Value, out attributeId))
                {
                    attributeId = 0;
                }

                if (attributeId == 0)
                {
                    attribute              = new Rock.Model.Attribute();
                    attribute.IsSystem     = false;
                    attribute.EntityTypeId = _entityTypeId;
                    attribute.EntityTypeQualifierColumn = _entityQualifierColumn;
                    attribute.EntityTypeQualifierValue  = _entityQualifierValue;
                    attributeService.Add(attribute, CurrentPersonId);
                }
                else
                {
                    AttributeCache.Flush(attributeId);
                    attribute = attributeService.Get(attributeId);
                }

                attribute.Key         = tbKey.Text;
                attribute.Name        = tbName.Text;
                attribute.Category    = tbCategory.Text;
                attribute.Description = tbDescription.Text;
                attribute.FieldTypeId = int.Parse(ddlFieldType.SelectedValue);

                var fieldType = FieldTypeCache.Read(attribute.FieldTypeId);

                foreach (var oldQualifier in attribute.AttributeQualifiers.ToList())
                {
                    attributeQualifierService.Delete(oldQualifier, CurrentPersonId);
                }

                attribute.AttributeQualifiers.Clear();

                List <Control> configControls = new List <Control>();
                foreach (var key in fieldType.Field.ConfigurationKeys())
                {
                    configControls.Add(phFieldTypeQualifiers.FindControl("configControl_" + key));
                }

                foreach (var configValue in fieldType.Field.ConfigurationValues(configControls))
                {
                    AttributeQualifier qualifier = new AttributeQualifier();
                    qualifier.IsSystem = false;
                    qualifier.Key      = configValue.Key;
                    qualifier.Value    = configValue.Value.Value ?? string.Empty;
                    attribute.AttributeQualifiers.Add(qualifier);
                }

                attribute.DefaultValue = tbDefaultValue.Text;
                attribute.IsMultiValue = cbMultiValue.Checked;
                attribute.IsRequired   = cbRequired.Checked;

                attributeService.Save(attribute, CurrentPersonId);
            }

            BindGrid();

            pnlDetails.Visible = false;
            pnlList.Visible    = true;
        }
示例#6
0
        /// <summary>
        /// Saves any attribute edits made to an attribute
        /// </summary>
        /// <param name="newAttribute">The new attribute.</param>
        /// <param name="entityTypeId">The entity type identifier.</param>
        /// <param name="entityTypeQualifierColumn">The entity type qualifier column.</param>
        /// <param name="entityTypeQualifierValue">The entity type qualifier value.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        /// <remarks>
        /// If a rockContext value is included, this method will save any previous changes made to the context
        /// </remarks>
        public static Rock.Model.Attribute SaveAttributeEdits(Rock.Model.Attribute newAttribute, int?entityTypeId, string entityTypeQualifierColumn, string entityTypeQualifierValue, RockContext rockContext = null)
        {
            rockContext = rockContext ?? new RockContext();

            var internalAttributeService  = new AttributeService(rockContext);
            var attributeQualifierService = new AttributeQualifierService(rockContext);
            var categoryService           = new CategoryService(rockContext);

            // If attribute is not valid, return null
            if (!newAttribute.IsValid)
            {
                return(null);
            }

            // Create a attribute model that will be saved
            Rock.Model.Attribute attribute = null;

            // Check to see if this was an existing or new attribute
            if (newAttribute.Id > 0)
            {
                // If editing an existing attribute, remove all the old qualifiers in case they were changed
                foreach (var oldQualifier in attributeQualifierService.GetByAttributeId(newAttribute.Id).ToList())
                {
                    attributeQualifierService.Delete(oldQualifier);
                }
                rockContext.SaveChanges();

                // Then re-load the existing attribute
                attribute = internalAttributeService.Get(newAttribute.Id);
            }

            if (attribute == null)
            {
                // If the attribute didn't exist, create it
                attribute = new Rock.Model.Attribute();
                internalAttributeService.Add(attribute);
            }
            else
            {
                // If it did exist, set the new attribute ID and GUID since we're copying all properties in the next step
                newAttribute.Id   = attribute.Id;
                newAttribute.Guid = attribute.Guid;
            }

            // Copy all the properties from the new attribute to the attribute model
            attribute.CopyPropertiesFrom(newAttribute);

            // Add any qualifiers
            foreach (var qualifier in newAttribute.AttributeQualifiers)
            {
                attribute.AttributeQualifiers.Add(new AttributeQualifier {
                    Key = qualifier.Key, Value = qualifier.Value, IsSystem = qualifier.IsSystem
                });
            }

            // Add any categories
            attribute.Categories.Clear();
            foreach (var category in newAttribute.Categories)
            {
                attribute.Categories.Add(categoryService.Get(category.Id));
            }

            attribute.EntityTypeId = entityTypeId;
            attribute.EntityTypeQualifierColumn = entityTypeQualifierColumn;
            attribute.EntityTypeQualifierValue  = entityTypeQualifierValue;

            rockContext.SaveChanges();

            if (attribute != null)
            {
                Rock.Web.Cache.AttributeCache.Flush(attribute.Id);

                // If this is a global attribute, flush all global attributes
                if (!entityTypeId.HasValue && entityTypeQualifierColumn == string.Empty && entityTypeQualifierValue == string.Empty)
                {
                    Rock.Web.Cache.GlobalAttributesCache.Flush();
                }
            }

            return(attribute);
        }
示例#7
0
        /// <summary>
        /// Adds or Updates a <see cref="Rock.Model.Attribute" /> item for the attribute.
        /// </summary>
        /// <param name="property">The property.</param>
        /// <param name="entityTypeId">The entity type id.</param>
        /// <param name="entityQualifierColumn">The entity qualifier column.</param>
        /// <param name="entityQualifierValue">The entity qualifier value.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        /// <remarks>
        /// If a rockContext value is included, this method will save any previous changes made to the context
        /// </remarks>
        private static bool UpdateAttribute(FieldAttribute property, int?entityTypeId, string entityQualifierColumn, string entityQualifierValue, RockContext rockContext = null)
        {
            bool updated = false;

            rockContext = rockContext ?? new RockContext();

            var attributeService          = new AttributeService(rockContext);
            var attributeQualifierService = new AttributeQualifierService(rockContext);
            var fieldTypeService          = new FieldTypeService(rockContext);
            var categoryService           = new CategoryService(rockContext);

            var propertyCategories = property.Category.SplitDelimitedValues(false).ToList();

            // Look for an existing attribute record based on the entity, entityQualifierColumn and entityQualifierValue
            Model.Attribute attribute = attributeService.Get(entityTypeId, entityQualifierColumn, entityQualifierValue, property.Key);
            if (attribute == null)
            {
                // If an existing attribute record doesn't exist, create a new one
                updated = true;

                attribute = new Model.Attribute();
                attribute.EntityTypeId = entityTypeId;
                attribute.EntityTypeQualifierColumn = entityQualifierColumn;
                attribute.EntityTypeQualifierValue  = entityQualifierValue;
                attribute.Key          = property.Key;
                attribute.IconCssClass = string.Empty;
                attribute.IsGridColumn = false;
            }
            else
            {
                // Check to see if the existing attribute record needs to be updated
                if (attribute.Name != property.Name ||
                    attribute.DefaultValue != property.DefaultValue ||
                    attribute.Description != property.Description ||
                    attribute.Order != property.Order ||
                    attribute.FieldType.Assembly != property.FieldTypeAssembly ||
                    attribute.FieldType.Class != property.FieldTypeClass ||
                    attribute.IsRequired != property.IsRequired)
                {
                    updated = true;
                }

                // Check category
                else if (attribute.Categories.Select(c => c.Name).Except(propertyCategories).Any() ||
                         propertyCategories.Except(attribute.Categories.Select(c => c.Name)).Any())
                {
                    updated = true;
                }

                // Check the qualifier values
                else if (attribute.AttributeQualifiers.Select(q => q.Key).Except(property.FieldConfigurationValues.Select(c => c.Key)).Any() ||
                         property.FieldConfigurationValues.Select(c => c.Key).Except(attribute.AttributeQualifiers.Select(q => q.Key)).Any())
                {
                    updated = true;
                }
                else
                {
                    foreach (var attributeQualifier in attribute.AttributeQualifiers)
                    {
                        if (!property.FieldConfigurationValues.ContainsKey(attributeQualifier.Key) ||
                            property.FieldConfigurationValues[attributeQualifier.Key].Value != attributeQualifier.Value)
                        {
                            updated = true;
                            break;
                        }
                    }
                }
            }

            if (updated)
            {
                // Update the attribute
                attribute.Name         = property.Name;
                attribute.Description  = property.Description;
                attribute.DefaultValue = property.DefaultValue;
                attribute.Order        = property.Order;
                attribute.IsRequired   = property.IsRequired;

                attribute.Categories.Clear();
                if (propertyCategories.Any())
                {
                    foreach (string propertyCategory in propertyCategories)
                    {
                        int attributeEntityTypeId = EntityTypeCache.Read(typeof(Rock.Model.Attribute)).Id;
                        var category = categoryService.Get(propertyCategory, attributeEntityTypeId, "EntityTypeId", entityTypeId.ToString()).FirstOrDefault();
                        if (category == null)
                        {
                            category              = new Category();
                            category.Name         = propertyCategory;
                            category.EntityTypeId = attributeEntityTypeId;
                            category.EntityTypeQualifierColumn = "EntityTypeId";
                            category.EntityTypeQualifierValue  = entityTypeId.ToString();
                            category.Order = 0;
                        }
                        attribute.Categories.Add(category);
                    }
                }

                foreach (var qualifier in attribute.AttributeQualifiers.ToList())
                {
                    attributeQualifierService.Delete(qualifier);
                }
                attribute.AttributeQualifiers.Clear();

                foreach (var configValue in property.FieldConfigurationValues)
                {
                    var qualifier = new Model.AttributeQualifier();
                    qualifier.Key   = configValue.Key;
                    qualifier.Value = configValue.Value.Value;
                    attribute.AttributeQualifiers.Add(qualifier);
                }

                // Try to set the field type by searching for an existing field type with the same assembly and class name
                if (attribute.FieldType == null || attribute.FieldType.Assembly != property.FieldTypeAssembly ||
                    attribute.FieldType.Class != property.FieldTypeClass)
                {
                    attribute.FieldType = fieldTypeService.Queryable().FirstOrDefault(f =>
                                                                                      f.Assembly == property.FieldTypeAssembly &&
                                                                                      f.Class == property.FieldTypeClass);
                }

                // If this is a new attribute, add it, otherwise remove the exiting one from the cache
                if (attribute.Id == 0)
                {
                    attributeService.Add(attribute);
                }
                else
                {
                    AttributeCache.Flush(attribute.Id);
                }

                rockContext.SaveChanges();

                return(true);
            }
            else
            {
                return(false);
            }
        }
示例#8
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)
        {
            using (new UnitOfWorkScope())
            {
                MarketingCampaignAdType        marketingCampaignAdType;
                MarketingCampaignAdTypeService marketingCampaignAdTypeService = new MarketingCampaignAdTypeService();

                int marketingCampaignAdTypeId = int.Parse(hfMarketingCampaignAdTypeId.Value);

                if (marketingCampaignAdTypeId == 0)
                {
                    marketingCampaignAdType = new MarketingCampaignAdType();
                    marketingCampaignAdTypeService.Add(marketingCampaignAdType, CurrentPersonId);
                }
                else
                {
                    marketingCampaignAdType = marketingCampaignAdTypeService.Get(marketingCampaignAdTypeId);
                }

                marketingCampaignAdType.Name          = tbName.Text;
                marketingCampaignAdType.DateRangeType = (DateRangeTypeEnum)int.Parse(ddlDateRangeType.SelectedValue);

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

                RockTransactionScope.WrapTransaction(() =>
                {
                    marketingCampaignAdTypeService.Save(marketingCampaignAdType, CurrentPersonId);

                    // get it back to make sure we have a good Id for it for the Attributes
                    marketingCampaignAdType = marketingCampaignAdTypeService.Get(marketingCampaignAdType.Guid);

                    // delete AdTypeAttributes that are no longer configured in the UI
                    AttributeService attributeService = new AttributeService();
                    string qualifierValue             = marketingCampaignAdType.Id.ToString();
                    int typeId = new MarketingCampaignAd().TypeId;
                    var qry    = attributeService.GetByEntityTypeId(typeId).AsQueryable()
                                 .Where(a => a.EntityTypeQualifierColumn == "MarketingCampaignAdTypeId" &&
                                        a.EntityTypeQualifierValue.Equals(qualifierValue));

                    var deletedAttributes = from attr in qry.ToList()
                                            where !(from d in AttributesState
                                                    select d.Guid).Contains(attr.Guid)
                                            select attr;

                    deletedAttributes.ToList().ForEach(a =>
                    {
                        var attr = attributeService.Get(a.Guid);
                        if (attr != null)
                        {
                            Rock.Web.Cache.AttributeCache.Flush(attr.Id);
                            attributeService.Delete(attr, CurrentPersonId);
                            attributeService.Save(attr, CurrentPersonId);
                        }
                    });

                    // add/update the AdTypes that are assigned in the UI
                    foreach (var attributeState in AttributesState)
                    {
                        // remove old qualifiers in case they changed
                        var qualifierService = new AttributeQualifierService();
                        foreach (var oldQualifier in qualifierService.GetByAttributeId(attributeState.Id).ToList())
                        {
                            qualifierService.Delete(oldQualifier, CurrentPersonId);
                            qualifierService.Save(oldQualifier, CurrentPersonId);
                        }

                        Attribute attribute = qry.FirstOrDefault(a => a.Guid.Equals(attributeState.Guid));
                        if (attribute == null)
                        {
                            attribute = attributeState.Clone() as Rock.Model.Attribute;
                            attributeService.Add(attribute, CurrentPersonId);
                        }
                        else
                        {
                            attributeState.Id = attribute.Id;
                            attribute.FromDictionary(attributeState.ToDictionary());

                            foreach (var qualifier in attributeState.AttributeQualifiers)
                            {
                                attribute.AttributeQualifiers.Add(qualifier.Clone() as AttributeQualifier);
                            }
                        }

                        attribute.EntityTypeQualifierColumn = "MarketingCampaignAdTypeId";
                        attribute.EntityTypeQualifierValue  = marketingCampaignAdType.Id.ToString();
                        attribute.EntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(MarketingCampaignAd)).Id;
                        Rock.Web.Cache.AttributeCache.Flush(attribute.Id);
                        attributeService.Save(attribute, CurrentPersonId);
                    }
                });
            }
            NavigateToParentPage();
        }