Exemple #1
0
        /// <summary>
        /// Saves a <see cref="Rock.Model.Person">Person's</see> user preference setting by key.
        /// </summary>
        /// <param name="person">The <see cref="Rock.Model.Person"/> who the preference value belongs to.</param>
        /// <param name="key">A <see cref="System.String"/> representing the key (name) of the preference setting.</param>
        /// <param name="value">The value.</param>
        public static void SaveUserPreference(Person person, string key, string value)
        {
            int?PersonEntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(Person.USER_VALUE_ENTITY).Id;

            using (var rockContext = new RockContext())
            {
                var attributeService = new Model.AttributeService(rockContext);
                var attribute        = attributeService.Get(PersonEntityTypeId, string.Empty, string.Empty, key);

                if (attribute == null)
                {
                    var fieldTypeService = new Model.FieldTypeService(rockContext);
                    var fieldType        = FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid());

                    attribute              = new Model.Attribute();
                    attribute.IsSystem     = false;
                    attribute.EntityTypeId = PersonEntityTypeId;
                    attribute.EntityTypeQualifierColumn = string.Empty;
                    attribute.EntityTypeQualifierValue  = string.Empty;
                    attribute.Key          = key;
                    attribute.Name         = key;
                    attribute.IconCssClass = string.Empty;
                    attribute.DefaultValue = string.Empty;
                    attribute.IsMultiValue = false;
                    attribute.IsRequired   = false;
                    attribute.Description  = string.Empty;
                    attribute.FieldTypeId  = fieldType.Id;
                    attribute.Order        = 0;

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

                var attributeValueService = new Model.AttributeValueService(rockContext);
                var attributeValue        = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, person.Id);

                if (string.IsNullOrWhiteSpace(value))
                {
                    // Delete existing value if no existing value
                    if (attributeValue != null)
                    {
                        attributeValueService.Delete(attributeValue);
                    }
                }
                else
                {
                    if (attributeValue == null)
                    {
                        attributeValue             = new Model.AttributeValue();
                        attributeValue.AttributeId = attribute.Id;
                        attributeValue.EntityId    = person.Id;
                        attributeValueService.Add(attributeValue);
                    }
                    attributeValue.Value = value;
                }

                rockContext.SaveChanges();
            }
        }
Exemple #2
0
        /// <summary>
        /// Uses reflection to find any <see cref="FieldAttribute" /> attributes for the specified type and will create and/or update
        /// a <see cref="Rock.Model.Attribute" /> record for each attribute defined.
        /// </summary>
        /// <param name="type">The type (should be a <see cref="IHasAttributes" /> object.</param>
        /// <param name="entityTypeId">The entity type id.</param>
        /// <param name="entityQualifierColumn">The entity qualifier column.</param>
        /// <param name="entityQualifierValue">The entity qualifier value.</param>
        /// <param name="currentPersonId">The current person id.</param>
        /// <returns></returns>
        public static bool UpdateAttributes(Type type, int?entityTypeId, string entityQualifierColumn, string entityQualifierValue, int?currentPersonId)
        {
            bool attributesUpdated = false;

            List <string> existingKeys = new List <string>();

            var blockProperties = new List <FieldAttribute>();

            // If a ContextAwareAttribute exists without an EntityType defined, add a property attribute to specify the type
            int properties = 0;

            foreach (var customAttribute in type.GetCustomAttributes(typeof(ContextAwareAttribute), true))
            {
                var contextAttribute = (ContextAwareAttribute)customAttribute;
                if (contextAttribute != null && contextAttribute.EntityType == null)
                {
                    string propertyKeyName = string.Format("ContextEntityType{0}", properties > 0 ? properties.ToString() : "");
                    properties++;

                    blockProperties.Add(new EntityTypeFieldAttribute("Entity Type", false, "The type of entity that will provide context for this block", false, "Context", 0, propertyKeyName));
                }
            }

            // Add any property attributes that were defined for the block
            foreach (var customAttribute in type.GetCustomAttributes(typeof(FieldAttribute), true))
            {
                blockProperties.Add((FieldAttribute)customAttribute);
            }

            // Create any attributes that need to be created
            var attributeService = new Model.AttributeService();

            if (blockProperties.Count > 0)
            {
                var attributeQualifierService = new Model.AttributeQualifierService();
                var fieldTypeService          = new Model.FieldTypeService();
                var categoryService           = new Model.CategoryService();

                foreach (var blockProperty in blockProperties)
                {
                    attributesUpdated = UpdateAttribute(attributeService, attributeQualifierService, fieldTypeService, categoryService,
                                                        blockProperty, entityTypeId, entityQualifierColumn, entityQualifierValue, currentPersonId) || attributesUpdated;
                    existingKeys.Add(blockProperty.Key);
                }
            }

            // Remove any old attributes
            foreach (var a in attributeService.Get(entityTypeId, entityQualifierColumn, entityQualifierValue).ToList())
            {
                if (!existingKeys.Contains(a.Key))
                {
                    attributeService.Delete(a, currentPersonId);
                    attributeService.Save(a, currentPersonId);
                }
            }

            return(attributesUpdated);
        }
Exemple #3
0
        /// <summary>
        /// Creates the control(s) necessary for prompting user for a new value
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id"></param>
        /// <returns>
        /// The control
        /// </returns>
        public override Control EditControl(Dictionary <string, ConfigurationValue> configurationValues, string id)
        {
            ListControl editControl;

            if (configurationValues != null && configurationValues.ContainsKey(ALLOW_MULTIPLE_KEY) && configurationValues[ALLOW_MULTIPLE_KEY].Value.AsBoolean())
            {
                editControl = new RockListBox {
                    ID = id
                };
                editControl.AddCssClass("checkboxlist-group");
            }
            else
            {
                editControl = new RockDropDownList {
                    ID = id, EnhanceForLongLists = true
                };
                editControl.Items.Add(new ListItem());
            }

            if (configurationValues != null && configurationValues.ContainsKey(ENTITY_TYPE_KEY))
            {
                Guid?entityTypeGuid = configurationValues[ENTITY_TYPE_KEY].Value.AsGuidOrNull();
                if (entityTypeGuid.HasValue)
                {
                    var entityType = EntityTypeCache.Get(entityTypeGuid.Value);
                    if (entityType != null)
                    {
                        Rock.Model.AttributeService       attributeService = new Model.AttributeService(new RockContext());
                        IQueryable <Rock.Model.Attribute> attributeQuery;
                        if (configurationValues.ContainsKey(QUALIFIER_COLUMN_KEY) && configurationValues.ContainsKey(QUALIFIER_VALUE_KEY))
                        {
                            attributeQuery = attributeService
                                             .GetByEntityTypeQualifier(entityType.Id, configurationValues[QUALIFIER_COLUMN_KEY].Value, configurationValues[QUALIFIER_VALUE_KEY].Value, true);
                        }
                        else
                        {
                            attributeQuery = attributeService.GetByEntityTypeId(entityType.Id, true);
                        }

                        List <AttributeCache> attributeList = attributeQuery.ToAttributeCacheList();

                        if (attributeList.Any())
                        {
                            foreach (var attribute in attributeList.OrderBy(a => a.Name))
                            {
                                editControl.Items.Add(new ListItem(attribute.Name, attribute.Id.ToString(), attribute.IsActive));
                            }
                        }
                        return(editControl);
                    }
                }
            }

            return(null);
        }
        /// <summary>
        /// Saves a <see cref="Rock.Model.Person">Person's</see> user preference setting by key.
        /// </summary>
        /// <param name="person">The <see cref="Rock.Model.Person"/> who the preference value belongs to.</param>
        /// <param name="key">A <see cref="System.String"/> representing the key (name) of the preference setting. </param>
        /// <param name="values">A list of <see cref="System.String"/> values representing the value of the preference setting.</param>
        /// <param name="personId">A <see cref="System.Int32"/> representing the Id of the <see cref="Rock.Model.Person"/> saving the setting.</param>
        public void SaveUserPreference(Person person, string key, List <string> values, int?personId)
        {
            int?PersonEntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(Person.USER_VALUE_ENTITY).Id;

            var attributeService = new Model.AttributeService();
            var attribute        = attributeService.Get(PersonEntityTypeId, string.Empty, string.Empty, key);

            if (attribute == null)
            {
                var fieldTypeService = new Model.FieldTypeService();
                var fieldType        = fieldTypeService.GetByGuid(new Guid(Rock.SystemGuid.FieldType.TEXT));

                attribute              = new Model.Attribute();
                attribute.IsSystem     = false;
                attribute.EntityTypeId = PersonEntityTypeId;
                attribute.EntityTypeQualifierColumn = string.Empty;
                attribute.EntityTypeQualifierValue  = string.Empty;
                attribute.Key          = key;
                attribute.Name         = key;
                attribute.DefaultValue = string.Empty;
                attribute.IsMultiValue = false;
                attribute.IsRequired   = false;
                attribute.Description  = string.Empty;
                attribute.FieldTypeId  = fieldType.Id;
                attribute.Order        = 0;

                attributeService.Add(attribute, personId);
                attributeService.Save(attribute, personId);
            }

            var attributeValueService = new Model.AttributeValueService();

            // Delete existing values
            var attributeValues = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, person.Id).ToList();

            foreach (var attributeValue in attributeValues)
            {
                attributeValueService.Delete(attributeValue, personId);
                attributeValueService.Save(attributeValue, personId);
            }

            // Save new values
            foreach (var value in values.Where(v => !string.IsNullOrWhiteSpace(v)))
            {
                var attributeValue = new Model.AttributeValue();
                attributeValue.AttributeId = attribute.Id;
                attributeValue.EntityId    = person.Id;
                attributeValue.Value       = value;
                attributeValueService.Add(attributeValue, personId);
                attributeValueService.Save(attributeValue, personId);
            }
        }
Exemple #5
0
        /// <summary>
        /// Uses reflection to find any <see cref="FieldAttribute" /> attributes for the specified type and will create and/or update
        /// a <see cref="Rock.Model.Attribute" /> record for each attribute defined.
        /// </summary>
        /// <param name="type">The type (should be a <see cref="IHasAttributes" /> object.</param>
        /// <param name="entityTypeId">The entity type id.</param>
        /// <param name="entityQualifierColumn">The entity qualifier column.</param>
        /// <param name="entityQualifierValue">The entity qualifier value.</param>
        /// <param name="currentPersonId">The current person id.</param>
        /// <returns></returns>
        public static bool UpdateAttributes(Type type, int?entityTypeId, string entityQualifierColumn, string entityQualifierValue, int?currentPersonId)
        {
            bool attributesUpdated = false;

            List <string> existingKeys = new List <string>();

            var blockProperties = new List <FieldAttribute>();

            // If a ContextAwareAttribute exists without an EntityType defined, add a property attribute to specify the type
            int properties = 0;

            foreach (var customAttribute in type.GetCustomAttributes(typeof(ContextAwareAttribute), true))
            {
                var contextAttribute = (ContextAwareAttribute)customAttribute;
                if (String.IsNullOrWhiteSpace(contextAttribute.EntityType))
                {
                    string propertyKeyName = string.Format("ContextEntityType{0}", properties > 0 ? properties.ToString() : "");
                    properties++;

                    blockProperties.Add(new TextFieldAttribute(0, "Context Entity Type", propertyKeyName, "Filter", "Context Entity Type", false, ""));
                }
            }

            // Add any property attributes that were defined for the block
            foreach (var customAttribute in type.GetCustomAttributes(typeof(FieldAttribute), true))
            {
                blockProperties.Add((FieldAttribute)customAttribute);
            }

            // Create any attributes that need to be created
            foreach (var blockProperty in blockProperties)
            {
                attributesUpdated = UpdateAttribute(blockProperty, entityTypeId, entityQualifierColumn, entityQualifierValue, currentPersonId) || attributesUpdated;
                existingKeys.Add(blockProperty.Key);
            }

            // Remove any old attributes
            Model.AttributeService attributeService = new Model.AttributeService();
            foreach (var a in attributeService.Get(entityTypeId, entityQualifierColumn, entityQualifierValue).ToList())
            {
                if (!existingKeys.Contains(a.Key))
                {
                    attributeService.Delete(a, currentPersonId);
                    attributeService.Save(a, currentPersonId);
                }
            }

            return(attributesUpdated);
        }
Exemple #6
0
        /// <summary>
        /// Creates the control(s) necessary for prompting user for a new value
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id"></param>
        /// <returns>
        /// The control
        /// </returns>
        public override Control EditControl(Dictionary <string, ConfigurationValue> configurationValues, string id)
        {
            ListControl editControl;

            if (configurationValues != null && configurationValues.ContainsKey(ALLOW_MULTIPLE_KEY) && configurationValues[ALLOW_MULTIPLE_KEY].Value.AsBoolean())
            {
                editControl = new RockCheckBoxList {
                    ID = id
                };
                editControl.AddCssClass("checkboxlist-group");
            }
            else
            {
                editControl = new RockDropDownList {
                    ID = id
                };
                editControl.Items.Add(new ListItem());
            }

            if (configurationValues != null && configurationValues.ContainsKey(ENTITY_TYPE_KEY))
            {
                Guid?entityTypeGuid = configurationValues[ENTITY_TYPE_KEY].Value.AsGuidOrNull();
                if (entityTypeGuid.HasValue)
                {
                    var entityType = EntityTypeCache.Read(entityTypeGuid.Value);
                    if (entityType != null)
                    {
                        Rock.Model.AttributeService attributeService = new Model.AttributeService(new RockContext());
                        var attributes = attributeService.GetByEntityTypeId(entityType.Id);
                        if (attributes.Any())
                        {
                            foreach (var attribute in attributes.OrderBy(a => a.Name))
                            {
                                editControl.Items.Add(new ListItem(attribute.Name, attribute.Id.ToString()));
                            }
                        }
                        return(editControl);
                    }
                }
            }

            return(null);
        }
        /// <summary>
        /// Returns a <see cref="Rock.Model.Person"/> user preference value by preference setting's key.
        /// </summary>
        /// <param name="person">The <see cref="Rock.Model.Person"/> to retrieve the preference value for.</param>
        /// <param name="key">A <see cref="System.String"/> representing the key name of the preference setting.</param>
        /// <returns>A list of <see cref="System.String"/> containing the values associated with the user's preference setting.</returns>
        public List <string> GetUserPreference(Person person, string key)
        {
            int?PersonEntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(Person.USER_VALUE_ENTITY).Id;

            var attributeService = new Model.AttributeService();
            var attribute        = attributeService.Get(PersonEntityTypeId, string.Empty, string.Empty, key);

            if (attribute != null)
            {
                var attributeValueService = new Model.AttributeValueService();
                var attributeValues       = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, person.Id);
                if (attributeValues != null && attributeValues.Count() > 0)
                {
                    return(attributeValues.Select(v => v.Value).ToList());
                }
            }

            return(null);
        }
Exemple #8
0
        /// <summary>
        /// Saves the user preferences.
        /// </summary>
        private void SaveUserPreferences()
        {
            RockBlock rockBlock = this.RockBlock();

            if (rockBlock != null)
            {
                string keyPrefix = string.Format("grid-filter-{0}-", rockBlock.BlockId);

                foreach (var userPreference in _userPreferences)
                {
                    string keyPrefixUserPreferenceKey = string.Format("{0}{1}|", keyPrefix, userPreference.Key);
                    string key = string.Format("{0}{1}", keyPrefixUserPreferenceKey, userPreference.Name);

                    // No duplicate user preference key values before the '|' are allowed.
                    // This search for any keys that match before the '|' but mismatch after '|' and delete it before writing the user preference.
                    int?personEntityTypeId = EntityTypeCache.Get(Person.USER_VALUE_ENTITY).Id;

                    using (var rockContext = new Rock.Data.RockContext())
                    {
                        var attributeService = new Model.AttributeService(rockContext);
                        var attributes       = attributeService
                                               .Queryable()
                                               .Where(a => a.EntityTypeId == personEntityTypeId)
                                               .Where(a => a.Key.StartsWith(keyPrefixUserPreferenceKey))
                                               .Where(a => a.Key != key);

                        if (attributes.Count() != 0)
                        {
                            foreach (var attribute in attributes)
                            {
                                rockBlock.DeleteUserPreference(attribute.Key);
                            }
                        }
                        rockContext.SaveChanges();
                    }

                    rockBlock.SetUserPreference(key, userPreference.Value);
                }
            }
        }
Exemple #9
0
        /// <summary>
        /// Returns a <see cref="Rock.Model.Person"/> user preference value by preference setting's key.
        /// </summary>
        /// <param name="person">The <see cref="Rock.Model.Person"/> to retrieve the preference value for.</param>
        /// <param name="key">A <see cref="System.String"/> representing the key name of the preference setting.</param>
        /// <returns>A list of <see cref="System.String"/> containing the values associated with the user's preference setting.</returns>
        public static string GetUserPreference(Person person, string key)
        {
            int?PersonEntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(Person.USER_VALUE_ENTITY).Id;

            using (var rockContext = new Rock.Data.RockContext())
            {
                var attributeService = new Model.AttributeService(rockContext);
                var attribute        = attributeService.Get(PersonEntityTypeId, string.Empty, string.Empty, key);

                if (attribute != null)
                {
                    var attributeValueService = new Model.AttributeValueService(rockContext);
                    var attributeValue        = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, person.Id);
                    if (attributeValue != null)
                    {
                        return(attributeValue.Value);
                    }
                }
            }

            return(null);
        }
        /// <summary>
        /// Creates the control(s) necessary for prompting user for a new value
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id"></param>
        /// <returns>
        /// The control
        /// </returns>
        public override Control EditControl( Dictionary<string, ConfigurationValue> configurationValues, string id )
        {
            ListControl editControl;

            if ( configurationValues != null && configurationValues.ContainsKey( ALLOW_MULTIPLE_KEY ) && configurationValues[ALLOW_MULTIPLE_KEY].Value.AsBoolean() )
            {
                editControl = new RockCheckBoxList { ID = id };
                editControl.AddCssClass( "checkboxlist-group" );
            }
            else
            {
                editControl = new RockDropDownList { ID = id };
                editControl.Items.Add( new ListItem() );
            }

            if ( configurationValues != null && configurationValues.ContainsKey( ENTITY_TYPE_KEY ) )
            {
                Guid? entityTypeGuid = configurationValues[ENTITY_TYPE_KEY].Value.AsGuidOrNull();
                if ( entityTypeGuid.HasValue )
                {
                    var entityType = EntityTypeCache.Read( entityTypeGuid.Value );
                    if ( entityType != null )
                    {
                        Rock.Model.AttributeService attributeService = new Model.AttributeService( new RockContext() );
                        var attributes = attributeService.GetByEntityTypeId( entityType.Id );
                        if ( attributes.Any() )
                        {
                            foreach ( var attribute in attributes.OrderBy( a => a.Name ) )
                            {
                                editControl.Items.Add( new ListItem( attribute.Name, attribute.Id.ToString() ) );
                            }
                        }
                        return editControl;
                    }
                }
            }

            return null;
        }
Exemple #11
0
        /// <summary>
        /// Adds or Updates a <see cref="Rock.Model.Attribute" /> item for the attribute.
        /// </summary>
        /// <param name="attributeService">The attribute service.</param>
        /// <param name="attributeQualifierService">The attribute qualifier service.</param>
        /// <param name="fieldTypeService">The field type service.</param>
        /// <param name="categoryService">The category service.</param>
        /// <param name="property">The property.</param>
        /// <param name="entityTypeId">The entity type id.</param>
        /// <param name="entityQualifierColumn">The entity qualifier column.</param>
        /// <param name="entityQualifierValue">The entity qualifier value.</param>
        /// <param name="currentPersonId">The current person id.</param>
        /// <returns></returns>
        private static bool UpdateAttribute(Model.AttributeService attributeService, Model.AttributeQualifierService attributeQualifierService, Model.FieldTypeService fieldTypeService, Model.CategoryService categoryService,
                                            FieldAttribute property, int?entityTypeId, string entityQualifierColumn, string entityQualifierValue, int?currentPersonId)
        {
            bool updated = false;

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

            // Look for an existing attribute record based on the entity, entityQualifierColumn and entityQualifierValue
            Model.Attribute attribute = attributeService.Get(
                entityTypeId, entityQualifierColumn, entityQualifierValue, property.Key);

            if (attribute == null)
            {
                // If an existing attribute record doesn't exist, create a new one
                updated   = true;
                attribute = new Model.Attribute();
                attribute.EntityTypeId = entityTypeId;
                attribute.EntityTypeQualifierColumn = entityQualifierColumn;
                attribute.EntityTypeQualifierValue  = entityQualifierValue;
                attribute.Key          = property.Key;
                attribute.IsGridColumn = false;
            }
            else
            {
                // Check to see if the existing attribute record needs to be updated
                if (attribute.Name != property.Name ||
                    attribute.DefaultValue != property.DefaultValue ||
                    attribute.Description != property.Description ||
                    attribute.Order != property.Order ||
                    attribute.FieldType.Assembly != property.FieldTypeAssembly ||
                    attribute.FieldType.Class != property.FieldTypeClass ||
                    attribute.IsRequired != property.IsRequired)
                {
                    updated = true;
                }

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

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

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

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

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

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

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

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

                attributeService.Save(attribute, currentPersonId);

                return(true);
            }
            else
            {
                return(false);
            }
        }
        /// <summary>
        /// Returns a <see cref="Rock.Model.Person"/> user preference value by preference setting's key.
        /// </summary>
        /// <param name="person">The <see cref="Rock.Model.Person"/> to retrieve the preference value for.</param>
        /// <param name="key">A <see cref="System.String"/> representing the key name of the preference setting.</param>
        /// <returns>A list of <see cref="System.String"/> containing the values associated with the user's preference setting.</returns>
        public static string GetUserPreference( Person person, string key )
        {
            int? personEntityTypeId = Rock.Web.Cache.EntityTypeCache.Read( Person.USER_VALUE_ENTITY ).Id;

            using ( var rockContext = new Rock.Data.RockContext() )
            {
                var attributeService = new Model.AttributeService( rockContext );
                var attribute = attributeService.Get( personEntityTypeId, string.Empty, string.Empty, key );

                if ( attribute != null )
                {
                    var attributeValueService = new Model.AttributeValueService( rockContext );
                    var attributeValue = attributeValueService.GetByAttributeIdAndEntityId( attribute.Id, person.Id );
                    if ( attributeValue != null )
                    {
                        return attributeValue.Value;
                    }
                }
            }

            return null;
        }
        /// <summary>
        /// Deletes a <see cref="Rock.Model.Person">Person's</see> user preference setting by key and SavesChanges()
        /// </summary>
        /// <param name="person">The <see cref="Rock.Model.Person"/> who the preference value belongs to.</param>
        /// <param name="key">A <see cref="System.String"/> representing the key (name) of the preference setting.</param>
        public static void DeleteUserPreference( Person person, string key )
        {
            int? personEntityTypeId = Rock.Web.Cache.EntityTypeCache.Read( Person.USER_VALUE_ENTITY ).Id;

            using ( var rockContext = new RockContext() )
            {
                var attributeService = new Model.AttributeService( rockContext );
                var attribute = attributeService.Get( personEntityTypeId, string.Empty, string.Empty, key );

                if ( attribute != null )
                {
                    var attributeValueService = new Model.AttributeValueService( rockContext );
                    var attributeValue = attributeValueService.GetByAttributeIdAndEntityId( attribute.Id, person.Id );
                    if ( attributeValue != null )
                    {
                        attributeValueService.Delete( attributeValue );
                    }

                    attributeService.Delete( attribute );
                    rockContext.SaveChanges();
                }
            }
        }
Exemple #14
0
        /// <summary>
        /// Uses reflection to find any <see cref="FieldAttribute" /> attributes for the specified type and will create and/or update
        /// a <see cref="Rock.Model.Attribute" /> record for each attribute defined.
        /// </summary>
        /// <param name="type">The type (should be a <see cref="IHasAttributes" /> object.</param>
        /// <param name="entityTypeId">The entity type id.</param>
        /// <param name="entityQualifierColumn">The entity qualifier column.</param>
        /// <param name="entityQualifierValue">The entity qualifier value.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        /// <remarks>
        /// If a rockContext value is included, this method will save any previous changes made to the context
        /// </remarks>
        public static bool UpdateAttributes( Type type, int? entityTypeId, string entityQualifierColumn, string entityQualifierValue, RockContext rockContext = null )
        {
            bool attributesUpdated = false;

            List<string> existingKeys = new List<string>();

            var blockProperties = new List<FieldAttribute>();

            // If a ContextAwareAttribute exists without an EntityType defined, add a property attribute to specify the type
            int properties = 0;
            foreach ( var customAttribute in type.GetCustomAttributes( typeof( ContextAwareAttribute ), true ) )
            {
                var contextAttribute = (ContextAwareAttribute)customAttribute;
                if ( contextAttribute != null && contextAttribute.EntityType == null )
                {
                    if ( contextAttribute.IsConfigurable )
                    {
                        string propertyKeyName = string.Format( "ContextEntityType{0}", properties > 0 ? properties.ToString() : "" );
                        properties++;

                        blockProperties.Add( new EntityTypeFieldAttribute( "Entity Type", false, "The type of entity that will provide context for this block", false, "Context", 0, propertyKeyName ) );
                    }
                }
            }

            // Add any property attributes that were defined for the block
            foreach ( var customAttribute in type.GetCustomAttributes( typeof( FieldAttribute ), true ) )
            {
                blockProperties.Add( (FieldAttribute)customAttribute );
            }

            rockContext = rockContext ?? new RockContext();

            // Create any attributes that need to be created
            foreach ( var blockProperty in blockProperties )
            {
                try
                {
                    attributesUpdated = UpdateAttribute( blockProperty, entityTypeId, entityQualifierColumn, entityQualifierValue, rockContext ) || attributesUpdated;
                    existingKeys.Add( blockProperty.Key );
                }
                catch ( Exception ex )
                {
                    ExceptionLogService.LogException( new Exception( string.Format( "Could not update a block attribute ( Entity Type Id: {0}; Property Name: {1} ). ", entityTypeId, blockProperty.Name ), ex ), null );
                }
            }

            // Remove any old attributes
            try
            {
                var attributeService = new Model.AttributeService( rockContext );
                foreach ( var a in attributeService.Get( entityTypeId, entityQualifierColumn, entityQualifierValue ).ToList() )
                {
                    if ( !existingKeys.Contains( a.Key ) )
                    {
                        attributeService.Delete( a );
                    }
                }
                rockContext.SaveChanges();
            }
            catch ( Exception ex )
            {
                ExceptionLogService.LogException( new Exception( "Could not delete one or more old attributes.", ex ), null );
            }

            return attributesUpdated;
        }
        /// <summary>
        /// Saves a <see cref="Rock.Model.Person">Person's</see> user preference setting by key and SavesChanges()
        /// </summary>
        /// <param name="person">The <see cref="Rock.Model.Person"/> who the preference value belongs to.</param>
        /// <param name="key">A <see cref="System.String"/> representing the key (name) of the preference setting.</param>
        /// <param name="value">The value.</param>
        public static void SaveUserPreference( Person person, string key, string value )
        {
            int? personEntityTypeId = Rock.Web.Cache.EntityTypeCache.Read( Person.USER_VALUE_ENTITY ).Id;

            using ( var rockContext = new RockContext() )
            {
                var attributeService = new Model.AttributeService( rockContext );
                var attribute = attributeService.Get( personEntityTypeId, string.Empty, string.Empty, key );

                if ( attribute == null )
                {
                    var fieldTypeService = new Model.FieldTypeService( rockContext );
                    var fieldType = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT.AsGuid() );

                    attribute = new Model.Attribute();
                    attribute.IsSystem = false;
                    attribute.EntityTypeId = personEntityTypeId;
                    attribute.EntityTypeQualifierColumn = string.Empty;
                    attribute.EntityTypeQualifierValue = string.Empty;
                    attribute.Key = key;
                    attribute.Name = key;
                    attribute.IconCssClass = string.Empty;
                    attribute.DefaultValue = string.Empty;
                    attribute.IsMultiValue = false;
                    attribute.IsRequired = false;
                    attribute.Description = string.Empty;
                    attribute.FieldTypeId = fieldType.Id;
                    attribute.Order = 0;

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

                var attributeValueService = new Model.AttributeValueService( rockContext );
                var attributeValue = attributeValueService.GetByAttributeIdAndEntityId( attribute.Id, person.Id );

                if ( string.IsNullOrWhiteSpace( value ) )
                {
                    // Delete existing value if no existing value
                    if ( attributeValue != null )
                    {
                        attributeValueService.Delete( attributeValue );
                    }
                }
                else
                {
                    if ( attributeValue == null )
                    {
                        attributeValue = new Model.AttributeValue();
                        attributeValue.AttributeId = attribute.Id;
                        attributeValue.EntityId = person.Id;
                        attributeValueService.Add( attributeValue );
                    }

                    attributeValue.Value = value;
                }

                rockContext.SaveChanges();
            }
        }
        /// <summary>
        /// Returns a <see cref="Rock.Model.Person"/> user preference value by preference setting's key.
        /// </summary>
        /// <param name="person">The <see cref="Rock.Model.Person"/> to retrieve the preference value for.</param>
        /// <param name="key">A <see cref="System.String"/> representing the key name of the preference setting.</param>
        /// <returns>A list of <see cref="System.String"/> containing the values associated with the user's preference setting.</returns>
        public List<string> GetUserPreference( Person person, string key )
        {
            int? PersonEntityTypeId = Rock.Web.Cache.EntityTypeCache.Read( Person.USER_VALUE_ENTITY ).Id;

            var attributeService = new Model.AttributeService();
            var attribute = attributeService.Get( PersonEntityTypeId, string.Empty, string.Empty, key );

            if (attribute != null)
            {
                var attributeValueService = new Model.AttributeValueService();
                var attributeValues = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, person.Id);
                if (attributeValues != null && attributeValues.Count() > 0)
                    return attributeValues.Select( v => v.Value).ToList();
            }

            return null;
        }
        /// <summary>
        /// Saves a <see cref="Rock.Model.Person">Person's</see> user preference setting by key.
        /// </summary>
        /// <param name="person">The <see cref="Rock.Model.Person"/> who the preference value belongs to.</param>
        /// <param name="key">A <see cref="System.String"/> representing the key (name) of the preference setting. </param>
        /// <param name="values">A list of <see cref="System.String"/> values representing the value of the preference setting.</param>
        /// <param name="personId">A <see cref="System.Int32"/> representing the Id of the <see cref="Rock.Model.Person"/> saving the setting.</param>
        public void SaveUserPreference(Person person, string key, List<string> values, int? personId)
        {
            int? PersonEntityTypeId = Rock.Web.Cache.EntityTypeCache.Read( Person.USER_VALUE_ENTITY ).Id;

            var attributeService = new Model.AttributeService();
            var attribute = attributeService.Get( PersonEntityTypeId, string.Empty, string.Empty, key );

            if ( attribute == null )
            {
                var fieldTypeService = new Model.FieldTypeService();
                var fieldType = fieldTypeService.GetByGuid( new Guid( Rock.SystemGuid.FieldType.TEXT ) );

                attribute = new Model.Attribute();
                attribute.IsSystem = false;
                attribute.EntityTypeId = PersonEntityTypeId;
                attribute.EntityTypeQualifierColumn = string.Empty;
                attribute.EntityTypeQualifierValue = string.Empty;
                attribute.Key = key;
                attribute.Name = key;
                attribute.DefaultValue = string.Empty;
                attribute.IsMultiValue = false;
                attribute.IsRequired = false;
                attribute.Description = string.Empty;
                attribute.FieldTypeId = fieldType.Id;
                attribute.Order = 0;

                attributeService.Add( attribute, personId );
                attributeService.Save( attribute, personId );
            }

            var attributeValueService = new Model.AttributeValueService();

            // Delete existing values
            var attributeValues = attributeValueService.GetByAttributeIdAndEntityId( attribute.Id, person.Id ).ToList();
            foreach ( var attributeValue in attributeValues )
            {
                attributeValueService.Delete( attributeValue, personId );
                attributeValueService.Save( attributeValue, personId );
            }

            // Save new values
            foreach ( var value in values.Where( v => !string.IsNullOrWhiteSpace( v ) ) )
            {
                var attributeValue = new Model.AttributeValue();
                attributeValue.AttributeId = attribute.Id;
                attributeValue.EntityId = person.Id;
                attributeValue.Value = value;
                attributeValueService.Add( attributeValue, personId );
                attributeValueService.Save( attributeValue, personId );
            }
        }
        /// <summary>
        /// Saves the user preferences.
        /// </summary>
        /// <param name="person">The person.</param>
        /// <param name="preferences">The preferences.</param>
        public static void SaveUserPreferences( Person person, Dictionary<string, string> preferences )
        {
            if ( preferences != null )
            {
                int? personEntityTypeId = Rock.Web.Cache.EntityTypeCache.Read( Person.USER_VALUE_ENTITY ).Id;

                using ( var rockContext = new RockContext() )
                {
                    var attributeService = new Model.AttributeService( rockContext );
                    var attributes = attributeService
                        .Get( personEntityTypeId, string.Empty, string.Empty )
                        .Where( a => preferences.Keys.Contains( a.Key ) )
                        .ToList();

                    bool wasUpdated = false;
                    foreach ( var attributeKeyValue in preferences )
                    {
                        var attribute = attributes.FirstOrDefault( a => a.Key == attributeKeyValue.Key );

                        if ( attribute == null )
                        {
                            var fieldTypeService = new Model.FieldTypeService( rockContext );
                            var fieldType = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT.AsGuid() );

                            attribute = new Model.Attribute();
                            attribute.IsSystem = false;
                            attribute.EntityTypeId = personEntityTypeId;
                            attribute.EntityTypeQualifierColumn = string.Empty;
                            attribute.EntityTypeQualifierValue = string.Empty;
                            attribute.Key = attributeKeyValue.Key;
                            attribute.Name = attributeKeyValue.Key;
                            attribute.IconCssClass = string.Empty;
                            attribute.DefaultValue = string.Empty;
                            attribute.IsMultiValue = false;
                            attribute.IsRequired = false;
                            attribute.Description = string.Empty;
                            attribute.FieldTypeId = fieldType.Id;
                            attribute.Order = 0;

                            attributeService.Add( attribute );

                            wasUpdated = true;
                        }
                    }

                    if ( wasUpdated )
                    {
                        // Save any new attributes
                        rockContext.SaveChanges();

                        // Requery attributes ( so they all have ids )
                        attributes = attributeService
                            .Get( personEntityTypeId, string.Empty, string.Empty )
                            .Where( a => preferences.Keys.Contains( a.Key ) )
                            .ToList();
                    }

                    var attributeIds = attributes.Select( a => a.Id ).ToList();

                    var attributeValueService = new Model.AttributeValueService( rockContext );
                    var attributeValues = attributeValueService.Queryable( "Attribute" )
                        .Where( v =>
                            attributeIds.Contains( v.AttributeId ) &&
                            v.EntityId.HasValue &&
                            v.EntityId.Value == person.Id )
                        .ToList();

                    wasUpdated = false;
                    foreach ( var attributeKeyValue in preferences )
                    {
                        if ( string.IsNullOrWhiteSpace( attributeKeyValue.Value ) )
                        {
                            foreach ( var attributeValue in attributeValues
                                .Where( v =>
                                    v.Attribute != null &&
                                    v.Attribute.Key == attributeKeyValue.Key )
                                .ToList() )
                            {
                                attributeValueService.Delete( attributeValue );
                                attributeValues.Remove( attributeValue );
                                wasUpdated = true;
                            }
                        }
                        else
                        {
                            var attributeValue = attributeValues
                                .Where( v =>
                                    v.Attribute != null &&
                                    v.Attribute.Key == attributeKeyValue.Key )
                                .FirstOrDefault();

                            if ( attributeValue == null )
                            {
                                var attribute = attributes
                                    .Where( a => a.Key == attributeKeyValue.Key )
                                    .FirstOrDefault();
                                if ( attribute != null )
                                {
                                    attributeValue = new Model.AttributeValue();
                                    attributeValue.AttributeId = attribute.Id;
                                    attributeValue.EntityId = person.Id;
                                    attributeValueService.Add( attributeValue );
                                }
                            }

                            wasUpdated = wasUpdated || ( attributeValue.Value != attributeKeyValue.Value );
                            attributeValue.Value = attributeKeyValue.Value;
                        }
                    }

                    if ( wasUpdated )
                    {
                        rockContext.SaveChanges();
                    }
                }
            }
        }
Exemple #19
0
        /// <summary>
        /// Adds or Updates a <see cref="Rock.Model.Attribute" /> item for the attribute.
        /// </summary>
        /// <param name="property">The property.</param>
        /// <param name="entityTypeId">The entity type id.</param>
        /// <param name="entityQualifierColumn">The entity qualifier column.</param>
        /// <param name="entityQualifierValue">The entity qualifier value.</param>
        /// <param name="currentPersonId">The current person id.</param>
        /// <returns></returns>
        private static bool UpdateAttribute(FieldAttribute property, int?entityTypeId, string entityQualifierColumn, string entityQualifierValue, int?currentPersonId)
        {
            bool updated = false;

            Model.AttributeService attributeService = new Model.AttributeService();
            Model.FieldTypeService fieldTypeService = new Model.FieldTypeService();

            // Look for an existing attribute record based on the entity, entityQualifierColumn and entityQualifierValue
            Model.Attribute attribute = attributeService.Get(
                entityTypeId, entityQualifierColumn, entityQualifierValue, property.Key);

            if (attribute == null)
            {
                // If an existing attribute record doesn't exist, create a new one
                updated   = true;
                attribute = new Model.Attribute();
                attribute.EntityTypeId = entityTypeId;
                attribute.EntityTypeQualifierColumn = entityQualifierColumn;
                attribute.EntityTypeQualifierValue  = entityQualifierValue;
                attribute.Key          = property.Key;
                attribute.IsGridColumn = false;
            }
            else
            {
                // Check to see if the existing attribute record needs to be updated
                if (attribute.Name != property.Name ||
                    attribute.Category != property.Category ||
                    attribute.DefaultValue != property.DefaultValue ||
                    attribute.Description != property.Description ||
                    attribute.Order != property.Order ||
                    attribute.FieldType.Assembly != property.FieldTypeAssembly ||
                    attribute.FieldType.Class != property.FieldTypeClass ||
                    attribute.IsRequired != property.IsRequired)
                {
                    updated = true;
                }
            }

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

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

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

                attributeService.Save(attribute, currentPersonId);

                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #20
0
        /// <summary>
        /// Uses reflection to find any <see cref="FieldAttribute" /> attributes for the specified type and will create and/or update
        /// a <see cref="Rock.Model.Attribute" /> record for each attribute defined.
        /// </summary>
        /// <param name="type">The type (should be a <see cref="IHasAttributes" /> object.</param>
        /// <param name="entityTypeId">The entity type id.</param>
        /// <param name="entityQualifierColumn">The entity qualifier column.</param>
        /// <param name="entityQualifierValue">The entity qualifier value.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        /// <remarks>
        /// If a rockContext value is included, this method will save any previous changes made to the context
        /// </remarks>
        public static bool UpdateAttributes(Type type, int?entityTypeId, string entityQualifierColumn, string entityQualifierValue, RockContext rockContext = null)
        {
            bool attributesUpdated = false;

            List <string> existingKeys = new List <string>();

            var blockProperties = new List <FieldAttribute>();

            // If a ContextAwareAttribute exists without an EntityType defined, add a property attribute to specify the type
            int properties = 0;

            foreach (var customAttribute in type.GetCustomAttributes(typeof(ContextAwareAttribute), true))
            {
                var contextAttribute = (ContextAwareAttribute)customAttribute;
                if (contextAttribute != null && contextAttribute.EntityType == null)
                {
                    if (contextAttribute.IsConfigurable)
                    {
                        string propertyKeyName = string.Format("ContextEntityType{0}", properties > 0 ? properties.ToString() : "");
                        properties++;

                        blockProperties.Add(new EntityTypeFieldAttribute("Entity Type", false, "The type of entity that will provide context for this block", false, "Context", 0, propertyKeyName));
                    }
                }
            }

            // Add any property attributes that were defined for the block
            foreach (var customAttribute in type.GetCustomAttributes(typeof(FieldAttribute), true))
            {
                blockProperties.Add((FieldAttribute)customAttribute);
            }

            rockContext = rockContext ?? new RockContext();

            // Create any attributes that need to be created
            foreach (var blockProperty in blockProperties)
            {
                try
                {
                    attributesUpdated = UpdateAttribute(blockProperty, entityTypeId, entityQualifierColumn, entityQualifierValue, rockContext) || attributesUpdated;
                    existingKeys.Add(blockProperty.Key);
                }
                catch (Exception ex)
                {
                    ExceptionLogService.LogException(new Exception(string.Format("Could not update a block attribute ( Entity Type Id: {0}; Property Name: {1} ). ", entityTypeId, blockProperty.Name), ex), null);
                }
            }

            // Remove any old attributes
            try
            {
                var attributeService = new Model.AttributeService(rockContext);
                foreach (var a in attributeService.Get(entityTypeId, entityQualifierColumn, entityQualifierValue).ToList())
                {
                    if (!existingKeys.Contains(a.Key))
                    {
                        attributeService.Delete(a);
                    }
                }
                rockContext.SaveChanges();
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(new Exception("Could not delete one or more old attributes.", ex), null);
            }

            return(attributesUpdated);
        }