コード例 #1
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="contentTypeId">The marketing campaign ad type identifier.</param>
        public void ShowDetail(int contentTypeId)
        {
            var rockContext = new RockContext();
            ContentChannelType contentType = null;

            if (!contentTypeId.Equals(0))
            {
                contentType = GetContentChannelType(contentTypeId);
                pdAuditDetails.SetEntity(contentType, ResolveRockUrl("~"));
            }
            if (contentType == null)
            {
                contentType = new ContentChannelType {
                    Id = 0
                };
                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }

            string title = contentType.Id > 0 ?
                           ActionTitle.Edit(ContentChannelType.FriendlyTypeName) :
                           ActionTitle.Add(ContentChannelType.FriendlyTypeName);

            lTitle.Text = title.FormatAsHtmlTitle();

            hfId.Value = contentType.Id.ToString();

            tbName.Text = contentType.Name;
            ddlDateRangeType.BindToEnum <ContentChannelDateType>();
            ddlDateRangeType.SetValue((int)contentType.DateRangeType);
            cbIncludeTime.Checked     = contentType.IncludeTime;
            cbDisablePriority.Checked = contentType.DisablePriority;

            // load attribute data
            ChannelAttributesState = new List <Attribute>();
            ItemAttributesState    = new List <Attribute>();

            AttributeService attributeService = new AttributeService(new RockContext());

            string qualifierValue = contentType.Id.ToString();

            attributeService.GetByEntityTypeId(new ContentChannel().TypeId).AsQueryable()
            .Where(a =>
                   a.EntityTypeQualifierColumn.Equals("ContentChannelTypeId", StringComparison.OrdinalIgnoreCase) &&
                   a.EntityTypeQualifierValue.Equals(qualifierValue))
            .ToList()
            .ForEach(a => ChannelAttributesState.Add(a));
            BindChannelAttributesGrid();

            attributeService.GetByEntityTypeId(new ContentChannelItem().TypeId).AsQueryable()
            .Where(a =>
                   a.EntityTypeQualifierColumn.Equals("ContentChannelTypeId", StringComparison.OrdinalIgnoreCase) &&
                   a.EntityTypeQualifierValue.Equals(qualifierValue))
            .ToList()
            .ForEach(a => ItemAttributesState.Add(a));
            BindItemAttributesGrid();
        }
コード例 #2
0
        private IQueryable <Rock.Model.Attribute> GetData(RockContext rockContext)
        {
            IQueryable <Rock.Model.Attribute> query = null;

            AttributeService attributeService = new AttributeService(rockContext);

            if (_configuredType)
            {
                query = attributeService.Get(_entityTypeId, _entityQualifierColumn, _entityQualifierValue);
            }
            else
            {
                int entityTypeId = int.MinValue;
                if (int.TryParse(rFilter.GetUserPreference("Entity Type"), out entityTypeId))
                {
                    if (entityTypeId > 0)
                    {
                        query = attributeService.GetByEntityTypeId(entityTypeId);
                    }
                }
            }

            if (query == null)
            {
                query = attributeService.GetByEntityTypeId(null);
            }

            var selectedCategoryIds = new List <int>();

            rFilter.GetUserPreference("Categories").SplitDelimitedValues().ToList().ForEach(s => selectedCategoryIds.Add(int.Parse(s)));
            if (selectedCategoryIds.Any())
            {
                query = query.Where(a => a.Categories.Any(c => selectedCategoryIds.Contains(c.Id)));
            }

            if (_enableOrdering)
            {
                query = query.OrderBy(a => a.Order);
            }
            else
            {
                SortProperty sortProperty = rGrid.SortProperty;
                if (sortProperty != null)
                {
                    query = query.Sort(sortProperty);
                }
                else
                {
                    query = query.OrderBy(a => a.Key);
                }
            }

            return(query);
        }
コード例 #3
0
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="contentChannel">Type of the content.</param>
        protected void ShowEditDetails(ContentChannel contentChannel)
        {
            if (contentChannel != null)
            {
                hfId.Value = contentChannel.Id.ToString();
                string title = contentChannel.Id > 0 ?
                               ActionTitle.Edit(ContentChannel.FriendlyTypeName) :
                               ActionTitle.Add(ContentChannel.FriendlyTypeName);

                SetHeadingInfo(contentChannel, title);

                SetEditMode(true);

                LoadDropdowns();

                tbName.Text        = contentChannel.Name;
                tbDescription.Text = contentChannel.Description;
                ddlChannelType.SetValue(contentChannel.ContentChannelTypeId);
                ddlContentControlType.SetValue(contentChannel.ContentControlType.ConvertToInt().ToString());
                tbRootImageDirectory.Text           = contentChannel.RootImageDirectory;
                tbRootImageDirectory.Visible        = contentChannel.ContentControlType == ContentControlType.HtmlEditor;
                tbIconCssClass.Text                 = contentChannel.IconCssClass;
                cbRequireApproval.Checked           = contentChannel.RequiresApproval;
                cbItemsManuallyOrdered.Checked      = contentChannel.ItemsManuallyOrdered;
                cbChildItemsManuallyOrdered.Checked = contentChannel.ChildItemsManuallyOrdered;
                cbEnableRss.Checked                 = contentChannel.EnableRss;

                divRss.Attributes["style"] = cbEnableRss.Checked ? "display:block" : "display:none";
                tbChannelUrl.Text          = contentChannel.ChannelUrl;
                tbItemUrl.Text             = contentChannel.ItemUrl;
                nbTimetoLive.Text          = (contentChannel.TimeToLive ?? 0).ToString();

                ChildContentChannelsList = new List <int>();
                contentChannel.ChildContentChannels.ToList().ForEach(a => ChildContentChannelsList.Add(a.Id));
                BindChildContentChannelsGrid();

                AddAttributeControls(contentChannel);

                // load attribute data
                ItemAttributesState = new List <Attribute>();
                AttributeService attributeService = new AttributeService(new RockContext());

                string qualifierValue = contentChannel.Id.ToString();

                attributeService.GetByEntityTypeId(new ContentChannelItem().TypeId).AsQueryable()
                .Where(a =>
                       a.EntityTypeQualifierColumn.Equals("ContentChannelId", StringComparison.OrdinalIgnoreCase) &&
                       a.EntityTypeQualifierValue.Equals(qualifierValue))
                .ToList()
                .ForEach(a => ItemAttributesState.Add(a));

                // Set order
                int newOrder = 0;
                ItemAttributesState.ForEach(a => a.Order = newOrder++);

                BindItemAttributesGrid();
            }
        }
コード例 #4
0
        /// <summary>
        /// Gets the query for all attributes that will be presented in the list.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <returns>A queryable that will enumerate to all the attributes.</returns>
        private IQueryable <Rock.Model.Attribute> GetAttributeQuery(RockContext rockContext, Guid?entityTypeGuid)
        {
            IQueryable <Rock.Model.Attribute> query = null;
            AttributeService attributeService       = new AttributeService(rockContext);

            if (entityTypeGuid.HasValue)
            {
                if (entityTypeGuid.Value == default)
                {
                    // entity type not configured in block or in filter, so get Global Attributes
                    query = attributeService.GetByEntityTypeId(null, true);
                    query = query.Where(t => t.EntityTypeQualifierColumn == null || t.EntityTypeQualifierColumn == "");
                }
                else if (GetAttributeValue(AttributeKey.Entity).AsGuidOrNull().HasValue)
                {
                    // entity type is configured in block, so get by the entityType and qualifiers specified in the block settings
                    var entityTypeCache       = EntityTypeCache.Get(entityTypeGuid.Value);
                    var entityQualifierColumn = GetAttributeValue(AttributeKey.EntityQualifierColumn);
                    var entityQualifierValue  = GetAttributeValue(AttributeKey.EntityQualifierValue);
                    query = attributeService.GetByEntityTypeQualifier(entityTypeCache.Id, entityQualifierColumn, entityQualifierValue, true);
                }
                else
                {
                    // entity type is selected in the filter, so get all the attributes for that entityType. (There is no userfilter for qualifiers, so don't filter by those)
                    var entityTypeCache = EntityTypeCache.Get(entityTypeGuid.Value);
                    query = attributeService.GetByEntityTypeId(entityTypeCache.Id, true);
                }
            }

            // if filtering by block setting of categories
            if (!string.IsNullOrWhiteSpace(GetAttributeValue(AttributeKey.CategoryFilter)))
            {
                try
                {
                    var categoryGuids = GetAttributeValue(AttributeKey.CategoryFilter).Split(',').Select(Guid.Parse).ToList();

                    query = query.Where(a => a.Categories.Any(c => categoryGuids.Contains(c.Guid)));
                }
                catch { }
            }

            query = query.OrderBy(a => a.Order);

            return(query);
        }
コード例 #5
0
        /// <summary>
        /// Binds the defined type attributes grid.
        /// </summary>
        private void BindDefinedTypeAttributesGrid()
        {
            AttributeService attributeService = new AttributeService();

            string qualifierValue           = hfDefinedTypeId.Value;
            var    qryDefinedTypeAttributes = attributeService.GetByEntityTypeId(new DefinedValue().TypeId).AsQueryable()
                                              .Where(a => a.EntityTypeQualifierColumn.Equals("DefinedTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                     a.EntityTypeQualifierValue.Equals(qualifierValue));

            gDefinedTypeAttributes.DataSource = qryDefinedTypeAttributes.OrderBy(a => a.Name).ToList();
            gDefinedTypeAttributes.DataBind();
        }
コード例 #6
0
        /// <summary>
        /// Binds the defined values grid.
        /// </summary>
        protected void BindDefinedValuesGrid()
        {
            AttributeService attributeService = new AttributeService();

            int definedTypeId = hfDefinedTypeId.ValueAsInt();

            // add attributes with IsGridColumn to grid
            string qualifierValue           = hfDefinedTypeId.Value;
            var    qryDefinedTypeAttributes = attributeService.GetByEntityTypeId(new DefinedValue().TypeId).AsQueryable()
                                              .Where(a => a.EntityTypeQualifierColumn.Equals("DefinedTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                     a.EntityTypeQualifierValue.Equals(qualifierValue));

            qryDefinedTypeAttributes = qryDefinedTypeAttributes.Where(a => a.IsGridColumn);

            List <Attribute> gridItems = qryDefinedTypeAttributes.ToList();

            foreach (var item in gDefinedValues.Columns.OfType <AttributeField>().ToList())
            {
                gDefinedValues.Columns.Remove(item);
            }

            foreach (var item in gridItems.OrderBy(a => a.Order).ThenBy(a => a.Name))
            {
                string dataFieldExpression = item.Key;
                bool   columnExists        = gDefinedValues.Columns.OfType <AttributeField>().FirstOrDefault(a => a.DataField.Equals(dataFieldExpression)) != null;
                if (!columnExists)
                {
                    AttributeField boundField = new AttributeField();
                    boundField.DataField      = dataFieldExpression;
                    boundField.HeaderText     = item.Name;
                    boundField.SortExpression = string.Empty;
                    int insertPos = gDefinedValues.Columns.IndexOf(gDefinedValues.Columns.OfType <ReorderField>().First());
                    gDefinedValues.Columns.Insert(insertPos, boundField);
                }
            }

            var queryable = new DefinedValueService().Queryable().Where(a => a.DefinedTypeId == definedTypeId).OrderBy(a => a.Order);

            //SortProperty sortProperty = gDefinedValues.SortProperty;
            //if ( sortProperty != null )
            //{
            //    queryable = queryable.Sort( sortProperty );
            //}
            //else
            //{
            //    queryable = queryable.OrderBy( a => a.Id );
            //}

            var result = queryable.ToList();

            gDefinedValues.DataSource = result;
            gDefinedValues.DataBind();
        }
コード例 #7
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="marketingCampaignAdTypeId">The marketing campaign ad type id.</param>
        protected void ShowEdit(int marketingCampaignAdTypeId)
        {
            pnlList.Visible    = false;
            pnlDetails.Visible = true;

            MarketingCampaignAdTypeService marketingCampaignAdTypeService = new MarketingCampaignAdTypeService();
            MarketingCampaignAdType        marketingCampaignAdType        = marketingCampaignAdTypeService.Get(marketingCampaignAdTypeId);
            bool readOnly = false;

            AttributesState = new List <Attribute>().ToDto();

            if (marketingCampaignAdType != null)
            {
                hfMarketingCampaignAdTypeId.Value = marketingCampaignAdType.Id.ToString();
                tbName.Text = marketingCampaignAdType.Name;
                ddlDateRangeType.SelectedValue = ((int)marketingCampaignAdType.DateRangeType).ToString();

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

                AttributesState = qry.ToList().ToDto();

                readOnly = marketingCampaignAdType.IsSystem;

                if (marketingCampaignAdType.IsSystem)
                {
                    lActionTitle.Text = ActionTitle.View(MarketingCampaignAdType.FriendlyTypeName);
                    btnCancel.Text    = "Close";
                }
                else
                {
                    lActionTitle.Text = ActionTitle.Edit(MarketingCampaignAdType.FriendlyTypeName);
                    btnCancel.Text    = "Cancel";
                }
            }
            else
            {
                lActionTitle.Text = ActionTitle.Add(MarketingCampaignAdType.FriendlyTypeName);

                hfMarketingCampaignAdTypeId.Value = 0.ToString();
                tbName.Text = string.Empty;
            }

            iconIsSystem.Visible = readOnly;
            btnSave.Visible      = !readOnly;

            BindMarketingCampaignAdAttributeTypeGrid();
        }
コード例 #8
0
        /// <summary>
        /// Handles the GridReorder event of the gBlockTypeAttributes control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="GridReorderEventArgs"/> instance containing the event data.</param>
        void gBlockTypeAttributes_GridReorder(object sender, GridReorderEventArgs e)
        {
            var    blockTypeStaticAttributeKeys = GetBlockTypeStaticAttributeKeys();
            string qualifierValue = hfBlockTypeId.Value;

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

            int order      = 0;
            var attributes = attributeService
                             .GetByEntityTypeId(new Rock.Model.Block().TypeId).AsQueryable()
                             .Where(a =>
                                    a.EntityTypeQualifierColumn.Equals("BlockTypeId", StringComparison.OrdinalIgnoreCase) &&
                                    a.EntityTypeQualifierValue.Equals(qualifierValue))
                             .OrderBy(a => a.Order)
                             .ThenBy(a => a.Name)
                             .ToList();

            foreach (var attribute in attributes)
            {
                attribute.Order = order++;
                AttributeCache.Flush(attribute.Id);
            }

            var movedItem = attributes.Where(a => a.Order == e.OldIndex).FirstOrDefault();

            if (movedItem != null)
            {
                if (e.NewIndex < e.OldIndex)
                {
                    // Moved up
                    foreach (var otherItem in attributes.Where(a => a.Order < e.OldIndex && a.Order >= e.NewIndex))
                    {
                        otherItem.Order = otherItem.Order + 1;
                    }
                }
                else
                {
                    // Moved Down
                    foreach (var otherItem in attributes.Where(a => a.Order > e.OldIndex && a.Order <= e.NewIndex))
                    {
                        otherItem.Order = otherItem.Order - 1;
                    }
                }

                movedItem.Order = e.NewIndex;
                rockContext.SaveChanges();
            }

            BindBlockTypeAttributesGrid();
        }
コード例 #9
0
        /// <summary>
        /// Binds the workflow type attributes grid.
        /// </summary>
        private void BindWorkflowTypeAttributesGrid()
        {
            AttributeService attributeService = new AttributeService();

            int workflowTypeId = hfWorkflowTypeId.ValueAsInt();

            string qualifierValue            = workflowTypeId.ToString();
            var    qryWorkflowTypeAttributes = attributeService.GetByEntityTypeId(new Workflow().TypeId).AsQueryable()
                                               .Where(a => a.EntityTypeQualifierColumn.Equals("WorkflowTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                      a.EntityTypeQualifierValue.Equals(qualifierValue));

            gWorkflowTypeAttributes.DataSource = qryWorkflowTypeAttributes.OrderBy(a => a.Name).ToList();
            gWorkflowTypeAttributes.DataBind();
        }
コード例 #10
0
        /// <summary>
        /// Populates the block variable EventOccurrenceAttributesState with data
        /// </summary>
        /// <param name="eventItemId">The event item identifier.</param>
        private void LoadEventOccurrenceAttributes(int eventItemId)
        {
            var attributeService = new AttributeService(new RockContext());

            EventOccurrenceAttributesState = attributeService
                                             .GetByEntityTypeId(new EventItemOccurrence().TypeId, true)
                                             .AsQueryable()
                                             .AsNoTracking()
                                             .Where(a =>
                                                    a.EntityTypeQualifierColumn.Equals("EventItemId", StringComparison.OrdinalIgnoreCase) &&
                                                    a.EntityTypeQualifierValue.Equals(eventItemId.ToString()))
                                             .OrderBy(a => a.Order)
                                             .ThenBy(a => a.Name)
                                             .ToList();

            BindEventOccurrenceAttributesGrid();
        }
コード例 #11
0
        /// <summary>
        /// Evaluate the list of child entities. This is a list of key value pairs that identify
        /// the property that the child came from as well as the child entity itself. Implementations
        /// of this method may add or remove from this list. For example, a WorkflowActionForm has
        /// it's actions encoded in a single string. This must processed to include any other
        /// objects that should exist (such as a DefinedValue for the button type).
        /// </summary>
        /// <param name="entity">The parent entity of the children.</param>
        /// <param name="children">The child entities and what properties of the parent they came from.</param>
        /// <param name="helper">The helper class for this export.</param>
        protected override void EvaluateChildEntities(WorkflowType entity, List <KeyValuePair <string, IEntity> > children, EntityCoder helper)
        {
            var attributeService = new AttributeService(helper.RockContext);

            var items = attributeService
                        .GetByEntityTypeId(new Model.Workflow().TypeId).AsQueryable()
                        .Where(a =>
                               a.EntityTypeQualifierColumn.Equals("WorkflowTypeId", StringComparison.OrdinalIgnoreCase) &&
                               a.EntityTypeQualifierValue.Equals(entity.Id.ToString()))
                        .ToList();

            //
            // We have to special process the attributes since we modify them.
            //
            foreach (var item in items)
            {
                children.Add(new KeyValuePair <string, IEntity>("AttributeTypes", item));
            }
        }
コード例 #12
0
ファイル: CalendarDetail.ascx.cs プロジェクト: ewin66/rockrms
        /// <summary>
        /// Loads the state details.
        /// </summary>
        /// <param name="eventCalendar">The event calendar.</param>
        /// <param name="rockContext">The rock context.</param>
        private void LoadStateDetails(EventCalendar eventCalendar, RockContext rockContext)
        {
            var attributeService = new AttributeService(rockContext);

            EventAttributesState = attributeService
                                   .GetByEntityTypeId(new EventCalendarItem().TypeId, true).AsQueryable()
                                   .Where(a =>
                                          a.EntityTypeQualifierColumn.Equals("EventCalendarId", StringComparison.OrdinalIgnoreCase) &&
                                          a.EntityTypeQualifierValue.Equals(eventCalendar.Id.ToString()))
                                   .OrderBy(a => a.Order)
                                   .ThenBy(a => a.Name)
                                   .ToList();

            ContentChannelsState = new Dictionary <Guid, string>();
            new EventCalendarContentChannelService(rockContext)
            .Queryable()
            .Where(c => c.EventCalendarId == eventCalendar.Id)
            .ToList()
            .ForEach(c => ContentChannelsState.Add(c.ContentChannel.Guid, c.ContentChannel.Name));
        }
コード例 #13
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            IQueryable <Rock.Model.Attribute> query;

            AttributeService attributeService = new AttributeService();

            if (_configuredType)
            {
                query = attributeService.Get(_entityTypeId, _entityQualifierColumn, _entityQualifierValue);
            }
            else
            {
                query = attributeService.GetByEntityTypeId(ddlEntityType.SelectedValueAsInt());
            }

            List <int> selectedCategoryIds = cpCategoriesFilter.SelectedValuesAsInt().Where(v => v != 0).ToList();

            if (selectedCategoryIds.Any())
            {
                query = query.
                        Where(a => a.Categories.Any(c => selectedCategoryIds.Contains(c.Id)));
            }

            SortProperty sortProperty = rGrid.SortProperty;

            if (sortProperty != null)
            {
                query = query.
                        Sort(sortProperty);
            }
            else
            {
                query = query.
                        OrderBy(a => a.Key);
            }

            rGrid.DataSource = query.ToList();
            rGrid.DataBind();
        }
コード例 #14
0
        /// <summary>
        /// Ensures the tracked attributes exists.
        /// </summary>
        /// <param name="trackedAttributeKey">The tracked attribute key.</param>
        /// <param name="trackedAttributeName">Name of the tracked attribute.</param>
        /// <param name="fieldTypeGuid">The field type unique identifier.</param>
        private void EnsureTrackedAttributeExists(string trackedAttributeKey, string trackedAttributeName, Guid fieldTypeGuid)
        {
            var entityTypeIdPerson = EntityTypeCache.GetId <Rock.Model.Person>();
            var fieldTypeId        = FieldTypeCache.GetId(fieldTypeGuid);

            if (!entityTypeIdPerson.HasValue || !fieldTypeId.HasValue)
            {
                // shouldn't happen, but just in case
                return;
            }

            var rockContext = new RockContext();

            var attributeService = new AttributeService(rockContext);

            var trackedAttribute = attributeService.GetByEntityTypeId(entityTypeIdPerson.Value).Where(a => a.Key == trackedAttributeKey).FirstOrDefault();

            if (trackedAttribute == null)
            {
                trackedAttribute = new Rock.Model.Attribute();
                trackedAttribute.EntityTypeId = entityTypeIdPerson;
                trackedAttribute.Key          = trackedAttributeKey;
                trackedAttribute.Name         = trackedAttributeName;
                trackedAttribute.FieldTypeId  = fieldTypeId.Value;
                attributeService.Add(trackedAttribute);
                rockContext.SaveChanges();
            }
            else
            {
                if (trackedAttribute.FieldTypeId != fieldTypeId.Value)
                {
                    trackedAttribute.FieldTypeId = fieldTypeId.Value;
                    rockContext.SaveChanges();
                }
            }
        }
コード例 #15
0
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="group">The group.</param>
        private void ShowEditDetails(Group group)
        {
            if (group.Id == 0)
            {
                lReadOnlyTitle.Text = ActionTitle.Add(Group.FriendlyTypeName).FormatAsHtmlTitle();
            }
            else
            {
                lReadOnlyTitle.Text = group.Name.FormatAsHtmlTitle();
            }

            SetEditMode(true);

            tbName.Text              = group.Name;
            tbDescription.Text       = group.Description;
            cbIsSecurityRole.Checked = group.IsSecurityRole;
            cbIsActive.Checked       = group.IsActive;

            LoadDropDowns();

            GroupMemberAttributesState = new ViewStateList <Attribute>();

            gpParentGroup.SetValue(group.ParentGroup ?? new GroupService().Get(group.ParentGroupId ?? 0));

            // GroupType depends on Selected ParentGroup
            ddlParentGroup_SelectedIndexChanged(null, null);
            gpParentGroup.Label = "Parent Group";

            if (group.Id == 0 && ddlGroupType.Items.Count > 1)
            {
                if (GetAttributeValue("LimittoSecurityRoleGroups").FromTrueFalse())
                {
                    // default GroupType for new Group to "Security Roles"  if LimittoSecurityRoleGroups
                    var securityRoleGroupType = new GroupTypeService().Queryable().FirstOrDefault(a => a.Guid.Equals(new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE)));
                    if (securityRoleGroupType != null)
                    {
                        ddlGroupType.SetValue(securityRoleGroupType.Id);
                    }
                    else
                    {
                        ddlGroupType.SelectedIndex = 0;
                    }
                }
                else
                {
                    // if this is a new group (and not "LimitToSecurityRoleGroups", and there is more than one choice for GroupType, default to no selection so they are forced to choose (vs unintentionallly choosing the default one)
                    ddlGroupType.SelectedIndex = 0;
                }
            }
            else
            {
                ddlGroupType.SetValue(group.GroupTypeId);
            }

            ddlCampus.SetValue(group.CampusId);

            phGroupTypeAttributes.Controls.Clear();
            GroupType groupType = new GroupTypeService().Get(group.GroupTypeId);

            if (groupType != null)
            {
                groupType.LoadAttributes();
                Rock.Attribute.Helper.AddDisplayControls(groupType, phGroupTypeAttributes);
            }

            phGroupAttributes.Controls.Clear();
            group.LoadAttributes();
            Rock.Attribute.Helper.AddEditControls(group, phGroupAttributes, true);

            // if this block's attribute limit group to SecurityRoleGroups, don't let them edit the SecurityRole checkbox value
            if (GetAttributeValue("LimittoSecurityRoleGroups").FromTrueFalse())
            {
                cbIsSecurityRole.Enabled = false;
                cbIsSecurityRole.Checked = true;
            }

            AttributeService attributeService = new AttributeService();

            string qualifierValue           = group.Id.ToString();
            var    qryGroupMemberAttributes = attributeService.GetByEntityTypeId(new GroupMember().TypeId).AsQueryable()
                                              .Where(a => a.EntityTypeQualifierColumn.Equals("GroupId", StringComparison.OrdinalIgnoreCase) &&
                                                     a.EntityTypeQualifierValue.Equals(qualifierValue));

            GroupMemberAttributesState.AddAll(qryGroupMemberAttributes.ToList());
            BindGroupMemberAttributesGrid();
        }
コード例 #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)
        {
            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);
        }
コード例 #17
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        /// <param name="itemKeyValue">The item key value.</param>
        public void ShowDetail(string itemKey, int itemKeyValue)
        {
            if (!itemKey.Equals("binaryFileTypeId"))
            {
                return;
            }

            pnlDetails.Visible = true;
            BinaryFileType binaryFileType = null;

            if (!itemKeyValue.Equals(0))
            {
                binaryFileType    = new BinaryFileTypeService().Get(itemKeyValue);
                lActionTitle.Text = ActionTitle.Edit(BinaryFileType.FriendlyTypeName);
            }
            else
            {
                binaryFileType = new BinaryFileType {
                    Id = 0
                };
                lActionTitle.Text = ActionTitle.Add(BinaryFileType.FriendlyTypeName);
            }

            BinaryFileAttributesState = new ViewStateList <Attribute>();

            hfBinaryFileTypeId.Value = binaryFileType.Id.ToString();
            tbName.Text          = binaryFileType.Name;
            tbDescription.Text   = binaryFileType.Description;
            tbIconCssClass.Text  = binaryFileType.IconCssClass;
            imgIconSmall.ImageId = binaryFileType.IconSmallFileId;
            imgIconLarge.ImageId = binaryFileType.IconLargeFileId;

            if (binaryFileType.StorageEntityType != null)
            {
                cpStorageType.SelectedValue = binaryFileType.StorageEntityType.Guid.ToString();
            }

            AttributeService attributeService = new AttributeService();

            string qualifierValue          = binaryFileType.Id.ToString();
            var    qryBinaryFileAttributes = attributeService.GetByEntityTypeId(new BinaryFile().TypeId).AsQueryable()
                                             .Where(a => a.EntityTypeQualifierColumn.Equals("BinaryFileTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                    a.EntityTypeQualifierValue.Equals(qualifierValue));

            BinaryFileAttributesState.AddAll(qryBinaryFileAttributes.ToList());
            BindBinaryFileAttributesGrid();

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if (!IsUserAuthorized("Edit"))
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(BinaryFileType.FriendlyTypeName);
            }

            if (binaryFileType.IsSystem)
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlySystem(BinaryFileType.FriendlyTypeName);
            }

            if (readOnly)
            {
                lActionTitle.Text = ActionTitle.View(BinaryFileType.FriendlyTypeName);
                btnCancel.Text    = "Close";
            }

            tbName.ReadOnly               = readOnly;
            tbDescription.ReadOnly        = readOnly;
            tbIconCssClass.ReadOnly       = readOnly;
            imgIconLarge.Enabled          = !readOnly;
            imgIconSmall.Enabled          = !readOnly;
            gBinaryFileAttributes.Enabled = !readOnly;

            btnSave.Visible = !readOnly;
        }
コード例 #18
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        /// <param name="itemKeyValue">The item key value.</param>
        public void ShowDetail(string itemKey, int itemKeyValue)
        {
            if (!itemKey.Equals("binaryFileTypeId"))
            {
                return;
            }

            pnlDetails.Visible = true;
            BinaryFileType binaryFileType;

            var rockContext = new RockContext();

            if (!itemKeyValue.Equals(0))
            {
                binaryFileType    = new BinaryFileTypeService(rockContext).Get(itemKeyValue);
                lActionTitle.Text = ActionTitle.Edit(BinaryFileType.FriendlyTypeName).FormatAsHtmlTitle();
            }
            else
            {
                binaryFileType = new BinaryFileType {
                    Id = 0
                };
                lActionTitle.Text = ActionTitle.Add(BinaryFileType.FriendlyTypeName).FormatAsHtmlTitle();
            }

            BinaryFileAttributesState = new ViewStateList <Attribute>();

            hfBinaryFileTypeId.Value = binaryFileType.Id.ToString();
            tbName.Text                = binaryFileType.Name;
            tbDescription.Text         = binaryFileType.Description;
            tbIconCssClass.Text        = binaryFileType.IconCssClass;
            cbAllowCaching.Checked     = binaryFileType.AllowCaching;
            cbRequiresSecurity.Checked = binaryFileType.RequiresSecurity;

            if (binaryFileType.StorageEntityType != null)
            {
                cpStorageType.SelectedValue = binaryFileType.StorageEntityType.Guid.ToString().ToUpper();
            }

            AttributeService attributeService = new AttributeService(rockContext);

            string qualifierValue          = binaryFileType.Id.ToString();
            var    qryBinaryFileAttributes = attributeService.GetByEntityTypeId(new BinaryFile().TypeId).AsQueryable()
                                             .Where(a => a.EntityTypeQualifierColumn.Equals("BinaryFileTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                    a.EntityTypeQualifierValue.Equals(qualifierValue));

            BinaryFileAttributesState.AddAll(qryBinaryFileAttributes.ToList());
            BindBinaryFileAttributesGrid();

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if (!IsUserAuthorized(Authorization.EDIT))
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(BinaryFileType.FriendlyTypeName);
            }

            if (binaryFileType.IsSystem)
            {
                nbEditModeMessage.Text = EditModeMessage.System(BinaryFileType.FriendlyTypeName);
            }

            phAttributes.Controls.Clear();
            binaryFileType.LoadAttributes();

            if (readOnly || binaryFileType.IsSystem)
            {
                lActionTitle.Text = ActionTitle.View(BinaryFileType.FriendlyTypeName).FormatAsHtmlTitle();
                btnCancel.Text    = "Close";
                Rock.Attribute.Helper.AddDisplayControls(binaryFileType, phAttributes);
            }
            else
            {
                Rock.Attribute.Helper.AddEditControls(binaryFileType, phAttributes, true);
            }

            tbName.ReadOnly               = readOnly || binaryFileType.IsSystem;
            tbDescription.ReadOnly        = readOnly || binaryFileType.IsSystem;
            tbIconCssClass.ReadOnly       = readOnly || binaryFileType.IsSystem;
            cbAllowCaching.Enabled        = !readOnly && !binaryFileType.IsSystem;
            cbRequiresSecurity.Enabled    = !readOnly && !binaryFileType.IsSystem;
            gBinaryFileAttributes.Enabled = !readOnly && !binaryFileType.IsSystem;

            // allow storagetype to be edited if IsSystem
            cpStorageType.Enabled = !readOnly;

            // allow save to be clicked if IsSystem since some things can be edited
            btnSave.Visible = !readOnly;
        }
コード例 #19
0
        /// <summary>
        /// Updates the social media dropdowns.
        /// </summary>
        /// <param name="channelGuid">The channel unique identifier.</param>
        private void UpdateSocialMediaDropdowns(Guid?channelGuid)
        {
            List <AttributeCache> channelAttributes = new List <AttributeCache>();
            List <AttributeCache> itemAttributes    = new List <AttributeCache>();

            if (channelGuid.HasValue)
            {
                var rockContext = new RockContext();
                var channel     = new ContentChannelService(rockContext).GetNoTracking(channelGuid.Value);

                // add channel attributes
                channel.LoadAttributes();
                channelAttributes = channel.Attributes.Select(a => a.Value).ToList();

                // add item attributes
                AttributeService attributeService = new AttributeService(rockContext);
                itemAttributes = attributeService.GetByEntityTypeId(new ContentChannelItem().TypeId, false).AsQueryable()
                                 .Where(a => (
                                            a.EntityTypeQualifierColumn.Equals("ContentChannelTypeId", StringComparison.OrdinalIgnoreCase) &&
                                            a.EntityTypeQualifierValue.Equals(channel.ContentChannelTypeId.ToString())
                                            ) || (
                                            a.EntityTypeQualifierColumn.Equals("ContentChannelId", StringComparison.OrdinalIgnoreCase) &&
                                            a.EntityTypeQualifierValue.Equals(channel.Id.ToString())
                                            ))
                                 .OrderByDescending(a => a.EntityTypeQualifierColumn)
                                 .ThenBy(a => a.Order)
                                 .ToAttributeCacheList();
            }

            RockDropDownList[] attributeDropDowns = new RockDropDownList[]
            {
                ddlMetaDescriptionAttribute,
                ddlOpenGraphTitleAttribute,
                ddlOpenGraphDescriptionAttribute,
                ddlOpenGraphImageAttribute,
                ddlTwitterTitleAttribute,
                ddlTwitterDescriptionAttribute,
                ddlTwitterImageAttribute,
                ddlMetaDescriptionAttribute
            };

            RockDropDownList[] attributeDropDownsImage = new RockDropDownList[]
            {
                ddlOpenGraphImageAttribute,
                ddlTwitterImageAttribute,
            };

            foreach (var attributeDropDown in attributeDropDowns)
            {
                attributeDropDown.Items.Clear();
                attributeDropDown.Items.Add(new ListItem());
                foreach (var attribute in channelAttributes)
                {
                    string computedKey = "C^" + attribute.Key;
                    if (attributeDropDownsImage.Contains(attributeDropDown))
                    {
                        if (attribute.FieldType.Name == "Image")
                        {
                            attributeDropDown.Items.Add(new ListItem("Channel: " + attribute.Name, computedKey));
                        }
                    }
                    else
                    {
                        attributeDropDown.Items.Add(new ListItem("Channel: " + attribute.Name, computedKey));
                    }
                }

                // get all the possible Item attributes for items in this Content Channel and add those as options too
                foreach (var attribute in itemAttributes.DistinctBy(a => a.Key).ToList())
                {
                    string computedKey = "I^" + attribute.Key;
                    if (attributeDropDownsImage.Contains(attributeDropDown))
                    {
                        if (attribute.FieldType.Name == "Image")
                        {
                            attributeDropDown.Items.Add(new ListItem("Item: " + attribute.Name, computedKey));
                        }
                    }
                    else
                    {
                        attributeDropDown.Items.Add(new ListItem("Item: " + attribute.Name, computedKey));
                    }
                }
            }
        }
コード例 #20
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        public void ShowEdit()
        {
            int?filterId = hfDataFilterId.Value.AsIntegerOrNull();

            if (ChannelGuid.HasValue)
            {
                var rockContext = new RockContext();
                var channel     = new ContentChannelService(rockContext).Queryable("ContentChannelType")
                                  .FirstOrDefault(c => c.Guid.Equals(ChannelGuid.Value));
                if (channel != null)
                {
                    cblStatus.Visible = channel.RequiresApproval && !channel.ContentChannelType.DisableStatus;

                    var            filterService = new DataViewFilterService(rockContext);
                    DataViewFilter filter        = null;

                    if (filterId.HasValue)
                    {
                        filter = filterService.Get(filterId.Value);
                    }

                    if (filter == null || filter.ExpressionType == FilterExpressionType.Filter)
                    {
                        filter                = new DataViewFilter();
                        filter.Guid           = new Guid();
                        filter.ExpressionType = FilterExpressionType.GroupAll;
                    }

                    CreateFilterControl(channel, filter, true, rockContext);

                    kvlOrder.CustomKeys = new Dictionary <string, string>();
                    kvlOrder.CustomKeys.Add("", "");
                    kvlOrder.CustomKeys.Add("Title", "Title");
                    kvlOrder.CustomKeys.Add("Priority", "Priority");
                    kvlOrder.CustomKeys.Add("Status", "Status");
                    kvlOrder.CustomKeys.Add("StartDateTime", "Start");
                    kvlOrder.CustomKeys.Add("ExpireDateTime", "Expire");
                    kvlOrder.CustomKeys.Add("Order", "Order");

                    string currentMetaDescriptionAttribute = GetAttributeValue("MetaDescriptionAttribute") ?? string.Empty;
                    string currentMetaImageAttribute       = GetAttributeValue("MetaImageAttribute") ?? string.Empty;

                    // add channel attributes
                    channel.LoadAttributes();
                    foreach (var attribute in channel.Attributes)
                    {
                        var    field       = attribute.Value.FieldType.Field;
                        string computedKey = "C^" + attribute.Key;
                    }

                    // add item attributes
                    AttributeService attributeService = new AttributeService(rockContext);
                    var itemAttributes = attributeService.GetByEntityTypeId(new ContentChannelItem().TypeId).AsQueryable()
                                         .Where(a => (
                                                    a.EntityTypeQualifierColumn.Equals("ContentChannelTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                    a.EntityTypeQualifierValue.Equals(channel.ContentChannelTypeId.ToString())
                                                    ) || (
                                                    a.EntityTypeQualifierColumn.Equals("ContentChannelId", StringComparison.OrdinalIgnoreCase) &&
                                                    a.EntityTypeQualifierValue.Equals(channel.Id.ToString())
                                                    ))
                                         .OrderByDescending(a => a.EntityTypeQualifierColumn)
                                         .ThenBy(a => a.Order)
                                         .ToList();

                    foreach (var attribute in itemAttributes)
                    {
                        string attrKey = "Attribute:" + attribute.Key;
                        if (!kvlOrder.CustomKeys.ContainsKey(attrKey))
                        {
                            kvlOrder.CustomKeys.Add("Attribute:" + attribute.Key, attribute.Name);

                            string computedKey = "I^" + attribute.Key;

                            var field = attribute.FieldType.Name;
                        }
                    }
                }
            }
        }
コード例 #21
0
        /// <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));
        }
コード例 #22
0
ファイル: SiteDetail.ascx.cs プロジェクト: ewin66/rockrms
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="site">The site.</param>
        private void ShowEditDetails(Rock.Model.Site site)
        {
            if (site.Id == 0)
            {
                nbDefaultPageNotice.Visible = true;
                lReadOnlyTitle.Text         = ActionTitle.Add(Rock.Model.Site.FriendlyTypeName).FormatAsHtmlTitle();
            }
            else
            {
                nbDefaultPageNotice.Visible = false;
                lReadOnlyTitle.Text         = site.Name.FormatAsHtmlTitle();
            }

            SetEditMode(true);

            LoadDropDowns();

            tbSiteName.ReadOnly = site.IsSystem;
            tbSiteName.Text     = site.Name;

            tbDescription.ReadOnly = site.IsSystem;
            tbDescription.Text     = site.Description;

            ddlTheme.Enabled = !site.IsSystem;
            ddlTheme.SetValue(site.Theme);

            imgSiteIcon.BinaryFileId = site.FavIconBinaryFileId;
            imgSiteLogo.BinaryFileId = site.SiteLogoBinaryFileId;

            if (site.DefaultPageRoute != null)
            {
                ppDefaultPage.SetValue(site.DefaultPageRoute);
            }
            else
            {
                ppDefaultPage.SetValue(site.DefaultPage);
            }

            if (site.LoginPageRoute != null)
            {
                ppLoginPage.SetValue(site.LoginPageRoute);
            }
            else
            {
                ppLoginPage.SetValue(site.LoginPage);
            }

            if (site.ChangePasswordPageRoute != null)
            {
                ppChangePasswordPage.SetValue(site.ChangePasswordPageRoute);
            }
            else
            {
                ppChangePasswordPage.SetValue(site.ChangePasswordPage);
            }

            if (site.CommunicationPageRoute != null)
            {
                ppCommunicationPage.SetValue(site.CommunicationPageRoute);
            }
            else
            {
                ppCommunicationPage.SetValue(site.CommunicationPage);
            }

            if (site.RegistrationPageRoute != null)
            {
                ppRegistrationPage.SetValue(site.RegistrationPageRoute);
            }
            else
            {
                ppRegistrationPage.SetValue(site.RegistrationPage);
            }

            if (site.PageNotFoundPageRoute != null)
            {
                ppPageNotFoundPage.SetValue(site.PageNotFoundPageRoute);
            }
            else
            {
                ppPageNotFoundPage.SetValue(site.PageNotFoundPage);
            }

            tbErrorPage.Text = site.ErrorPage;

            tbSiteDomains.Text            = string.Join("\n", site.SiteDomains.OrderBy(d => d.Order).Select(d => d.Domain).ToArray());
            tbGoogleAnalytics.Text        = site.GoogleAnalyticsCode;
            cbRequireEncryption.Checked   = site.RequiresEncryption;
            cbEnableForShortening.Checked = site.EnabledForShortening;

            cbEnableMobileRedirect.Checked = site.EnableMobileRedirect;
            ppMobilePage.SetValue(site.MobilePage);
            tbExternalURL.Text         = site.ExternalUrl;
            tbAllowedFrameDomains.Text = site.AllowedFrameDomains;
            cbRedirectTablets.Checked  = site.RedirectTablets;
            cbEnablePageViews.Checked  = site.EnablePageViews;

            int channelMediumWebsiteValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id;
            var interactionChannelForSite   = new InteractionChannelService(new RockContext()).Queryable()
                                              .Where(a => a.ChannelTypeMediumValueId == channelMediumWebsiteValueId && a.ChannelEntityId == site.Id).FirstOrDefault();

            if (interactionChannelForSite != null)
            {
                nbPageViewRetentionPeriodDays.Text = interactionChannelForSite.RetentionDuration.ToString();
            }

            cbEnableIndexing.Checked     = site.IsIndexEnabled;
            tbIndexStartingLocation.Text = site.IndexStartingLocation;

            // disable the indexing features if indexing on site is disabled
            var siteEntityType = EntityTypeCache.Get("Rock.Model.Site");

            if (siteEntityType != null && !siteEntityType.IsIndexingEnabled)
            {
                cbEnableIndexing.Visible        = false;
                tbIndexStartingLocation.Visible = false;
            }

            var attributeService     = new AttributeService(new RockContext());
            var siteIdQualifierValue = site.Id.ToString();

            PageAttributesState = attributeService.GetByEntityTypeId(new Page().TypeId, true).AsQueryable()
                                  .Where(a =>
                                         a.EntityTypeQualifierColumn.Equals("SiteId", StringComparison.OrdinalIgnoreCase) &&
                                         a.EntityTypeQualifierValue.Equals(siteIdQualifierValue))
                                  .OrderBy(a => a.Order)
                                  .ThenBy(a => a.Name)
                                  .ToList();
            BindPageAttributesGrid();

            SetControlsVisiblity();
        }
コード例 #23
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        /// <param name="itemKeyValue">The item key value.</param>
        public void ShowDetail(string itemKey, int itemKeyValue)
        {
            if (!itemKey.Equals("marketingCampaignAdTypeId"))
            {
                return;
            }

            pnlDetails.Visible = true;
            MarketingCampaignAdType marketingCampaignAdType = null;

            if (!itemKeyValue.Equals(0))
            {
                marketingCampaignAdType = new MarketingCampaignAdTypeService().Get(itemKeyValue);
                lActionTitle.Text       = ActionTitle.Edit(MarketingCampaignAdType.FriendlyTypeName).FormatAsHtmlTitle();
            }
            else
            {
                marketingCampaignAdType = new MarketingCampaignAdType {
                    Id = 0
                };
                lActionTitle.Text = ActionTitle.Add(MarketingCampaignAdType.FriendlyTypeName).FormatAsHtmlTitle();
            }

            LoadDropDowns();

            // load data into UI controls
            AttributesState = new ViewStateList <Attribute>();

            hfMarketingCampaignAdTypeId.Value = marketingCampaignAdType.Id.ToString();
            tbName.Text = marketingCampaignAdType.Name;
            ddlDateRangeType.SetValue((int)marketingCampaignAdType.DateRangeType);

            AttributeService attributeService = new AttributeService();

            string qualifierValue = marketingCampaignAdType.Id.ToString();
            var    qry            = attributeService.GetByEntityTypeId(new MarketingCampaignAd().TypeId).AsQueryable()
                                    .Where(a => a.EntityTypeQualifierColumn.Equals("MarketingCampaignAdTypeId", StringComparison.OrdinalIgnoreCase) &&
                                           a.EntityTypeQualifierValue.Equals(qualifierValue));

            AttributesState.AddAll(qry.ToList());
            BindMarketingCampaignAdAttributeTypeGrid();

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if (!IsUserAuthorized("Edit"))
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(MarketingCampaignAdType.FriendlyTypeName);
            }

            if (marketingCampaignAdType.IsSystem)
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlySystem(MarketingCampaignAdType.FriendlyTypeName);
            }

            if (readOnly)
            {
                lActionTitle.Text = ActionTitle.View(MarketingCampaignAdType.FriendlyTypeName);
                btnCancel.Text    = "Close";
            }

            tbName.ReadOnly          = readOnly;
            ddlDateRangeType.Enabled = !readOnly;
            gMarketingCampaignAdAttributeTypes.Enabled = !readOnly;

            btnSave.Visible = !readOnly;
        }
コード例 #24
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            WorkflowService workflowService = new WorkflowService();
            SortProperty    sortProperty    = gWorkflows.SortProperty;

            var qry = workflowService.Queryable();

            WorkflowType workflowType = this.ContextEntity <WorkflowType>();

            if (workflowType == null)
            {
                pnlWorkflowList.Visible = false;
                return;
            }

            // if this isn't currently a persisted workflow type, and there are no records, hide the panel
            if (!workflowType.IsPersisted)
            {
                if (qry.Count() == 0)
                {
                    pnlWorkflowList.Visible = false;
                    return;
                }
            }

            if (!string.IsNullOrWhiteSpace(workflowType.WorkTerm))
            {
                gWorkflows.RowItemText = workflowType.WorkTerm;
                lGridTitle.Text        = workflowType.WorkTerm.Pluralize();
            }

            AttributeService attributeService = new AttributeService();

            // add attributes with IsGridColumn to grid
            string qualifierValue            = workflowType.Id.ToString();
            var    qryWorkflowTypeAttributes = attributeService.GetByEntityTypeId(new Workflow().TypeId).AsQueryable()
                                               .Where(a => a.EntityTypeQualifierColumn.Equals("WorkflowTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                      a.EntityTypeQualifierValue.Equals(qualifierValue));

            qryWorkflowTypeAttributes = qryWorkflowTypeAttributes.Where(a => a.IsGridColumn);

            List <Attribute> gridItems = qryWorkflowTypeAttributes.ToList();

            foreach (var item in gWorkflows.Columns.OfType <AttributeField>().ToList())
            {
                gWorkflows.Columns.Remove(item);
            }

            foreach (var item in gridItems.OrderBy(a => a.Order).ThenBy(a => a.Name))
            {
                string dataFieldExpression = item.Key;
                bool   columnExists        = gWorkflows.Columns.OfType <AttributeField>().FirstOrDefault(a => a.DataField.Equals(dataFieldExpression)) != null;
                if (!columnExists)
                {
                    AttributeField boundField = new AttributeField();
                    boundField.DataField      = dataFieldExpression;
                    boundField.HeaderText     = item.Name;
                    boundField.SortExpression = string.Empty;
                    int insertPos = gWorkflows.Columns.IndexOf(gWorkflows.Columns.OfType <DeleteField>().First());
                    gWorkflows.Columns.Insert(insertPos, boundField);
                }
            }


            pnlWorkflowList.Visible = true;

            qry = qry.Where(a => a.WorkflowTypeId.Equals(workflowType.Id));

            if (sortProperty != null)
            {
                gWorkflows.DataSource = qry.Sort(sortProperty).ToList();
            }
            else
            {
                gWorkflows.DataSource = qry.OrderBy(s => s.Name).ToList();
            }

            gWorkflows.DataBind();
        }
コード例 #25
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="binaryFileTypeId">The binary file type identifier.</param>
        public void ShowDetail(int binaryFileTypeId)
        {
            pnlDetails.Visible = true;
            BinaryFileType binaryFileType = null;

            var rockContext = new RockContext();

            if (!binaryFileTypeId.Equals(0))
            {
                binaryFileType    = new BinaryFileTypeService(rockContext).Get(binaryFileTypeId);
                lActionTitle.Text = ActionTitle.Edit(BinaryFileType.FriendlyTypeName).FormatAsHtmlTitle();
                pdAuditDetails.SetEntity(binaryFileType, ResolveRockUrl("~"));
            }

            if (binaryFileType == null)
            {
                binaryFileType = new BinaryFileType {
                    Id = 0
                };
                lActionTitle.Text = ActionTitle.Add(BinaryFileType.FriendlyTypeName).FormatAsHtmlTitle();

                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }

            BinaryFileAttributesState = new List <Attribute>();

            hfBinaryFileTypeId.Value = binaryFileType.Id.ToString();
            tbName.Text         = binaryFileType.Name;
            tbDescription.Text  = binaryFileType.Description;
            tbIconCssClass.Text = binaryFileType.IconCssClass;
            cbCacheToServerFileSystem.Checked = binaryFileType.CacheToServerFileSystem;

            if (binaryFileType.CacheControlHeaderSettings != null)
            {
                cpCacheSettings.CurrentCacheablity = JsonConvert.DeserializeObject <RockCacheability>(binaryFileType.CacheControlHeaderSettings);
            }

            cbRequiresViewSecurity.Checked = binaryFileType.RequiresViewSecurity;

            nbMaxWidth.Text  = binaryFileType.MaxWidth.ToString();
            nbMaxHeight.Text = binaryFileType.MaxHeight.ToString();

            ddlPreferredFormat.BindToEnum <Format>();
            ddlPreferredFormat.SetValue(( int )binaryFileType.PreferredFormat);

            ddlPreferredResolution.BindToEnum <Resolution>();
            ddlPreferredResolution.SetValue(( int )binaryFileType.PreferredResolution);

            ddlPreferredColorDepth.BindToEnum <ColorDepth>();
            ddlPreferredColorDepth.SetValue(( int )binaryFileType.PreferredColorDepth);

            cbPreferredRequired.Checked = binaryFileType.PreferredRequired;

            if (binaryFileType.StorageEntityType != null)
            {
                cpStorageType.SelectedValue = binaryFileType.StorageEntityType.Guid.ToString().ToUpper();
            }

            AttributeService attributeService = new AttributeService(rockContext);

            string qualifierValue          = binaryFileType.Id.ToString();
            var    qryBinaryFileAttributes = attributeService.GetByEntityTypeId(new BinaryFile().TypeId, true).AsQueryable()
                                             .Where(a => a.EntityTypeQualifierColumn.Equals("BinaryFileTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                    a.EntityTypeQualifierValue.Equals(qualifierValue));

            BinaryFileAttributesState = qryBinaryFileAttributes.ToList();

            BindBinaryFileAttributesGrid();

            // render UI based on Authorized and IsSystem
            bool readOnly       = false;
            bool restrictedEdit = false;

            nbEditModeMessage.Text = string.Empty;
            if (!IsUserAuthorized(Authorization.EDIT))
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(BinaryFileType.FriendlyTypeName);
            }

            if (binaryFileType.IsSystem)
            {
                restrictedEdit         = true;
                nbEditModeMessage.Text = EditModeMessage.System(BinaryFileType.FriendlyTypeName);
            }

            phAttributes.Controls.Clear();
            binaryFileType.LoadAttributes();

            if (readOnly)
            {
                lActionTitle.Text = ActionTitle.View(BinaryFileType.FriendlyTypeName).FormatAsHtmlTitle();
                btnCancel.Text    = "Close";
            }

            if (readOnly)
            {
                Rock.Attribute.Helper.AddDisplayControls(binaryFileType, phAttributes);
            }
            else
            {
                Rock.Attribute.Helper.AddEditControls(binaryFileType, phAttributes, true, BlockValidationGroup);
            }

            // the only thing we'll restrict for restrictedEdit is the Name (plus they won't be able to remove Attributes that are marked as IsSystem
            tbName.ReadOnly = readOnly || restrictedEdit;

            gBinaryFileAttributes.Enabled = !readOnly;
            gBinaryFileAttributes.Columns.OfType <EditField>().First().Visible = !readOnly;
            gBinaryFileAttributes.Actions.ShowAdd = !readOnly;

            // allow these to be edited in restricted edit mode if not readonly
            tbDescription.ReadOnly            = readOnly;
            tbIconCssClass.ReadOnly           = readOnly;
            cbCacheToServerFileSystem.Enabled = !readOnly;
            cpCacheSettings.Enabled           = !readOnly;
            cbRequiresViewSecurity.Enabled    = !readOnly;
            cpStorageType.Enabled             = !readOnly;
            nbMaxWidth.ReadOnly            = readOnly;
            nbMaxHeight.ReadOnly           = readOnly;
            ddlPreferredFormat.Enabled     = !readOnly;
            ddlPreferredResolution.Enabled = !readOnly;
            ddlPreferredColorDepth.Enabled = !readOnly;
            cbPreferredRequired.Enabled    = !readOnly;
            btnSave.Visible = !readOnly;
        }
コード例 #26
0
        /// <summary>
        /// Loads Rock data that's used globally by the transform
        /// </summary>
        private void LoadExistingRockData()
        {
            var lookupContext         = new RockContext();
            var attributeValueService = new AttributeValueService(lookupContext);
            var attributeService      = new AttributeService(lookupContext);

            IntegerFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.INTEGER)).Id;
            TextFieldTypeId    = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.TEXT)).Id;
            PersonEntityTypeId = EntityTypeCache.Read("Rock.Model.Person").Id;
            CampusList         = CampusCache.All();

            int attributeEntityTypeId = EntityTypeCache.Read("Rock.Model.Attribute").Id;
            int batchEntityTypeId     = EntityTypeCache.Read("Rock.Model.FinancialBatch").Id;
            int userLoginTypeId       = EntityTypeCache.Read("Rock.Model.UserLogin").Id;

            int visitInfoCategoryId = new CategoryService(lookupContext).GetByEntityTypeId(attributeEntityTypeId)
                                      .Where(c => c.Name == "Visit Information").Select(c => c.Id).FirstOrDefault();

            // Look up and create attributes for F1 unique identifiers if they don't exist
            var personAttributes = attributeService.GetByEntityTypeId(PersonEntityTypeId).AsNoTracking().ToList();

            var householdAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("F1HouseholdId", StringComparison.InvariantCultureIgnoreCase));

            if (householdAttribute == null)
            {
                householdAttribute                           = new Rock.Model.Attribute();
                householdAttribute.Key                       = "F1HouseholdId";
                householdAttribute.Name                      = "F1 Household Id";
                householdAttribute.FieldTypeId               = IntegerFieldTypeId;
                householdAttribute.EntityTypeId              = PersonEntityTypeId;
                householdAttribute.EntityTypeQualifierValue  = string.Empty;
                householdAttribute.EntityTypeQualifierColumn = string.Empty;
                householdAttribute.Description               = "The FellowshipOne household identifier for the person that was imported";
                householdAttribute.DefaultValue              = string.Empty;
                householdAttribute.IsMultiValue              = false;
                householdAttribute.IsRequired                = false;
                householdAttribute.Order                     = 0;

                lookupContext.Attributes.Add(householdAttribute);
                lookupContext.SaveChanges(DisableAuditing);
                personAttributes.Add(householdAttribute);
            }

            var individualAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("F1IndividualId", StringComparison.InvariantCultureIgnoreCase));

            if (individualAttribute == null)
            {
                individualAttribute                           = new Rock.Model.Attribute();
                individualAttribute.Key                       = "F1IndividualId";
                individualAttribute.Name                      = "F1 Individual Id";
                individualAttribute.FieldTypeId               = IntegerFieldTypeId;
                individualAttribute.EntityTypeId              = PersonEntityTypeId;
                individualAttribute.EntityTypeQualifierValue  = string.Empty;
                individualAttribute.EntityTypeQualifierColumn = string.Empty;
                individualAttribute.Description               = "The FellowshipOne individual identifier for the person that was imported";
                individualAttribute.DefaultValue              = string.Empty;
                individualAttribute.IsMultiValue              = false;
                individualAttribute.IsRequired                = false;
                individualAttribute.Order                     = 0;

                lookupContext.Attributes.Add(individualAttribute);
                lookupContext.SaveChanges(DisableAuditing);
                personAttributes.Add(individualAttribute);
            }

            var secondaryEmailAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("SecondaryEmail", StringComparison.InvariantCultureIgnoreCase));

            if (secondaryEmailAttribute == null)
            {
                secondaryEmailAttribute                           = new Rock.Model.Attribute();
                secondaryEmailAttribute.Key                       = "SecondaryEmail";
                secondaryEmailAttribute.Name                      = "Secondary Email";
                secondaryEmailAttribute.FieldTypeId               = TextFieldTypeId;
                secondaryEmailAttribute.EntityTypeId              = PersonEntityTypeId;
                secondaryEmailAttribute.EntityTypeQualifierValue  = string.Empty;
                secondaryEmailAttribute.EntityTypeQualifierColumn = string.Empty;
                secondaryEmailAttribute.Description               = "The secondary email for this person";
                secondaryEmailAttribute.DefaultValue              = string.Empty;
                secondaryEmailAttribute.IsMultiValue              = false;
                secondaryEmailAttribute.IsRequired                = false;
                secondaryEmailAttribute.Order                     = 0;

                lookupContext.Attributes.Add(secondaryEmailAttribute);
                var visitInfoCategory = new CategoryService(lookupContext).Get(visitInfoCategoryId);
                secondaryEmailAttribute.Categories.Add(visitInfoCategory);
                lookupContext.SaveChanges(DisableAuditing);
            }

            var infellowshipLoginAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("InFellowshipLogin", StringComparison.InvariantCultureIgnoreCase));

            if (infellowshipLoginAttribute == null)
            {
                infellowshipLoginAttribute                           = new Rock.Model.Attribute();
                infellowshipLoginAttribute.Key                       = "InFellowshipLogin";
                infellowshipLoginAttribute.Name                      = "InFellowship Login";
                infellowshipLoginAttribute.FieldTypeId               = TextFieldTypeId;
                infellowshipLoginAttribute.EntityTypeId              = PersonEntityTypeId;
                infellowshipLoginAttribute.EntityTypeQualifierValue  = string.Empty;
                infellowshipLoginAttribute.EntityTypeQualifierColumn = string.Empty;
                infellowshipLoginAttribute.Description               = "The InFellowship login for this person";
                infellowshipLoginAttribute.DefaultValue              = string.Empty;
                infellowshipLoginAttribute.IsMultiValue              = false;
                infellowshipLoginAttribute.IsRequired                = false;
                infellowshipLoginAttribute.Order                     = 0;

                // don't add a category as this attribute is only used via the API
                lookupContext.Attributes.Add(infellowshipLoginAttribute);
                lookupContext.SaveChanges(DisableAuditing);
            }

            IndividualIdAttribute      = AttributeCache.Read(individualAttribute.Id);
            HouseholdIdAttribute       = AttributeCache.Read(householdAttribute.Id);
            InFellowshipLoginAttribute = AttributeCache.Read(infellowshipLoginAttribute.Id);
            SecondaryEmailAttribute    = AttributeCache.Read(secondaryEmailAttribute.Id);

            // Set AuthProviderEntityTypeId if Apollos/Infellowship provider exists
            var f1AuthProvider = "cc.newspring.F1.Security.Authentication.F1Migrator";
            var cache          = EntityTypeCache.Read(f1AuthProvider);

            AuthProviderEntityTypeId = cache == null ? (int?)null : cache.Id;

            var aliasIdList = new PersonAliasService(lookupContext).Queryable().AsNoTracking()
                              .Select(pa => new
            {
                PersonAliasId = pa.Id,
                PersonId      = pa.PersonId,
                IndividualId  = pa.ForeignId,
                FamilyRole    = pa.Person.ReviewReasonNote
            }).ToList();
            var householdIdList = attributeValueService.GetByAttributeId(householdAttribute.Id).AsNoTracking()
                                  .Select(av => new
            {
                PersonId    = (int)av.EntityId,
                HouseholdId = av.Value
            }).ToList();

            ImportedPeople = householdIdList.GroupJoin(aliasIdList,
                                                       household => household.PersonId,
                                                       aliases => aliases.PersonId,
                                                       (household, aliases) => new PersonKeys
            {
                PersonAliasId = aliases.Select(a => a.PersonAliasId).FirstOrDefault(),
                PersonId      = household.PersonId,
                IndividualId  = aliases.Select(a => a.IndividualId).FirstOrDefault(),
                HouseholdId   = household.HouseholdId.AsType <int?>(),
                FamilyRoleId  = aliases.Select(a => a.FamilyRole.ConvertToEnum <FamilyRole>(0)).FirstOrDefault()
            }
                                                       ).ToList();

            ImportedBatches = new FinancialBatchService(lookupContext).Queryable().AsNoTracking()
                              .Where(b => b.ForeignId != null)
                              .ToDictionary(t => (int)t.ForeignId, t => (int?)t.Id);
        }
コード例 #27
0
        /// <summary>
        /// Gets the data.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private IQueryable <Rock.Model.Attribute> GetData(RockContext rockContext)
        {
            IQueryable <Rock.Model.Attribute> query = null;

            AttributeService attributeService = new AttributeService(rockContext);

            if (_entityTypeId.HasValue)
            {
                if (_entityTypeId == default(int))
                {
                    // entity type not configured in block or in filter, so get Global Attributes
                    query = attributeService.GetByEntityTypeId(null, true);
                    query = query.Where(t => t.EntityTypeQualifierColumn == null || t.EntityTypeQualifierColumn == "");
                }
                else if (_isEntityTypeConfigured)
                {
                    // entity type is configured in block, so get by the entityType and qualifiers specified in the block settings
                    query = attributeService.GetByEntityTypeQualifier(_entityTypeId, _entityQualifierColumn, _entityQualifierValue, true);
                }
                else
                {
                    // entity type is selected in the filter, so get all the attributes for that entityType. (There is no userfilter for qualifiers, so don't filter by those)
                    query = attributeService.GetByEntityTypeId(_entityTypeId, true);
                }
            }

            // if filtering by block setting of categories
            if (!string.IsNullOrWhiteSpace(GetAttributeValue("CategoryFilter")))
            {
                try
                {
                    var categoryGuids = GetAttributeValue("CategoryFilter").Split(',').Select(Guid.Parse).ToList();

                    query = query.Where(a => a.Categories.Any(c => categoryGuids.Contains(c.Guid)));
                }
                catch { }
            }

            if (ddlAnalyticsEnabled.Visible)
            {
                var filterValue = ddlAnalyticsEnabled.SelectedValue.AsBooleanOrNull();
                if (filterValue.HasValue)
                {
                    query = query.Where(a => (a.IsAnalytic || a.IsAnalyticHistory) == filterValue);
                }
            }

            if (ddlActiveFilter.Visible)
            {
                var filterValue = ddlActiveFilter.SelectedValue.AsBooleanOrNull();
                if (filterValue.HasValue)
                {
                    query = query.Where(a => a.IsActive == filterValue);
                }
            }

            var selectedCategoryIds = new List <int>();

            rFilter.GetUserPreference("Categories").SplitDelimitedValues().ToList().ForEach(s => selectedCategoryIds.Add(int.Parse(s)));
            if (selectedCategoryIds.Any())
            {
                query = query.Where(a => a.Categories.Any(c => selectedCategoryIds.Contains(c.Id)));
            }

            query = query.OrderBy(a => a.Order);

            return(query);
        }
コード例 #28
0
        /// <summary>
        /// Loads the Entity Attribute data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadEntityAttributeValues(CSVInstance csvData)
        {
            var lookupContext           = new RockContext();
            var importedAttributeValues = new AttributeValueService(lookupContext).Queryable().Count(a => a.ForeignKey != null);
            var entityTypes             = EntityTypeCache.All().Where(e => e.IsEntity && e.IsSecured).ToList();
            var attributeService        = new AttributeService(lookupContext);
            var attributeValues         = new List <AttributeValue>();

            var completedItems = 0;
            var addedItems     = 0;

            int?      entityTypeId            = null;
            var       prevEntityTypeName      = string.Empty;
            var       prevAttributeForeignKey = string.Empty;
            var       prevRockKey             = string.Empty;
            Attribute attribute        = null;
            Type      contextModelType = null;

            System.Data.Entity.DbContext contextDbContext = null;
            IService       contextService             = null;
            IHasAttributes entity                     = null;
            var            prevAttributeValueEntityId = string.Empty;

            ReportProgress(0, string.Format("Verifying attribute value import ({0:N0} already imported).", importedAttributeValues));

            string[] row;
            // Uses a look-ahead enumerator: this call will move to the next record immediately
            while ((row = csvData.Database.FirstOrDefault()) != null)
            {
                var entityTypeName           = row[AttributeEntityTypeName];
                var attributeForeignKey      = row[AttributeId];
                var rockKey                  = row[AttributeRockKey];
                var attributeValueForeignKey = row[AttributeValueId];
                var attributeValueEntityId   = row[AttributeValueEntityId];
                var attributeValue           = row[AttributeValue];

                if (!string.IsNullOrWhiteSpace(entityTypeName) &&
                    !string.IsNullOrWhiteSpace(attributeValueEntityId) &&
                    !string.IsNullOrWhiteSpace(attributeValue) &&
                    (!string.IsNullOrEmpty(attributeForeignKey) || !string.IsNullOrEmpty(rockKey)))
                {
                    var findNewEntity = false;

                    if (!entityTypeId.HasValue || !prevEntityTypeName.Equals(entityTypeName, StringComparison.OrdinalIgnoreCase))
                    {
                        entityTypeId       = entityTypes.FirstOrDefault(et => et.Name.Equals(entityTypeName)).Id;
                        prevEntityTypeName = entityTypeName;
                        findNewEntity      = true;

                        contextModelType = entityTypes.FirstOrDefault(et => et.Name.Equals(entityTypeName)).GetEntityType();
                        contextDbContext = Reflection.GetDbContextForEntityType(contextModelType);
                        if (contextDbContext != null)
                        {
                            contextService = Reflection.GetServiceForEntityType(contextModelType, contextDbContext);
                        }
                    }

                    if (entityTypeId.HasValue && contextService != null)
                    {
                        if (!string.IsNullOrWhiteSpace(attributeForeignKey) && !prevAttributeForeignKey.Equals(attributeForeignKey, StringComparison.OrdinalIgnoreCase))
                        {
                            attribute = attributeService.GetByEntityTypeId(entityTypeId).FirstOrDefault(a => a.ForeignKey == attributeForeignKey);
                            prevAttributeForeignKey = attributeForeignKey;
                            prevRockKey             = string.Empty;
                        }
                        else if (string.IsNullOrWhiteSpace(attributeForeignKey))
                        {
                            // if no FK provided force attribute to null so the rockKey is tested
                            attribute = null;
                        }

                        if (attribute == null && !string.IsNullOrWhiteSpace(rockKey) && !prevRockKey.Equals(rockKey, StringComparison.OrdinalIgnoreCase))
                        {
                            attribute               = attributeService.GetByEntityTypeId(entityTypeId).FirstOrDefault(a => a.Key == rockKey);
                            prevRockKey             = rockKey;
                            prevAttributeForeignKey = string.Empty;
                        }

                        if (attribute != null)
                        {
                            // set the fk if it wasn't for some reason
                            if (string.IsNullOrWhiteSpace(attribute.ForeignKey) && !string.IsNullOrWhiteSpace(attributeForeignKey))
                            {
                                var updatedAttributeRockContext = new RockContext();
                                var updatedAttributeService     = new AttributeService(updatedAttributeRockContext);
                                var updatedAttribute            = updatedAttributeService.GetByEntityTypeId(entityTypeId).FirstOrDefault(a => a.Id == attribute.Id);
                                updatedAttribute.ForeignKey = attributeForeignKey;
                                updatedAttribute.ForeignId  = attributeForeignKey.AsIntegerOrNull();
                                updatedAttributeRockContext.SaveChanges(DisableAuditing);
                            }

                            if (entity == null || (findNewEntity || !prevAttributeValueEntityId.Equals(attributeValueEntityId, StringComparison.OrdinalIgnoreCase)))
                            {
                                MethodInfo qryMethod    = contextService.GetType().GetMethod("Queryable", new Type[] { });
                                var        entityQry    = qryMethod.Invoke(contextService, new object[] { }) as IQueryable <IEntity>;
                                var        entityResult = entityQry.Where(e => e.ForeignKey.Equals(attributeValueEntityId, StringComparison.OrdinalIgnoreCase));
                                entity = entityResult.FirstOrDefault() as IHasAttributes;
                                prevAttributeValueEntityId = attributeValueEntityId;
                            }

                            if (entity != null)
                            {
                                var av = CreateEntityAttributeValue(lookupContext, attribute, entity, attributeValue, attributeValueForeignKey);

                                if (av != null && !attributeValues.Where(e => e.EntityId == av.EntityId).Where(a => a.AttributeId == av.AttributeId).Any())
                                {
                                    attributeValues.Add(av);
                                    addedItems++;
                                }
                            }
                        }
                    }
                }

                completedItems++;
                if (completedItems % (ReportingNumber * 10) < 1)
                {
                    ReportProgress(0, string.Format("{0:N0} attribute values processed.", completedItems));
                }

                if (completedItems % ReportingNumber < 1)
                {
                    SaveAttributeValues(lookupContext, attributeValues);
                    attributeValues.Clear();
                    lookupContext.Dispose();
                    lookupContext    = new RockContext();
                    attributeService = new AttributeService(lookupContext);

                    ReportPartialProgress();
                }
            }

            if (attributeValues.Any())
            {
                SaveAttributeValues(lookupContext, attributeValues);
            }

            ReportProgress(100, string.Format("Finished attribute value import: {0:N0} attribute values imported.", addedItems));
            return(completedItems);
        }
コード例 #29
0
        /// <summary>
        /// Loads Rock data that's used globally by the transform
        /// </summary>
        private void LoadExistingRockData()
        {
            var lookupContext         = new RockContext();
            var attributeValueService = new AttributeValueService(lookupContext);
            var attributeService      = new AttributeService(lookupContext);

            IntegerFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.INTEGER)).Id;
            TextFieldTypeId    = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.TEXT)).Id;
            PersonEntityTypeId = EntityTypeCache.Read("Rock.Model.Person").Id;
            CampusList         = CampusCache.All(lookupContext);

            int attributeEntityTypeId = EntityTypeCache.Read("Rock.Model.Attribute").Id;
            int batchEntityTypeId     = EntityTypeCache.Read("Rock.Model.FinancialBatch").Id;
            int userLoginTypeId       = EntityTypeCache.Read("Rock.Model.UserLogin").Id;

            int visitInfoCategoryId = new CategoryService(lookupContext).GetByEntityTypeId(attributeEntityTypeId)
                                      .Where(c => c.Name == "Visit Information").Select(c => c.Id).FirstOrDefault();

            // Look up and create attributes for F1 unique identifiers if they don't exist
            var personAttributes = attributeService.GetByEntityTypeId(PersonEntityTypeId).ToList();

            var householdAttribute = personAttributes.FirstOrDefault(a => a.Key == "F1HouseholdId");

            if (householdAttribute == null)
            {
                householdAttribute                           = new Rock.Model.Attribute();
                householdAttribute.Key                       = "F1HouseholdId";
                householdAttribute.Name                      = "F1 Household Id";
                householdAttribute.FieldTypeId               = IntegerFieldTypeId;
                householdAttribute.EntityTypeId              = PersonEntityTypeId;
                householdAttribute.EntityTypeQualifierValue  = string.Empty;
                householdAttribute.EntityTypeQualifierColumn = string.Empty;
                householdAttribute.Description               = "The FellowshipOne household identifier for the person that was imported";
                householdAttribute.DefaultValue              = string.Empty;
                householdAttribute.IsMultiValue              = false;
                householdAttribute.IsRequired                = false;
                householdAttribute.Order                     = 0;

                lookupContext.Attributes.Add(householdAttribute);
                lookupContext.SaveChanges(DisableAudit);
                personAttributes.Add(householdAttribute);
            }

            var individualAttribute = personAttributes.FirstOrDefault(a => a.Key == "F1IndividualId");

            if (individualAttribute == null)
            {
                individualAttribute                           = new Rock.Model.Attribute();
                individualAttribute.Key                       = "F1IndividualId";
                individualAttribute.Name                      = "F1 Individual Id";
                individualAttribute.FieldTypeId               = IntegerFieldTypeId;
                individualAttribute.EntityTypeId              = PersonEntityTypeId;
                individualAttribute.EntityTypeQualifierValue  = string.Empty;
                individualAttribute.EntityTypeQualifierColumn = string.Empty;
                individualAttribute.Description               = "The FellowshipOne individual identifier for the person that was imported";
                individualAttribute.DefaultValue              = string.Empty;
                individualAttribute.IsMultiValue              = false;
                individualAttribute.IsRequired                = false;
                individualAttribute.Order                     = 0;

                lookupContext.Attributes.Add(individualAttribute);
                lookupContext.SaveChanges(DisableAudit);
                personAttributes.Add(individualAttribute);
            }

            var secondaryEmailAttribute = personAttributes.FirstOrDefault(a => a.Key == "SecondaryEmail");

            if (secondaryEmailAttribute == null)
            {
                secondaryEmailAttribute                           = new Rock.Model.Attribute();
                secondaryEmailAttribute.Key                       = "SecondaryEmail";
                secondaryEmailAttribute.Name                      = "Secondary Email";
                secondaryEmailAttribute.FieldTypeId               = TextFieldTypeId;
                secondaryEmailAttribute.EntityTypeId              = PersonEntityTypeId;
                secondaryEmailAttribute.EntityTypeQualifierValue  = string.Empty;
                secondaryEmailAttribute.EntityTypeQualifierColumn = string.Empty;
                secondaryEmailAttribute.Description               = "The secondary email for this person";
                secondaryEmailAttribute.DefaultValue              = string.Empty;
                secondaryEmailAttribute.IsMultiValue              = false;
                secondaryEmailAttribute.IsRequired                = false;
                secondaryEmailAttribute.Order                     = 0;

                lookupContext.Attributes.Add(secondaryEmailAttribute);
                var visitInfoCategory = new CategoryService(lookupContext).Get(visitInfoCategoryId);
                secondaryEmailAttribute.Categories.Add(visitInfoCategory);
                lookupContext.SaveChanges(DisableAudit);
            }

            IndividualAttributeId     = individualAttribute.Id;
            HouseholdAttributeId      = householdAttribute.Id;
            SecondaryEmailAttributeId = secondaryEmailAttribute.Id;

            ReportProgress(0, "Checking for existing data...");
            var listHouseholdId  = attributeValueService.GetByAttributeId(householdAttribute.Id).Select(av => new { PersonId = av.EntityId, HouseholdId = av.Value }).ToList();
            var listIndividualId = attributeValueService.GetByAttributeId(individualAttribute.Id).Select(av => new { PersonId = av.EntityId, IndividualId = av.Value }).ToList();

            // var listHouseholdId = new PersonService().Queryable().Select( )

            ImportedPeople = listHouseholdId.GroupJoin(listIndividualId,
                                                       household => household.PersonId,
                                                       individual => individual.PersonId,
                                                       (household, individual) => new ImportedPerson
            {
                PersonAliasId = household.PersonId,
                HouseholdId   = household.HouseholdId.AsType <int?>(),
                IndividualId  = individual.Select(i => i.IndividualId.AsType <int?>()).FirstOrDefault()
            }
                                                       ).ToList();

            ImportedBatches = new FinancialBatchService(lookupContext).Queryable()
                              .Where(b => b.ForeignId != null)
                              .Select(b => new { F1Id = b.ForeignId, BatchId = b.Id })
                              .ToDictionary(t => t.F1Id.AsType <int>(), t => (int?)t.BatchId);
        }
コード例 #30
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)
        {
            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;
        }