/// <summary>
        /// Handles the Save filters event.
        /// </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 mdFilter_SaveClick(object sender, EventArgs e)
        {
            Rock.Model.Attribute attribute = null;

            // Sets the attribute to use the "CustomSetting" attribute
            var entityTypeId = EntityTypeCache.Get(Rock.SystemGuid.EntityType.ATTRIBUTE).Id;
            var entityId     = EntityTypeCache.Get(Rock.SystemGuid.EntityType.BLOCK).Id;

            edtFilter.CategoryIds = CategoryCache.All()
                                    .Where(c =>
                                           c.Name == "CustomSetting" &&
                                           c.EntityTypeId == entityTypeId &&
                                           c.EntityTypeQualifierColumn == "EntityTypeId" &&
                                           c.EntityTypeQualifierValue == entityId.ToString())
                                    .Select(c => c.Id);

            // ISSUE JME - When adding a new attribute the edtFilter does not load here with it's default value setting.
            // currently you need to add the attribute then edit it again to add a default value.
            attribute = Helper.SaveAttributeEdits(edtFilter, _blockTypeEntityId, "Id", _block.Id.ToString());

            // Attribute will be null if it was not valid
            if (attribute == null)
            {
                return;
            }

            mdFilter.Hide();
            BindGrid();
        }
Example #2
0
        private void BindMinistryList()
        {
            AttributeService attributeService = new AttributeService(new RockContext());

            Rock.Model.Attribute ministryAttribute = attributeService.Get(MinistryAreaAttributeIDSetting);

            if (ministryAttribute != null)
            {
                ddlMinistry.Items.Clear();
                if (!UserCanEdit)
                {
                    CurrentPerson.LoadAttributes();
                    var ministryGuids = CurrentPerson.AttributeValues[AttributeCache.Get(MinistryAreaAttributeIDSetting).Key].Value.Split(',').AsGuidList();
                    ddlMinistry.DataSource = DefinedValueCache.All().Where(dv => ministryGuids.Contains(dv.Guid)).OrderBy(l => l.Value);
                }
                else
                {
                    ddlMinistry.DataSource = definedTypeService.Get(ministryAttribute.AttributeQualifiers.Where(aq => aq.Key == "definedtype").FirstOrDefault().Value.AsInteger()).DefinedValues.OrderBy(l => l.Value);
                }
                ddlMinistry.DataTextField  = "Value";
                ddlMinistry.DataValueField = "Id";
                ddlMinistry.DataBind();

                ddlMinistry.Items.Insert(0, new ListItem("<All>", "0"));
                ddlMinistry.SelectedValue = "0";
            }
        }
        /// <summary>
        /// Handles the Add actions event.
        /// </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 gFilters_Add(object sender, EventArgs e)
        {
            var rockContext      = new RockContext();
            var attributeService = new AttributeService(rockContext);

            // Reset attribute editor fields.
            edtFilter.Name            = string.Empty;
            edtFilter.Key             = string.Empty;
            edtFilter.AbbreviatedName = "";

            Rock.Model.Attribute attribute = new Rock.Model.Attribute();

            // Set attribute fields to those from a new attribute to made sure the AttributeEditor / ViewState has no leftover values.
            edtFilter.AttributeGuid       = attribute.Guid;
            edtFilter.AttributeId         = attribute.Id;
            edtFilter.IsFieldTypeEditable = true;
            edtFilter.SetAttributeFieldType(FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT).Id, null);

            edtFilter.ReservedKeyNames = AttributeCache.AllForEntityType(_blockTypeEntityId)
                                         .Where(a =>
                                                a.EntityTypeQualifierColumn == "Id" &&
                                                a.EntityTypeQualifierValue == _block.Id.ToString())
                                         .Select(a => a.Key)
                                         .Distinct()
                                         .ToList();

            mdFilter.Title = "Add Filter";
            mdFilter.Show();
        }
Example #4
0
        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        public static void SetValue(string key, string value)
        {
            var rockContext      = new Rock.Data.RockContext();
            var attributeService = new AttributeService(rockContext);
            var attribute        = attributeService.GetSystemSetting(key);

            if (attribute == null)
            {
                attribute             = new Rock.Model.Attribute();
                attribute.FieldTypeId = FieldTypeCache.Get(new Guid(SystemGuid.FieldType.TEXT)).Id;
                attribute.EntityTypeQualifierColumn = Rock.Model.Attribute.SYSTEM_SETTING_QUALIFIER;
                attribute.EntityTypeQualifierValue  = string.Empty;
                attribute.Key          = key;
                attribute.Name         = key.SplitCase();
                attribute.DefaultValue = value;
                attributeService.Add(attribute);
            }
            else
            {
                attribute.DefaultValue = value;
            }

            // NOTE: Service Layer will automatically update this Cache (see Attribute.cs UpdateCache)
            rockContext.SaveChanges();

            if (key == Rock.SystemKey.SystemSetting.START_DAY_OF_WEEK)
            {
                RockDateTime.FirstDayOfWeek = value.ConvertToEnumOrNull <DayOfWeek>() ?? RockDateTime.DefaultFirstDayOfWeek;
            }
        }
Example #5
0
        /// <summary>
        /// Gs the defined type attributes_ show edit.
        /// </summary>
        /// <param name="attributeGuid">The attribute GUID.</param>
        protected void gDefinedTypeAttributes_ShowEdit(Guid attributeGuid)
        {
            pnlDetails.Visible = false;
            vsDetails.Enabled  = false;
            pnlDefinedTypeAttributes.Visible = true;

            Attribute attribute;

            if (attributeGuid.Equals(Guid.Empty))
            {
                attribute             = new Attribute();
                attribute.FieldTypeId = FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT).Id;
                edtDefinedTypeAttributes.ActionTitle = ActionTitle.Add("attribute for defined type " + tbTypeName.Text);
            }
            else
            {
                AttributeService attributeService = new AttributeService(new RockContext());
                attribute = attributeService.Get(attributeGuid);
                edtDefinedTypeAttributes.ActionTitle = ActionTitle.Edit("attribute for defined type " + tbTypeName.Text);
            }

            edtDefinedTypeAttributes.ReservedKeyNames = new AttributeService(new RockContext())
                                                        .GetByEntityTypeId(new DefinedValue().TypeId, true).AsQueryable()
                                                        .Where(a =>
                                                               a.EntityTypeQualifierColumn.Equals("DefinedTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                               a.EntityTypeQualifierValue.Equals(hfDefinedTypeId.Value) &&
                                                               !a.Guid.Equals(attributeGuid))
                                                        .Select(a => a.Key)
                                                        .Distinct()
                                                        .ToList();

            edtDefinedTypeAttributes.SetAttributeProperties(attribute, typeof(DefinedValue));

            this.HideSecondaryBlocks(true);
        }
Example #6
0
        /// <summary>
        /// gs the page attributes show edit.
        /// </summary>
        /// <param name="attributeGuid">The attribute unique identifier.</param>
        protected void gPageAttributes_ShowEdit(Guid attributeGuid)
        {
            Attribute attribute;

            if (attributeGuid.Equals(Guid.Empty))
            {
                attribute                     = new Attribute();
                attribute.FieldTypeId         = FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT).Id;
                edtPageAttributes.ActionTitle = ActionTitle.Add("attribute for pages of site " + tbSiteName.Text);
            }
            else
            {
                attribute = PageAttributesState.First(a => a.Guid.Equals(attributeGuid));
                edtPageAttributes.ActionTitle = ActionTitle.Edit("attribute for pages of site " + tbSiteName.Text);
            }

            var reservedKeyNames = new List <string>();

            PageAttributesState.Where(a => !a.Guid.Equals(attributeGuid)).Select(a => a.Key).ToList().ForEach(a => reservedKeyNames.Add(a));
            edtPageAttributes.ReservedKeyNames = reservedKeyNames.ToList();

            edtPageAttributes.SetAttributeProperties(attribute, typeof(Rock.Model.Page));

            dlgPageAttribute.Show();
            HideSecondaryBlocks(true);
        }
Example #7
0
        private void SaveWidgityItemAttribute()
        {
            var attribute = new Rock.Model.Attribute();

            edtWidgityItemAttributes.GetAttributeProperties(attribute);

            attribute.EntityTypeId = EntityTypeCache.Get(typeof(WidgityItem)).Id;
            attribute.EntityTypeQualifierColumn = "WidgityTypeId";
            attribute.EntityTypeQualifierValue  = PageParameter(PageParameterKey.WidgityTypeId);

            var existingAttribute = WidgityItemAttributes.Where(a => a.Guid == attribute.Guid).FirstOrDefault();

            if (existingAttribute == null)   //new attribute
            {
                attribute.Order = WidgityItemAttributes.Any() ? WidgityItemAttributes.Max(a => a.Order) + 1 : 0;
                WidgityItemAttributes.Add(attribute);
            }
            else //existing attribute
            {
                foreach (var att in WidgityItemAttributes)
                {
                    if (att.Guid == existingAttribute.Guid)
                    {
                        var index = WidgityItemAttributes.IndexOf(att);
                        WidgityItemAttributes.Remove(att);
                        WidgityItemAttributes.Insert(index, attribute);
                        break;
                    }
                }
            }
            SaveState();
        }
        /// <summary>
        /// Handles the Click event of the btnSaveAttribute 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 btnSaveAttribute_Click(object sender, EventArgs e)
        {
            Attribute attribute = new Attribute();

            attribute.Guid         = new Guid(hfAttributeGuid.Value);
            attribute.Key          = tbAttributeKey.Text;
            attribute.Name         = tbAttributeName.Text;
            attribute.Category     = tbAttributeCategory.Text;
            attribute.Description  = tbAttributeDescription.Text;
            attribute.DefaultValue = tbAttributeDefaultValue.Text;
            attribute.FieldTypeId  = int.Parse(ddlAttributeFieldType.SelectedValue);
            attribute.IsMultiValue = cbAttributeMultiValue.Checked;
            attribute.IsRequired   = cbAttributeRequired.Checked;

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

            AttributesState.RemoveDto <AttributeDto>(attribute.Guid);
            AttributesState.Add(new AttributeDto(attribute));

            pnlDetails.Visible         = true;
            pnlList.Visible            = false;
            pnlAdTypeAttribute.Visible = false;

            BindMarketingCampaignAdAttributeTypeGrid();
        }
Example #9
0
        /// <summary>
        /// Gets the attribute properties.
        /// </summary>
        /// <param name="attribute">The attribute.</param>
        public void GetAttributeProperties(Rock.Model.Attribute attribute)
        {
            if (attribute != null)
            {
                attribute.Id           = this.AttributeId ?? 0;
                attribute.Guid         = this.AttributeGuid;
                attribute.Name         = this.Name;
                attribute.Key          = this.Key;
                attribute.Description  = this.Description;
                attribute.FieldTypeId  = this.FieldTypeId ?? 0;
                attribute.IsMultiValue = false;
                attribute.IsRequired   = this.Required;
                attribute.IsGridColumn = this.ShowInGrid;

                attribute.Categories.Clear();
                new CategoryService().Queryable().Where(c => this.CategoryIds.Contains(c.Id)).ToList().ForEach(c =>
                                                                                                               attribute.Categories.Add(c));

                attribute.AttributeQualifiers.Clear();
                foreach (var qualifier in Qualifiers)
                {
                    AttributeQualifier attributeQualifier = new AttributeQualifier();
                    attributeQualifier.IsSystem = false;
                    attributeQualifier.Key      = qualifier.Key;
                    attributeQualifier.Value    = qualifier.Value.Value ?? string.Empty;
                    attribute.AttributeQualifiers.Add(attributeQualifier);
                }

                attribute.DefaultValue = this.DefaultValue;
            }
        }
Example #10
0
        /// <summary>
        /// Handles the SaveClick event of the mdAttribute 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 mdAttribute_SaveClick(object sender, EventArgs e)
        {
            Rock.Model.Attribute attribute = null;

            if (_configuredType)
            {
                attribute = Rock.Attribute.Helper.SaveAttributeEdits(edtAttribute, _entityTypeId, _entityQualifierColumn, _entityQualifierValue);
            }
            else
            {
                attribute = Rock.Attribute.Helper.SaveAttributeEdits(edtAttribute, ddlAttrEntityType.SelectedValueAsInt(), tbAttrQualifierField.Text, tbAttrQualifierValue.Text);
            }

            // Attribute will be null if it was not valid
            if (attribute == null)
            {
                return;
            }

            AttributeCache.FlushEntityAttributes();

            HideDialog();

            BindGrid();
        }
Example #11
0
        /// <summary>
        /// Copies from model.
        /// </summary>
        /// <param name="attribute">The attribute.</param>
        /// <param name="qualifiers">The qualifiers.</param>
        public void CopyFromModel(Rock.Model.Attribute attribute, Dictionary <string, string> qualifiers)
        {
            this.Id           = attribute.Id;
            this.Guid         = attribute.Guid;
            this.IsSystem     = attribute.IsSystem;
            this.FieldTypeId  = attribute.FieldTypeId;
            this.EntityTypeId = attribute.EntityTypeId;
            this.EntityTypeQualifierColumn = attribute.EntityTypeQualifierColumn;
            this.EntityTypeQualifierValue  = attribute.EntityTypeQualifierValue;
            this.Key          = attribute.Key;
            this.Name         = attribute.Name;
            this.Description  = attribute.Description;
            this.Order        = attribute.Order;
            this.IsGridColumn = attribute.IsGridColumn;
            this.DefaultValue = attribute.DefaultValue;
            this.IsMultiValue = attribute.IsMultiValue;
            this.IsRequired   = attribute.IsRequired;

            this.TypeId           = attribute.TypeId;
            this.TypeName         = attribute.TypeName;
            this.SupportedActions = attribute.SupportedActions;

            this.QualifierValues = new Dictionary <string, ConfigurationValue>();
            foreach (var qualifier in qualifiers)
            {
                this.QualifierValues.Add(qualifier.Key, new ConfigurationValue(qualifier.Value));
            }

            this.categoryIds = attribute.Categories.Select(c => c.Id).ToList();
        }
        /// <summary>
        /// Gs the marketing campaign ad attribute type_ show edit.
        /// </summary>
        /// <param name="attributeId">The attribute id.</param>
        protected void gItemAttributes_ShowEdit(Guid attributeGuid)
        {
            Attribute attribute;

            if (attributeGuid.Equals(Guid.Empty))
            {
                attribute                     = new Attribute();
                attribute.FieldTypeId         = FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT).Id;
                edtItemAttributes.ActionTitle = ActionTitle.Add(tbName.Text + " Item Attribute");
            }
            else
            {
                attribute = ItemAttributesState.First(a => a.Guid.Equals(attributeGuid));
                edtItemAttributes.ActionTitle = ActionTitle.Edit(tbName.Text + " Item Attribute");
            }

            edtItemAttributes.ReservedKeyNames = ItemAttributesState.Where(a => !a.Guid.Equals(attributeGuid)).Select(a => a.Key).ToList();

            edtItemAttributes.SetAttributeProperties(attribute, typeof(ContentChannelItem));

            // always enable the display of the indexing option as the channel decides whether or not to index not the type
            edtItemAttributes.IsIndexingEnabledVisible = true;

            ShowDialog("ItemAttributes", true);
        }
Example #13
0
        /// <summary>
        /// Saves any attribute edits made using an Attribute Editor control
        /// </summary>
        /// <param name="edtAttribute">The edt attribute.</param>
        /// <param name="entityTypeId">The entity type identifier.</param>
        /// <param name="entityTypeQualifierColumn">The entity type qualifier column.</param>
        /// <param name="entityTypeQualifierValue">The entity type qualifier value.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        /// <remarks>
        /// If a rockContext value is included, this method will save any previous changes made to the context
        /// </remarks>
        public static Rock.Model.Attribute SaveAttributeEdits(AttributeEditor edtAttribute, int?entityTypeId, string entityTypeQualifierColumn, string entityTypeQualifierValue, RockContext rockContext = null)
        {
            // Create and update a new attribute object with new values
            var newAttribute = new Rock.Model.Attribute();

            edtAttribute.GetAttributeProperties(newAttribute);

            rockContext = rockContext ?? new RockContext();
            var internalAttributeService = new AttributeService(rockContext);

            Rock.Model.Attribute attribute = null;

            if (newAttribute.Id > 0)
            {
                attribute = internalAttributeService.Get(newAttribute.Id);
            }

            if (attribute == null)
            {
                newAttribute.Order = internalAttributeService.Queryable().Max(a => a.Order) + 1;
            }
            else
            {
                newAttribute.Order = attribute.Order;
            }

            return(SaveAttributeEdits(newAttribute, entityTypeId, entityTypeQualifierColumn, entityTypeQualifierValue, rockContext));
        }
Example #14
0
        /// <summary>
        /// gs the item attributes show edit.
        /// </summary>
        /// <param name="attributeGuid">The attribute unique identifier.</param>
        protected void gItemAttributes_ShowEdit(Guid attributeGuid)
        {
            Attribute attribute;

            if (attributeGuid.Equals(Guid.Empty))
            {
                attribute                     = new Attribute();
                attribute.FieldTypeId         = FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT).Id;
                edtItemAttributes.ActionTitle = ActionTitle.Add(tbName.Text + " Item Attribute");
            }
            else
            {
                attribute = ItemAttributesState.First(a => a.Guid.Equals(attributeGuid));
                edtItemAttributes.ActionTitle = ActionTitle.Edit(tbName.Text + " Item Attribute");
            }


            List <string> reservedKeys = ItemAttributesState.Where(a => !a.Guid.Equals(attributeGuid)).Select(a => a.Key).ToList();

            reservedKeys.AddRange(ItemInheritedKey);
            edtItemAttributes.ReservedKeyNames = reservedKeys;

            edtItemAttributes.SetAttributeProperties(attribute, typeof(ContentChannelItem));

            edtItemAttributes.IsIndexingEnabledVisible = cbIndexChannel.Visible && cbIndexChannel.Checked;

            ShowDialog("ItemAttributes", true);
        }
        /// <summary>
        /// Handles the Delete event of the gWorkflowTypeAttributes control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gWorkflowTypeAttributes_Delete(object sender, RowEventArgs e)
        {
            Guid             attributeGuid    = (Guid)e.RowKeyValue;
            AttributeService attributeService = new AttributeService();
            Attribute        attribute        = attributeService.Get(attributeGuid);

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

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

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

            qryParams["workflowTypeId"] = hfWorkflowTypeId.Value;
            NavigateToPage(RockPage.Guid, qryParams);
        }
Example #16
0
        /// <summary>
        /// Gs the group type attributes_ show edit.
        /// </summary>
        /// <param name="attributeGuid">The attribute GUID.</param>
        protected void gAttributes_ShowEdit(Guid attributeGuid)
        {
            Attribute attribute;

            if (attributeGuid.Equals(Guid.Empty))
            {
                attribute                 = new Attribute();
                attribute.FieldTypeId     = FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT).Id;
                edtAttributes.ActionTitle = ActionTitle.Add("attribute for matrix attributes that use matrix template " + tbName.Text);
            }
            else
            {
                attribute = AttributesState.First(a => a.Guid.Equals(attributeGuid));
                edtAttributes.ActionTitle = ActionTitle.Edit("attribute for matrix attributes that use matrix template " + tbName.Text);
            }

            var reservedKeyNames = new List <string>();

            AttributesState.Where(a => !a.Guid.Equals(attributeGuid)).Select(a => a.Key).ToList().ForEach(a => reservedKeyNames.Add(a));
            edtAttributes.ReservedKeyNames = reservedKeyNames.ToList();

            edtAttributes.ExcludedFieldTypes = new FieldTypeCache[] { FieldTypeCache.Read <MatrixFieldType>() };
            edtAttributes.SetAttributeProperties(attribute, typeof(AttributeMatrixTemplate));

            dlgAttribute.Show();
        }
        /// <summary>
        /// Gs the marketing campaign ad attribute type_ show edit.
        /// </summary>
        /// <param name="attributeId">The attribute id.</param>
        protected void gMarketingCampaignAdAttributeType_ShowEdit(Guid attributeGuid)
        {
            pnlDetails.Visible         = false;
            pnlList.Visible            = false;
            pnlAdTypeAttribute.Visible = true;

            if (attributeGuid != Guid.Empty)
            {
                Attribute attribute = AttributesState.First(a => a.Guid.Equals(attributeGuid)).ToModel();
                lAttributeActionTitle.Text          = ActionTitle.Edit("attribute for ad type " + tbName.Text);
                hfAttributeGuid.Value               = attribute.Guid.ToString();
                tbAttributeKey.Text                 = attribute.Key;
                tbAttributeName.Text                = attribute.Name;
                tbAttributeCategory.Text            = attribute.Category;
                tbAttributeDescription.Text         = attribute.Description;
                tbAttributeDefaultValue.Text        = attribute.DefaultValue;
                ddlAttributeFieldType.SelectedValue = attribute.FieldTypeId.ToString();
                cbAttributeMultiValue.Checked       = attribute.IsMultiValue;
                cbAttributeRequired.Checked         = attribute.IsRequired;
            }
            else
            {
                hfAttributeGuid.Value         = Guid.NewGuid().ToString();
                lAttributeActionTitle.Text    = ActionTitle.Add("attribute for ad type " + tbName.Text);
                tbAttributeKey.Text           = string.Empty;
                tbAttributeName.Text          = string.Empty;
                tbAttributeCategory.Text      = string.Empty;
                tbAttributeDescription.Text   = string.Empty;
                tbAttributeDefaultValue.Text  = string.Empty;
                cbAttributeMultiValue.Checked = false;
                cbAttributeRequired.Checked   = false;
            }
        }
        /// <summary>
        /// Gs the defined type attributes_ show edit.
        /// </summary>
        /// <param name="attributeGuid">The attribute GUID.</param>
        protected void gDefinedTypeAttributes_ShowEdit(Guid attributeGuid)
        {
            pnlDetails.Visible = false;
            vsDetails.Enabled  = false;
            pnlDefinedTypeAttributes.Visible = true;

            Attribute attribute;

            if (attributeGuid.Equals(Guid.Empty))
            {
                attribute             = new Attribute();
                attribute.FieldTypeId = FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT).Id;
                edtDefinedTypeAttributes.ActionTitle = ActionTitle.Add("attribute for defined type " + tbTypeName.Text);
            }
            else
            {
                AttributeService attributeService = new AttributeService();
                attribute = attributeService.Get(attributeGuid);
                edtDefinedTypeAttributes.ActionTitle = ActionTitle.Edit("attribute for defined type " + tbTypeName.Text);
            }

            edtDefinedTypeAttributes.SetAttributeProperties(attribute, typeof(DefinedValue));

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

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

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

            AttributeCache.FlushEntityAttributes();

            BindDefinedTypeAttributesGrid();
        }
Example #20
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)
        {
            Rock.Model.Attribute attribute = null;

            if (_configuredType)
            {
                attribute = Rock.Attribute.Helper.SaveAttributeEdits(edtAttribute,
                                                                     _entityTypeId, _entityQualifierColumn, _entityQualifierValue, CurrentPersonId);
            }
            else
            {
                attribute = Rock.Attribute.Helper.SaveAttributeEdits(edtAttribute,
                                                                     ddlAttrEntityType.SelectedValueAsInt(), tbAttrQualifierField.Text, tbAttrQualifierValue.Text, CurrentPersonId);
            }

            // Attribute will be null if it was not valid
            if (attribute == null)
            {
                return;
            }

            BindGrid();

            pnlDetails.Visible = false;
            pnlList.Visible    = true;
        }
Example #21
0
        /// <summary>
        /// Handles the Save filters event.
        /// </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 mdFilter_SaveClick(object sender, EventArgs e)
        {
            Rock.Model.Attribute attribute = null;

            // sets the attribute to use the "CustomSetting" attribute
            var entityTypeId = EntityTypeCache.Get(Rock.SystemGuid.EntityType.ATTRIBUTE).Id;
            var entityId     = EntityTypeCache.Get(Rock.SystemGuid.EntityType.BLOCK).Id;

            edtFilter.CategoryIds = new CategoryService(new RockContext()).Queryable().Where(c => c.Name == "CustomSetting" &&
                                                                                             c.EntityTypeId == entityTypeId &&
                                                                                             c.EntityTypeQualifierColumn == "EntityTypeId" &&
                                                                                             c.EntityTypeQualifierValue == entityId.ToString())
                                    .Select(c => c.Id);

            attribute = Helper.SaveAttributeEdits(edtFilter, _blockTypeEntityId, "Id", _block.Id.ToString());

            // Attribute will be null if it was not valid
            if (attribute == null)
            {
                return;
            }

            mdFilter.Hide();
            BindGrid();
        }
Example #22
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="attributeId">The attribute id.</param>
        protected void ShowEdit(int attributeId)
        {
            var attributeModel = new AttributeService().Get(attributeId);

            if (attributeModel == null)
            {
                lAttributeTitle.Text = ("Add Attribute").FormatAsHtmlTitle();

                attributeModel             = new Rock.Model.Attribute();
                attributeModel.FieldTypeId = FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT).Id;

                if (!_configuredType)
                {
                    int entityTypeId = int.MinValue;
                    if (int.TryParse(rFilter.GetUserPreference("Entity Type"), out entityTypeId) && entityTypeId > 0)
                    {
                        attributeModel.EntityTypeId = entityTypeId;
                    }
                }

                List <int> selectedCategoryIds = cpCategoriesFilter.SelectedValuesAsInt().ToList();
                new CategoryService().Queryable().Where(c => selectedCategoryIds.Contains(c.Id)).ToList().ForEach(c =>
                                                                                                                  attributeModel.Categories.Add(c));
                edtAttribute.ActionTitle = Rock.Constants.ActionTitle.Add(Rock.Model.Attribute.FriendlyTypeName);
            }
            else
            {
                edtAttribute.ActionTitle = Rock.Constants.ActionTitle.Edit(Rock.Model.Attribute.FriendlyTypeName);
                lAttributeTitle.Text     = ("Edit " + attributeModel.Name).FormatAsHtmlTitle();
            }

            Type type = null;

            if (_entityTypeId.HasValue)
            {
                type = EntityTypeCache.Read(_entityTypeId.Value).GetEntityType();
            }
            edtAttribute.SetAttributeProperties(attributeModel, type);

            if (_configuredType)
            {
                ddlAttrEntityType.Visible    = false;
                tbAttrQualifierField.Visible = false;
                tbAttrQualifierValue.Visible = false;
            }
            else
            {
                ddlAttrEntityType.Visible    = true;
                tbAttrQualifierField.Visible = true;
                tbAttrQualifierValue.Visible = true;

                ddlAttrEntityType.SetValue(attributeModel.EntityTypeId.HasValue ? attributeModel.EntityTypeId.Value.ToString() : "0");
                tbAttrQualifierField.Text = attributeModel.EntityTypeQualifierColumn;
                tbAttrQualifierValue.Text = attributeModel.EntityTypeQualifierValue;
            }

            pnlList.Visible    = false;
            pnlDetails.Visible = true;
        }
Example #23
0
        private List <DefinedValueCache> GetMinistryAreas()
        {
            AttributeService attributeService = new AttributeService(new Rock.Data.RockContext());

            Rock.Model.Attribute ministryArea = attributeService.Get(MinistryAreaAttributeGuid.Value);

            return(DefinedTypeCache.Get(ministryArea.AttributeQualifiers.Where(aq => aq.Key == "definedtype").Select(aq => aq.Value).FirstOrDefault().AsInteger()).DefinedValues.ToList());
        }
Example #24
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            using (new UnitOfWorkScope())
            {
                RockTransactionScope.WrapTransaction(() =>
                {
                    var attributeService           = new AttributeService();
                    Rock.Model.Attribute attribute = null;

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

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

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

                    edtAttribute.GetAttributeProperties(attribute);

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

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

            BindGrid();

            pnlDetails.Visible = false;
            pnlList.Visible    = true;
        }
Example #25
0
        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        /// <param name="currentPersonId">The current person id.</param>
        /// <param name="saveValue">if set to <c>true</c> [save value].</param>
        public void SetValue(string key, string value, int?currentPersonId, bool saveValue)
        {
            if (saveValue)
            {
                using (new Rock.Data.UnitOfWorkScope())
                {
                    // Save new value
                    var attributeValueService = new AttributeValueService();
                    var attributeValue        = attributeValueService.GetGlobalAttributeValue(key);

                    if (attributeValue == null)
                    {
                        var attributeService = new AttributeService();
                        var attribute        = attributeService.GetGlobalAttribute(key);
                        if (attribute == null)
                        {
                            attribute             = new Rock.Model.Attribute();
                            attribute.FieldTypeId = FieldTypeCache.Read(new Guid(SystemGuid.FieldType.TEXT)).Id;
                            attribute.EntityTypeQualifierColumn = string.Empty;
                            attribute.EntityTypeQualifierValue  = string.Empty;
                            attribute.Key  = key;
                            attribute.Name = key.SplitCase();
                            attributeService.Add(attribute, currentPersonId);
                            attributeService.Save(attribute, currentPersonId);

                            Attributes.Add(AttributeCache.Read(attribute.Id));
                        }

                        attributeValue = new AttributeValue();
                        attributeValueService.Add(attributeValue, currentPersonId);
                        attributeValue.IsSystem    = false;
                        attributeValue.AttributeId = attribute.Id;

                        if (!AttributeValues.Keys.Contains(key))
                        {
                            AttributeValues.Add(key, new KeyValuePair <string, string>(attribute.Name, value));
                        }
                    }

                    attributeValue.Value = value;
                    attributeValueService.Save(attributeValue, currentPersonId);
                }
            }

            var attributeCache = Attributes.FirstOrDefault(a => a.Key.Equals(key, StringComparison.OrdinalIgnoreCase));

            if (attributeCache != null)   // (Should never be null)
            {
                if (AttributeValues.Keys.Contains(key))
                {
                    AttributeValues[key] = new KeyValuePair <string, string>(attributeCache.Name, value);
                }
                else
                {
                    AttributeValues.Add(key, new KeyValuePair <string, string>(attributeCache.Name, value));
                }
            }
        }
Example #26
0
        /// <summary>
        /// Displays the edit list.
        /// </summary>
        private void DisplayEditList()
        {
            lEditHeader.Text = GetAttributeValue("EditHeader");
            lEditFooter.Text = GetAttributeValue("EditFooter");

            if (_definedType != null)
            {
                using (var rockContext = new RockContext())
                {
                    var entityType  = EntityTypeCache.Get("Rock.Model.DefinedValue");
                    var definedType = new DefinedTypeService(rockContext).Get(_definedType.Id);
                    if (definedType != null && entityType != null)
                    {
                        var attributeService = new AttributeService(rockContext);
                        var attributes       = new AttributeService(rockContext)
                                               .GetByEntityTypeQualifier(entityType.Id, "DefinedTypeId", definedType.Id.ToString(), false)
                                               .ToList();

                        // Verify (and create if necessary) the "Is Link" attribute
                        if (!attributes.Any(a => a.Key == "IsLink"))
                        {
                            var fieldType = FieldTypeCache.Get(Rock.SystemGuid.FieldType.BOOLEAN);
                            if (entityType != null && fieldType != null)
                            {
                                var attribute = new Rock.Model.Attribute();
                                attributeService.Add(attribute);
                                attribute.EntityTypeId = entityType.Id;
                                attribute.EntityTypeQualifierColumn = "DefinedTypeId";
                                attribute.EntityTypeQualifierValue  = definedType.Id.ToString();
                                attribute.FieldTypeId  = fieldType.Id;
                                attribute.Name         = "Is Link";
                                attribute.Key          = "IsLink";
                                attribute.Description  = "Flag indicating if value is a link (vs Header)";
                                attribute.IsGridColumn = true;
                                attribute.DefaultValue = true.ToString();

                                var qualifier1 = new AttributeQualifier();
                                qualifier1.Key   = "truetext";
                                qualifier1.Value = "Yes";
                                attribute.AttributeQualifiers.Add(qualifier1);

                                var qualifier2 = new AttributeQualifier();
                                qualifier2.Key   = "falsetext";
                                qualifier2.Value = "No";
                                attribute.AttributeQualifiers.Add(qualifier2);

                                rockContext.SaveChanges();
                            }
                        }
                    }
                }

                BindGrid();

                pnlView.Visible = false;
                pnlEdit.Visible = true;
            }
        }
Example #27
0
        private DateTime GetDateTimeActivated(WorkflowAction action)
        {
            var dateActivated = RockDateTime.Now;

            // Use the current action type' guid as the key for a 'Delay Activated' attribute
            string AttrKey = action.ActionTypeCache.Guid.ToString();

            // Check to see if the action's activity does not yet have the the 'Delay Activated' attribute.
            // The first time this action runs on any workflow instance using this action instance, the
            // attribute will not exist and need to be created
            if (!action.Activity.Attributes.ContainsKey(AttrKey))
            {
                var attribute = new Rock.Model.Attribute();
                attribute.EntityTypeId = action.Activity.TypeId;
                attribute.EntityTypeQualifierColumn = "ActivityTypeId";
                attribute.EntityTypeQualifierValue  = action.Activity.ActivityTypeId.ToString();
                attribute.Name        = "Delay Activated";
                attribute.Key         = AttrKey;
                attribute.FieldTypeId = FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()).Id;

                // Need to save the attribute now (using different context) so that an attribute id is returned.
                using (var newRockContext = new RockContext())
                {
                    new AttributeService(newRockContext).Add(attribute);
                    newRockContext.SaveChanges();
                    AttributeCache.FlushEntityAttributes();
                    WorkflowActivityTypeCache.Flush(action.Activity.ActivityTypeId);
                }

                action.Activity.Attributes.Add(AttrKey, AttributeCache.Read(attribute));
                var attributeValue = new AttributeValueCache();
                attributeValue.AttributeId = attribute.Id;
                attributeValue.Value       = dateActivated.ToString("o");
                action.Activity.AttributeValues.Add(AttrKey, attributeValue);

                action.AddLogEntry(string.Format("Delay Activated at {0}", dateActivated), true);
            }
            else
            {
                // Check to see if this action instance has a value for the 'Delay Activated' attrbute
                DateTime?activated = action.Activity.GetAttributeValue(AttrKey).AsDateTime();
                if (activated.HasValue)
                {
                    return(activated.Value);
                }
                else
                {
                    // If no value exists, set the value to the current time
                    action.Activity.SetAttributeValue(AttrKey, dateActivated.ToString("o"));
                    action.AddLogEntry(string.Format("Delay Activated at {0}", dateActivated), true);
                }
            }

            return(dateActivated);
        }
Example #28
0
        /// <summary>
        /// Saves the attribute value.
        /// </summary>
        /// <param name="workflow">The workflow.</param>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        /// <param name="fieldType">Type of the field.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="qualifiers">The qualifiers.</param>
        /// <returns></returns>
        private static bool SaveAttributeValue(Rock.Model.Workflow workflow, string key, string value,
                                               FieldTypeCache fieldType, RockContext rockContext, Dictionary <string, string> qualifiers = null)
        {
            bool createdNewAttribute = false;

            if (workflow.Attributes.ContainsKey(key))
            {
                workflow.SetAttributeValue(key, value);
            }
            else
            {
                // Read the attribute
                var attributeService = new AttributeService(rockContext);
                var attribute        = attributeService
                                       .Get(workflow.TypeId, "WorkflowTypeId", workflow.WorkflowTypeId.ToString())
                                       .Where(a => a.Key == key)
                                       .FirstOrDefault();

                // If workflow attribute doesn't exist, create it
                // ( should only happen first time a background check is processed for given workflow type)
                if (attribute == null)
                {
                    attribute = new Rock.Model.Attribute();
                    attribute.EntityTypeId = workflow.TypeId;
                    attribute.EntityTypeQualifierColumn = "WorkflowTypeId";
                    attribute.EntityTypeQualifierValue  = workflow.WorkflowTypeId.ToString();
                    attribute.Name        = key.SplitCase();
                    attribute.Key         = key;
                    attribute.FieldTypeId = fieldType.Id;
                    attributeService.Add(attribute);

                    if (qualifiers != null)
                    {
                        foreach (var keyVal in qualifiers)
                        {
                            var qualifier = new Rock.Model.AttributeQualifier();
                            qualifier.Key   = keyVal.Key;
                            qualifier.Value = keyVal.Value;
                            attribute.AttributeQualifiers.Add(qualifier);
                        }
                    }

                    createdNewAttribute = true;
                }

                // Set the value for this action's instance to the current time
                var attributeValue = new Rock.Model.AttributeValue();
                attributeValue.Attribute = attribute;
                attributeValue.EntityId  = workflow.Id;
                attributeValue.Value     = value;
                new AttributeValueService(rockContext).Add(attributeValue);
            }

            return(createdNewAttribute);
        }
Example #29
0
        /// <summary>
        /// Saves any attribute edits made using an Attribute Editor control
        /// </summary>
        /// <param name="edtAttribute">The edt attribute.</param>
        /// <param name="attributeService">The attribute service.</param>
        /// <param name="attributeQualifierService">The attribute qualifier service.</param>
        /// <param name="categoryService">The category service.</param>
        /// <param name="entityTypeId">The entity type identifier.</param>
        /// <param name="entityTypeQualifierColumn">The entity type qualifier column.</param>
        /// <param name="entityTypeQualifierValue">The entity type qualifier value.</param>
        /// <param name="currentPersonId">The current person identifier.</param>
        /// <returns></returns>
        public static Rock.Model.Attribute SaveAttributeEdits(AttributeEditor edtAttribute, AttributeService attributeService, AttributeQualifierService attributeQualifierService, CategoryService categoryService,
                                                              int?entityTypeId, string entityTypeQualifierColumn, string entityTypeQualifierValue, int?currentPersonId)
        {
            // Create and update a new attribute object with new values
            var newAttribute = new Rock.Model.Attribute();

            edtAttribute.GetAttributeProperties(newAttribute);

            return(SaveAttributeEdits(newAttribute, attributeService, attributeQualifierService, categoryService,
                                      entityTypeId, entityTypeQualifierColumn, entityTypeQualifierValue, currentPersonId));
        }
Example #30
0
        /// <summary>
        /// Adds Attribute model to cache, and returns cached object.
        /// </summary>
        /// <param name="attributeModel">The attribute model.</param>
        /// <param name="qualifiers">The qualifiers.</param>
        /// <returns></returns>
        public static AttributeCache Read(Rock.Model.Attribute attributeModel, Dictionary <string, string> qualifiers)
        {
            AttributeCache attribute = new AttributeCache(attributeModel, qualifiers);

            string cacheKey = AttributeCache.CacheKey(attributeModel.Id);

            ObjectCache cache = MemoryCache.Default;

            cache.Set(cacheKey, attribute, new CacheItemPolicy());

            return(attribute);
        }
Example #31
0
        /// <summary>
        /// Maps the activity ministry.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        private void MapActivityMinistry( IQueryable<Row> tableData )
        {
            int groupEntityTypeId = EntityTypeCache.Read( "Rock.Model.Group" ).Id;
            var attributeService = new AttributeService();

            // Add an Attribute for the unique F1 Ministry Id
            var ministryAttributeId = attributeService.Queryable().Where( a => a.EntityTypeId == groupEntityTypeId
                && a.Key == "F1MinistryId" ).Select( a => a.Id ).FirstOrDefault();
            if ( ministryAttributeId == 0 )
            {
                var newMinistryAttribute = new Rock.Model.Attribute();
                newMinistryAttribute.Key = "F1MinistryId";
                newMinistryAttribute.Name = "F1 Ministry Id";
                newMinistryAttribute.FieldTypeId = IntegerFieldTypeId;
                newMinistryAttribute.EntityTypeId = groupEntityTypeId;
                newMinistryAttribute.EntityTypeQualifierValue = string.Empty;
                newMinistryAttribute.EntityTypeQualifierColumn = string.Empty;
                newMinistryAttribute.Description = "The FellowshipOne identifier for the ministry that was imported";
                newMinistryAttribute.DefaultValue = string.Empty;
                newMinistryAttribute.IsMultiValue = false;
                newMinistryAttribute.IsRequired = false;
                newMinistryAttribute.Order = 0;

                attributeService.Add( newMinistryAttribute, ImportPersonAlias );
                attributeService.Save( newMinistryAttribute, ImportPersonAlias );
                ministryAttributeId = newMinistryAttribute.Id;
            }

            // Get previously imported Ministries
            var importedMinistries = new AttributeValueService().GetByAttributeId( ministryAttributeId )
                .Select( av => new { RLCId = av.Value.AsType<int?>(), LocationId = av.EntityId } )
                .ToDictionary( t => t.RLCId, t => t.LocationId );

            foreach ( var row in tableData )
            {
                int? ministryId = row["Ministry_ID"] as int?;
                if ( ministryId != null && !importedMinistries.ContainsKey( ministryId ) )
                {
                    // Activity_ID
                    // Ministry_Name
                    // Activity_Name
                    // Ministry_Active
                    // Activity_Active
                }
            }
        }
Example #32
0
        /// <summary>
        /// Loads the individual data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadIndividuals( CSVInstance csvData )
        {
            var lookupContext = new RockContext();
            var groupTypeRoleService = new GroupTypeRoleService( lookupContext );
            var groupMemberService = new GroupMemberService( lookupContext );

            // Marital statuses: Married, Single, Separated, etc
            var maritalStatusTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS ), lookupContext ).DefinedValues;

            // Connection statuses: Member, Visitor, Attendee, etc
            var connectionStatusTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS ), lookupContext ).DefinedValues;
            int memberConnectionStatusId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER ) ).Id;
            int visitorConnectionStatusId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_VISITOR ) ).Id;
            int attendeeConnectionStatusId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_ATTENDEE ) ).Id;

            // Suffix type: Dr., Jr., II, etc
            var suffixTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_SUFFIX ), lookupContext ).DefinedValues;

            // Title type: Mr., Mrs. Dr., etc
            var titleTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_TITLE ), lookupContext ).DefinedValues;

            // Record statuses: Active, Inactive, Pending
            int? recordStatusActiveId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE ), lookupContext ).Id;
            int? recordStatusInactiveId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ), lookupContext ).Id;
            int? recordStatusPendingId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING ), lookupContext ).Id;

            // Deceased record status reason (others available: No Activity, Moved, etc)
            var recordStatusDeceasedId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_REASON_DECEASED ) ).Id;

            // Record type: Person
            int? personRecordTypeId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON ), lookupContext ).Id;

            // Group roles: Owner, Adult, Child, others
            GroupTypeRole ownerRole = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER ) );
            int adultRoleId = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ).Id;
            int childRoleId = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD ) ).Id;

            // Phone types: Home, Work, Mobile
            var numberTypeValues = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE ), lookupContext ).DefinedValues;

            // Personal note type id
            var personalNoteTypeId = new NoteTypeService( lookupContext ).Get( new Guid( Rock.SystemGuid.NoteType.PERSON_TIMELINE_NOTE ) ).Id;

            // School defined type
            var schoolDefinedType = DefinedTypeCache.Read( new Guid( "576FF1E2-6225-4565-A16D-230E26167A3D" ) );

            // Look up existing Person attributes
            var personAttributes = new AttributeService( lookupContext ).GetByEntityTypeId( PersonEntityTypeId ).ToList();
            var schoolAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "School" ) );

            // Text field type id
            int textFieldTypeId = FieldTypeCache.Read( new Guid( Rock.SystemGuid.FieldType.TEXT ), lookupContext ).Id;
            int dateFieldTypeId = FieldTypeCache.Read( new Guid( Rock.SystemGuid.FieldType.DATE ), lookupContext ).Id;

            // Attribute entity type id
            int attributeEntityTypeId = EntityTypeCache.Read( "Rock.Model.Attribute" ).Id;

            // Visit info category
            var visitInfoCategory = new CategoryService( lookupContext ).GetByEntityTypeId( attributeEntityTypeId )
                    .Where( c => c.Name == "Visit Information" ).FirstOrDefault();

            // Look for custom attributes in the Individual file
            var allFields = csvData.TableNodes.FirstOrDefault().Children.Select( ( node, index ) => new { node = node, index = index } ).ToList();
            Dictionary<int, string> customAttributes = allFields
                .Where( f => f.index > SecurityNote )
                .ToDictionary( f => f.index, f => f.node.Name.RemoveWhitespace() );

            // Add any attributes if they don't already exist
            if ( customAttributes.Any() )
            {
                var newAttributes = new List<Rock.Model.Attribute>();
                foreach ( var newAttributePair in customAttributes.Where( ca => !personAttributes.Any( a => a.Key == ca.Value ) ) )
                {
                    var newAttribute = new Rock.Model.Attribute();
                    newAttribute.Name = newAttributePair.Value;
                    newAttribute.Key = newAttributePair.Value.RemoveWhitespace();
                    newAttribute.Description = newAttributePair.Value + " created by CSV import";
                    newAttribute.EntityTypeQualifierValue = string.Empty;
                    newAttribute.EntityTypeQualifierColumn = string.Empty;
                    newAttribute.EntityTypeId = PersonEntityTypeId;
                    newAttribute.FieldTypeId = textFieldTypeId;
                    newAttribute.DefaultValue = string.Empty;
                    newAttribute.IsMultiValue = false;
                    newAttribute.IsGridColumn = false;
                    newAttribute.IsRequired = false;
                    newAttribute.Order = 0;
                    newAttributes.Add( newAttribute );
                }

                lookupContext.Attributes.AddRange( newAttributes );
                lookupContext.SaveChanges( DisableAuditing );
                personAttributes.AddRange( newAttributes );
            }

            // Set the supported date formats
            var dateFormats = new[] { "yyyy-MM-dd", "MM/dd/yyyy", "MM/dd/yy" };

            var currentFamilyGroup = new Group();
            var newFamilyList = new List<Group>();
            var newVisitorList = new List<Group>();
            var newNoteList = new List<Note>();

            int completed = 0;
            int newFamilies = 0;
            int newPeople = 0;
            ReportProgress( 0, string.Format( "Starting Individual import ({0:N0} already exist).", ImportedPeopleKeys.Count() ) );

            string[] row;
            row = csvData.Database.FirstOrDefault();
            while ( row != null )
            {
                int groupRoleId = adultRoleId;
                bool isFamilyRelationship = true;

                string rowFamilyName = row[FamilyName];
                string rowFamilyKey = row[FamilyId];
                string rowPersonKey = row[PersonId];
                int? rowFamilyId = rowFamilyKey.AsType<int?>();
                int? rowPersonId = rowPersonKey.AsType<int?>();

                // Check that this person isn't already in our data
                var personExists = ImportedFamilies.Any( g => g.Members.Any( m => m.Person.ForeignKey == rowPersonKey ) );
                if ( !personExists )
                {
                    #region person create

                    var person = new Person();
                    person.ForeignKey = rowPersonKey;
                    person.ForeignId = rowPersonId;
                    person.SystemNote = string.Format( "Imported via Excavator on {0}", ImportDateTime );
                    person.RecordTypeValueId = personRecordTypeId;
                    person.CreatedByPersonAliasId = ImportPersonAliasId;
                    string firstName = row[FirstName].Left( 50 );
                    string nickName = row[NickName].Left( 50 );
                    person.FirstName = firstName;
                    person.NickName = string.IsNullOrWhiteSpace( nickName ) ? firstName : nickName;
                    person.MiddleName = row[MiddleName].Left( 50 );
                    person.LastName = row[LastName].Left( 50 );

                    DateTime createdDateValue;
                    if ( DateTime.TryParseExact( row[CreatedDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out createdDateValue ) )
                    {
                        person.CreatedDateTime = createdDateValue;
                        person.ModifiedDateTime = ImportDateTime;
                    }
                    else
                    {
                        person.CreatedDateTime = ImportDateTime;
                        person.ModifiedDateTime = ImportDateTime;
                    }

                    DateTime birthDate;
                    if ( DateTime.TryParseExact( row[DateOfBirth], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out birthDate ) )
                    {
                        person.BirthDay = birthDate.Day;
                        person.BirthMonth = birthDate.Month;
                        person.BirthYear = birthDate.Year;
                    }

                    DateTime graduationDate;
                    if ( DateTime.TryParseExact( row[GraduationDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out graduationDate ) )
                    {
                        person.GraduationYear = graduationDate.Year;
                    }

                    DateTime anniversary;
                    if ( DateTime.TryParseExact( row[Anniversary], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out anniversary ) )
                    {
                        person.AnniversaryDate = anniversary;
                    }

                    string gender = row[Gender];
                    if ( gender != null )
                    {
                        switch ( gender.Trim().ToLower() )
                        {
                            case "m":
                            case "male":
                                person.Gender = Rock.Model.Gender.Male;
                                break;

                            case "f":
                            case "female":
                                person.Gender = Rock.Model.Gender.Female;
                                break;

                            default:
                                person.Gender = Rock.Model.Gender.Unknown;
                                break;
                        }
                    }

                    string prefix = row[Prefix];
                    if ( !string.IsNullOrWhiteSpace( prefix ) )
                    {
                        prefix = prefix.RemoveSpecialCharacters().Trim();
                        person.TitleValueId = titleTypes.Where( s => prefix == s.Value.RemoveSpecialCharacters() )
                            .Select( s => (int?)s.Id ).FirstOrDefault();
                    }

                    string suffix = row[Suffix];
                    if ( !string.IsNullOrWhiteSpace( suffix ) )
                    {
                        suffix = suffix.RemoveSpecialCharacters().Trim();
                        person.SuffixValueId = suffixTypes.Where( s => suffix == s.Value.RemoveSpecialCharacters() )
                            .Select( s => (int?)s.Id ).FirstOrDefault();
                    }

                    string maritalStatus = row[MaritalStatus];
                    if ( !string.IsNullOrWhiteSpace( maritalStatus ) )
                    {
                        person.MaritalStatusValueId = maritalStatusTypes.Where( dv => dv.Value == maritalStatus )
                            .Select( dv => (int?)dv.Id ).FirstOrDefault();
                    }
                    else
                    {
                        person.MaritalStatusValueId = maritalStatusTypes.Where( dv => dv.Value == "Unknown" )
                            .Select( dv => ( int? )dv.Id ).FirstOrDefault();
                    }

                    string familyRole = row[FamilyRole];
                    if ( !string.IsNullOrWhiteSpace( familyRole ) )
                    {
                        if ( familyRole == "Visitor" )
                        {
                            isFamilyRelationship = false;
                        }

                        if ( familyRole == "Child" || person.Age < 18 )
                        {
                            groupRoleId = childRoleId;
                        }
                    }

                    string connectionStatus = row[ConnectionStatus];
                    if ( !string.IsNullOrWhiteSpace( connectionStatus ) )
                    {
                        if ( connectionStatus == "Member" )
                        {
                            person.ConnectionStatusValueId = memberConnectionStatusId;
                        }
                        else if ( connectionStatus == "Visitor" )
                        {
                            person.ConnectionStatusValueId = visitorConnectionStatusId;
                        }
                        else
                        {
                            // look for user-defined connection type or default to Attendee
                            var customConnectionType = connectionStatusTypes.Where( dv => dv.Value == connectionStatus )
                                .Select( dv => (int?)dv.Id ).FirstOrDefault();

                            person.ConnectionStatusValueId = customConnectionType ?? attendeeConnectionStatusId;
                            person.RecordStatusValueId = recordStatusActiveId;
                        }
                    }

                    string recordStatus = row[RecordStatus];
                    if ( !string.IsNullOrWhiteSpace( recordStatus ) )
                    {
                        switch ( recordStatus.Trim().ToLower() )
                        {
                            case "active":
                                person.RecordStatusValueId = recordStatusActiveId;
                                break;

                            case "inactive":
                                person.RecordStatusValueId = recordStatusInactiveId;
                                break;

                            default:
                                person.RecordStatusValueId = recordStatusPendingId;
                                break;
                        }
                    }

                    string isDeceasedValue = row[IsDeceased];
                    if ( !string.IsNullOrWhiteSpace( isDeceasedValue ) )
                    {
                        switch ( isDeceasedValue.Trim().ToLower() )
                        {
                            case "y":
                            case "yes":
                                person.IsDeceased = true;
                                person.RecordStatusReasonValueId = recordStatusDeceasedId;
                                person.RecordStatusValueId = recordStatusInactiveId;
                                break;

                            default:
                                person.IsDeceased = false;
                                break;
                        }
                    }

                    var personNumbers = new Dictionary<string, string>();
                    personNumbers.Add( "Home", row[HomePhone] );
                    personNumbers.Add( "Mobile", row[MobilePhone] );
                    personNumbers.Add( "Work", row[WorkPhone] );
                    string smsAllowed = row[AllowSMS];

                    foreach ( var numberPair in personNumbers.Where( n => !string.IsNullOrWhiteSpace( n.Value ) ) )
                    {
                        var extension = string.Empty;
                        var countryCode = Rock.Model.PhoneNumber.DefaultCountryCode();
                        var normalizedNumber = string.Empty;
                        var countryIndex = numberPair.Value.IndexOf( '+' );
                        int extensionIndex = numberPair.Value.LastIndexOf( 'x' ) > 0 ? numberPair.Value.LastIndexOf( 'x' ) : numberPair.Value.Length;
                        if ( countryIndex >= 0 )
                        {
                            countryCode = numberPair.Value.Substring( countryIndex, countryIndex + 3 ).AsNumeric();
                            normalizedNumber = numberPair.Value.Substring( countryIndex + 3, extensionIndex - 3 ).AsNumeric().TrimStart( new Char[] { '0' } );
                            extension = numberPair.Value.Substring( extensionIndex );
                        }
                        else if ( extensionIndex > 0 )
                        {
                            normalizedNumber = numberPair.Value.Substring( 0, extensionIndex ).AsNumeric();
                            extension = numberPair.Value.Substring( extensionIndex ).AsNumeric();
                        }
                        else
                        {
                            normalizedNumber = numberPair.Value.AsNumeric();
                        }

                        if ( !string.IsNullOrWhiteSpace( normalizedNumber ) )
                        {
                            var currentNumber = new PhoneNumber();
                            currentNumber.CountryCode = countryCode;
                            currentNumber.CreatedByPersonAliasId = ImportPersonAliasId;
                            currentNumber.Extension = extension.Left( 20 );
                            currentNumber.Number = normalizedNumber.TrimStart( new Char[] { '0' } ).Left( 20 );
                            currentNumber.NumberFormatted = PhoneNumber.FormattedNumber( currentNumber.CountryCode, currentNumber.Number );
                            currentNumber.NumberTypeValueId = numberTypeValues.Where( v => v.Value.Equals( numberPair.Key ) )
                                .Select( v => ( int? )v.Id ).FirstOrDefault();
                            if ( numberPair.Key == "Mobile" )
                            {
                                switch ( smsAllowed.Trim().ToLower() )
                                {
                                    case "y":
                                    case "yes":
                                    case "active":
                                        currentNumber.IsMessagingEnabled = true;
                                        break;

                                    default:
                                        currentNumber.IsMessagingEnabled = false;
                                        break;
                                }
                            }

                            person.PhoneNumbers.Add( currentNumber );
                        }
                    }

                    // Map Person attributes
                    person.Attributes = new Dictionary<string, AttributeCache>();
                    person.AttributeValues = new Dictionary<string, AttributeValueCache>();

                    bool isEmailActive;
                    switch ( row[IsEmailActive].Trim().ToLower() )
                    {
                        case "n":
                        case "no":
                        case "inactive":
                            isEmailActive = false;
                            break;

                        default:
                            isEmailActive = true;
                            break;
                    }

                    EmailPreference emailPreference;
                    switch ( row[AllowBulkEmail].Trim().ToLower() )
                    {
                        case "n":
                        case "no":
                        case "inactive":
                            emailPreference = EmailPreference.NoMassEmails;
                            break;

                        default:
                            emailPreference = EmailPreference.EmailAllowed;
                            break;
                    }

                    person.EmailPreference = emailPreference;
                    string primaryEmail = row[Email].Trim().Left( 75 );
                    if ( !string.IsNullOrWhiteSpace( primaryEmail ) )
                    {
                        if ( primaryEmail.IsEmail() )
                        {
                            person.Email = primaryEmail;
                            person.IsEmailActive = isEmailActive;
                        }
                        else
                        {
                            LogException( "InvalidPrimaryEmail", string.Format( "PersonId: {0} - Email: {1}", rowPersonKey, primaryEmail ) );
                        }
                    }

                    string schoolName = row[School];
                    if ( !string.IsNullOrWhiteSpace( schoolName ) )
                    {
                        // Add school if it doesn't exist
                        Guid schoolGuid;
                        var schoolExists = lookupContext.DefinedValues.Any( s => s.DefinedTypeId == schoolDefinedType.Id && s.Value.Equals( schoolName ) );
                        if ( !schoolExists )
                        {
                            var newSchool = new DefinedValue();
                            newSchool.DefinedTypeId = schoolDefinedType.Id;
                            newSchool.Value = schoolName;
                            newSchool.Order = 0;

                            lookupContext.DefinedValues.Add( newSchool );
                            lookupContext.SaveChanges();

                            schoolGuid = newSchool.Guid;
                        }
                        else
                        {
                            schoolGuid = lookupContext.DefinedValues.FirstOrDefault( s => s.Value.Equals( schoolName ) ).Guid;
                        }

                        AddPersonAttribute( schoolAttribute, person, schoolGuid.ToString().ToUpper() );
                    }

                    foreach ( var attributePair in customAttributes )
                    {
                        string newAttributeValue = row[attributePair.Key];
                        if ( !string.IsNullOrWhiteSpace( newAttributeValue ) )
                        {
                            // check if this attribute value is a date
                            DateTime valueAsDateTime;
                            if ( DateTime.TryParseExact( newAttributeValue, dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out valueAsDateTime ) )
                            {
                                newAttributeValue = valueAsDateTime.ToString( "yyyy-MM-dd" );
                            }

                            int? newAttributeId = personAttributes.Where( a => a.Key == attributePair.Value.RemoveWhitespace() )
                                .Select( a => (int?)a.Id ).FirstOrDefault();
                            if ( newAttributeId != null )
                            {
                                var newAttribute = AttributeCache.Read( (int)newAttributeId );
                                AddPersonAttribute( newAttribute, person, newAttributeValue );
                            }
                        }
                    }

                    // Add notes to timeline
                    var notePairs = new Dictionary<string, string>();
                    notePairs.Add( "General", row[GeneralNote] );
                    notePairs.Add( "Medical", row[MedicalNote] );
                    notePairs.Add( "Security", row[SecurityNote] );

                    foreach ( var notePair in notePairs.Where( n => !string.IsNullOrWhiteSpace( n.Value ) ) )
                    {
                        var newNote = new Note();
                        newNote.NoteTypeId = personalNoteTypeId;
                        newNote.CreatedByPersonAliasId = ImportPersonAliasId;
                        newNote.CreatedDateTime = ImportDateTime;
                        newNote.Text = notePair.Value;
                        newNote.ForeignKey = rowPersonKey;
                        newNote.ForeignId = rowPersonId;
                        newNote.Caption = string.Format( "{0} Note", notePair.Key );

                        if ( !notePair.Key.Equals( "General" ) )
                        {
                            newNote.IsAlert = true;
                        }

                        newNoteList.Add( newNote );
                    }

                    #endregion person create

                    var groupMember = new GroupMember();
                    groupMember.Person = person;
                    groupMember.GroupRoleId = groupRoleId;
                    groupMember.CreatedDateTime = ImportDateTime;
                    groupMember.ModifiedDateTime = ImportDateTime;
                    groupMember.CreatedByPersonAliasId = ImportPersonAliasId;
                    groupMember.GroupMemberStatus = GroupMemberStatus.Active;

                    if ( rowFamilyKey != currentFamilyGroup.ForeignKey )
                    {
                        // person not part of the previous family, see if that family exists or create a new one
                        currentFamilyGroup = ImportedFamilies.FirstOrDefault( g => g.ForeignKey == rowFamilyKey );
                        if ( currentFamilyGroup == null )
                        {
                            currentFamilyGroup = CreateFamilyGroup( row[FamilyName], rowFamilyKey );
                            newFamilyList.Add( currentFamilyGroup );
                            newFamilies++;
                        }
                        else
                        {
                            lookupContext.Groups.Attach( currentFamilyGroup );
                            lookupContext.Entry( currentFamilyGroup ).State = EntityState.Modified;
                        }

                        currentFamilyGroup.Members.Add( groupMember );
                    }
                    else
                    {
                        // person is part of this family group, check if they're a visitor
                        if ( isFamilyRelationship || currentFamilyGroup.Members.Count() < 1 )
                        {
                            currentFamilyGroup.Members.Add( groupMember );
                        }
                        else
                        {
                            var visitorFamily = CreateFamilyGroup( person.LastName + " Family", rowFamilyKey );
                            visitorFamily.Members.Add( groupMember );
                            newFamilyList.Add( visitorFamily );
                            newVisitorList.Add( visitorFamily );
                            newFamilies++;
                        }
                    }

                    // look ahead 1 row
                    string rowNextFamilyKey = "-1";
                    if ( (row = csvData.Database.FirstOrDefault()) != null )
                    {
                        rowNextFamilyKey = row[FamilyId];
                    }

                    newPeople++;
                    completed++;
                    if ( completed % (ReportingNumber * 10) < 1 )
                    {
                        ReportProgress( 0, string.Format( "{0:N0} people imported.", completed ) );
                    }

                    if ( newPeople >= ReportingNumber && rowNextFamilyKey != currentFamilyGroup.ForeignKey )
                    {
                        SaveIndividuals( newFamilyList, newVisitorList, newNoteList );
                        lookupContext.SaveChanges();
                        ReportPartialProgress();

                        // Clear out variables
                        currentFamilyGroup = new Group();
                        newFamilyList.Clear();
                        newVisitorList.Clear();
                        newNoteList.Clear();
                        newPeople = 0;
                    }
                }
                else
                {
                    row = csvData.Database.FirstOrDefault();
                }
            }

            // Save any changes to new families
            if ( newFamilyList.Any() )
            {
                SaveIndividuals( newFamilyList, newVisitorList, newNoteList );
            }

            // Save any changes to existing families
            lookupContext.SaveChanges();
            DetachAllInContext( lookupContext );
            lookupContext.Dispose();

            ReportProgress( 0, string.Format( "Finished individual import: {0:N0} families and {1:N0} people added.", newFamilies, completed ) );
            return completed;
        }
        /// <summary>
        /// Gs the group attributes_ show edit.
        /// </summary>
        /// <param name="attributeGuid">The attribute GUID.</param>
        protected void gAttributes_ShowEdit( Guid attributeGuid )
        {
            Attribute attribute;
            if ( attributeGuid.Equals( Guid.Empty ) )
            {
                attribute = new Attribute();
                attribute.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT ).Id;
                edtAttributes.ActionTitle = ActionTitle.Add( "attribute for workflows of workflow type " + tbName.Text );
            }
            else
            {
                attribute = AttributesState.First( a => a.Guid.Equals( attributeGuid ) );
                edtAttributes.ActionTitle = ActionTitle.Edit( "attribute for workflows of workflow type " + tbName.Text );
            }

            edtAttributes.ReservedKeyNames = AttributesState.Where( a => !a.Guid.Equals( attributeGuid ) ).Select( a => a.Key ).ToList();

            edtAttributes.SetAttributeProperties( attribute, typeof( Group ) );

            ShowDialog( "Attributes" );
        }
        /// <summary>
        /// Shows the form field edit.
        /// </summary>
        /// <param name="formGuid">The form unique identifier.</param>
        /// <param name="formFieldGuid">The form field unique identifier.</param>
        private void ShowFormFieldEdit( Guid formGuid, Guid formFieldGuid )
        {
            if ( FormFieldsState.ContainsKey( formGuid ) )
            {
                ShowDialog( "Attributes" );

                var fieldList = FormFieldsState[formGuid];

                RegistrationTemplateFormField formField = fieldList.FirstOrDefault( a => a.Guid.Equals( formFieldGuid ) );
                if ( formField == null )
                {
                    formField = new RegistrationTemplateFormField();
                    formField.Guid = formFieldGuid;
                    formField.FieldSource = RegistrationFieldSource.PersonAttribute;
                }

                ceAttributePreText.Text = formField.PreText;
                ceAttributePostText.Text = formField.PostText;
                ddlFieldSource.SetValue( formField.FieldSource.ConvertToInt() );
                ddlPersonField.SetValue( formField.PersonFieldType.ConvertToInt() );
                lPersonField.Text = formField.PersonFieldType.ConvertToString();

                ddlPersonAttributes.Items.Clear();
                var person = new Person();
                person.LoadAttributes();
                foreach ( var attr in person.Attributes
                    .OrderBy( a => a.Value.Name )
                    .Select( a => a.Value ) )
                {
                    if ( attr.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
                    {
                        ddlPersonAttributes.Items.Add( new ListItem( attr.Name, attr.Id.ToString() ) );
                    }
                }

                ddlGroupTypeAttributes.Items.Clear();
                var group = new Group();
                group.GroupTypeId = gtpGroupType.SelectedGroupTypeId ?? 0;
                var groupMember = new GroupMember();
                groupMember.Group = group;
                groupMember.LoadAttributes();
                foreach ( var attr in groupMember.Attributes
                    .OrderBy( a => a.Value.Name )
                    .Select( a => a.Value ) )
                {
                    if ( attr.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
                    {
                        ddlGroupTypeAttributes.Items.Add( new ListItem( attr.Name, attr.Id.ToString() ) );
                    }
                }

                var attribute = new Attribute();
                attribute.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT ).Id;

                if ( formField.FieldSource == RegistrationFieldSource.PersonAttribute )
                {
                    ddlPersonAttributes.SetValue( formField.AttributeId );
                }
                else if ( formField.FieldSource == RegistrationFieldSource.GroupMemberAttribute )
                {
                    ddlGroupTypeAttributes.SetValue( formField.AttributeId );
                }
                else if ( formField.FieldSource == RegistrationFieldSource.RegistrationAttribute )
                {
                    if ( formField.Attribute != null )
                    {
                        attribute = formField.Attribute;
                    }
                }

                edtRegistrationAttribute.SetAttributeProperties( attribute, typeof( RegistrationTemplate ) );

                cbInternalField.Checked = formField.IsInternal;
                cbShowOnGrid.Checked = formField.IsGridField;
                cbRequireInInitialEntry.Checked = formField.IsRequired;
                cbUsePersonCurrentValue.Checked = formField.ShowCurrentValue;
                cbCommonValue.Checked = formField.IsSharedValue;

                hfFormGuid.Value = formGuid.ToString();
                hfAttributeGuid.Value = formFieldGuid.ToString();

                lPersonField.Visible = formField.FieldSource == RegistrationFieldSource.PersonField && (
                    formField.PersonFieldType == RegistrationPersonFieldType.FirstName ||
                    formField.PersonFieldType == RegistrationPersonFieldType.LastName );

                SetFieldDisplay();
            }

            BuildControls( true );
        }
        /// <summary>
        /// Gs the binary file attributes_ show edit.
        /// </summary>
        /// <param name="attributeGuid">The attribute GUID.</param>
        protected void gBinaryFileAttributes_ShowEdit( Guid attributeGuid )
        {
            pnlDetails.Visible = false;
            pnlBinaryFileAttribute.Visible = true;

            Attribute attribute;
            if ( attributeGuid.Equals( Guid.Empty ) )
            {
                attribute = new Attribute();
                attribute.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT ).Id;
                edtBinaryFileAttributes.ActionTitle = ActionTitle.Add( "attribute for binary files of type " + tbName.Text );
            }
            else
            {
                attribute = BinaryFileAttributesState.First( a => a.Guid.Equals( attributeGuid ) );
                edtBinaryFileAttributes.ActionTitle = ActionTitle.Edit( "attribute for binary files of type " + tbName.Text );
            }

            edtBinaryFileAttributes.ReservedKeyNames = BinaryFileAttributesState.Where( a => !a.Guid.Equals( attributeGuid ) ).Select( a => a.Key ).ToList();

            edtBinaryFileAttributes.SetAttributeProperties( attribute, typeof( BinaryFile ) );
        }
Example #36
0
        private double HoursElapsed( WorkflowAction action )
        {
            // Use the current action type' guid as the key for a 'DateTime Sent' attribute
            string AttrKey = action.ActionType.Guid.ToString() + "_DateTimeSent";

            // Check to see if the action's activity does not yet have the the 'DateTime Sent' attribute.
            // The first time this action runs on any workflow instance using this action instance, the
            // attribute will not exist and need to be created
            if ( !action.Activity.Attributes.ContainsKey( AttrKey ) )
            {
                var attribute = new Rock.Model.Attribute();
                attribute.EntityTypeId = action.Activity.TypeId;
                attribute.EntityTypeQualifierColumn = "ActivityTypeId";
                attribute.EntityTypeQualifierValue = action.Activity.ActivityTypeId.ToString();
                attribute.Name = "DateTime Sent";
                attribute.Key = AttrKey;
                attribute.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT.AsGuid() ).Id;

                // Need to save the attribute now (using different context) so that an attribute id is returned.
                using ( var newRockContext = new RockContext() )
                {
                    new AttributeService( newRockContext ).Add( attribute );
                    newRockContext.SaveChanges();
                }

                action.Activity.Attributes.Add( AttrKey, AttributeCache.Read( attribute ) );
                var attributeValue = new AttributeValueCache();
                attributeValue.AttributeId = attribute.Id;
                attributeValue.Value = RockDateTime.Now.ToString( "o" );
                action.Activity.AttributeValues.Add( AttrKey, attributeValue );
            }
            else
            {
                // Check to see if this action instance has a value for the 'Delay Activated' attrbute
                DateTime? dateSent = action.Activity.GetAttributeValue( AttrKey ).AsDateTime();
                if ( dateSent.HasValue )
                {
                    // If a value does exist, check to see if the number of minutes to delay has passed
                    // since the value was saved
                    return RockDateTime.Now.Subtract( dateSent.Value ).TotalHours;
                }
                else
                {
                    // If no value exists, set the value to the current time
                    action.Activity.SetAttributeValue( AttrKey, RockDateTime.Now.ToString( "o" ) );
                }
            }

            return 0.0D;
        }
        private static void SaveAttributeValue( Rock.Model.Workflow workflow, string key, string value, 
            FieldTypeCache fieldType, RockContext rockContext, Dictionary<string, string> qualifiers = null )
        {
            if (workflow.Attributes.ContainsKey(key))
            {
                workflow.SetAttributeValue( key, value );
            }
            else
            {
                // If workflow attribute doesn't exist, create it
                // ( should only happen first time a background check is processed for given workflow type)
                var attribute = new Rock.Model.Attribute();
                attribute.EntityTypeId = workflow.WorkflowType.TypeId;
                attribute.EntityTypeQualifierColumn = "WorkflowTypeId";
                attribute.EntityTypeQualifierValue = workflow.WorkflowTypeId.ToString();
                attribute.Name = key.SplitCase();
                attribute.Key = key;
                attribute.FieldTypeId = fieldType.Id;

                if ( qualifiers != null )
                {
                    foreach( var keyVal in qualifiers )
                    {
                        var qualifier = new Rock.Model.AttributeQualifier();
                        qualifier.Key = keyVal.Key;
                        qualifier.Value = keyVal.Value;
                        attribute.AttributeQualifiers.Add( qualifier );
                    }
                }

                // Set the value for this action's instance to the current time
                var attributeValue = new Rock.Model.AttributeValue();
                attributeValue.Attribute = attribute;
                attributeValue.EntityId = workflow.Id;
                attributeValue.Value = value;
                new AttributeValueService( rockContext ).Add( attributeValue );
            }
        }
Example #38
0
        /// <summary>
        /// Shows the attribute edit.
        /// </summary>
        /// <param name="attributeGuid">The attribute unique identifier.</param>
        private void ShowAttributeEdit( Guid attributeGuid )
        {
            Attribute attribute;
            if ( attributeGuid.Equals( Guid.Empty ) )
            {
                attribute = new Attribute();
                attribute.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT ).Id;
            }
            else
            {
                attribute = AttributesState.First( a => a.Guid.Equals( attributeGuid ) );
            }

            edtAttributes.ReservedKeyNames = AttributesState.Where( a => !a.Guid.Equals( attributeGuid ) ).Select( a => a.Key ).ToList();
            edtAttributes.AllowSearchVisible = true;
            edtAttributes.SetAttributeProperties( attribute, typeof( EventCalendar ) );

            ShowDialog( "Attributes" );
        }
Example #39
0
        /// <summary>
        /// Gs the group member attributes_ show edit.
        /// </summary>
        /// <param name="attributeGuid">The attribute GUID.</param>
        protected void gGroupMemberAttributes_ShowEdit( Guid attributeGuid )
        {
            Attribute attribute;
            if ( attributeGuid.Equals( Guid.Empty ) )
            {
                attribute = new Attribute();
                attribute.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT ).Id;
                edtGroupMemberAttributes.ActionTitle = ActionTitle.Add( "attribute for group members of " + tbName.Text );
            }
            else
            {
                attribute = GroupMemberAttributesState.First( a => a.Guid.Equals( attributeGuid ) );
                edtGroupMemberAttributes.ActionTitle = ActionTitle.Edit( "attribute for group members of " + tbName.Text );
            }

            edtGroupMemberAttributes.SetAttributeProperties( attribute, typeof( GroupMember ) );

            ShowDialog( "GroupMemberAttributes", true );
        }
Example #40
0
        /// <summary>
        /// Maps the RLC data to rooms, locations & classes
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        private void MapRLC( IQueryable<Row> tableData )
        {
            int locationEntityTypeId = EntityTypeCache.Read( "Rock.Model.Location" ).Id;
            int groupEntityTypeId = EntityTypeCache.Read( "Rock.Model.Group" ).Id;
            var attributeService = new AttributeService();

            // Add an Attribute for the unique F1 RLC Id
            var rlcAttributeId = attributeService.Queryable().Where( a => a.EntityTypeId == locationEntityTypeId
                && a.Key == "F1RLCId" ).Select( a => a.Id ).FirstOrDefault();
            if ( rlcAttributeId == 0 )
            {
                var newRLCAttribute = new Rock.Model.Attribute();
                newRLCAttribute.Key = "F1RLCId";
                newRLCAttribute.Name = "F1 RLC Id";
                newRLCAttribute.FieldTypeId = IntegerFieldTypeId;
                newRLCAttribute.EntityTypeId = locationEntityTypeId;
                newRLCAttribute.EntityTypeQualifierValue = string.Empty;
                newRLCAttribute.EntityTypeQualifierColumn = string.Empty;
                newRLCAttribute.Description = "The FellowshipOne identifier for the RLC (Room/Location/Class) that was imported";
                newRLCAttribute.DefaultValue = string.Empty;
                newRLCAttribute.IsMultiValue = false;
                newRLCAttribute.IsRequired = false;
                newRLCAttribute.Order = 0;

                attributeService.Add( newRLCAttribute, ImportPersonAlias );
                attributeService.Save( newRLCAttribute, ImportPersonAlias );
                rlcAttributeId = newRLCAttribute.Id;
            }

            // Add an Attribute for the unique F1 Activity Id
            var activityAttributeId = attributeService.Queryable().Where( a => a.EntityTypeId == locationEntityTypeId
                && a.Key == "F1ActivityId" ).Select( a => a.Id ).FirstOrDefault();
            if ( rlcAttributeId == 0 )
            {
                var newActivityAttribute = new Rock.Model.Attribute();
                newActivityAttribute.Key = "F1ActivityId";
                newActivityAttribute.Name = "F1 Activity Id";
                newActivityAttribute.FieldTypeId = IntegerFieldTypeId;
                newActivityAttribute.EntityTypeId = locationEntityTypeId;
                newActivityAttribute.EntityTypeQualifierValue = string.Empty;
                newActivityAttribute.EntityTypeQualifierColumn = string.Empty;
                newActivityAttribute.Description = "The FellowshipOne identifier for the activity that was imported";
                newActivityAttribute.DefaultValue = string.Empty;
                newActivityAttribute.IsMultiValue = false;
                newActivityAttribute.IsRequired = false;
                newActivityAttribute.Order = 0;

                attributeService.Add( newActivityAttribute, ImportPersonAlias );
                attributeService.Save( newActivityAttribute, ImportPersonAlias );
                activityAttributeId = newActivityAttribute.Id;
            }

            var rlcAttribute = AttributeCache.Read( rlcAttributeId );
            var activityAttribute = AttributeCache.Read( activityAttributeId );

            // Get any previously imported RLCs
            var importedRLC = new AttributeValueService().GetByAttributeId( rlcAttributeId )
                .Select( av => new { RLCId = av.Value.AsType<int?>(), LocationId = av.EntityId } )
                .ToDictionary( t => t.RLCId, t => t.LocationId );

            ImportedActivities = new AttributeValueService().GetByAttributeId( activityAttributeId )
                .Select( av => new { ActivityId = av.Value.AsType<int?>(), GroupId = av.EntityId } )
                .ToDictionary( t => t.ActivityId, t => t.GroupId );

            foreach ( var row in tableData )
            {
                int? rlcId = row["RLC_ID"] as int?;
                if ( rlcId != null && !importedRLC.ContainsKey( rlcId ) )
                {
                    // Activity_ID
                    // RLC_Name
                    // Activity_Group_ID
                    // Start_Age_Date
                    // End_Age_Date
                    // Is_Active
                    // Room_Code
                    // Room_Desc
                    // Room_Name
                    // Max_Capacity
                    // Building_Name
                }
            }
        }
Example #41
0
        /// <summary>
        /// Adds any registration templates given in the XML file.
        /// </summary>
        /// <param name="elemFamilies"></param>
        /// <param name="rockContext"></param>
        private void AddRegistrationTemplates( XElement elemRegistrationTemplates, RockContext rockContext )
        {
            if ( elemRegistrationTemplates == null )
            {
                return;
            }

            // Get attribute values from RegistrationTemplateDetail block
            // Get instance of the attribute.
            string defaultConfirmationEmail = string.Empty;
            string defaultReminderEmail = string.Empty;
            string defaultSuccessText = string.Empty;
            string defaultPaymentReminderEmail = string.Empty;

            //CodeEditorFieldAttribute MyAttribute = (CodeEditorFieldAttribute)System.Attribute.GetCustomAttribute( typeof( RockWeb.Blocks.Event.RegistrationTemplateDetail ), typeof( CodeEditorFieldAttribute ) );
            var blockAttributes = System.Attribute.GetCustomAttributes( typeof( RockWeb.Blocks.Event.RegistrationTemplateDetail ), typeof( CodeEditorFieldAttribute ) );
            foreach ( CodeEditorFieldAttribute blockAttribute in blockAttributes )
            {
                switch ( blockAttribute.Name )
                {
                    case "Default Confirmation Email":
                        defaultConfirmationEmail = blockAttribute.DefaultValue;
                        break;

                    case "Default Reminder Email":
                        defaultReminderEmail = blockAttribute.DefaultValue;
                        break;

                    case "Default Success Text":
                        defaultSuccessText = blockAttribute.DefaultValue;
                        break;

                    case "Default Payment Reminder Email":
                        defaultPaymentReminderEmail = blockAttribute.DefaultValue;
                        break;

                    default:
                        break;
                }
            }

            RegistrationTemplateService registrationTemplateService = new RegistrationTemplateService( rockContext );

            // Add a template for each...
            foreach ( var element in elemRegistrationTemplates.Elements( "registrationTemplate" ) )
            {
                // skip any illegally formatted items
                if ( element.Attribute( "guid" ) == null )
                {
                    continue;
                }

                int categoryId = CategoryCache.Read( element.Attribute( "categoryGuid" ).Value.Trim().AsGuid() ).Id;

                // Find the group type and
                var groupType = GroupTypeCache.Read( element.Attribute( "groupTypeGuid" ).Value.Trim().AsGuid() );

                RegistrantsSameFamily registrantsSameFamily;
                if ( element.Attribute( "registrantsInSameFamily" ) != null )
                {
                    Enum.TryParse( element.Attribute( "registrantsInSameFamily" ).Value.Trim(), out registrantsSameFamily );
                }
                else
                {
                    registrantsSameFamily = RegistrantsSameFamily.Ask;
                }

                bool setCostOnInstance = true;
                if ( element.Attribute( "setCostOn" ).Value.Trim() == "template" )
                {
                    setCostOnInstance = false;
                }

                RegistrationNotify notify = RegistrationNotify.None;
                RegistrationNotify matchNotify;
                foreach ( string item in element.Attribute( "notify" ).Value.SplitDelimitedValues( whitespace: false ) )
                {
                    if ( Enum.TryParse( item.Replace( " ", string.Empty ), out matchNotify ) )
                    {
                        notify = notify | matchNotify;
                    }
                }

                // Now find the matching financial gateway
                FinancialGatewayService financialGatewayService = new FinancialGatewayService( rockContext );
                string gatewayName = element.Attribute( "financialGateway" ) != null ? element.Attribute( "financialGateway" ).Value : "Test Gateway";
                var financialGateway = financialGatewayService.Queryable()
                    .Where( g => g.Name == gatewayName )
                    .FirstOrDefault();

                RegistrationTemplate registrationTemplate = new RegistrationTemplate()
                {
                    Guid = element.Attribute( "guid" ).Value.Trim().AsGuid(),
                    Name = element.Attribute( "name" ).Value.Trim(),
                    IsActive = true,
                    CategoryId = categoryId,
                    GroupTypeId = groupType.Id,
                    GroupMemberRoleId = groupType.DefaultGroupRoleId,
                    GroupMemberStatus = GroupMemberStatus.Active,
                    Notify = notify,
                    AddPersonNote = element.Attribute( "addPersonNote" ) != null ? element.Attribute( "addPersonNote" ).Value.AsBoolean() : false,
                    LoginRequired = element.Attribute( "loginRequired" ) != null ? element.Attribute( "loginRequired" ).Value.AsBoolean() : false,
                    AllowExternalRegistrationUpdates = element.Attribute( "allowExternalUpdatesToSavedRegistrations" ) != null ? element.Attribute( "allowExternalUpdatesToSavedRegistrations" ).Value.AsBoolean() : false,
                    AllowGroupPlacement = element.Attribute( "allowGroupPlacement" ) != null ? element.Attribute( "allowGroupPlacement" ).Value.AsBoolean() : false,
                    AllowMultipleRegistrants = element.Attribute( "allowMultipleRegistrants" ) != null ? element.Attribute( "allowMultipleRegistrants" ).Value.AsBoolean() : false,
                    MaxRegistrants = element.Attribute( "maxRegistrants" ).Value.AsInteger(),
                    RegistrantsSameFamily = registrantsSameFamily,
                    SetCostOnInstance = setCostOnInstance,
                    FinancialGatewayId = financialGateway.Id,
                    BatchNamePrefix = element.Attribute( "batchNamePrefix" ) != null ? element.Attribute( "batchNamePrefix" ).Value.Trim() : string.Empty,
                    Cost = element.Attribute( "cost" ).Value.AsDecimal(),
                    MinimumInitialPayment = element.Attribute( "minInitialPayment" ).Value.AsDecimal(),
                    RegistrationTerm = element.Attribute( "registrationTerm" ) != null ? element.Attribute( "registrationTerm" ).Value.Trim() : "Registration",
                    RegistrantTerm = element.Attribute( "registrantTerm" ) != null ? element.Attribute( "registrantTerm" ).Value.Trim() : "Registrant",
                    FeeTerm = element.Attribute( "feeTerm" ) != null ? element.Attribute( "feeTerm" ).Value.Trim() : "Additional Options",
                    DiscountCodeTerm = element.Attribute( "discountCodeTerm" ) != null ? element.Attribute( "discountCodeTerm" ).Value.Trim() : "Discount Code",
                    ConfirmationFromName = "{{ RegistrationInstance.ContactPersonAlias.Person.FullName }}",
                    ConfirmationFromEmail = "{{ RegistrationInstance.ContactEmail }}",
                    ConfirmationSubject = "{{ RegistrationInstance.Name }} Confirmation",
                    ConfirmationEmailTemplate = defaultConfirmationEmail,
                    ReminderFromName = "{{ RegistrationInstance.ContactPersonAlias.Person.FullName }}",
                    ReminderFromEmail = "{{ RegistrationInstance.ContactEmail }}",
                    ReminderSubject = "{{ RegistrationInstance.Name }} Reminder",
                    ReminderEmailTemplate = defaultReminderEmail,
                    SuccessTitle = "Congratulations {{ Registration.FirstName }}",
                    SuccessText = defaultSuccessText,
                    PaymentReminderEmailTemplate = defaultPaymentReminderEmail,
                    PaymentReminderFromEmail = "{{ RegistrationInstance.ContactEmail }}",
                    PaymentReminderFromName = "{{ RegistrationInstance.ContactPersonAlias.Person.FullName }}",
                    PaymentReminderSubject = "{{ RegistrationInstance.Name }} Payment Reminder",
                    PaymentReminderTimeSpan = element.Attribute( "paymentReminderTimeSpan" ) != null ? element.Attribute( "paymentReminderTimeSpan" ).Value.AsInteger() : 0,
                    CreatedDateTime = RockDateTime.Now,
                    ModifiedDateTime = RockDateTime.Now,
                };

                registrationTemplateService.Add( registrationTemplate );

                rockContext.SaveChanges();
                var x = registrationTemplate.Id;

                string name = element.Attribute( "name" ).Value.Trim();
                bool allowExternalUpdatesToSavedRegistrations = element.Attribute( "allowExternalUpdatesToSavedRegistrations" ).Value.AsBoolean();
                bool addPersonNote = element.Attribute( "addPersonNote" ).Value.AsBoolean();
                bool loginRequired = element.Attribute( "loginRequired" ).Value.AsBoolean();
                Guid guid = element.Attribute( "guid" ).Value.Trim().AsGuid();

                // Find any Form elements and add them to the template
                int formOrder = 0;
                var registrationAttributeQualifierColumn = "RegistrationTemplateId";
                int? registrationRegistrantEntityTypeId = EntityTypeCache.Read( typeof( Rock.Model.RegistrationRegistrant ) ).Id;
                if ( element.Elements( "forms" ).Count() > 0 )
                {
                    foreach ( var formElement in element.Elements( "forms" ).Elements( "form" ) )
                    {
                        formOrder++;
                        var form = new RegistrationTemplateForm();
                        form.Guid = formElement.Attribute( "guid" ).Value.Trim().AsGuid();
                        registrationTemplate.Forms.Add( form );
                        form.Name = formElement.Attribute( "name" ).Value.Trim();
                        form.Order = formOrder;

                        int ffOrder = 0;
                        if ( formElement.Elements( "formFields" ).Count() > 0 )
                        {
                            foreach ( var formFieldElement in formElement.Elements( "formFields" ).Elements( "field" ) )
                            {
                                ffOrder++;
                                var formField = new RegistrationTemplateFormField();
                                formField.Guid = Guid.NewGuid();
                                formField.CreatedDateTime = RockDateTime.Now;

                                form.Fields.Add( formField );

                                switch ( formFieldElement.Attribute( "source" ).Value.Trim().ToLowerInvariant() )
                                {
                                    case "person field":
                                        formField.FieldSource = RegistrationFieldSource.PersonField;
                                        break;
                                    case "person attribute":
                                        formField.FieldSource = RegistrationFieldSource.PersonAttribute;
                                        break;
                                    case "group member attribute":
                                        formField.FieldSource = RegistrationFieldSource.GroupMemberAttribute;
                                        break;
                                    case "registration attribute":
                                        formField.FieldSource = RegistrationFieldSource.RegistrationAttribute;

                                        //var qualifierValue = RegistrationTemplate.Id.ToString();
                                        var attrState = new Rock.Model.Attribute();

                                        attrState.Guid = formFieldElement.Attribute( "guid" ).Value.AsGuid();
                                        attrState.Name = formFieldElement.Attribute( "name" ).Value.Trim();
                                        attrState.Key = attrState.Name.RemoveSpecialCharacters().Replace( " ", string.Empty );
                                        var type = formFieldElement.Attribute( "type" ).Value.Trim();
                                        var fieldType = FieldTypeCache.All().Where( f => f.Name == type ).FirstOrDefault();
                                        attrState.FieldTypeId = fieldType.Id;
                                        var attribute = Helper.SaveAttributeEdits( attrState, registrationRegistrantEntityTypeId, registrationAttributeQualifierColumn, registrationTemplate.Id.ToString(), rockContext );
                                        //rockContext.ChangeTracker.DetectChanges();
                                        rockContext.SaveChanges( disablePrePostProcessing: true );
                                        formField.Attribute = attribute;

                                        break;
                                    default:
                                        throw new NotSupportedException( string.Format( "unknown form field source: {0}", formFieldElement.Attribute( "source" ).Value ) );
                                }

                                formField.AttributeId = null;
                                if ( !formField.AttributeId.HasValue &&
                                    formField.FieldSource == RegistrationFieldSource.RegistrationAttribute &&
                                    formField.Attribute != null )
                                {
                                    var attr = AttributeCache.Read( formField.Attribute.Guid, rockContext );
                                    if ( attr != null )
                                    {
                                        formField.AttributeId = attr.Id;
                                    }
                                }

                                RegistrationPersonFieldType registrationPersonFieldType;
                                if ( formField.FieldSource == RegistrationFieldSource.PersonField && formFieldElement.Attribute( "name" ) != null &&
                                    Enum.TryParse( formFieldElement.Attribute( "name" ).Value.Replace( " ", string.Empty ).Trim(), out registrationPersonFieldType ) )
                                {
                                    formField.PersonFieldType = registrationPersonFieldType;
                                }

                                formField.IsInternal = formFieldElement.Attribute( "isInternal" ) != null ? formFieldElement.Attribute( "isInternal" ).Value.AsBoolean() : false;
                                formField.IsSharedValue = formFieldElement.Attribute( "isCommon" ) != null ? formFieldElement.Attribute( "isCommon" ).Value.AsBoolean() : false;
                                formField.ShowCurrentValue = formFieldElement.Attribute( "showCurrentValue" ) != null ? formFieldElement.Attribute( "showCurrentValue" ).Value.AsBoolean() : false;
                                formField.PreText = formFieldElement.Attribute( "preText" ) != null ? formFieldElement.Attribute( "preText" ).Value : string.Empty;
                                formField.PostText = formFieldElement.Attribute( "postText" ) != null ? formFieldElement.Attribute( "postText" ).Value : string.Empty;
                                formField.IsGridField = formFieldElement.Attribute( "showOnGrid" ) != null ? formFieldElement.Attribute( "showOnGrid" ).Value.AsBoolean() : false;
                                formField.IsRequired = formFieldElement.Attribute( "isRequired" ) != null ? formFieldElement.Attribute( "isRequired" ).Value.AsBoolean() : false;
                                formField.Order = ffOrder;
                                formField.CreatedDateTime = RockDateTime.Now;
                            }
                        }
                    }
                }

                // Discounts
                int discountOrder = 0;
                if ( element.Elements( "discounts" ) != null )
                {
                    foreach ( var discountElement in element.Elements( "discounts" ).Elements( "discount" ) )
                    {
                        discountOrder++;
                        var discount = new RegistrationTemplateDiscount();
                        discount.Guid = Guid.NewGuid();
                        registrationTemplate.Discounts.Add( discount );

                        discount.Code = discountElement.Attribute( "code" ).Value;

                        switch ( discountElement.Attribute( "type" ).Value.Trim().ToLowerInvariant() )
                        {
                            case "percentage":
                                discount.DiscountPercentage = discountElement.Attribute( "value" ).Value.Trim().AsDecimal() * 0.01m;
                                discount.DiscountAmount = 0.0m;
                                break;
                            case "amount":
                                discount.DiscountPercentage = 0.0m;
                                discount.DiscountAmount = discountElement.Attribute( "value" ).Value.Trim().AsDecimal();
                                break;
                            default:
                                throw new NotSupportedException( string.Format( "unknown discount type: {0}", discountElement.Attribute( "type" ).Value ) );
                        }
                        discount.Order = discountOrder;
                    }
                }

                // Fees
                int feeOrder = 0;
                if ( element.Elements( "fees" ) != null )
                {
                    foreach ( var feeElement in element.Elements( "fees" ).Elements( "fee" ) )
                    {
                        feeOrder++;
                        var fee = new RegistrationTemplateFee();
                        fee.Guid = Guid.NewGuid();
                        registrationTemplate.Fees.Add( fee );

                        switch ( feeElement.Attribute( "type" ).Value.Trim().ToLowerInvariant() )
                        {
                            case "multiple":
                                fee.FeeType = RegistrationFeeType.Multiple;
                                fee.CostValue = FormatMultipleFeeCosts( feeElement.Elements( "option" ) );
                                break;
                            case "single":
                                fee.FeeType = RegistrationFeeType.Single;
                                fee.CostValue = feeElement.Attribute( "cost" ).Value.Trim();
                                break;
                            default:
                                throw new NotSupportedException( string.Format( "unknown fee type: {0}", feeElement.Attribute( "type" ).Value ) );
                        }

                        fee.Name = feeElement.Attribute( "name" ).Value.Trim();
                        fee.DiscountApplies = feeElement.Attribute( "discountApplies" ).Value.AsBoolean();
                        fee.AllowMultiple = feeElement.Attribute( "enableQuantity" ).Value.AsBoolean();
                        fee.Order = feeOrder;
                    }
                }
            }
        }
Example #42
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="attributeId">The attribute id.</param>
        protected void ShowEdit( int attributeId )
        {
            var rockContext = new RockContext();
            var attributeService = new AttributeService( rockContext );
            var attributeModel = attributeService.Get( attributeId );

            if ( attributeModel == null )
            {
                mdAttribute.Title = "Add Attribute".FormatAsHtmlTitle();

                attributeModel = new Rock.Model.Attribute();
                attributeModel.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT ).Id;

                if ( !_configuredType )
                {
                    int entityTypeId = int.MinValue;
                    if ( int.TryParse( rFilter.GetUserPreference( "Entity Type" ), out entityTypeId ) && entityTypeId > 0 )
                    {
                        attributeModel.EntityTypeId = entityTypeId;
                    }
                }
                else
                {
                    attributeModel.EntityTypeId = _entityTypeId;
                    attributeModel.EntityTypeQualifierColumn = _entityQualifierColumn;
                    attributeModel.EntityTypeQualifierValue = _entityQualifierValue;
                }

                List<int> selectedCategoryIds = cpCategoriesFilter.SelectedValuesAsInt().ToList();
                new CategoryService( rockContext ).Queryable().Where( c => selectedCategoryIds.Contains( c.Id ) ).ToList().ForEach( c =>
                    attributeModel.Categories.Add( c ) );
                edtAttribute.ActionTitle = Rock.Constants.ActionTitle.Add( Rock.Model.Attribute.FriendlyTypeName );
            }
            else
            {
                if ( attributeModel.EntityType != null && attributeModel.EntityType.IsIndexingSupported == true && attributeModel.EntityType.IsIndexingEnabled )
                {
                    edtAttribute.IsIndexingEnabledVisible = true;
                }

                edtAttribute.ActionTitle = Rock.Constants.ActionTitle.Edit( Rock.Model.Attribute.FriendlyTypeName );
                mdAttribute.Title = ( "Edit " + attributeModel.Name ).FormatAsHtmlTitle();

                edtAttribute.IsIndexingEnabled = attributeModel.IsIndexEnabled;
            }

            Type type = null;
            if ( attributeModel.EntityTypeId.HasValue )
            {
                type = EntityTypeCache.Read( attributeModel.EntityTypeId.Value ).GetEntityType();
                edtAttribute.ReservedKeyNames = attributeService.Get( attributeModel.EntityTypeId, attributeModel.EntityTypeQualifierColumn, attributeModel.EntityTypeQualifierValue )
                    .Where( a => a.Id != attributeId )
                    .Select( a => a.Key )
                    .Distinct()
                    .ToList();
            }

            edtAttribute.SetAttributeProperties( attributeModel, type );
            edtAttribute.AttributeEntityTypeId = attributeModel.EntityTypeId;

            if ( _configuredType )
            {
                pnlEntityTypeQualifier.Visible = false;
            }
            else
            {
                pnlEntityTypeQualifier.Visible = true;

                ddlAttrEntityType.SetValue( attributeModel.EntityTypeId.HasValue ? attributeModel.EntityTypeId.Value.ToString() : "0" );
                tbAttrQualifierField.Text = attributeModel.EntityTypeQualifierColumn;
                tbAttrQualifierValue.Text = attributeModel.EntityTypeQualifierValue;
            }

            ShowDialog( "Attribute", true );
        }
        /// <summary>
        /// Gs the marketing campaign ad attribute type_ show edit.
        /// </summary>
        /// <param name="attributeId">The attribute id.</param>
        protected void gMarketingCampaignAdAttributeType_ShowEdit( Guid attributeGuid )
        {
            pnlDetails.Visible = false;
            pnlAdTypeAttribute.Visible = true;

            Attribute attribute;
            if ( attributeGuid.Equals( Guid.Empty ) )
            {
                attribute = new Attribute();
                attribute.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT ).Id;
                edtAdTypeAttributes.ActionTitle = ActionTitle.Add( "attribute for ad type " + tbName.Text );

            }
            else
            {
                attribute = AttributesState.First( a => a.Guid.Equals( attributeGuid ) );
                edtAdTypeAttributes.ActionTitle = ActionTitle.Edit( "attribute for ad type " + tbName.Text );
            }

            edtAdTypeAttributes.ReservedKeyNames = AttributesState.Where( a => !a.Guid.Equals( attributeGuid ) ).Select( a => a.Key ).ToList();

            edtAdTypeAttributes.SetAttributeProperties( attribute, typeof( MarketingCampaignAd ) );
        }
Example #44
0
        /// <summary>
        /// Gs the defined type attributes_ show edit.
        /// </summary>
        /// <param name="attributeGuid">The attribute GUID.</param>
        protected void gDefinedTypeAttributes_ShowEdit( Guid attributeGuid )
        {
            pnlDetails.Visible = false;
            vsDetails.Enabled = false;
            pnlDefinedTypeAttributes.Visible = true;

            Attribute attribute;
            if ( attributeGuid.Equals( Guid.Empty ) )
            {
                attribute = new Attribute();
                attribute.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT ).Id;
                edtDefinedTypeAttributes.ActionTitle = ActionTitle.Add( "attribute for defined type " + tbTypeName.Text );
            }
            else
            {
                AttributeService attributeService = new AttributeService();
                attribute = attributeService.Get( attributeGuid );
                edtDefinedTypeAttributes.ActionTitle = ActionTitle.Edit( "attribute for defined type " + tbTypeName.Text );
            }

            edtDefinedTypeAttributes.SetAttributeProperties( attribute, typeof( DefinedValue ) );

            this.HideSecondaryBlocks( true );
        }
        /// <summary>
        /// Gs the defined type attributes_ show edit.
        /// </summary>
        /// <param name="attributeGuid">The attribute GUID.</param>
        protected void gDefinedTypeAttributes_ShowEdit( Guid attributeGuid )
        {
            pnlDetails.Visible = false;
            vsDetails.Enabled = false;
            pnlDefinedTypeAttributes.Visible = true;

            Attribute attribute;
            if ( attributeGuid.Equals( Guid.Empty ) )
            {
                attribute = new Attribute();
                attribute.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT ).Id;
                edtDefinedTypeAttributes.ActionTitle = ActionTitle.Add( "attribute for defined type " + tbTypeName.Text );
            }
            else
            {
                AttributeService attributeService = new AttributeService( new RockContext() );
                attribute = attributeService.Get( attributeGuid );
                edtDefinedTypeAttributes.ActionTitle = ActionTitle.Edit( "attribute for defined type " + tbTypeName.Text );
            }

            edtDefinedTypeAttributes.ReservedKeyNames = new AttributeService( new RockContext() )
                .GetByEntityTypeId( new DefinedValue().TypeId ).AsQueryable()
                .Where( a =>
                    a.EntityTypeQualifierColumn.Equals( "DefinedTypeId", StringComparison.OrdinalIgnoreCase ) &&
                    a.EntityTypeQualifierValue.Equals( hfDefinedTypeId.Value ) &&
                    !a.Guid.Equals(attributeGuid) )
                .Select( a => a.Key )
                .Distinct()
                .ToList();

            edtDefinedTypeAttributes.SetAttributeProperties( attribute, typeof( DefinedValue ) );

            this.HideSecondaryBlocks( true );
        }
Example #46
0
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            // Get the number of minutes to delay
            int? minutes = GetAttributeValue( action, "MinutesToDelay" ).AsIntegerOrNull();
            if ( !minutes.HasValue || minutes.Value <= 0 )
            {
                return true;
            }

            // Use the current action type' guid as the key for a 'Delay Activated' attribute
            string AttrKey = action.ActionType.Guid.ToString();

            // Check to see if the action's activity does not yet have the the 'Delay Activated' attribute.
            // The first time this action runs on any workflow instance using this action instance, the
            // attribute will not exist and need to be created
            if ( !action.Activity.Attributes.ContainsKey( AttrKey ) )
            {
                var attribute = new Rock.Model.Attribute();
                attribute.EntityTypeId = action.Activity.TypeId;
                attribute.EntityTypeQualifierColumn = "ActivityTypeId";
                attribute.EntityTypeQualifierValue = action.Activity.ActivityTypeId.ToString();
                attribute.Name = "Delay Activated";
                attribute.Key = AttrKey;
                attribute.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT.AsGuid() ).Id;

                // Need to save the attribute now (using different context) so that an attribute id is returned.
                var newRockContext = new RockContext();
                new AttributeService( newRockContext ).Add( attribute );
                newRockContext.SaveChanges();

                action.Activity.Attributes.Add( AttrKey, AttributeCache.Read( attribute ) );
                var attributeValue = new Rock.Model.AttributeValue();
                attributeValue.AttributeId = attribute.Id;
                attributeValue.Value = RockDateTime.Now.ToString( "o" );
                action.Activity.AttributeValues.Add( AttrKey, attributeValue );

                action.AddLogEntry( string.Format( "{0:N0} Minute Delay Activated.", minutes.Value ), true );
            }
            else
            {
                // Check to see if this action instance has a value for the 'Delay Activated' attrbute
                DateTime? activated = action.Activity.GetAttributeValue( AttrKey ).AsDateTime();
                if ( !activated.HasValue )
                {
                    // If no value exists, set the value to the current time
                    action.Activity.SetAttributeValue( AttrKey, RockDateTime.Now.ToString( "o" ) );
                    action.AddLogEntry( string.Format( "{0:N0} Minute Delay Activated.", minutes.Value ), true );
                }
                else
                {
                    // If a value does exist, check to see if the number of minutes to delay has passed
                    // since the value was saved
                    if ( activated.Value.AddMinutes( minutes.Value ).CompareTo( RockDateTime.Now ) < 0 )
                    {

                        // If delay has elapsed, return True ( so that processing of activity will continue )
                        action.AddLogEntry( string.Format( "{0:N0} Minute Delay Completed.", minutes.Value ), true );
                        return true;
                    }
                }
            }

            // If delay has not elapsed, return false so that processing of activity stops
            return false;
        }
Example #47
0
        /// <summary>
        /// Shows the attribute edit.
        /// </summary>
        /// <param name="attributeGuid">The attribute unique identifier.</param>
        private void ShowActivityAttributeEdit( Guid activityTypeGuid, Guid attributeGuid )
        {
            if ( ActivityAttributesState.ContainsKey( activityTypeGuid ) )
            {
                var attributeList = ActivityAttributesState[activityTypeGuid];

                Attribute attribute;
                if ( attributeGuid.Equals( Guid.Empty ) )
                {
                    attribute = new Attribute();
                    attribute.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT ).Id;
                    edtActivityAttributes.ActionTitle = ActionTitle.Add( "Add Activity Attribute" );
                }
                else
                {
                    attribute = attributeList.First( a => a.Guid.Equals( attributeGuid ) );
                    edtActivityAttributes.ActionTitle = ActionTitle.Edit( "Edit Activity Attribute" );
                }

                edtActivityAttributes.ReservedKeyNames = attributeList.Where( a => !a.Guid.Equals( attributeGuid ) ).Select( a => a.Key ).ToList();

                edtActivityAttributes.SetAttributeProperties( attribute, typeof( WorkflowActivity ) );

                hfActivityTypeGuid.Value = activityTypeGuid.ToString();

                ShowDialog( "ActivityAttributes" );
            }

            BuildControls( true );
        }
Example #48
0
        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        /// <param name="saveValue">if set to <c>true</c> [save value].</param>
        /// <param name="rockContext">The rock context.</param>
        public void SetValue( string key, string value, bool saveValue, RockContext rockContext = null )
        {
            if ( saveValue )
            {
                if ( rockContext == null )
                {
                    rockContext = new RockContext();
                }

                // Save new value
                var attributeValueService = new AttributeValueService( rockContext );
                var attributeValue = attributeValueService.GetGlobalAttributeValue( key );

                if ( attributeValue == null )
                {
                    var attributeService = new AttributeService( rockContext );
                    var attribute = attributeService.GetGlobalAttribute( key );
                    if ( attribute == null )
                    {
                        attribute = new Rock.Model.Attribute();
                        attribute.FieldTypeId = FieldTypeCache.Read( new Guid( SystemGuid.FieldType.TEXT ) ).Id;
                        attribute.EntityTypeQualifierColumn = string.Empty;
                        attribute.EntityTypeQualifierValue = string.Empty;
                        attribute.Key = key;
                        attribute.Name = key.SplitCase();
                        attributeService.Add( attribute );
                        rockContext.SaveChanges();

                        Attributes.Add( AttributeCache.Read( attribute.Id ) );
                    }

                    attributeValue = new AttributeValue();
                    attributeValueService.Add( attributeValue );
                    attributeValue.IsSystem = false;
                    attributeValue.AttributeId = attribute.Id;

                    if ( !AttributeValues.Keys.Contains( key ) )
                    {
                        AttributeValues.Add( key, new KeyValuePair<string, string>( attribute.Name, value ) );
                    }
                }

                attributeValue.Value = value;
                rockContext.SaveChanges();
            }

            var attributeCache = Attributes.FirstOrDefault( a => a.Key.Equals( key, StringComparison.OrdinalIgnoreCase ) );
            if ( attributeCache != null ) // (Should never be null)
            {
                if ( AttributeValues.Keys.Contains( key ) )
                {
                    AttributeValues[key] = new KeyValuePair<string, string>( attributeCache.Name, value );
                }
                else
                {
                    AttributeValues.Add( key, new KeyValuePair<string, string>( attributeCache.Name, value ) );
                }
            }
        }
        /// <summary>
        /// Gs the group attributes_ show edit.
        /// </summary>
        /// <param name="attributeGuid">The attribute GUID.</param>
        protected void gGroupMemberAttributes_ShowEdit( Guid attributeGuid )
        {
            Attribute attribute;
            if ( attributeGuid.Equals( Guid.Empty ) )
            {
                attribute = new Attribute();
                attribute.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT ).Id;
                edtGroupMemberAttributes.ActionTitle = ActionTitle.Add( "attribute for members in groups of group type " + tbName.Text );
            }
            else
            {
                attribute = GroupMemberAttributesState.First( a => a.Guid.Equals( attributeGuid ) );
                edtGroupMemberAttributes.ActionTitle = ActionTitle.Edit( "attribute for members in groups of group type " + tbName.Text );
            }

            var reservedKeyNames = new List<string>();
            GroupMemberAttributesInheritedState.Select( a => a.Key ).ToList().ForEach( a => reservedKeyNames.Add( a ) );
            GroupMemberAttributesState.Where( a => !a.Guid.Equals( attributeGuid ) ).Select( a => a.Key ).ToList().ForEach( a => reservedKeyNames.Add( a ) );
            edtGroupMemberAttributes.ReservedKeyNames = reservedKeyNames.ToList();

            edtGroupMemberAttributes.SetAttributeProperties( attribute, typeof( GroupMember ) );

            ShowDialog( "GroupMemberAttributes" );
        }
Example #50
0
        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        /// <param name="saveValue">if set to <c>true</c> [save value].</param>
        /// <param name="rockContext">The rock context.</param>
        public void SetValue( string key, string value, bool saveValue, RockContext rockContext )
        {
            AttributeCache attributeCache = null;

            if ( saveValue )
            {
                // Save new value
                rockContext = rockContext ?? new RockContext();
                var attributeValueService = new AttributeValueService( rockContext );
                var attributeValue = attributeValueService.GetGlobalAttributeValue( key );

                if ( attributeValue == null )
                {
                    var attributeService = new AttributeService( rockContext );
                    var attribute = attributeService.GetGlobalAttribute( key );
                    if ( attribute == null )
                    {
                        attribute = new Rock.Model.Attribute();
                        attribute.FieldTypeId = FieldTypeCache.Read( new Guid( SystemGuid.FieldType.TEXT ) ).Id;
                        attribute.EntityTypeQualifierColumn = string.Empty;
                        attribute.EntityTypeQualifierValue = string.Empty;
                        attribute.Key = key;
                        attribute.Name = key.SplitCase();
                        attributeService.Add( attribute );
                        rockContext.SaveChanges();
                    }

                    attributeValue = new AttributeValue();
                    attributeValue.IsSystem = false;
                    attributeValue.AttributeId = attribute.Id;
                    attributeValueService.Add( attributeValue );
                }

                attributeValue.Value = value;
                rockContext.SaveChanges();
            }

            lock(_obj)
            {
                attributeIds = null;
            }

            AttributeValues.AddOrUpdate( key, value, ( k, v ) => value );

            attributeCache = Attributes.FirstOrDefault( a => a.Key.Equals( key, StringComparison.OrdinalIgnoreCase ) );
            if ( attributeCache != null )
            {
                value = attributeCache.FieldType.Field.FormatValue( null, value, attributeCache.QualifierValues, false );
            }
            AttributeValuesFormatted.AddOrUpdate( key, value, (k, v) => value);
        }
        /// <summary>
        /// Handles the Click event of the btnSaveBinaryFileAttribute 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 btnSaveBinaryFileAttribute_Click( object sender, EventArgs e )
        {
            Attribute attribute = new Attribute();
            edtBinaryFileAttributes.GetAttributeProperties( attribute );

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

            BinaryFileAttributesState.RemoveEntity( attribute.Guid );
            BinaryFileAttributesState.Add( attribute );

            pnlDetails.Visible = true;
            pnlBinaryFileAttribute.Visible = false;

            BindBinaryFileAttributesGrid();
        }
        /// <summary>
        /// Shows the edit attribute dialog.
        /// </summary>
        /// <param name="attributeGuid">The attribute unique identifier.</param>
        protected void gAttributes_ShowEdit( Guid attributeGuid )
        {
            Attribute attribute;
            if ( attributeGuid.Equals( Guid.Empty ) )
            {
                attribute = new Attribute();
                attribute.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT ).Id;
            }
            else
            {
                attribute = AttributesState.First( a => a.Guid.Equals( attributeGuid ) );
            }

            edtAttributes.ActionTitle = ActionTitle.Edit( "attribute for Opportunities of Connection type " + tbName.Text );
            var reservedKeyNames = new List<string>();
            AttributesState.Where( a => !a.Guid.Equals( attributeGuid ) ).Select( a => a.Key ).ToList().ForEach( a => reservedKeyNames.Add( a ) );
            edtAttributes.AllowSearchVisible = true;
            edtAttributes.ReservedKeyNames = reservedKeyNames.ToList();
            edtAttributes.SetAttributeProperties( attribute, typeof( ConnectionType ) );

            ShowDialog( "Attributes" );
        }
Example #53
0
        private string EmailStatus( WorkflowAction action )
        {
            // Use the current action type' guid as the key for a 'Email Status' attribute
            string AttrKey = action.ActionType.Guid.ToString() + "_EmailStatus";

            // Check to see if the action's activity does not yet have the the 'Email Status' attribute.
            // The first time this action runs on any workflow instance using this action instance, the
            // attribute will not exist and need to be created
            if ( !action.Activity.Attributes.ContainsKey( AttrKey ) )
            {
                var attribute = new Rock.Model.Attribute();
                attribute.EntityTypeId = action.Activity.TypeId;
                attribute.EntityTypeQualifierColumn = "ActivityTypeId";
                attribute.EntityTypeQualifierValue = action.Activity.ActivityTypeId.ToString();
                attribute.Name = "Email Status";
                attribute.Key = AttrKey;
                attribute.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT.AsGuid() ).Id;

                // Need to save the attribute now (using different context) so that an attribute id is returned.
                using ( var newRockContext = new RockContext() )
                {
                    new AttributeService( newRockContext ).Add( attribute );
                    newRockContext.SaveChanges();
                }

                action.Activity.Attributes.Add( AttrKey, AttributeCache.Read( attribute ) );
                var attributeValue = new AttributeValueCache();
                attributeValue.AttributeId = attribute.Id;
                attributeValue.Value = string.Empty;
                action.Activity.AttributeValues.Add( AttrKey, attributeValue );
            }
            else
            {
                return action.Activity.GetAttributeValue( AttrKey );
            }

            return string.Empty;
        }
Example #54
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            using ( new UnitOfWorkScope() )
            {
                var attributeService = new AttributeService();
                var attributeQualifierService = new AttributeQualifierService();

                Rock.Model.Attribute attribute;

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

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

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

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

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

                attribute.AttributeQualifiers.Clear();

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

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

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

                attributeService.Save( attribute, CurrentPersonId );
            }

            BindGrid();

            pnlDetails.Visible = false;
            pnlList.Visible = true;
        }
Example #55
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 );
        }
        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        public static void SetValue( string key, string value )
        {
            var rockContext = new Rock.Data.RockContext();
            var attributeService = new AttributeService( rockContext );
            var attribute = attributeService.GetSystemSetting( key );

            if ( attribute == null )
            {
                attribute = new Rock.Model.Attribute();
                attribute.FieldTypeId = FieldTypeCache.Read( new Guid( SystemGuid.FieldType.TEXT ) ).Id;
                attribute.EntityTypeQualifierColumn = Rock.Model.Attribute.SYSTEM_SETTING_QUALIFIER;
                attribute.EntityTypeQualifierValue = string.Empty;
                attribute.Key = key;
                attribute.Name = key.SplitCase();
                attribute.DefaultValue = value;
                attributeService.Add( attribute );
            }
            else
            {
                attribute.DefaultValue = value;
            }

            rockContext.SaveChanges();

            AttributeCache.Flush( attribute.Id );

            var settings = SystemSettings.Read();
            var attributeCache = settings.Attributes.FirstOrDefault( a => a.Key.Equals( key, StringComparison.OrdinalIgnoreCase ) );
            if ( attributeCache != null )
            {
                attributeCache.DefaultValue = value;
            }
            else
            {
                settings.Attributes.Add( AttributeCache.Read( attribute.Id ) );
            }
        }
Example #57
0
        /// <summary>
        /// Saves any attribute edits made using an Attribute Editor control
        /// </summary>
        /// <param name="edtAttribute">The edt attribute.</param>
        /// <param name="entityTypeId">The entity type identifier.</param>
        /// <param name="entityTypeQualifierColumn">The entity type qualifier column.</param>
        /// <param name="entityTypeQualifierValue">The entity type qualifier value.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        /// <remarks>
        /// If a rockContext value is included, this method will save any previous changes made to the context
        /// </remarks>
        public static Rock.Model.Attribute SaveAttributeEdits( AttributeEditor edtAttribute, int? entityTypeId, string entityTypeQualifierColumn, string entityTypeQualifierValue, RockContext rockContext = null )
        {
            // Create and update a new attribute object with new values
            var newAttribute = new Rock.Model.Attribute();
            edtAttribute.GetAttributeProperties( newAttribute );

            rockContext = rockContext ?? new RockContext();
            var internalAttributeService = new AttributeService( rockContext );
            Rock.Model.Attribute attribute = null;

            if ( newAttribute.Id > 0 )
            {
                attribute = internalAttributeService.Get( newAttribute.Id );
            }

            if ( attribute == null )
            {
                newAttribute.Order = internalAttributeService.Queryable().Max( a => a.Order ) + 1;
            }
            else
            {
                newAttribute.Order = attribute.Order;
            } 
            
            return SaveAttributeEdits( newAttribute, entityTypeId, entityTypeQualifierColumn, entityTypeQualifierValue, rockContext );
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            bool hasValidationErrors = false;

            var rockContext = new RockContext();

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

            int parentGroupTypeId = hfParentGroupTypeId.ValueAsInt();

            var groupTypeUIList = new List<GroupType>();

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

            var groupTypeDBList = new List<GroupType>();

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

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

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

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

            int binaryFileFieldTypeID = FieldTypeCache.Read( Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid() ).Id;

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

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

                rockContext.SaveChanges();

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

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

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

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

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

                        return;
                    }

                    rockContext.SaveChanges();

                    groupTypeDB.SaveAttributeValues( rockContext );

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

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

                    rockContext.SaveChanges();

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

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

                            return;
                        }

                        attributeService.Add( attribute );
                    }

                    rockContext.SaveChanges();
                }

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

                    groupDB.Name = groupUI.Name;

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

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

                    groupDB.Order = groupUI.Order;

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

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

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

                        return;
                    }

                    rockContext.SaveChanges();

                    groupDB.SaveAttributeValues();
                }

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

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

                rockContext.SaveChanges();

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

                rockContext.SaveChanges();
            } );

            if ( !hasValidationErrors )
            {
                NavigateToParentPage();
            }
        }
        /// <summary>
        /// Gs the marketing campaign ad attribute type_ show edit.
        /// </summary>
        /// <param name="attributeId">The attribute id.</param>
        protected void gItemAttributes_ShowEdit( Guid attributeGuid )
        {
            Attribute attribute;
            if ( attributeGuid.Equals( Guid.Empty ) )
            {
                attribute = new Attribute();
                attribute.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT ).Id;
                edtItemAttributes.ActionTitle = ActionTitle.Add( tbName.Text + " Item Attribute" );

            }
            else
            {
                attribute = ItemAttributesState.First( a => a.Guid.Equals( attributeGuid ) );
                edtItemAttributes.ActionTitle = ActionTitle.Edit( tbName.Text + " Item Attribute" );
            }

            edtItemAttributes.ReservedKeyNames = ItemAttributesState.Where( a => !a.Guid.Equals( attributeGuid ) ).Select( a => a.Key ).ToList();

            edtItemAttributes.SetAttributeProperties( attribute, typeof( ContentChannelItem ) );

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

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

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

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

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

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

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

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

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

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

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

            rockContext.SaveChanges();

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

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

            return attribute;
        }