/// <summary> /// Sets the value. /// </summary> /// <param name="entityType">Type of the entity.</param> public void SetValue( EntityTypeCache entityType ) { ItemId = Constants.None.IdValue; ItemName = Constants.None.TextHtml; if ( entityType != null ) { ItemId = entityType.Id.ToString(); ItemName = ActionContainer.GetComponentName(entityType.Name); var action = ActionContainer.GetComponent( entityType.Name ); if ( action != null ) { var actionType = action.GetType(); var obj = actionType.GetCustomAttributes( typeof( ActionCategoryAttribute ), true ).FirstOrDefault(); if ( obj != null ) { var actionCategory = obj as ActionCategoryAttribute; if ( actionCategory != null ) { var categoryEntry = ActionContainer.Instance.Categories.Where( c => c.Value == actionCategory.CategoryName ).FirstOrDefault(); InitialItemParentIds = categoryEntry.Key.ToString(); } } } } }
/// <summary> /// Copies the model. /// </summary> /// <param name="entityTypeModel">The field type model.</param> /// <returns></returns> public static EntityTypeCache CopyModel( Rock.Model.EntityType entityTypeModel ) { EntityTypeCache entityType = new EntityTypeCache( entityTypeModel ); // update static dictionary object with name/id combination if ( entityTypes.ContainsKey( entityType.Name ) ) { entityTypes[entityType.Name] = entityType.Id; } else { entityTypes.Add( entityType.Name, entityType.Id ); } return entityType; }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit( EventArgs e ) { base.OnInit( e ); gReport.DataKeyNames = new string[] { "Guid" }; gReport.GridRebind += gReport_GridRebind; int tagId = int.MinValue; if ( int.TryParse( PageParameter( "tagId" ), out tagId ) && tagId > 0 ) { Tag _tag = new TagService().Get( tagId ); if ( _tag != null ) { TagId = tagId; TagEntityType = EntityTypeCache.Read( _tag.EntityTypeId ); if ( TagEntityType != null ) { Type modelType = TagEntityType.GetEntityType(); lTaggedTitle.Text = "Tagged " + modelType.Name.Pluralize(); if ( modelType != null ) { Dictionary<string, BoundField> boundFields = gReport.Columns.OfType<BoundField>().ToDictionary( a => a.DataField ); foreach ( var column in gReport.GetPreviewColumns( modelType ) ) { int insertPos = gReport.Columns.IndexOf( gReport.Columns.OfType<DeleteField>().First() ); gReport.Columns.Insert( insertPos, column ); } if ( TagEntityType.Name == "Rock.Model.Person" ) { gReport.PersonIdField = "Id"; } BindGrid(); } } } } }
/// <summary> /// Gets the current context object for a given entity type. /// </summary> /// <param name="entity">The <see cref="Rock.Web.Cache.EntityTypeCache"/> containing a reference to the entity.</param> /// <returns>An object that implements the <see cref="Rock.Data.IEntity"/> interface referencing the context object. </returns> public Rock.Data.IEntity GetCurrentContext( EntityTypeCache entity ) { if ( this.ModelContext.ContainsKey( entity.Name ) ) { var keyModel = this.ModelContext[entity.Name]; if ( keyModel.Entity == null ) { if ( entity.Name.Equals( "Rock.Model.Person", StringComparison.OrdinalIgnoreCase ) ) { if ( string.IsNullOrWhiteSpace( keyModel.Key ) ) { keyModel.Entity = new PersonService( new RockContext() ) .Queryable( "MaritalStatusValue,ConnectionStatusValue,RecordStatusValue,RecordStatusReasonValue,RecordTypevalue,SuffixValue,TitleValue,GivingGroup,Photo,Aliases", true, true ) .Where( p => p.Id == keyModel.Id ).FirstOrDefault(); } else { keyModel.Entity = new PersonService( new RockContext() ).GetByPublicKey( keyModel.Key ); } } else { Type modelType = entity.GetEntityType(); if ( modelType == null ) { // if the Type isn't found in the Rock.dll (it might be from a Plugin), lookup which assessmbly it is in and look in there string[] assemblyNameParts = entity.AssemblyName.Split( new char[] { ',' } ); if ( assemblyNameParts.Length > 1 ) { modelType = Type.GetType( string.Format( "{0}, {1}", entity.Name, assemblyNameParts[1] ) ); } } if ( modelType != null ) { // In the case of core Rock.dll Types, we'll just use Rock.Data.Service<> and Rock.Data.RockContext<> // otherwise find the first (and hopefully only) Service<> and dbContext we can find in the Assembly. Type serviceType = typeof( Rock.Data.Service<> ); Type contextType = typeof( Rock.Data.RockContext ); if ( modelType.Assembly != serviceType.Assembly ) { var serviceTypeLookup = Reflection.SearchAssembly( modelType.Assembly, serviceType ); if ( serviceTypeLookup.Any() ) { serviceType = serviceTypeLookup.First().Value; } var contextTypeLookup = Reflection.SearchAssembly( modelType.Assembly, typeof( System.Data.Entity.DbContext ) ); if ( contextTypeLookup.Any() ) { contextType = contextTypeLookup.First().Value; } } System.Data.Entity.DbContext dbContext = Activator.CreateInstance( contextType ) as System.Data.Entity.DbContext; Type service = serviceType.MakeGenericType( new Type[] { modelType } ); var serviceInstance = Activator.CreateInstance( service, dbContext ); if ( string.IsNullOrWhiteSpace( keyModel.Key ) ) { MethodInfo getMethod = service.GetMethod( "Get", new Type[] { typeof( int ) } ); keyModel.Entity = getMethod.Invoke( serviceInstance, new object[] { keyModel.Id } ) as Rock.Data.IEntity; } else { MethodInfo getMethod = service.GetMethod( "GetByPublicKey" ); keyModel.Entity = getMethod.Invoke( serviceInstance, new object[] { keyModel.Key } ) as Rock.Data.IEntity; } } } if ( keyModel.Entity != null && keyModel.Entity is Rock.Attribute.IHasAttributes ) { Rock.Attribute.Helper.LoadAttributes( keyModel.Entity as Rock.Attribute.IHasAttributes ); } } return keyModel.Entity; } return null; }
/// <summary> /// Reads the specified field type model. /// </summary> /// <param name="entityTypeModel">The field type model.</param> /// <returns></returns> public static EntityTypeCache Read( EntityType entityTypeModel ) { string cacheKey = EntityTypeCache.CacheKey( entityTypeModel.Id ); ObjectCache cache = MemoryCache.Default; EntityTypeCache entityType = cache[cacheKey] as EntityTypeCache; if ( entityType != null ) { entityType.CopyFromModel( entityTypeModel ); } else { entityType = new EntityTypeCache( entityTypeModel ); var cachePolicy = new CacheItemPolicy(); cache.Set( cacheKey, entityType, cachePolicy ); cache.Set( entityType.Guid.ToString(), entityType.Id, cachePolicy ); } return entityType; }
/// <summary> /// Reads the specified GUID. /// </summary> /// <param name="guid">The GUID.</param> /// <param name="rockContext">The rock context.</param> /// <returns></returns> public static EntityTypeCache Read( Guid guid, RockContext rockContext = null ) { ObjectCache cache = MemoryCache.Default; object cacheObj = cache[guid.ToString()]; EntityTypeCache entityType = null; if ( cacheObj != null ) { entityType = Read( (int)cacheObj ); } if ( entityType == null ) { rockContext = rockContext ?? new RockContext(); var entityTypeService = new EntityTypeService( rockContext ); var entityTypeModel = entityTypeService.Get( guid ); if ( entityTypeModel != null ) { entityType = new EntityTypeCache( entityTypeModel ); var cachePolicy = new CacheItemPolicy(); cache.Set( EntityTypeCache.CacheKey( entityType.Id ), entityType, cachePolicy ); cache.Set( entityType.Guid.ToString(), entityType.Id, cachePolicy ); } } return entityType; }
/// <summary> /// Returns EntityType object from cache. If entityBlockType does not already exist in cache, it /// will be read and added to cache /// </summary> /// <param name="id">The identifier.</param> /// <param name="rockContext">The rock context.</param> /// <returns></returns> public static EntityTypeCache Read( int id, RockContext rockContext = null ) { string cacheKey = EntityTypeCache.CacheKey( id ); ObjectCache cache = MemoryCache.Default; EntityTypeCache entityType = cache[cacheKey] as EntityTypeCache; if ( entityType == null ) { rockContext = rockContext ?? new RockContext(); var entityTypeService = new EntityTypeService( rockContext ); var entityTypeModel = entityTypeService.Get( id ); if ( entityTypeModel != null ) { entityType = new EntityTypeCache( entityTypeModel ); var cachePolicy = new CacheItemPolicy(); cache.Set( cacheKey, entityType, cachePolicy ); cache.Set( entityType.Guid.ToString(), entityType.Id, cachePolicy ); } } return entityType; }
/// <summary> /// Parses the where. /// </summary> /// <param name="whereClause">The where clause.</param> /// <param name="type">The type.</param> /// <param name="service">The service.</param> /// <param name="parmExpression">The parm expression.</param> /// <param name="entityType">Type of the entity.</param> /// <param name="entityTypeCache">The entity type cache.</param> /// <returns></returns> private Expression ParseWhere( string whereClause, Type type, IService service, ParameterExpression parmExpression, Type entityType, EntityTypeCache entityTypeCache ) { Expression returnExpression = null; // find locations of and/or's var expressionComponents = Regex.Split( whereClause, @"(\|\||&&)" ); var currentExpressionComparisonType = ExpressionComparisonType.And; foreach ( var component in expressionComponents ) { if ( component == "||" ) { currentExpressionComparisonType = ExpressionComparisonType.Or; continue; } if ( component == "&&" ) { currentExpressionComparisonType = ExpressionComparisonType.And; continue; } // parse the part to get the expression string regexPattern = @"([a-zA-Z]+)|(==|<=|>=|<|!=|\^=|\*=|\*!|_=|_!|>|\$=|#=)|("".*""|\d+)"; var expressionParts = Regex.Matches( component, regexPattern ) .Cast<Match>() .Select( m => m.Value ) .ToList(); if ( expressionParts.Count == 3 ) { var property = expressionParts[0]; var operatorType = expressionParts[1]; var value = expressionParts[2].Replace( "\"", "" ); List<string> selectionParms = new List<string>(); selectionParms.Add( PropertyComparisonConverstion( operatorType ).ToString() ); selectionParms.Add( value ); selectionParms.Add( property ); Expression expression = null; if ( entityType.GetProperty( property ) != null ) { var entityProperty = entityType.GetProperty( property ); expression = ExpressionHelper.PropertyFilterExpression( selectionParms, parmExpression, property, entityProperty.PropertyType ); } else { AttributeCache filterAttribute = null; foreach ( var id in AttributeCache.GetByEntity( entityTypeCache.Id ).SelectMany( a => a.AttributeIds ) ) { var attribute = AttributeCache.Read( id ); if ( attribute.Key == property ) { filterAttribute = attribute; } } if ( filterAttribute != null ) { var attributeEntityField = EntityHelper.GetEntityFieldForAttribute( filterAttribute ); expression = ExpressionHelper.GetAttributeExpression( service, parmExpression, attributeEntityField, selectionParms ); } } if ( returnExpression == null ) { returnExpression = expression; } else { if ( currentExpressionComparisonType == ExpressionComparisonType.And ) { returnExpression = Expression.AndAlso( returnExpression, expression ); } else { returnExpression = Expression.OrElse( returnExpression, expression ); } } } else { // error in parsing expression throw new Exception( "Error in Where expression" ); } } return returnExpression; }
/// <summary> /// Gets the data view expression. /// </summary> /// <param name="dataViewId">The data view identifier.</param> /// <param name="service">The service.</param> /// <param name="parmExpression">The parm expression.</param> /// <param name="entityTypeCache">The entity type cache.</param> /// <returns></returns> /// <exception cref="System.Exception"></exception> private Expression GetDataViewExpression( int dataViewId, IService service, ParameterExpression parmExpression, EntityTypeCache entityTypeCache ) { var dataViewSource = new DataViewService( _rockContext ).Get( dataViewId ); bool isCorrectDataType = dataViewSource.EntityTypeId == entityTypeCache.Id; if ( isCorrectDataType ) { List<string> errorMessages = new List<string>(); var whereExpression = dataViewSource.GetExpression( service, parmExpression, out errorMessages ); return whereExpression; } else { throw new Exception( string.Format( "The DataView provided is not of type {0}.", entityTypeCache.FriendlyName ) ); } }
private static void RegisterEntityCommand( EntityTypeCache entityType ) { if ( entityType != null ) { string entityName = entityType.FriendlyName.RemoveSpaces().ToLower(); // if entity name is already registered, use the full class name with namespace Type tagType = Template.GetTagType( entityName ); if ( tagType != null ) { entityName = entityType.Name.Replace( '.', '_' ); } Template.RegisterTag<Rock.Lava.Blocks.RockEntity>( entityName ); } }
/// <summary> /// Reads the specified GUID. /// </summary> /// <param name="guid">The GUID.</param> /// <returns></returns> public static EntityTypeCache Read( Guid guid ) { ObjectCache cache = MemoryCache.Default; object cacheObj = cache[guid.ToString()]; if ( cacheObj != null ) { return Read( (int)cacheObj ); } else { var entityTypeService = new EntityTypeService(); var entityTypeModel = entityTypeService.Get( guid ); if ( entityTypeModel != null ) { var entityType = new EntityTypeCache( entityTypeModel ); var cachePolicy = new CacheItemPolicy(); cache.Set( EntityTypeCache.CacheKey( entityType.Id ), entityType, cachePolicy ); cache.Set( entityType.Guid.ToString(), entityType.Id, cachePolicy ); return entityType; } else { return null; } } }
/// <summary> /// Returns EntityType object from cache. If entityBlockType does not already exist in cache, it /// will be read and added to cache /// </summary> /// <param name="id"></param> /// <returns></returns> public static EntityTypeCache Read( int id ) { string cacheKey = EntityTypeCache.CacheKey( id ); ObjectCache cache = MemoryCache.Default; EntityTypeCache entityType = cache[cacheKey] as EntityTypeCache; if ( entityType != null ) { return entityType; } else { var entityTypeService = new EntityTypeService(); var entityTypeModel = entityTypeService.Get( id ); if ( entityTypeModel != null ) { entityType = new EntityTypeCache( entityTypeModel ); var cachePolicy = new CacheItemPolicy(); cache.Set( cacheKey, entityType, cachePolicy ); cache.Set( entityType.Guid.ToString(), entityType.Id, cachePolicy ); return entityType; } else { return null; } } }
/// <summary> /// Adds the control. /// </summary> /// <param name="controls">The controls.</param> /// <param name="options">The options.</param> /// <returns></returns> public Control AddControl(ControlCollection controls, AttributeControlOptions options) { options.LabelText = options.LabelText ?? Name; options.HelpText = options.HelpText ?? Description; options.AttributeControlId = options.AttributeControlId ?? $"attribute_field_{Id}"; EntityTypeCache entityType = EntityTypeId.HasValue ? EntityTypeCache.Get(this.EntityTypeId.Value) : null; bool showPrePostHtml = (entityType?.AttributesSupportPrePostHtml ?? false) && (options?.ShowPrePostHtml ?? true); var attributeControl = FieldType.Field.EditControl(QualifierValues, options.SetId ? options.AttributeControlId : string.Empty); if (attributeControl == null) { return(null); } var hasAttributeIdControl = attributeControl as IHasAttributeId; if (hasAttributeIdControl != null) { hasAttributeIdControl.AttributeId = this.Id; } if (options.SetId) { attributeControl.ClientIDMode = ClientIDMode.AutoID; } // If the control is a RockControl var rockControl = attributeControl as IRockControl; var controlHasRequired = attributeControl as IHasRequired; if (showPrePostHtml) { if (this.PreHtml.IsNotNullOrWhiteSpace()) { controls.Add(new Literal { Text = this.PreHtml }); } } if (rockControl != null) { var isRequired = options.Required ?? IsRequired; rockControl.Label = options.LabelText; rockControl.Help = options.HelpText; rockControl.Warning = options.WarningText; rockControl.Required = isRequired; rockControl.ValidationGroup = options.ValidationGroup; if (options.LabelText.IsNullOrWhiteSpace() && isRequired) { rockControl.RequiredErrorMessage = $"{Name} is required."; } controls.Add(attributeControl); } else { if (controlHasRequired != null) { controlHasRequired.Required = options.Required ?? IsRequired; controlHasRequired.ValidationGroup = options.ValidationGroup; } bool renderLabel = !string.IsNullOrEmpty(options.LabelText); bool renderHelp = !string.IsNullOrWhiteSpace(options.HelpText); bool renderWarning = !string.IsNullOrWhiteSpace(options.WarningText); if (renderLabel || renderHelp || renderWarning) { var div = new DynamicControlsHtmlGenericControl("div") { ID = $"_formgroup_div_{Id}" }; controls.Add(div); div.Controls.Clear(); div.AddCssClass("form-group"); if (IsRequired) { div.AddCssClass("required"); } div.ClientIDMode = ClientIDMode.AutoID; if (renderLabel) { var label = new Label { ID = $"_label_{Id}", ClientIDMode = ClientIDMode.AutoID, Text = options.LabelText, CssClass = "control-label", AssociatedControlID = attributeControl.ID }; div.Controls.Add(label); } if (renderHelp) { var helpBlock = new HelpBlock { ID = $"_helpBlock_{Id}", ClientIDMode = ClientIDMode.AutoID, Text = options.HelpText }; div.Controls.Add(helpBlock); } if (renderWarning) { var warningBlock = new WarningBlock { ID = $"_warningBlock_{Id}", ClientIDMode = ClientIDMode.AutoID, Text = options.WarningText }; div.Controls.Add(warningBlock); } div.Controls.Add(attributeControl); } else { controls.Add(attributeControl); } } if (options.ShowPrePostHtml) { if (this.PostHtml.IsNotNullOrWhiteSpace()) { controls.Add(new Literal { Text = this.PostHtml }); } } if (options.SetValue) { FieldType.Field.SetEditValue(attributeControl, QualifierValues, options.Value); } return(attributeControl); }
/// <summary> /// Gets a list of all <seealso cref="AttributeCache">Attributes</seealso> for a specific entityType. /// </summary> /// <returns></returns> public static AttributeCache[] AllForEntityType <T>() { var entityTypeId = EntityTypeCache.Get <T>()?.Id; return(AllForEntityType(entityTypeId ?? 0)); }