Example #1
0
        /// <summary>
        /// Handles the Delete event of the rGrid control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void rGrid_Delete(object sender, RowEventArgs e)
        {
            var rockContext      = new RockContext();
            var attributeService = new AttributeService(rockContext);

            var attribute = attributeService.Get(e.RowKeyId);

            if (attribute != null)
            {
                if ((!_entityTypeId.HasValue || _entityTypeId.Value == 0) &&
                    _entityQualifierColumn == string.Empty &&
                    _entityQualifierValue == string.Empty &&
                    (!_entityId.HasValue || _entityId.Value == 0)
                    )
                {
                    GlobalAttributesCache.Remove();
                }

                attributeService.Delete(attribute);

                rockContext.SaveChanges();
            }

            BindGrid();
        }
Example #2
0
        /// <summary>
        /// Handles the Delete event of the gDefinedTypeAttributes control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gDefinedTypeAttributes_Delete(object sender, RowEventArgs e)
        {
            Guid             attributeGuid    = (Guid)e.RowKeyValue;
            var              rockContext      = new RockContext();
            AttributeService attributeService = new AttributeService(rockContext);
            Attribute        attribute        = attributeService.Get(attributeGuid);

            if (attribute != null)
            {
                string errorMessage;
                if (!attributeService.CanDelete(attribute, out errorMessage))
                {
                    mdGridWarningAttributes.Show(errorMessage, ModalAlertType.Information);
                    return;
                }

                AttributeCache.Flush(attribute.Id);
                attributeService.Delete(attribute);
                rockContext.SaveChanges();
            }

            AttributeCache.FlushEntityAttributes();

            BindDefinedTypeAttributesGrid();
        }
Example #3
0
        /// <summary>
        /// Saves the attributes.
        /// </summary>
        /// <param name="channelId">The channel identifier.</param>
        /// <param name="entityTypeId">The entity type identifier.</param>
        /// <param name="attributes">The attributes.</param>
        /// <param name="rockContext">The rock context.</param>
        private void SaveAttributes(int channelId, int entityTypeId, List <Attribute> attributes, RockContext rockContext)
        {
            string qualifierColumn = "ContentChannelId";
            string qualifierValue  = channelId.ToString();

            AttributeService attributeService = new AttributeService(rockContext);

            // Get the existing attributes for this entity type and qualifier value
            var existingAttributes = attributeService.GetByEntityTypeQualifier(entityTypeId, qualifierColumn, qualifierValue, true);

            // Delete any of those attributes that were removed in the UI
            var selectedAttributeGuids = attributes.Select(a => a.Guid);

            foreach (var attr in existingAttributes.Where(a => !selectedAttributeGuids.Contains(a.Guid)))
            {
                attributeService.Delete(attr);
            }

            rockContext.SaveChanges();

            int newOrder = 1000;

            // Update the Attributes that were assigned in the UI
            foreach (var attr in attributes.OrderBy(a => a.Order))
            {
                // Artificially exaggerate the order so that all channel specific attributes are displayed after the content-type specific attributes (unless categorized)
                attr.Order = newOrder++;
                Rock.Attribute.Helper.SaveAttributeEdits(attr, entityTypeId, qualifierColumn, qualifierValue, rockContext);
            }
        }
Example #4
0
        /// <summary>
        /// Handles the Delete event of the gWorkflowTypeAttributes control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gWorkflowTypeAttributes_Delete(object sender, RowEventArgs e)
        {
            Guid             attributeGuid    = (Guid)e.RowKeyValue;
            AttributeService attributeService = new AttributeService();
            Attribute        attribute        = attributeService.Get(attributeGuid);

            if (attribute != null)
            {
                string errorMessage;
                if (!attributeService.CanDelete(attribute, out errorMessage))
                {
                    mdGridWarningAttributes.Show(errorMessage, ModalAlertType.Information);
                    return;
                }

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

            // reload page so that other blocks respond to any data that was changed
            var qryParams = new Dictionary <string, string>();

            qryParams["workflowTypeId"] = hfWorkflowTypeId.Value;
            NavigateToPage(this.CurrentPage.Guid, qryParams);
        }
Example #5
0
        /// <summary>
        /// Saves the attributes.
        /// </summary>
        /// <param name="contentTypeId">The content type identifier.</param>
        /// <param name="entityTypeId">The entity type identifier.</param>
        /// <param name="attributes">The attributes.</param>
        /// <param name="rockContext">The rock context.</param>
        private void SaveAttributes(int contentTypeId, int entityTypeId, List <Attribute> attributes, RockContext rockContext)
        {
            string qualifierColumn = "ContentChannelTypeId";
            string qualifierValue  = contentTypeId.ToString();

            AttributeService attributeService = new AttributeService(rockContext);

            // Get the existing attributes for this entity type and qualifier value
            var existingAttributes = attributeService.Get(entityTypeId, qualifierColumn, qualifierValue);

            // Delete any of those attributes that were removed in the UI
            var selectedAttributeGuids = attributes.Select(a => a.Guid);

            foreach (var attr in existingAttributes.Where(a => !selectedAttributeGuids.Contains(a.Guid)))
            {
                Rock.Web.Cache.AttributeCache.Flush(attr.Id);
                attributeService.Delete(attr);
            }

            rockContext.SaveChanges();

            // Update the Attributes that were assigned in the UI
            foreach (var attr in attributes)
            {
                Rock.Attribute.Helper.SaveAttributeEdits(attr, entityTypeId, qualifierColumn, qualifierValue, rockContext);
            }
        }
Example #6
0
        public BlockActionResult DeleteAttribute(Guid attributeGuid)
        {
            using (var rockContext = new RockContext())
            {
                var attributeService = new AttributeService(rockContext);
                var attribute        = attributeService.Get(attributeGuid);

                if (attribute == null)
                {
                    return(ActionBadRequest("Attribute not found."));
                }

                if (attribute.IsSystem)
                {
                    return(ActionBadRequest("System attributes cannot be deleted."));
                }

                if (!attribute.EntityTypeId.HasValue && attribute.EntityTypeQualifierColumn == string.Empty && attribute.EntityTypeQualifierValue == string.Empty && !GetEntityId().HasValue)
                {
                    GlobalAttributesCache.Remove();
                }

                attributeService.Delete(attribute);
                rockContext.SaveChanges();

                return(ActionOk());
            }
        }
 public void DeleteAttribute(int id)
 {
     using (ServiceDB serviceDB = new ServiceDB())
     {
         IUnitOfWork       uow     = new UnitOfWork(serviceDB);
         IAttributeService service = new AttributeService(uow);
         service.Delete(id);
     }
 }
Example #8
0
        /// <summary>
        /// Handles the Delete event of the rGridAttribute control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void rGridAttribute_Delete(object sender, RowEventArgs e)
        {
            var attributeService = new AttributeService();

            Rock.Model.Attribute attribute = attributeService.Get((int)rGridAttribute.DataKeys[e.RowIndex]["id"]);
            if (attribute != null)
            {
                attributeService.Delete(attribute, CurrentPersonId);
                attributeService.Save(attribute, CurrentPersonId);
            }

            rGridAttribute_Bind(hfIdType.Value);
        }
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <exception cref="System.NotImplementedException"></exception>

        public void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            int howMany        = dataMap.GetString("HowMany").AsIntegerOrNull() ?? 500000;
            var commandTimeout = dataMap.GetString("CommandTimeout").AsIntegerOrNull() ?? 3600;

            bool anyRemaining = UpdateSearchValueRecords(context, howMany, commandTimeout);

            if (!anyRemaining)
            {
                // Verify that there are not any history records that haven't been migrated
                using (var rockContext = new RockContext())
                {
                    rockContext.Database.CommandTimeout = commandTimeout;

                    var  attributeService = new AttributeService(rockContext);
                    var  attribute        = attributeService.Get("8F528431-A438-4488-8DC3-CA42E66C1B37".AsGuid());
                    bool valuesExist      = attribute != null;
                    if (valuesExist)
                    {
                        valuesExist = new AttributeValueService(rockContext)
                                      .Queryable().AsNoTracking()
                                      .Where(a => a.AttributeId == attribute.Id)
                                      .Any();
                    }

                    if (!valuesExist)
                    {
                        // Delete the attribute
                        if (attribute != null)
                        {
                            attributeService.Delete(attribute);
                        }

                        // delete job if there are no un-migrated history rows  left
                        var jobId      = context.GetJobId();
                        var jobService = new ServiceJobService(rockContext);
                        var job        = jobService.Get(jobId);
                        if (job != null)
                        {
                            jobService.Delete(job);
                            rockContext.SaveChanges();
                            return;
                        }
                    }
                }
            }
        }
Example #10
0
        /// <summary>
        /// Handes the Delete filters event.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
        protected void gFilters_Delete(object sender, RowEventArgs e)
        {
            var rockContext      = new RockContext();
            var attributeService = new AttributeService(rockContext);

            var attribute = attributeService.Get(e.RowKeyId);

            if (attribute != null)
            {
                attributeService.Delete(attribute);

                rockContext.SaveChanges();
            }

            BindGrid();
            LoadFilters();
        }
Example #11
0
        /// <summary>
        /// Saves the attributes.
        /// </summary>
        /// <param name="entityTypeId">The entity type identifier.</param>
        /// <param name="qualifierColumn">The qualifier column.</param>
        /// <param name="qualifierValue">The qualifier value.</param>
        /// <param name="viewStateAttributes">The view state attributes.</param>
        /// <param name="rockContext">The rock context.</param>
        private void SaveAttributes(int entityTypeId, string qualifierColumn, string qualifierValue, List <Attribute> viewStateAttributes, RockContext rockContext)
        {
            // Get the existing attributes for this entity type and qualifier value
            var attributeService = new AttributeService(rockContext);
            var attributes       = attributeService.GetByEntityTypeQualifier(entityTypeId, qualifierColumn, qualifierValue, true);

            // Delete any of those attributes that were removed in the UI
            var selectedAttributeGuids = viewStateAttributes.Select(a => a.Guid);

            foreach (var attr in attributes.Where(a => !selectedAttributeGuids.Contains(a.Guid)))
            {
                attributeService.Delete(attr);
                rockContext.SaveChanges();
            }

            // Update the Attributes that were assigned in the UI
            foreach (var attributeState in viewStateAttributes)
            {
                Helper.SaveAttributeEdits(attributeState, entityTypeId, qualifierColumn, qualifierValue, rockContext);
            }
        }
        /// <summary>
        /// Handles the Delete event of the gDefinedTypeAttributes control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gDefinedTypeAttributes_Delete(object sender, RowEventArgs e)
        {
            Guid             attributeGuid    = (Guid)e.RowKeyValue;
            AttributeService attributeService = new AttributeService();
            Attribute        attribute        = attributeService.Get(attributeGuid);

            if (attribute != null)
            {
                string errorMessage;
                if (!attributeService.CanDelete(attribute, out errorMessage))
                {
                    mdGridWarningAttributes.Show(errorMessage, ModalAlertType.Information);
                    return;
                }

                AttributeCache.Flush(attribute.Id);
                attributeService.Delete(attribute, CurrentPersonId);
                attributeService.Save(attribute, CurrentPersonId);
            }

            BindDefinedTypeAttributesGrid();
        }
Example #13
0
        /// <summary>
        /// Handles the DeleteClick event of the gBlockTypeAttributes control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs"/> instance containing the event data.</param>
        protected void gBlockTypeAttributes_DeleteClick(object sender, Rock.Web.UI.Controls.RowEventArgs e)
        {
            Guid             attributeGuid    = (Guid)e.RowKeyValue;
            var              rockContext      = new RockContext();
            AttributeService attributeService = new AttributeService(rockContext);
            Attribute        attribute        = attributeService.Get(attributeGuid);

            if (attribute != null)
            {
                string errorMessage;
                if (!attributeService.CanDelete(attribute, out errorMessage))
                {
                    mdGridWarningAttributes.Show(errorMessage, ModalAlertType.Information);
                    return;
                }

                attributeService.Delete(attribute);
                rockContext.SaveChanges();
            }

            BindBlockTypeAttributesGrid();
        }
        /// <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)
        {
            BinaryFileType binaryFileType;

            var rockContext = new RockContext();
            BinaryFileTypeService     binaryFileTypeService     = new BinaryFileTypeService(rockContext);
            AttributeService          attributeService          = new AttributeService(rockContext);
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext);
            CategoryService           categoryService           = new CategoryService(rockContext);

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

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

            binaryFileType.Name                       = tbName.Text;
            binaryFileType.Description                = tbDescription.Text;
            binaryFileType.IconCssClass               = tbIconCssClass.Text;
            binaryFileType.CacheToServerFileSystem    = cbCacheToServerFileSystem.Checked;
            binaryFileType.CacheControlHeaderSettings = cpCacheSettings.CurrentCacheablity.ToJson();
            binaryFileType.RequiresViewSecurity       = cbRequiresViewSecurity.Checked;
            binaryFileType.MaxWidth                   = nbMaxWidth.Text.AsInteger();
            binaryFileType.MaxHeight                  = nbMaxHeight.Text.AsInteger();
            binaryFileType.PreferredFormat            = ddlPreferredFormat.SelectedValueAsEnum <Format>();
            binaryFileType.PreferredResolution        = ddlPreferredResolution.SelectedValueAsEnum <Resolution>();
            binaryFileType.PreferredColorDepth        = ddlPreferredColorDepth.SelectedValueAsEnum <ColorDepth>();
            binaryFileType.PreferredRequired          = cbPreferredRequired.Checked;

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

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

            binaryFileType.LoadAttributes(rockContext);
            Rock.Attribute.Helper.GetEditValues(phAttributes, binaryFileType);

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

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

                // 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 */
                var entityTypeId = EntityTypeCache.Get(typeof(BinaryFile)).Id;

                // delete BinaryFileAttributes that are no longer configured in the UI
                var attributes             = attributeService.GetByEntityTypeQualifier(entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString(), true);
                var selectedAttributeGuids = BinaryFileAttributesState.Select(a => a.Guid);
                foreach (var attr in attributes.Where(a => !selectedAttributeGuids.Contains(a.Guid)))
                {
                    attributeService.Delete(attr);
                }

                rockContext.SaveChanges();

                // add/update the BinaryFileAttributes that are assigned in the UI
                foreach (var attributeState in BinaryFileAttributesState)
                {
                    Rock.Attribute.Helper.SaveAttributeEdits(attributeState, entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString(), rockContext);
                }

                // SaveAttributeValues for the BinaryFileType
                binaryFileType.SaveAttributeValues(rockContext);
            });

            NavigateToParentPage();
        }
        /// <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)
        {
            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);

            // check for duplicates
            if (marketingCampaignAdTypeService.Queryable().Count(a => a.Name.Equals(marketingCampaignAdType.Name, StringComparison.OrdinalIgnoreCase) && !a.Id.Equals(marketingCampaignAdType.Id)) > 0)
            {
                tbName.ShowErrorMessage(WarningMessage.DuplicateFoundMessage("name", MarketingCampaignAdType.FriendlyTypeName));
                return;
            }

            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();
                var qry = attributeService.GetByEntityTypeId(new MarketingCampaignAd().TypeId).AsQueryable()
                          .Where(a => a.EntityTypeQualifierColumn.Equals("MarketingCampaignAdTypeId", StringComparison.OrdinalIgnoreCase) &&
                                 a.EntityTypeQualifierValue.Equals(marketingCampaignAdType.Id.ToString()));

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

                deletedAttributes.ToList().ForEach(a =>
                {
                    var attr = attributeService.Get(a.Guid);
                    attributeService.Delete(attr, CurrentPersonId);
                    attributeService.Save(attr, CurrentPersonId);
                });

                // add/update the AdTypes that are assigned in the UI
                foreach (var attributeState in AttributesState)
                {
                    Attribute attribute = qry.FirstOrDefault(a => a.Guid.Equals(attributeState.Guid));
                    if (attribute == null)
                    {
                        attribute = attributeState.ToModel();
                        attributeService.Add(attribute, CurrentPersonId);
                    }
                    else
                    {
                        attributeState.Id = attribute.Id;
                        attributeState.CopyToModel(attribute);
                    }

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

            BindGrid();
            pnlDetails.Visible = false;
            pnlList.Visible    = true;
        }
Example #16
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)
        {
            AttributeMatrixTemplate attributeMatrixTemplate;
            var rockContext = new RockContext();
            var attributeMatrixTemplateService = new AttributeMatrixTemplateService(rockContext);

            int attributeMatrixTemplateId = int.Parse(hfAttributeMatrixTemplateId.Value);

            if (attributeMatrixTemplateId == 0)
            {
                attributeMatrixTemplate = new AttributeMatrixTemplate();
                attributeMatrixTemplateService.Add(attributeMatrixTemplate);
            }
            else
            {
                attributeMatrixTemplate = attributeMatrixTemplateService.Get(attributeMatrixTemplateId);
            }

            attributeMatrixTemplate.Name          = tbName.Text;
            attributeMatrixTemplate.IsActive      = cbIsActive.Checked;
            attributeMatrixTemplate.Description   = tbDescription.Text;
            attributeMatrixTemplate.MinimumRows   = tbMinimumRows.Text.AsIntegerOrNull();
            attributeMatrixTemplate.MaximumRows   = tbMaximumRows.Text.AsIntegerOrNull();
            attributeMatrixTemplate.FormattedLava = ceFormattedLava.Text;

            // need WrapTransaction due to Attribute saves
            rockContext.WrapTransaction(() =>
            {
                rockContext.SaveChanges();

                /* Save Attributes */

                var entityTypeIdAttributeMatrix = EntityTypeCache.GetId <AttributeMatrixItem>();

                // Get the existing attributes for this entity type and qualifier value
                var attributeService = new AttributeService(rockContext);
                var regFieldService  = new RegistrationTemplateFormFieldService(rockContext);
                var attributes       = attributeService.Get(entityTypeIdAttributeMatrix, "AttributeMatrixTemplateId", attributeMatrixTemplate.Id.ToString());

                // Delete any of those attributes that were removed in the UI
                var selectedAttributeGuids = AttributesState.Select(a => a.Guid);
                foreach (var attr in attributes.Where(a => !selectedAttributeGuids.Contains(a.Guid)))
                {
                    foreach (var field in regFieldService.Queryable().Where(f => f.AttributeId.HasValue && f.AttributeId.Value == attr.Id).ToList())
                    {
                        regFieldService.Delete(field);
                    }

                    attributeService.Delete(attr);
                    rockContext.SaveChanges();
                    Rock.Web.Cache.AttributeCache.Flush(attr.Id);
                }

                // Update the Attributes that were assigned in the UI
                foreach (var attributeState in AttributesState)
                {
                    Helper.SaveAttributeEdits(attributeState, entityTypeIdAttributeMatrix, "AttributeMatrixTemplateId", attributeMatrixTemplate.Id.ToString(), rockContext);
                }

                Rock.Web.Cache.AttributeCache.FlushEntityAttributes();
            });

            NavigateToParentPage();
        }
Example #17
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();
        }
Example #18
0
        /// <summary>
        /// Handles logic for updating all the form sections as well as attributes.
        /// This will create any new items and delete any removed items as well.
        /// </summary>
        /// <param name="formSettings">The form settings that contain all the configuration information.</param>
        /// <param name="actionForm">The <see cref="WorkflowActionForm"/> entity being updated.</param>
        /// <param name="workflowType">The <see cref="WorkflowType"/> that is being updated.</param>
        /// <param name="rockContext">The database context to operate in.</param>
        private static void UpdateFormSections(FormSettingsViewModel formSettings, WorkflowActionForm actionForm, WorkflowType workflowType, RockContext rockContext)
        {
            var attributeService     = new AttributeService(rockContext);
            var formAttributeService = new WorkflowActionFormAttributeService(rockContext);
            var formSectionService   = new WorkflowActionFormSectionService(rockContext);

            var nextAttributeOrder = actionForm.FormAttributes != null && actionForm.FormAttributes.Any()
                ? actionForm.FormAttributes.Select(a => a.Order).Max() + 1
                : 0;

            if (formSettings.Sections != null)
            {
                // Get all the section identifiers that are sticking around.
                var allValidSectionGuids = formSettings.Sections
                                           .Select(s => s.Guid)
                                           .ToList();

                // Get all the attribute identifiers that are sticking around.
                var allValidAttributeGuids = formSettings.Sections
                                             .SelectMany(s => s.Fields)
                                             .Select(f => f.Guid)
                                             .ToList();

                // Find all sections that no longer exist in this form.
                var sectionsToDelete = actionForm.FormSections
                                       .Where(s => !allValidSectionGuids.Contains(s.Guid))
                                       .ToList();

                // Find all form attributes that no longer exist in this form.
                var formAttributesToDelete = actionForm.FormAttributes
                                             .Where(a => !allValidAttributeGuids.Contains(a.Attribute.Guid))
                                             .ToList();

                var allFormFields = formSettings.Sections.SelectMany(s => s.Fields).ToList();

                // Delete all sections that no longer exist in this form.
                sectionsToDelete.ForEach(s =>
                {
                    formSectionService.Delete(s);
                });

                // Delete all form attributes that no longer exist in this form.
                formAttributesToDelete.ForEach(a =>
                {
                    if (a.Attribute.IsSystem)
                    {
                        attributeService.Delete(a.Attribute);
                    }
                    formAttributeService.Delete(a);
                });

                // Loop through all sections that need to be either added or updated.
                for (int sectionOrder = 0; sectionOrder < formSettings.Sections.Count; sectionOrder++)
                {
                    var section = formSettings.Sections[sectionOrder];

                    var formSection = AddOrUpdateFormSection(actionForm, workflowType, attributeService, formAttributeService, formSectionService, section, allFormFields, ref nextAttributeOrder);
                    formSection.Order = sectionOrder;
                }
            }
            else
            {
                // Remove all form attributes and sections.
                var nonUserAttributes = actionForm.FormAttributes
                                        .Select(a => a.Attribute)
                                        .Where(a => a.IsSystem)
                                        .ToList();

                attributeService.DeleteRange(nonUserAttributes);
                formAttributeService.DeleteRange(actionForm.FormAttributes);
                formSectionService.DeleteRange(actionForm.FormSections);
            }
        }
Example #19
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();
        }
        /// <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(() =>
                {
                    AttributeService attributeService = new AttributeService();
                    AttributeQualifierService attributeQualifierService = new AttributeQualifierService();
                    CategoryService categoryService = new CategoryService();

                    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);

                    var entityTypeId       = EntityTypeCache.Read(typeof(MarketingCampaignAd)).Id;
                    string qualifierColumn = "MarketingCampaignAdTypeId";
                    string qualifierValue  = marketingCampaignAdType.Id.ToString();

                    // Get the existing attributes for this entity type and qualifier value
                    var attributes = attributeService.Get(entityTypeId, qualifierColumn, qualifierValue);

                    // Delete any of those attributes that were removed in the UI
                    var selectedAttributeGuids = AttributesState.Select(a => a.Guid);
                    foreach (var attr in attributes.Where(a => !selectedAttributeGuids.Contains(a.Guid)))
                    {
                        Rock.Web.Cache.AttributeCache.Flush(attr.Id);

                        attributeService.Delete(attr, CurrentPersonId);
                        attributeService.Save(attr, CurrentPersonId);
                    }

                    // Update the Attributes that were assigned in the UI
                    foreach (var attributeState in AttributesState)
                    {
                        Rock.Attribute.Helper.SaveAttributeEdits(attributeState, attributeService, attributeQualifierService, categoryService,
                                                                 entityTypeId, qualifierColumn, qualifierValue, CurrentPersonId);
                    }
                });
            }

            NavigateToParentPage();
        }
Example #21
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            RockContext rockContext = new RockContext();

            rockContext.WrapTransaction(() =>
            {
                WidgityTypeService widgityTypeService = new WidgityTypeService(rockContext);
                AttributeService attributeService     = new AttributeService(rockContext);
                WidgityType widgityType = GetWidgityType(widgityTypeService);

                if (widgityType.Id == 0)
                {
                    widgityTypeService.Add(widgityType);
                }

                widgityType.Name                = tbName.Text;
                widgityType.Description         = tbDescription.Text;
                widgityType.EnabledLavaCommands = lcCommands.SelectedValue;
                widgityType.Icon                = tbIcon.Text;
                widgityType.Markdown            = ceMarkup.Text;
                widgityType.HasItems            = cbHasItems.Checked;
                var _ = widgityType.EntityTypes.ToList(); //Attach the entity types to context
                widgityType.EntityTypes = new EntityTypeService(rockContext).GetByIds(lbEntityTypes.SelectedValuesAsInt).ToList();
                widgityType.CategoryId  = pCategory.SelectedValueAsId();
                rockContext.SaveChanges();

                //Widgity Attributes
                var widgityEntityTypeId = EntityTypeCache.Get(typeof(Widgity)).Id;

                var actualAttributes = attributeService.Queryable()
                                       .Where(a => a.EntityTypeId == widgityEntityTypeId && a.EntityTypeQualifierValue == widgityType.Id.ToString())
                                       .OrderBy(a => a.Order)
                                       .ToList();

                //Remove deleted attributes
                foreach (var attribute in actualAttributes)
                {
                    if (!WidgityAttributes.Where(a => a.Guid == attribute.Guid).Any())
                    {
                        attributeService.Delete(attribute);
                    }
                }

                //Update db from viewstate
                foreach (var attribute in WidgityAttributes)
                {
                    if (attribute.Id == 0)
                    {
                        attribute.Order = WidgityAttributes.IndexOf(attribute);
                        attribute.EntityTypeQualifierValue = widgityType.Id.ToString();
                        attributeService.Add(attribute);
                    }
                    else
                    {
                        var trackedAttribute = actualAttributes.Where(a => a.Guid == attribute.Guid).FirstOrDefault();
                        trackedAttribute.CopyPropertiesFrom(attribute);
                        foreach (var qualifier in trackedAttribute.AttributeQualifiers)
                        {
                            var value = attribute.AttributeQualifiers.Where(q => q.Key == qualifier.Key).FirstOrDefault();
                            if (value != null)
                            {
                                qualifier.Value = value.Value;
                            }
                        }
                        trackedAttribute.Order = WidgityAttributes.IndexOf(attribute);
                    }
                }
                rockContext.SaveChanges();


                //Widgity Item Attributes
                var widgityItemEntityTypeId = EntityTypeCache.Get(typeof(WidgityItem)).Id;

                var actualItemAttributes = attributeService.Queryable()
                                           .Where(a => a.EntityTypeId == widgityItemEntityTypeId && a.EntityTypeQualifierValue == widgityType.Id.ToString())
                                           .OrderBy(a => a.Order)
                                           .ToList();

                //Remove deleted attributes
                foreach (var attribute in actualItemAttributes)
                {
                    if (!WidgityItemAttributes.Where(a => a.Guid == attribute.Guid).Any())
                    {
                        attributeService.Delete(attribute);
                    }
                }

                //Update db from viewstate
                foreach (var attribute in WidgityItemAttributes)
                {
                    if (attribute.Id == 0)
                    {
                        attribute.Order = WidgityItemAttributes.IndexOf(attribute);
                        attribute.EntityTypeQualifierValue = widgityType.Id.ToString();
                        attributeService.Add(attribute);
                    }
                    else
                    {
                        var trackedAttribute = actualItemAttributes.Where(a => a.Guid == attribute.Guid).FirstOrDefault();
                        trackedAttribute.CopyPropertiesFrom(attribute);
                        foreach (var qualifier in trackedAttribute.AttributeQualifiers)
                        {
                            var value = attribute.AttributeQualifiers.Where(q => q.Key == qualifier.Key).FirstOrDefault();
                            if (value != null)
                            {
                                qualifier.Value = value.Value;
                            }
                        }
                        trackedAttribute.Order = WidgityItemAttributes.IndexOf(attribute);
                    }
                }
                rockContext.SaveChanges();
            });
            WidgityTypeCache.Clear();
            WidgityCache.Clear();
            WidgityItemCache.Clear();
            NavigateToParentPage();
        }
Example #22
0
        /// <summary>
        /// Adds test data for Events that can be used to test inherited attributes.
        /// </summary>
        private static void InitializeInheritedAttributesTestData()
        {
            var rockContext = new RockContext();

            var EventCalendarPublicId   = EventCalendarCache.All().First(x => x.Name == "Public").Id;
            var EventCalendarInternalId = EventCalendarCache.All().First(x => x.Name == "Internal").Id;

            // Add Attributes for Calendars.
            // EventItem Attributes are defined per Calendar, so they are directly associated with the EventCalendarItem entity.
            // The Attributes collection for the EventItem shows the collection of attributes inherited from the EventCalendarItems associated with the event.
            var attributeService = new AttributeService(rockContext);
            var textFieldTypeId  = FieldTypeCache.GetId(SystemGuid.FieldType.TEXT.AsGuid()).GetValueOrDefault();

            // Add Attribute A for Internal Calendar.
            var attributeAInternal = attributeService.Get(InternalCalendarAttribute1Guid.AsGuid());

            if (attributeAInternal != null)
            {
                attributeService.Delete(attributeAInternal);
                rockContext.SaveChanges();
            }
            attributeAInternal = new Rock.Model.Attribute();
            attributeAInternal.EntityTypeId = EntityTypeCache.GetId(typeof(EventCalendarItem));
            attributeAInternal.EntityTypeQualifierColumn = "EventCalendarId";
            attributeAInternal.EntityTypeQualifierValue  = EventCalendarInternalId.ToString();
            attributeAInternal.Name        = InternalCalendarAttribute1Key;
            attributeAInternal.Key         = InternalCalendarAttribute1Key;
            attributeAInternal.Guid        = InternalCalendarAttribute1Guid.AsGuid();
            attributeAInternal.FieldTypeId = textFieldTypeId;

            attributeService.Add(attributeAInternal);
            rockContext.SaveChanges();

            // Add Attribute A for Public Calendar.
            var attributeAPublic = attributeService.Get(PublicCalendarAttribute1Guid.AsGuid());

            if (attributeAPublic != null)
            {
                attributeService.Delete(attributeAPublic);
                rockContext.SaveChanges();
            }
            attributeAPublic = new Rock.Model.Attribute();
            attributeAPublic.EntityTypeId = EntityTypeCache.GetId(typeof(EventCalendarItem));
            attributeAPublic.EntityTypeQualifierColumn = "EventCalendarId";
            attributeAPublic.EntityTypeQualifierValue  = EventCalendarPublicId.ToString();
            attributeAPublic.Name        = PublicCalendarAttribute1Key;
            attributeAPublic.Key         = PublicCalendarAttribute1Key;
            attributeAPublic.Guid        = PublicCalendarAttribute1Guid.AsGuid();
            attributeAPublic.FieldTypeId = textFieldTypeId;

            attributeService.Add(attributeAPublic);
            rockContext.SaveChanges();

            // Create a new Event: "Event A".
            // This event exists in the Internal and Public calendars.
            var eventItemService = new EventItemService(rockContext);

            var eventA = eventItemService.Get(EventAGuid.AsGuid());

            if (eventA != null)
            {
                eventItemService.Delete(eventA);
                rockContext.SaveChanges();
            }
            eventA      = new EventItem();
            eventA.Name = "Event A";
            eventA.Guid = EventAGuid.AsGuid();
            var eventACalendarInternal = new EventCalendarItem {
                EventCalendarId = EventCalendarInternalId, Guid = EventACalendarInternalGuid.AsGuid()
            };
            var eventACalendarPublic = new EventCalendarItem {
                EventCalendarId = EventCalendarPublicId, Guid = EventACalendarPublicGuid.AsGuid()
            };

            eventA.EventCalendarItems.Add(eventACalendarInternal);
            eventA.EventCalendarItems.Add(eventACalendarPublic);

            eventItemService.Add(eventA);

            rockContext.SaveChanges();

            // Create a new Event: "Event B".
            // This event exists in the Internal calendar only.
            // This event is created manually, to set the ID of Event B to match an Event Calendar Item associated with Event A.
            // The purpose is to create an EventItem and an EventCalendarItem that have an identical ID,
            // so we can verify that Attribute values for parent and child entities are correctly differentiated
            // by Entity Type when they are collated for inherited attributes.
            var eventB = eventItemService.Get(EventBGuid.AsGuid());

            if (eventB != null)
            {
                eventItemService.Delete(eventB);
                rockContext.SaveChanges();
            }

            var matchedID = eventACalendarInternal.Id;

            var sql = @"
SET IDENTITY_INSERT [EventItem] ON
;
INSERT INTO [EventItem] (Id, Name, Guid, IsActive)
VALUES (@p0, @p1, @p2, 1)
;
SET IDENTITY_INSERT [EventItem] OFF
;
";

            rockContext.Database.ExecuteSqlCommand(sql, matchedID, "Event B", EventBGuid.AsGuid());

            eventB = eventItemService.Get(EventBGuid.AsGuid());
            var eventBCalendarInternal = new EventCalendarItem {
                EventCalendarId = EventCalendarInternalId, Guid = EventBCalendarInternalGuid.AsGuid()
            };
            var eventBCalendarPublic = new EventCalendarItem {
                EventCalendarId = EventCalendarPublicId, Guid = EventBCalendarPublicGuid.AsGuid()
            };

            eventB.EventCalendarItems.Add(eventBCalendarInternal);
            eventB.EventCalendarItems.Add(eventBCalendarPublic);

            rockContext.SaveChanges();

            // Set Attribute Values.
            rockContext = new RockContext();
            AttributeCache.Clear();

            // Set Attribute Values for Event B.
            eventBCalendarPublic.LoadAttributes(rockContext);
            eventBCalendarPublic.SetAttributeValue(PublicCalendarAttribute1Key, "Event B Public");
            eventBCalendarPublic.SaveAttributeValues(rockContext);

            rockContext.SaveChanges();

            // Set Attribute Values for Event A
            eventACalendarInternal.LoadAttributes(rockContext);
            eventACalendarInternal.SetAttributeValue(InternalCalendarAttribute1Key, "Event A Internal");
            eventACalendarInternal.SaveAttributeValues(rockContext);

            eventACalendarPublic.LoadAttributes(rockContext);
            eventACalendarPublic.SetAttributeValue(PublicCalendarAttribute1Key, "Event A Public");
            eventACalendarPublic.SaveAttributeValues(rockContext);

            rockContext.SaveChanges();
        }
 public IHttpActionResult Delete(int id)
 {
     AttributeService.Delete(id);
     return(Ok());
 }
        /// <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)
        {
            BinaryFileType binaryFileType;

            var rockContext = new RockContext();
            BinaryFileTypeService     binaryFileTypeService     = new BinaryFileTypeService(rockContext);
            AttributeService          attributeService          = new AttributeService(rockContext);
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext);
            CategoryService           categoryService           = new CategoryService(rockContext);

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

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

            binaryFileType.Name             = tbName.Text;
            binaryFileType.Description      = tbDescription.Text;
            binaryFileType.IconCssClass     = tbIconCssClass.Text;
            binaryFileType.AllowCaching     = cbAllowCaching.Checked;
            binaryFileType.RequiresSecurity = cbRequiresSecurity.Checked;

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

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

            binaryFileType.LoadAttributes(rockContext);
            Rock.Attribute.Helper.GetEditValues(phAttributes, binaryFileType);

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

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

                // 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 */
                var entityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(BinaryFile)).Id;

                // delete BinaryFileAttributes that are no longer configured in the UI
                var attributes             = attributeService.Get(entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString());
                var selectedAttributeGuids = BinaryFileAttributesState.Select(a => a.Guid);
                foreach (var attr in attributes.Where(a => !selectedAttributeGuids.Contains(a.Guid)))
                {
                    Rock.Web.Cache.AttributeCache.Flush(attr.Id);
                    attributeService.Delete(attr);
                }
                rockContext.SaveChanges();

                // add/update the BinaryFileAttributes that are assigned in the UI
                foreach (var attributeState in BinaryFileAttributesState)
                {
                    Rock.Attribute.Helper.SaveAttributeEdits(attributeState, entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString(), rockContext);
                }

                // SaveAttributeValues for the BinaryFileType
                binaryFileType.SaveAttributeValues(rockContext);
            });


            NavigateToParentPage();
        }
        /// <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)
        {
            bool hasValidationErrors = false;

            var rockContext = new RockContext();

            GroupTypeService     groupTypeService     = new GroupTypeService(rockContext);
            GroupService         groupService         = new GroupService(rockContext);
            AttributeService     attributeService     = new AttributeService(rockContext);
            GroupLocationService groupLocationService = new GroupLocationService(rockContext);

            int parentGroupTypeId = hfParentGroupTypeId.ValueAsInt();

            var groupTypeUIList = new List <GroupType>();

            foreach (var checkinGroupTypeEditor in phCheckinGroupTypes.Controls.OfType <CheckinGroupTypeEditor>().ToList())
            {
                var groupType = checkinGroupTypeEditor.GetCheckinGroupType();
                groupTypeUIList.Add(groupType);
            }

            var groupTypeDBList = new List <GroupType>();

            var groupTypesToDelete = new List <GroupType>();
            var groupsToDelete     = new List <Group>();

            var groupTypesToAddUpdate = new List <GroupType>();
            var groupsToAddUpdate     = new List <Group>();

            GroupType parentGroupTypeDB = groupTypeService.Get(parentGroupTypeId);
            GroupType parentGroupTypeUI = parentGroupTypeDB.Clone(false);

            parentGroupTypeUI.ChildGroupTypes = groupTypeUIList;

            PopulateDeleteLists(groupTypesToDelete, groupsToDelete, parentGroupTypeDB, parentGroupTypeUI);
            PopulateAddUpdateLists(groupTypesToAddUpdate, groupsToAddUpdate, parentGroupTypeUI);

            int binaryFileFieldTypeID = FieldTypeCache.Read(Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid()).Id;
            int binaryFileTypeId      = new BinaryFileTypeService(rockContext).Get(new Guid(Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL)).Id;

            RockTransactionScope.WrapTransaction(() =>
            {
                // delete in reverse order to get deepest child items first
                groupsToDelete.Reverse();
                foreach (var groupToDelete in groupsToDelete)
                {
                    groupService.Delete(groupToDelete);
                }

                // delete in reverse order to get deepest child items first
                groupTypesToDelete.Reverse();
                foreach (var groupTypeToDelete in groupTypesToDelete)
                {
                    groupTypeService.Delete(groupTypeToDelete);
                }

                rockContext.SaveChanges();

                // Add/Update grouptypes and groups that are in the UI
                // Note:  We'll have to save all the groupTypes without changing the DB value of ChildGroupTypes, then come around again and save the ChildGroupTypes
                // since the ChildGroupTypes may not exist in the database yet
                foreach (GroupType groupTypeUI in groupTypesToAddUpdate)
                {
                    GroupType groupTypeDB = groupTypeService.Get(groupTypeUI.Guid);
                    if (groupTypeDB == null)
                    {
                        groupTypeDB      = new GroupType();
                        groupTypeDB.Id   = 0;
                        groupTypeDB.Guid = groupTypeUI.Guid;
                    }

                    groupTypeDB.Name  = groupTypeUI.Name;
                    groupTypeDB.Order = groupTypeUI.Order;
                    groupTypeDB.InheritedGroupTypeId = groupTypeUI.InheritedGroupTypeId;

                    groupTypeDB.Attributes      = groupTypeUI.Attributes;
                    groupTypeDB.AttributeValues = groupTypeUI.AttributeValues;

                    if (groupTypeDB.Id == 0)
                    {
                        groupTypeService.Add(groupTypeDB);
                    }

                    if (!groupTypeDB.IsValid)
                    {
                        hasValidationErrors = true;
                        CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupTypeEditor>().First(a => a.GroupTypeGuid == groupTypeDB.Guid);
                        groupTypeEditor.ForceContentVisible    = true;

                        return;
                    }

                    rockContext.SaveChanges();

                    groupTypeDB.SaveAttributeValues();

                    // get fresh from database to make sure we have Id so we can update the CheckinLabel Attributes
                    groupTypeDB = groupTypeService.Get(groupTypeDB.Guid);

                    // rebuild the CheckinLabel attributes from the UI (brute-force)
                    foreach (var labelAttributeDB in CheckinGroupTypeEditor.GetCheckinLabelAttributes(groupTypeDB))
                    {
                        var attribute = attributeService.Get(labelAttributeDB.Value.Guid);
                        Rock.Web.Cache.AttributeCache.Flush(attribute.Id);
                        attributeService.Delete(attribute);
                    }
                    rockContext.SaveChanges();

                    foreach (var checkinLabelAttributeInfo in GroupTypeCheckinLabelAttributesState[groupTypeUI.Guid])
                    {
                        var attribute = new Rock.Model.Attribute();
                        attribute.AttributeQualifiers.Add(new AttributeQualifier {
                            Key = "binaryFileType", Value = binaryFileTypeId.ToString()
                        });
                        attribute.Guid         = Guid.NewGuid();
                        attribute.FieldTypeId  = binaryFileFieldTypeID;
                        attribute.EntityTypeId = EntityTypeCache.GetId(typeof(GroupType));
                        attribute.EntityTypeQualifierColumn = "Id";
                        attribute.EntityTypeQualifierValue  = groupTypeDB.Id.ToString();
                        attribute.DefaultValue = checkinLabelAttributeInfo.BinaryFileId.ToString();
                        attribute.Key          = checkinLabelAttributeInfo.AttributeKey;
                        attribute.Name         = checkinLabelAttributeInfo.FileName;

                        if (!attribute.IsValid)
                        {
                            hasValidationErrors = true;
                            CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupTypeEditor>().First(a => a.GroupTypeGuid == groupTypeDB.Guid);
                            groupTypeEditor.ForceContentVisible    = true;

                            return;
                        }

                        attributeService.Add(attribute);
                    }
                    rockContext.SaveChanges();
                }

                // Add/Update Groups
                foreach (var groupUI in groupsToAddUpdate)
                {
                    Group groupDB = groupService.Get(groupUI.Guid);
                    if (groupDB == null)
                    {
                        groupDB      = new Group();
                        groupDB.Guid = groupUI.Guid;
                    }

                    groupDB.Name = groupUI.Name;

                    // delete any GroupLocations that were removed in the UI
                    foreach (var groupLocationDB in groupDB.GroupLocations.ToList())
                    {
                        if (!groupUI.GroupLocations.Select(a => a.LocationId).Contains(groupLocationDB.LocationId))
                        {
                            groupLocationService.Delete(groupLocationDB);
                        }
                    }

                    // add any GroupLocations that were added in the UI
                    foreach (var groupLocationUI in groupUI.GroupLocations)
                    {
                        if (!groupDB.GroupLocations.Select(a => a.LocationId).Contains(groupLocationUI.LocationId))
                        {
                            GroupLocation groupLocationDB = new GroupLocation {
                                LocationId = groupLocationUI.LocationId
                            };
                            groupDB.GroupLocations.Add(groupLocationDB);
                        }
                    }

                    groupDB.Order = groupUI.Order;

                    // get GroupTypeId from database in case the groupType is new
                    groupDB.GroupTypeId     = groupTypeService.Get(groupUI.GroupType.Guid).Id;
                    groupDB.Attributes      = groupUI.Attributes;
                    groupDB.AttributeValues = groupUI.AttributeValues;

                    if (groupDB.Id == 0)
                    {
                        groupService.Add(groupDB);
                    }

                    if (!groupDB.IsValid)
                    {
                        hasValidationErrors             = true;
                        hasValidationErrors             = true;
                        CheckinGroupEditor groupEditor  = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupEditor>().First(a => a.GroupGuid == groupDB.Guid);
                        groupEditor.ForceContentVisible = true;

                        return;
                    }

                    rockContext.SaveChanges();

                    groupDB.SaveAttributeValues();
                }

                /* now that we have all the grouptypes saved, now lets go back and save them again with the current UI ChildGroupTypes */

                // save main parentGroupType with current UI ChildGroupTypes
                parentGroupTypeDB.ChildGroupTypes = new List <GroupType>();
                parentGroupTypeDB.ChildGroupTypes.Clear();
                foreach (var childGroupTypeUI in parentGroupTypeUI.ChildGroupTypes)
                {
                    var childGroupTypeDB = groupTypeService.Get(childGroupTypeUI.Guid);
                    parentGroupTypeDB.ChildGroupTypes.Add(childGroupTypeDB);
                }

                rockContext.SaveChanges();

                // loop thru all the other GroupTypes in the UI and save their childgrouptypes
                foreach (var groupTypeUI in groupTypesToAddUpdate)
                {
                    var groupTypeDB             = groupTypeService.Get(groupTypeUI.Guid);
                    groupTypeDB.ChildGroupTypes = new List <GroupType>();
                    groupTypeDB.ChildGroupTypes.Clear();
                    foreach (var childGroupTypeUI in groupTypeUI.ChildGroupTypes)
                    {
                        var childGroupTypeDB = groupTypeService.Get(childGroupTypeUI.Guid);
                        groupTypeDB.ChildGroupTypes.Add(childGroupTypeDB);
                    }
                }

                rockContext.SaveChanges();
            });

            if (!hasValidationErrors)
            {
                NavigateToParentPage();
            }
        }
        /// <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);
        }
Example #27
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();
        }
        /// <summary>
        /// Maps the communication data.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        private void MapCommunication(IQueryable <Row> tableData)
        {
            var lookupContext    = new RockContext();
            var personService    = new PersonService(lookupContext);
            var attributeService = new AttributeService(lookupContext);

            var numberTypeValues = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE), lookupContext).DefinedValues;

            // Look up additional Person attributes (existing)
            var personAttributes = attributeService.GetByEntityTypeId(PersonEntityTypeId).ToList();

            // Remove previously defined Excavator social attributes & categories if they exist
            var oldFacebookAttribute = personAttributes.Where(a => a.Key == "FacebookUsername").FirstOrDefault();

            if (oldFacebookAttribute != null)
            {
                Rock.Web.Cache.AttributeCache.Flush(oldFacebookAttribute.Id);
                attributeService.Delete(oldFacebookAttribute);
                lookupContext.SaveChanges(true);
            }

            var oldTwitterAttribute = personAttributes.Where(a => a.Key == "TwitterUsername").FirstOrDefault();

            if (oldTwitterAttribute != null)
            {
                Rock.Web.Cache.AttributeCache.Flush(oldTwitterAttribute.Id);
                attributeService.Delete(oldTwitterAttribute);
                lookupContext.SaveChanges(true);
            }

            int attributeEntityTypeId = EntityTypeCache.Read("Rock.Model.Attribute").Id;
            var socialMediaCategory   = new CategoryService(lookupContext).GetByEntityTypeId(attributeEntityTypeId)
                                        .Where(c => c.Name == "Social Media" &&
                                               c.EntityTypeQualifierValue == PersonEntityTypeId.ToString() &&
                                               c.IconCssClass == "fa fa-twitter")
                                        .FirstOrDefault();

            if (socialMediaCategory != null)
            {
                lookupContext.Categories.Remove(socialMediaCategory);
                lookupContext.SaveChanges(true);
            }

            // Cached Rock attributes: Facebook, Twitter, Instagram
            var twitterAttribute        = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Twitter"));
            var facebookAttribute       = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Facebook"));
            var instagramAttribute      = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Instagram"));
            var secondaryEmailAttribute = AttributeCache.Read(SecondaryEmailAttributeId);

            var existingNumbers = new PhoneNumberService(lookupContext).Queryable().ToList();

            var newNumberList     = new List <PhoneNumber>();
            var updatedPersonList = new List <Person>();

            int completed  = 0;
            int totalRows  = tableData.Count();
            int percentage = (totalRows - 1) / 100 + 1;

            ReportProgress(0, string.Format("Verifying communication import ({0:N0} found, {1:N0} already exist).", totalRows, existingNumbers.Count()));

            foreach (var row in tableData)
            {
                string value        = row["Communication_Value"] as string;
                int?   individualId = row["Individual_ID"] as int?;
                int?   householdId  = row["Household_ID"] as int?;
                var    personList   = new List <int?>();

                if (individualId != null)
                {
                    int?personId = GetPersonAliasId(individualId, householdId);
                    if (personId != null)
                    {
                        personList.Add(personId);
                    }
                }
                else
                {
                    List <int?> personIds = GetFamilyByHouseholdId(householdId);
                    if (personIds.Any())
                    {
                        personList.AddRange(personIds);
                    }
                }

                if (personList.Any() && !string.IsNullOrWhiteSpace(value))
                {
                    DateTime?lastUpdated          = row["LastUpdatedDate"] as DateTime?;
                    string   communicationComment = row["Communication_Comment"] as string;
                    string   type     = row["Communication_Type"] as string;
                    bool     isListed = (bool)row["Listed"];
                    value = value.RemoveWhitespace();

                    // Communication value is a number
                    if (type.Contains("Phone") || type.Contains("Mobile"))
                    {
                        var extension        = string.Empty;
                        var countryCode      = Rock.Model.PhoneNumber.DefaultCountryCode();
                        var normalizedNumber = string.Empty;
                        var countryIndex     = value.IndexOf('+');
                        int extensionIndex   = value.LastIndexOf('x') > 0 ? value.LastIndexOf('x') : value.Length;
                        if (countryIndex >= 0)
                        {
                            countryCode      = value.Substring(countryIndex, countryIndex + 3).AsNumeric();
                            normalizedNumber = value.Substring(countryIndex + 3, extensionIndex - 3).AsNumeric();
                            extension        = value.Substring(extensionIndex);
                        }
                        else if (extensionIndex > 0)
                        {
                            normalizedNumber = value.Substring(0, extensionIndex).AsNumeric();
                            extension        = value.Substring(extensionIndex).AsNumeric();
                        }
                        else
                        {
                            normalizedNumber = value.AsNumeric();
                        }

                        if (!string.IsNullOrWhiteSpace(normalizedNumber))
                        {
                            foreach (var familyPersonId in personList)
                            {
                                bool numberExists = existingNumbers.Any(n => n.PersonId == familyPersonId && n.Number.Equals(value));
                                if (!numberExists)
                                {
                                    var newNumber = new PhoneNumber();
                                    newNumber.CreatedByPersonAliasId = ImportPersonAlias.Id;
                                    newNumber.ModifiedDateTime       = lastUpdated;
                                    newNumber.PersonId           = (int)familyPersonId;
                                    newNumber.IsMessagingEnabled = false;
                                    newNumber.CountryCode        = countryCode;
                                    newNumber.IsUnlisted         = !isListed;
                                    newNumber.Extension          = extension.Left(20);
                                    newNumber.Number             = normalizedNumber.Left(20);
                                    newNumber.Description        = communicationComment;

                                    newNumber.NumberTypeValueId = numberTypeValues.Where(v => type.StartsWith(v.Value))
                                                                  .Select(v => (int?)v.Id).FirstOrDefault();

                                    newNumberList.Add(newNumber);
                                    existingNumbers.Add(newNumber);
                                }
                            }

                            completed++;
                        }
                    }
                    else
                    {
                        var person = personService.Queryable(includeDeceased: true).FirstOrDefault(p => p.Id == personList.FirstOrDefault());
                        person.Attributes      = new Dictionary <string, AttributeCache>();
                        person.AttributeValues = new Dictionary <string, AttributeValue>();

                        if (value.IsValidEmail())
                        {
                            string secondaryEmail = string.Empty;
                            if (string.IsNullOrWhiteSpace(person.Email))
                            {
                                secondaryEmail          = person.Email;
                                person.Email            = value.Left(75);
                                person.IsEmailActive    = isListed;
                                person.ModifiedDateTime = lastUpdated;
                                person.EmailNote        = communicationComment;
                                lookupContext.SaveChanges(true);
                            }
                            else if (!person.Email.Equals(value))
                            {
                                secondaryEmail = value;
                            }

                            var existingSecondaryEmail = new AttributeValueService(lookupContext).Queryable().Where(av => av.AttributeId == SecondaryEmailAttributeId && av.EntityId == person.Id).FirstOrDefault();

                            if (!string.IsNullOrWhiteSpace(secondaryEmail) && existingSecondaryEmail == null)
                            {
                                person.Attributes.Add(secondaryEmailAttribute.Key, secondaryEmailAttribute);
                                person.AttributeValues.Add(secondaryEmailAttribute.Key, new AttributeValue()
                                {
                                    AttributeId = secondaryEmailAttribute.Id,
                                    Value       = secondaryEmail
                                });
                            }
                        }
                        else if (type.Contains("Twitter"))
                        {
                            person.Attributes.Add(twitterAttribute.Key, twitterAttribute);
                            person.AttributeValues.Add(twitterAttribute.Key, new AttributeValue()
                            {
                                AttributeId = twitterAttribute.Id,
                                Value       = value
                            });
                        }
                        else if (type.Contains("Facebook"))
                        {
                            var existingFacebook = new AttributeValueService(lookupContext).Queryable().Where(av => av.AttributeId == facebookAttribute.Id && av.EntityId == person.Id).FirstOrDefault();
                            if (existingFacebook == null)
                            {
                                person.Attributes.Add(facebookAttribute.Key, facebookAttribute);
                                person.AttributeValues.Add(facebookAttribute.Key, new AttributeValue()
                                {
                                    AttributeId = facebookAttribute.Id,
                                    Value       = value
                                });
                            }
                        }
                        else if (type.Contains("Instagram"))
                        {
                            person.Attributes.Add(instagramAttribute.Key, instagramAttribute);
                            person.AttributeValues.Add(instagramAttribute.Key, new AttributeValue()
                            {
                                AttributeId = instagramAttribute.Id,
                                Value       = value
                            });
                        }

                        updatedPersonList.Add(person);
                        completed++;
                    }

                    if (completed % percentage < 1)
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress(percentComplete, string.Format("{0:N0} records imported ({1}% complete).", completed, percentComplete));
                    }
                    else if (completed % ReportingNumber < 1)
                    {
                        SaveCommunication(newNumberList, updatedPersonList);

                        // reset so context doesn't bloat
                        lookupContext = new RockContext();
                        personService = new PersonService(lookupContext);
                        updatedPersonList.Clear();
                        newNumberList.Clear();
                        ReportPartialProgress();
                    }
                }
            }

            if (newNumberList.Any() || updatedPersonList.Any())
            {
                SaveCommunication(newNumberList, updatedPersonList);
            }

            ReportProgress(100, string.Format("Finished communication import: {0:N0} records imported.", completed));
        }
Example #29
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            hfAreaGroupClicked.Value = "true";

            using (var rockContext = new RockContext())
            {
                var attributeService = new AttributeService(rockContext);

                if (checkinArea.Visible)
                {
                    var groupTypeService = new GroupTypeService(rockContext);
                    var groupType        = groupTypeService.Get(checkinArea.GroupTypeGuid);
                    if (groupType != null)
                    {
                        groupType.LoadAttributes(rockContext);
                        checkinArea.GetGroupTypeValues(groupType);

                        if (groupType.IsValid)
                        {
                            rockContext.SaveChanges();
                            groupType.SaveAttributeValues(rockContext);

                            // rebuild the CheckinLabel attributes from the UI (brute-force)
                            foreach (var labelAttribute in CheckinArea.GetCheckinLabelAttributes(groupType.Attributes))
                            {
                                var attribute = attributeService.Get(labelAttribute.Value.Guid);
                                attributeService.Delete(attribute);
                            }

                            // Make sure default role is set
                            if (!groupType.DefaultGroupRoleId.HasValue && groupType.Roles.Any())
                            {
                                groupType.DefaultGroupRoleId = groupType.Roles.First().Id;
                            }

                            rockContext.SaveChanges();

                            int labelOrder            = 0;
                            int binaryFileFieldTypeID = FieldTypeCache.Get(Rock.SystemGuid.FieldType.LABEL.AsGuid()).Id;
                            foreach (var checkinLabelAttributeInfo in checkinArea.CheckinLabels)
                            {
                                var attribute = new Rock.Model.Attribute();
                                attribute.AttributeQualifiers.Add(new AttributeQualifier {
                                    Key = "binaryFileType", Value = Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL
                                });
                                attribute.Guid         = Guid.NewGuid();
                                attribute.FieldTypeId  = binaryFileFieldTypeID;
                                attribute.EntityTypeId = EntityTypeCache.GetId(typeof(GroupType));
                                attribute.EntityTypeQualifierColumn = "Id";
                                attribute.EntityTypeQualifierValue  = groupType.Id.ToString();
                                attribute.DefaultValue = checkinLabelAttributeInfo.BinaryFileGuid.ToString();
                                attribute.Key          = checkinLabelAttributeInfo.AttributeKey;
                                attribute.Name         = checkinLabelAttributeInfo.FileName;
                                attribute.Order        = labelOrder++;

                                if (!attribute.IsValid)
                                {
                                    return;
                                }

                                attributeService.Add(attribute);
                            }

                            rockContext.SaveChanges();

                            Rock.CheckIn.KioskDevice.Clear();

                            nbSaveSuccess.Visible = true;
                            BuildRows();
                        }
                        else
                        {
                            ShowInvalidResults(groupType.ValidationResults);
                        }
                    }
                }

                if (checkinGroup.Visible)
                {
                    var groupService         = new GroupService(rockContext);
                    var groupLocationService = new GroupLocationService(rockContext);

                    var group = groupService.Get(checkinGroup.GroupGuid);
                    if (group != null)
                    {
                        group.LoadAttributes(rockContext);
                        checkinGroup.GetGroupValues(group);

                        // populate groupLocations with whatever is currently in the grid, with just enough info to repopulate it and save it later
                        var newLocationIds = checkinGroup.Locations.Select(l => l.LocationId).ToList();
                        foreach (var groupLocation in group.GroupLocations.Where(l => !newLocationIds.Contains(l.LocationId)).ToList())
                        {
                            groupLocation.GroupLocationScheduleConfigs.Clear();

                            groupLocationService.Delete(groupLocation);
                            group.GroupLocations.Remove(groupLocation);
                        }

                        var existingLocationIds = group.GroupLocations.Select(g => g.LocationId).ToList();
                        foreach (var item in checkinGroup.Locations.Where(l => !existingLocationIds.Contains(l.LocationId)).ToList())
                        {
                            var groupLocation = new GroupLocation();
                            groupLocation.LocationId = item.LocationId;
                            group.GroupLocations.Add(groupLocation);
                        }

                        // Set the new order
                        foreach (var item in checkinGroup.Locations.OrderBy(l => l.Order).ToList())
                        {
                            var groupLocation = group.GroupLocations.FirstOrDefault(gl => gl.LocationId == item.LocationId);
                            groupLocation.Order = item.Order ?? 0;
                        }

                        if (group.IsValid)
                        {
                            rockContext.SaveChanges();
                            group.SaveAttributeValues(rockContext);

                            Rock.CheckIn.KioskDevice.Clear();
                            nbSaveSuccess.Visible = true;
                            BuildRows();
                        }
                        else
                        {
                            ShowInvalidResults(group.ValidationResults);
                        }
                    }
                }
            }

            hfIsDirty.Value = "false";
        }