public void Initializing(EntityMemberBox box, BootFX.Common.Entities.EntityMember member) { if (box == null) { throw new ArgumentNullException("box"); } if (member == null) { throw new ArgumentNullException("member"); } // set... if (member is EntityField) { EntityField field = (EntityField)member; if (field.EnumerationType != null) { this.EnumType = field.EnumerationType; } else { throw new InvalidOperationException(string.Format("Field '{0}' does not have an enumeration mapping.", member)); } } else { throw new NotSupportedException(string.Format("Cannot handle '{0}'.", member)); } }
/// <summary> /// Gets the sort specification for this attribute. /// </summary> /// <returns></returns> public SortSpecificationCollection GetSortSpecification(EntityType entityType) { if (entityType == null) { throw new ArgumentNullException("entityType"); } if (FieldNames == null) { throw new ArgumentNullException("FieldNames"); } if (Directions == null) { throw new ArgumentNullException("Directions"); } if (FieldNames.Length != Directions.Length) { throw ExceptionHelper.CreateLengthMismatchException("FieldNames", "Directions", FieldNames.Length, Directions.Length); } // create... SortSpecificationCollection specifications = new SortSpecificationCollection(); for (int index = 0; index < this.FieldNames.Length; index++) { string fieldName = FieldNames[index]; // get and add... EntityField field = entityType.Fields.GetField(fieldName, OnNotFound.ThrowException); specifications.Add(new SortSpecification(field, this.Directions[index])); } // return... return(specifications); }
public ValueListConstraint AddValueListConstraint(EntityField field, IEnumerable values, bool useFullyQualifiedNames = true) { var constraint = new ValueListConstraint(this.Creator, field, values, useFullyQualifiedNames); this.Add(constraint); return(constraint); }
public ArrayConstraint AddArrayExclusionConstraint(EntityField field, IEnumerable values, bool useFullyQualifiedNames = true) { var constraint = new ArrayConstraint(this.Creator, field, values, useFullyQualifiedNames, SqlOperator.NotEqualTo); this.Add(constraint); return(constraint); }
/// <summary> /// Creates an Delete statement. /// </summary> /// <returns></returns> public override SqlStatement[] GetStatements(WorkUnitProcessingContext context) { if (EntityType == null) { throw new ArgumentNullException("EntityType"); } if (Dialect == null) { throw new InvalidOperationException("Dialect is null."); } // create... SqlStatement statement = new SqlStatement(this.EntityType, this.Dialect); // sql... StringBuilder builder = new StringBuilder(); EntityField field = null; field = GetExtendedFields()[0]; // This is the field being updated AppendInsertIntoExtendedTable(context, field, builder, statement); builder.Append(")"); statement.CommandText = builder.ToString(); return(new SqlStatement[] { statement }); }
/// <summary> /// SheetからEntityTableへの変換 /// </summary> /// <param name="sheet">対象シート</param> /// <returns>変換したEntityTable</returns> /// <remarks> /// Excel格納情報 (列,行)表記 /// ( 2, 2) テーブル物理名(値は文字列) /// ( 2, 3) テーブル論理名(値は文字列) /// 以下フィールド情報。5行目はヘッダー、6行目から空白値まで値 /// ( 1, 6) フィールドNoの開始位置(値は数値) /// ( 2, 6) フィールド物理名の開始位置(値は文字列) /// ( 3, 6) フィールド論理名の開始位置(値は文字列) /// ( 4, 6) フィールドコメントの開始位置(値は文字列) /// ( 5, 6) フィールド型の開始位置(値は文字列) /// ( 6, 6) フィールドサイズの開始位置(値は数値) /// ( 7, 6) フィールドNull制約有無の開始位置(値は〇 or 空白) /// ( 8, 6) フィールドデフォルト値の開始位置(値は文字列) /// ( 9, 6) フィールド主キーの開始位置(値は〇 or 空白) /// /// </remarks> private EntityTable ConvertSheetToEntityTable(ExcelObject sheet) { var newEntityTable = new EntityTable { PhysicsName = sheet["B2"], LogicName = sheet["B3"] }; var fields = new List <EntityField>(); for (int cnt = 0; cnt < 65535; cnt++) { var row = (cnt + 6).ToString(); // フィールドのNo値が空白の場合、処理を抜ける if (string.IsNullOrEmpty(sheet["A" + row])) { break; } var field = new EntityField(); field.No = intParseEx(sheet["A" + row]); field.PhysicsName = sheet["B" + row]; field.LogicName = sheet["C" + row]; //field.Comment = sheet["D" + row]; field.FieldType = SqlServerConfiguration.ConvertFieldTypeToString(sheet["E" + row]); field.FieldSize = sheet["F" + row] == "" ? 0 : intParseEx(sheet["F" + row]); field.Nullable = sheet["G" + row] == "〇" ? true : false; field.Required = sheet["H" + row] == "〇" ? true : false; fields.Add(field); } newEntityTable.Fields = fields; return(newEntityTable); }
/// <summary> /// format field /// </summary> /// <param name="dbObjectName">db object name</param> /// <param name="field">field</param> /// <returns></returns> string FormatField(string dbObjectName, EntityField field) { if (field == null) { return(string.Empty); } var formatValue = field.GetQueryFormat(fieldFormatKey); if (formatValue.IsNullOrEmpty()) { string fieldName = string.Format("{0}.[{1}]", dbObjectName, field.FieldName); if (!field.QueryFormat.IsNullOrEmpty()) { formatValue = string.Format(field.QueryFormat + " AS [{1}]", fieldName, field.PropertyName); } else if (field.FieldName != field.PropertyName) { formatValue = string.Format("{0} AS [{1}]", fieldName, field.PropertyName); } else { formatValue = fieldName; } field.SetQueryFormat(fieldFormatKey, formatValue); } return(formatValue); }
private void ParseField(XmlNode node, Object obj) { try { EntityClass entity = (EntityClass)obj; EntityField field = entity.GetField(GetAttribute(node, "name")); if (field != null) { Log.Info("Parsing Field {0}...", field.Name); field.IsPreview = ToBool(GetAttribute(node, "isPreview")); field.Represents = ToBool(GetAttribute(node, "represents")); foreach (XmlNode child in node.ChildNodes) { if (child is XmlComment) { continue; } parsers[child.Name](child, field); } Log.Info("Field {0} parsed!", field.Name); } else { Log.Info("Ignoring field {0}. This field doesn't exist.", node.Name); } } catch (Exception e) { Log.Error("Error parsing field {0}! - {1}", GetAttribute(node, "name"), e.Message); } }
public UpdateMeshJob(EntityField entityField, int size, float materialScale) { this.entityField = entityField; this.size = size; this.meshBuilder = new MeshBuilder(materialScale); this.navMesh = new NavMesh(); }
private static EntityClass CreateRoleEntity(IProject project, EntityClass principal) { EntityClass role = new EntityClass("Roles", "public"); EntityField id = new EntityField("id"); id.IsPrimaryKey = true; id.IsPreview = true; id.Type = intType; EntityField name = new EntityField("name"); name.MaxSize = 20; name.IsRequired = true; name.Represents = true; name.IsPreview = true; name.Type = stringType; EntityField user = new EntityField("users"); user.Type = principal; user.Mult = Multiplicity.ManyToMany; user.InfoOnly = true; role.AddField(id); role.AddField(name); role.AddField(user); project.Model.Add(role); return(role); }
internal static EntityField CreateEntityField(EntityFieldElement value) { EntityField entityField = null; Type dataType = Type.GetType(value.DataType, false, true); if (dataType != null) { entityField = new EntityField(); entityField.Name = value.Name; entityField.ColumnName = value.ColumnName; entityField.DataType = dataType; entityField.DefaultValue = Support.ConvertStringToType(value.DefaultValue, dataType); entityField.AllowDBNull = value.AllowDBNull; entityField.MinValue = Support.ConvertStringToType(value.MinValue, dataType); entityField.MaxValue = Support.ConvertStringToType(value.MaxValue, dataType); entityField.MaxLength = value.MaxLength; entityField.Unique = value.Unique; entityField.Id = value.EntityId; // TODO: Do we need this property in XML config? Maybe try to see the associated entity to define the value. //if (entityField.Id != Guid.Empty) //// entityField.MappedHierarchyEntity = true; LoadEntityFieldValues(entityField, value.Values); } return(entityField); }
private void BuildParticipants(EntityClass participants) { EntityField participantsId = new EntityField("id"); participantsId.IsPreview = true; participantsId.IsRequired = true; participantsId.IsPrimaryKey = true; participantsId.Represents = true; participantsId.Type = intEntity; participants.Fields.Add(participantsId); EntityClass principal = (EntityClass)Project.Model.GetByName("Principal"); EntityField principalRef = new EntityField("principal"); principalRef.Mult = Multiplicity.ManyToOne; principalRef.Type = principal; participants.Fields.Add(principalRef); EntityField participantRef = new EntityField("Participants"); participantRef.Mult = Multiplicity.OneToMany; participantRef.Type = participants; principal.Fields.Add(participantRef); }
protected async Task <RepositoryResponse <TModel> > SaveAsync <TView>(JObject obj, Expression <Func <TModel, bool> > predicate) where TView : ViewModelBase <TDbContext, TModel, TView> { if (obj != null) { List <EntityField> fields = new List <EntityField>(); Type type = typeof(TModel); foreach (var item in obj.Properties()) { var propName = item.Name.ToTitleCase(); PropertyInfo propertyInfo = type.GetProperty(propName); if (propertyInfo != null) { object val = Convert.ChangeType(item.Value, propertyInfo.PropertyType); var field = new EntityField() { PropertyName = propName, PropertyValue = val }; fields.Add(field); } } var result = await DefaultRepository <TDbContext, TModel, TView> .Instance.UpdateFieldsAsync(predicate, fields); await MixCacheService.RemoveCacheAsync(); return(result); } return(new RepositoryResponse <TModel>()); }
/// <summary> /// Get fields /// </summary> /// <param name="serverType">Database server type</param> /// <param name="entityType">Entity type</param> /// <param name="propertyNames">Property names</param> /// <returns>Return properties relation entity fields</returns> internal static IEnumerable <EntityField> GetFields(DatabaseServerType serverType, Type entityType, IEnumerable <string> propertyNames) { if (propertyNames.IsNullOrEmpty()) { return(Array.Empty <EntityField>()); } var allFields = EntityManager.GetEntityConfiguration(entityType)?.AllFields; if (allFields.IsNullOrEmpty()) { return(Array.Empty <EntityField>()); } DatabaseServerEntityFields.TryGetValue(serverType.GetDatabaseServerEntityFormatKey(entityType), out var entityServerFields); List <EntityField> resultFields = new List <EntityField>(); foreach (var propertyName in propertyNames) { if (string.IsNullOrWhiteSpace(propertyName)) { continue; } EntityField propertyField = null; entityServerFields?.TryGetValue(propertyName, out propertyField); if (propertyField == null) { allFields.TryGetValue(propertyName, out propertyField); } if (propertyField != null) { resultFields.Add(propertyField); } } return(resultFields); }
public static string getDBDataType(EntityField field) { // find the correct mapping var mapping = _mappings.Where(m => m.DataTypeCode == field.Datatype).First(); return(mapping.DBDataType); }
protected async Task <RepositoryResponse <TModel> > SavePropertiesAsync(JObject obj, Expression <Func <TModel, bool> > predicate) { if (obj != null) { List <EntityField> fields = new List <EntityField>(); Type type = typeof(TModel); foreach (var item in obj.Properties()) { var propName = System.Globalization.CultureInfo.InvariantCulture.TextInfo.ToTitleCase(item.Name); PropertyInfo propertyInfo = type.GetProperty(propName); if (propertyInfo != null) { object val = Convert.ChangeType(item.Value, propertyInfo.PropertyType); var field = new EntityField() { PropertyName = propName, PropertyValue = val }; fields.Add(field); } } var result = await _repo.UpdateFieldsAsync(predicate, fields); return(result); } return(new RepositoryResponse <TModel>()); }
private void Save() { // validate the fields if (string.IsNullOrEmpty(txtName.Text.Trim())) { MessageBox.Show("Please provide a field name", "No Name"); return; } if (txtLength.Visible && string.IsNullOrEmpty(txtLength.Text.Trim())) { MessageBox.Show("Please provide a field length", "No Length"); } if (txtScale.Visible && string.IsNullOrEmpty(txtScale.Text.Trim())) { MessageBox.Show("Please provide a scale", "No Scale"); } var selType = cboDataType.SelectedItem as DataType; // determine if this is a new field if (_currentField == null) { _currentField = new EntityField(); _currentField.FieldName = txtName.Text.Trim(); _currentField.Datatype = selType.DataTypeCode; _currentField.MaxLength = selType.NeedsLength ? int.Parse(txtLength.Text) : 0; _currentField.Scale = selType.NeedsScale ? int.Parse(txtScale.Text) : 0; _currentField.IsRequired = chkRequired.Checked; } }
public void Set(EntityField <T> schemaField, IQueryBuilder subQuery) { AddFieldAssignment( QueryExpression.Column(schemaField.Column.Name), subQuery.BuildQuery() ); }
private EntityClass CreateLogger() { Entity intEntity = IntrinsicTypes.Create("System.Int32"); Entity stringEntity = IntrinsicTypes.Create("System.String"); Entity dateTimeEntity = IntrinsicTypes.Create("System.DateTime"); EntityClass logger = new EntityClass(); logger.Name = "RequestLogger"; logger.Visibility = "public"; EntityField field = new EntityField(); field.Name = "id"; field.IsPrimaryKey = true; field.IsPreview = true; field.Type = intEntity; logger.Fields.Add(field); field = new EntityField(); field.Name = "url"; field.IsPreview = true; field.Represents = true; field.Type = stringEntity; field.MaxSize = 1000; logger.Fields.Add(field); field = new EntityField(); field.Name = "date"; field.IsPreview = true; field.Type = dateTimeEntity; logger.Fields.Add(field); field = new EntityField(); field.Name = "requestTime"; field.IsPreview = true; field.Type = intEntity; logger.Fields.Add(field); field = new EntityField(); field.Name = "referrer"; field.Type = stringEntity; field.IsRequired = false; field.MaxSize = 1000; logger.Fields.Add(field); field = new EntityField(); field.Name = "ip"; field.Type = stringEntity; field.MaxSize = 15; logger.Fields.Add(field); field = new EntityField(); field.Name = "userAgent"; field.Type = stringEntity; field.MaxSize = 1500; logger.Fields.Add(field); return(logger); }
void SetCommandParameters() { int entityFieldsCount = Entity.Resource.All.Count; TableAttributeNames = new string[entityFieldsCount]; ParameterNames = new Dictionary <EntityField, string>(entityFieldsCount); Parameters = new Dictionary <EntityField, MySqlParameter>(); for (int i = 0; i < entityFieldsCount; i++) { string parameterName = string.Empty; EntityField field = Entity.Resource.All[i]; if (field.ManyToOne == null) { string name = field.Names[Entity]; TableAttributeNames[i] = name; parameterName = "@" + name; ParameterNames.Add(field, parameterName); } else { Entity foreignEntity = field.ManyToOne.Entity; string name = field.Names[foreignEntity]; TableAttributeNames[i] = name; parameterName = "@" + name; ParameterNames.Add(field, parameterName); } MySqlDbType type = MySqlTypeConverter.ConvertToMySqlTypeAsSqlDbType(Entity.Resource.All[i]); Parameters.Add(field, new MySqlParameter(parameterName, type)); } FirstRowIndexParameter = new MySqlParameter("@firstRowIndex", MySqlDbType.Int32); RowNumberParameter = new MySqlParameter("@rowNumber", MySqlDbType.Int32); }
/// <summary> /// Creates a SQL column from an entity field. /// </summary> /// <param name="field"></param> internal SqlColumn(EntityField field) : base(field.NativeName.Name, field.Name) { this.Initialize(field.DBType, field.Size, field.Flags); // mbr - 01-11-2005 - expression... this.DefaultExpression = field.DefaultExpression; }
private static JObject ProcessEntityField(EntityField x, List <Content> visited, Context context) { JObject f = ProcessFieldBase(x); f["Content"] = VisitDefinition(x.Content, visited, context); return(f); }
private void initFields() { _id = new PrimaryKeyField <projectNS.User, intermediateNS.User, L2SNS.User, long>(this, t => t.Id, (t, val) => t.Id = val); _accountId = new EntityField <projectNS.User, intermediateNS.User, L2SNS.User, long>(this, t => t.AccountId, (t, val) => t.AccountId = val); _companyId = new EntityField <projectNS.User, intermediateNS.User, L2SNS.User, long>(this, t => t.CompanyId, (t, val) => t.CompanyId = val); _account = new IntermediateEntityReference <projectNS.User, projectNS.Account, intermediateNS.User, intermediateNS.Account, L2SNS.User, L2SNS.Account>(this, __u => __u.Account, (__u, __account) => __u.Account = __account, __account => __account._user, false); _company = new IntermediateEntityReference <projectNS.User, projectNS.Company, intermediateNS.User, intermediateNS.Company, L2SNS.User, L2SNS.Company>(this, __u => __u.Company, (__u, __company) => __u.Company = __company, __company => __company._users, false); }
public EntityField(EntityField entityField) { entities = new LinkedList <Entity>(); foreach (Entity entity in entityField.entities) { entities.AddLast(entity); } }
private void Getfields() { ds = new DataSet();; Entities = new List <EntityStructure>(); if (File.Exists(Path.Combine(Dataconnection.ConnectionProp.FilePath, Dataconnection.ConnectionProp.FileName)) == true) { try { string json = File.ReadAllText(Path.Combine(Dataconnection.ConnectionProp.FilePath, Dataconnection.ConnectionProp.FileName)); ds = DMEEditor.ConfigEditor.JsonLoader.DeserializeSingleObject <DataSet>(json); int i = 0; foreach (DataTable tb in ds.Tables) { EntityStructure entityData = new EntityStructure(); string sheetname; sheetname = tb.TableName; entityData.EntityName = sheetname; entityData.DataSourceID = Dataconnection.ConnectionProp.ConnectionName; // entityData.SchemaOrOwnerOrDatabase = Database; List <EntityField> Fields = new List <EntityField>(); int y = 0; foreach (DataColumn field in tb.Columns) { Console.WriteLine(" " + field.ColumnName + ": " + field.DataType); EntityField f = new EntityField(); // f.tablename = sheetname; f.fieldname = field.ColumnName; f.fieldtype = field.DataType.ToString(); f.ValueRetrievedFromParent = false; f.EntityName = sheetname; f.FieldIndex = y; Fields.Add(f); y += 1; } i += 1; entityData.Fields = new List <EntityField>(); entityData.Fields.AddRange(Fields); Entities.Add(entityData); } } catch (Exception) { } } else { DMEEditor.AddLogMessage("Error", "Json File Not Found " + Dataconnection.ConnectionProp.FileName, DateTime.Now, -1, "", Errors.Failed); } }
/// <summary> /// Gets the column for the field. /// </summary> /// <param name="field"></param> /// <returns></returns> internal static SqlColumn GetColumn(EntityField field) { if (field == null) { throw new ArgumentNullException("field"); } return(new SqlColumn(field.NativeName.Name, field.Name, field.DBType, field.Size, field.Flags)); }
private void initFields() { _id = new PrimaryKeyField <projectNS.Company, intermediateNS.Company, L2SNS.Company, long>(this, t => t.Id, (t, val) => t.Id = val); _name = new EntityField <projectNS.Company, intermediateNS.Company, L2SNS.Company, string>(this, t => t.Name, (t, val) => t.Name = val); _type = new EntityField <projectNS.Company, intermediateNS.Company, L2SNS.Company, string>(this, t => t.Type, (t, val) => t.Type = val); _portfolioId = new EntityField <projectNS.Company, intermediateNS.Company, L2SNS.Company, long>(this, t => t.PortfolioId, (t, val) => t.PortfolioId = val); _users = new IntermediateEntityCollection <projectNS.Company, projectNS.User, intermediateNS.Company, intermediateNS.User, L2SNS.Company, L2SNS.User>(this, __user => __user._company); _portfolio = new IntermediateEntityReference <projectNS.Company, projectNS.Portfolio, intermediateNS.Company, intermediateNS.Portfolio, L2SNS.Company, L2SNS.Portfolio>(this, __c => __c.Portfolio, (__c, __portfolio) => __c.Portfolio = __portfolio, __portfolio => __portfolio._company, false); }
private void WriteFields() { var properties = this.EntityMeta.EntityProperties; for (int i = 0, c = properties.Count; i < c; i++) { var property = properties[i]; var mp = property.ManagedProperty; //只为树状实体输出以下两个属性。 if (mp == Entity.TreePIdProperty || mp == Entity.TreeIndexProperty) { if (!_entityModel.isTree) { continue; } } var serverType = ServerTypeHelper.GetServerType(property.PropertyType); if (serverType.Name == SupportedServerType.Unknown) { continue; } var pName = property.Name; var field = new EntityField { name = pName, type = serverType, persist = property.Runtime.CanWrite, }; if (mp != null) { //为外键添加一个视图属性 if (mp is IRefProperty) { _entityModel.fields.Add(field); var refMp = mp as IRefProperty; field = new EntityField { name = LabeledRefProperty(pName), type = ServerTypeHelper.GetServerType(typeof(string)), persist = false, }; } else { var v = mp.GetMeta(this.EntityMeta.EntityType).DefaultValue; field.defaultValue = EntityJsonConverter.ToClientValue(property.PropertyType, v); } } _entityModel.fields.Add(field); } }
public void OrElse(EntityField <T> schemaField, ComparisonOperator @operator, T entity) { OrElse(QueryExpression.Compare( QueryExpression.Column(schemaField.Column.Name, schemaField.Source.AliasIdentifierExpression), @operator, GetValueExpression(schemaField, entity) )); AddJoin(schemaField.Source); }
public void OrElse(EntityField <T> schemaField, ComparisonOperator @operator, IQueryBuilder subQuery) { OrElse(QueryExpression.Compare( QueryExpression.Column(schemaField.Column.Name, schemaField.Source.AliasIdentifierExpression), @operator, subQuery.BuildQuery() )); AddJoin(schemaField.Source); }
private static void CreateExceptionInfoEntity( IProject project ) { EntityClass exception = new EntityClass( "ExceptionInfo", "public" ); EntityField id = new EntityField( "id" ); id.IsPrimaryKey = true; id.IsPreview = true; id.Type = intType; EntityField name = new EntityField( "name" ); name.MaxSize = 15000; name.IsRequired = true; name.Type = stringType; EntityField message = new EntityField( "message" ); message.Represents = true; message.IsPreview = true; message.IsRequired = true; message.MaxSize = 15000; message.Type = stringType; EntityField date = new EntityField( "date" ); date.Type = dateTimeType; EntityField exceptions = new EntityField( "exceptions" ); exceptions.Mult = Multiplicity.OneToMany; exceptions.Type = exception; EntityField principal = null; principal = new EntityField( "principal" ); principal.Mult = Multiplicity.ManyToOne; EntityClass principalEntity = project.GetEntity( "Principal" ); principalEntity.Fields.Add( exceptions ); principal.Type = principalEntity; EntityField url = new EntityField( "url" ); url.Regex.Add( "$http://" ); url.MaxSize = 15000; url.Type = stringType; EntityField stackTrace = new EntityField( "stackTrace" ); stackTrace.MaxSize = 15000; stackTrace.IsRequired = true; stackTrace.Type = stringType; exception.AddField( id ); exception.AddField( name ); exception.AddField( message ); exception.AddField( date ); exception.AddField( principal ); exception.AddField( url ); exception.AddField( stackTrace ); project.Model.Add( exception ); }
/// <summary> /// Builds an expression for an attribute field /// </summary> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="entityField">The property.</param> /// <param name="values">The values.</param> /// <returns></returns> public Expression GetAttributeExpression( IService serviceInstance, ParameterExpression parameterExpression, EntityField entityField, List<string> values ) { ComparisonType comparisonType = ComparisonType.EqualTo; var service = new AttributeValueService( (RockContext)serviceInstance.Context ); var attributeValues = service.Queryable().Where( v => v.Attribute.Guid == entityField.AttributeGuid && v.EntityId.HasValue && v.Value != string.Empty ); ParameterExpression attributeValueParameterExpression = Expression.Parameter( typeof( AttributeValue ), "v" ); var filterExpression = entityField.FieldType.Field.AttributeFilterExpression( entityField.FieldConfig, values, attributeValueParameterExpression ); if ( filterExpression != null ) { attributeValues = attributeValues.Where( attributeValueParameterExpression, filterExpression, null ); } IQueryable<int> ids = attributeValues.Select( v => v.EntityId.Value ); if ( ids != null ) { MemberExpression propertyExpression = Expression.Property( parameterExpression, "Id" ); ConstantExpression idsExpression = Expression.Constant( ids.AsQueryable(), typeof( IQueryable<int> ) ); Expression expression = Expression.Call( typeof( Queryable ), "Contains", new Type[] { typeof( int ) }, idsExpression, propertyExpression ); if ( comparisonType == ComparisonType.NotEqualTo || comparisonType == ComparisonType.DoesNotContain || comparisonType == ComparisonType.IsBlank ) { return Expression.Not( expression ); } else { return expression; } } return null; }
public void Insert(int index, EntityField val) { List.Insert(index, val); }
public int IndexOf(EntityField val) { return List.IndexOf(val); }
public void CopyTo(EntityField[] array, int index) { List.CopyTo(array, index); }
public bool Contains(EntityField val) { return List.Contains(val); }
public void AddRange(EntityField[] val) { for (int i = 0; i < val.Length; i++) { Add(val[i]); } }
public int Add(EntityField val) { return List.Add(val); }
public void Remove(EntityField val) { List.Remove(val); }
private static EntityClass CreateRoleEntity( IProject project, EntityClass principal ) { EntityClass role = new EntityClass( "Roles", "public" ); EntityField id = new EntityField( "id" ); id.IsPrimaryKey = true; id.IsPreview = true; id.Type = intType; EntityField name = new EntityField( "name" ); name.MaxSize = 20; name.IsRequired = true; name.Represents = true; name.IsPreview = true; name.Type = stringType; EntityField user = new EntityField( "users" ); user.Type = principal; user.Mult = Multiplicity.ManyToMany; user.InfoOnly = true; role.AddField( id ); role.AddField( name ); role.AddField( user ); project.Model.Add( role ); return role; }
/// <summary> /// Builds an expression for an attribute field /// </summary> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="entityField">The property.</param> /// <param name="values">The values.</param> /// <returns></returns> public Expression GetAttributeExpression( IService serviceInstance, ParameterExpression parameterExpression, EntityField entityField, List<string> values ) { var service = new AttributeValueService( (RockContext)serviceInstance.Context ); var attributeValues = service.Queryable().Where( v => v.Attribute.Guid == entityField.AttributeGuid && v.EntityId.HasValue && v.Value != string.Empty ); ParameterExpression attributeValueParameterExpression = Expression.Parameter( typeof( AttributeValue ), "v" ); // Determine the appropriate comparison type to use for this Expression. // Attribute Value records only exist for Entities that have a value specified for the Attribute. // Therefore, if the specified comparison works by excluding certain values we must invert our filter logic: // first we find the Attribute Values that match those values and then we exclude the associated Entities from the result set. var comparisonType = ComparisonType.EqualTo; ComparisonType evaluatedComparisonType = comparisonType; if ( values.Count >= 2 ) { string comparisonValue = values[0]; if ( comparisonValue != "0" ) { comparisonType = comparisonValue.ConvertToEnum<ComparisonType>( ComparisonType.EqualTo ); } switch ( comparisonType ) { case ComparisonType.DoesNotContain: evaluatedComparisonType = ComparisonType.Contains; break; case ComparisonType.IsBlank: evaluatedComparisonType = ComparisonType.IsNotBlank; break; case ComparisonType.NotEqualTo: evaluatedComparisonType = ComparisonType.EqualTo; break; default: evaluatedComparisonType = comparisonType; break; } values[0] = evaluatedComparisonType.ToString(); } var filterExpression = entityField.FieldType.Field.AttributeFilterExpression( entityField.FieldConfig, values, attributeValueParameterExpression ); if ( filterExpression != null ) { attributeValues = attributeValues.Where( attributeValueParameterExpression, filterExpression, null ); } IQueryable<int> ids = attributeValues.Select( v => v.EntityId.Value ); MemberExpression propertyExpression = Expression.Property( parameterExpression, "Id" ); ConstantExpression idsExpression = Expression.Constant( ids.AsQueryable(), typeof( IQueryable<int> ) ); Expression expression = Expression.Call( typeof( Queryable ), "Contains", new Type[] { typeof( int ) }, idsExpression, propertyExpression ); // If we have used an inverted comparison type for the evaluation, invert the Expression so that it excludes the matching Entities. if ( comparisonType != evaluatedComparisonType ) { return Expression.Not( expression ); } else { return expression; } }
/// <summary> /// Builds an expression for an attribute field /// </summary> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="property">The property.</param> /// <param name="values">The values.</param> /// <returns></returns> public Expression GetAttributeExpression( IService serviceInstance, ParameterExpression parameterExpression, EntityField property, List<string> values ) { IEnumerable<int> ids = null; ComparisonType comparisonType = ComparisonType.EqualTo; var service = new AttributeValueService( (RockContext)serviceInstance.Context ); var attributeValues = service.Queryable().Where( v => v.Attribute.Guid == property.AttributeGuid && v.EntityId.HasValue && v.Value != string.Empty ).ToList(); switch ( property.FilterFieldType ) { case SystemGuid.FieldType.DATE: if ( values.Count == 2 ) { comparisonType = values[0].ConvertToEnum<ComparisonType>( ComparisonType.EqualTo ); if ( !( ComparisonType.IsBlank | ComparisonType.IsNotBlank ).HasFlag( comparisonType ) ) { DateTime dateValue = values[1].AsDateTime() ?? DateTime.MinValue; switch ( comparisonType ) { case ComparisonType.EqualTo: case ComparisonType.NotEqualTo: ids = attributeValues.Where( v => dateValue.CompareTo( Convert.ToDateTime( v.Value ) ) == 0 ).Select( v => v.EntityId.Value ); break; case ComparisonType.GreaterThan: ids = attributeValues.Where( v => dateValue.CompareTo( Convert.ToDateTime( v.Value ) ) <= 0 ).Select( v => v.EntityId.Value ); break; case ComparisonType.GreaterThanOrEqualTo: ids = attributeValues.Where( v => dateValue.CompareTo( Convert.ToDateTime( v.Value ) ) < 0 ).Select( v => v.EntityId.Value ); break; case ComparisonType.LessThan: ids = attributeValues.Where( v => dateValue.CompareTo( Convert.ToDateTime( v.Value ) ) >= 0 ).Select( v => v.EntityId.Value ); break; case ComparisonType.LessThanOrEqualTo: ids = attributeValues.Where( v => dateValue.CompareTo( Convert.ToDateTime( v.Value ) ) > 0 ).Select( v => v.EntityId.Value ); break; } } else { ids = attributeValues.Select( v => v.EntityId.Value ); } } break; case SystemGuid.FieldType.TIME: if ( values.Count == 2 ) { comparisonType = values[0].ConvertToEnum<ComparisonType>( ComparisonType.EqualTo ); if ( !( ComparisonType.IsBlank | ComparisonType.IsNotBlank ).HasFlag( comparisonType ) ) { TimeSpan timeValue = values[1].AsTimeSpan() ?? TimeSpan.MinValue; switch ( comparisonType ) { case ComparisonType.EqualTo: case ComparisonType.NotEqualTo: ids = attributeValues.Where( v => timeValue.CompareTo( v.Value.AsTimeSpan() ) == 0 ).Select( v => v.EntityId.Value ); break; case ComparisonType.GreaterThan: ids = attributeValues.Where( v => timeValue.CompareTo( v.Value.AsTimeSpan() ) <= 0 ).Select( v => v.EntityId.Value ); break; case ComparisonType.GreaterThanOrEqualTo: ids = attributeValues.Where( v => timeValue.CompareTo( v.Value.AsTimeSpan() ) < 0 ).Select( v => v.EntityId.Value ); break; case ComparisonType.LessThan: ids = attributeValues.Where( v => timeValue.CompareTo( v.Value.AsTimeSpan() ) >= 0 ).Select( v => v.EntityId.Value ); break; case ComparisonType.LessThanOrEqualTo: ids = attributeValues.Where( v => timeValue.CompareTo( v.Value.AsTimeSpan() ) > 0 ).Select( v => v.EntityId.Value ); break; } } else { ids = attributeValues.Select( v => v.EntityId.Value ); } } break; case SystemGuid.FieldType.DECIMAL: case SystemGuid.FieldType.INTEGER: if ( values.Count == 2 ) { comparisonType = values[0].ConvertToEnum<ComparisonType>( ComparisonType.EqualTo ); if ( !( ComparisonType.IsBlank | ComparisonType.IsNotBlank ).HasFlag( comparisonType ) ) { double numericValue = values[1].AsDoubleOrNull() ?? int.MinValue; switch ( comparisonType ) { case ComparisonType.EqualTo: case ComparisonType.NotEqualTo: ids = attributeValues.Where( v => numericValue.CompareTo( v.Value.AsDouble() ) == 0 ).Select( v => v.EntityId.Value ); break; case ComparisonType.GreaterThan: ids = attributeValues.Where( v => numericValue.CompareTo( v.Value.AsDouble() ) <= 0 ).Select( v => v.EntityId.Value ); break; case ComparisonType.GreaterThanOrEqualTo: ids = attributeValues.Where( v => numericValue.CompareTo( v.Value.AsDouble() ) < 0 ).Select( v => v.EntityId.Value ); break; case ComparisonType.LessThan: ids = attributeValues.Where( v => numericValue.CompareTo( v.Value.AsDouble() ) >= 0 ).Select( v => v.EntityId.Value ); break; case ComparisonType.LessThanOrEqualTo: ids = attributeValues.Where( v => numericValue.CompareTo( v.Value.AsDouble() ) > 0 ).Select( v => v.EntityId.Value ); break; } } else { ids = attributeValues.Select( v => v.EntityId.Value ); } } break; case SystemGuid.FieldType.TEXT: if ( values.Count == 2 ) { comparisonType = values[0].ConvertToEnum<ComparisonType>( ComparisonType.EqualTo ); switch ( comparisonType ) { case ComparisonType.Contains: case ComparisonType.DoesNotContain: ids = attributeValues.Where( v => v.Value.ToUpper().Contains( values[1].ToUpper() ) ).Select( v => v.EntityId.Value ); break; case ComparisonType.EqualTo: case ComparisonType.NotEqualTo: ids = attributeValues.Where( v => v.Value.Equals( values[1], StringComparison.CurrentCultureIgnoreCase ) ).Select( v => v.EntityId.Value ); break; case ComparisonType.IsBlank: case ComparisonType.IsNotBlank: ids = attributeValues.Select( v => v.EntityId.Value ); break; case ComparisonType.StartsWith: ids = attributeValues.Where( v => v.Value.StartsWith( values[1], StringComparison.CurrentCultureIgnoreCase ) ).Select( v => v.EntityId.Value ); break; case ComparisonType.EndsWith: ids = attributeValues.Where( v => v.Value.EndsWith( values[1], StringComparison.CurrentCultureIgnoreCase ) ).Select( v => v.EntityId.Value ); break; } } break; case SystemGuid.FieldType.DAY_OF_WEEK: case SystemGuid.FieldType.SINGLE_SELECT: if ( values.Count == 1 ) { ids = attributeValues.Where( v => v.Value == values[0] ).Select( v => v.EntityId.Value ); } break; case SystemGuid.FieldType.MULTI_SELECT: if ( values.Count == 1 ) { List<string> selectedValues = JsonConvert.DeserializeObject<List<string>>( values[0] ); ids = attributeValues.Where( v => selectedValues.Contains( v.Value ) ).Select( v => v.EntityId.Value ); } break; } if ( ids != null ) { MemberExpression propertyExpression = Expression.Property( parameterExpression, "Id" ); ConstantExpression idsExpression = Expression.Constant( ids.AsQueryable(), typeof( IQueryable<int> ) ); Expression expression = Expression.Call( typeof( Queryable ), "Contains", new Type[] { typeof( int ) }, idsExpression, propertyExpression ); if ( comparisonType == ComparisonType.NotEqualTo || comparisonType == ComparisonType.DoesNotContain || comparisonType == ComparisonType.IsBlank ) { return Expression.Not( expression ); } else { return expression; } } return null; }
/// <summary> /// Adds the field type controls. /// </summary> /// <param name="parentControl">The filter control.</param> /// <param name="controls">The controls.</param> /// <param name="entityField">The entity field.</param> protected void AddFieldTypeControls( Control parentControl, List<Control> controls, EntityField entityField ) { string controlIdPrefix = string.Format( "{0}_{1}", parentControl.ID, entityField.FieldKind == FieldKind.Attribute ? entityField.AttributeGuid.Value.ToString("n") : entityField.Name ); switch ( entityField.FilterFieldType ) { case SystemGuid.FieldType.DATE: var ddlDateCompare = ComparisonControl( DateFilterComparisonTypes ); ddlDateCompare.ID = string.Format( "{0}_ddlDateCompare", controlIdPrefix ); ddlDateCompare.AddCssClass( "js-filter-compare" ); parentControl.Controls.Add( ddlDateCompare ); controls.Add( ddlDateCompare ); var datePicker = new DatePicker(); datePicker.ID = string.Format( "{0}_dtPicker", controlIdPrefix ); datePicker.AddCssClass( "js-filter-control" ); parentControl.Controls.Add( datePicker ); controls.Add( datePicker ); break; case SystemGuid.FieldType.TIME: var ddlTimeCompare = ComparisonControl( DateFilterComparisonTypes ); ddlTimeCompare.ID = string.Format( "{0}_ddlTimeCompare", controlIdPrefix ); ddlTimeCompare.AddCssClass( "js-filter-compare" ); parentControl.Controls.Add( ddlTimeCompare ); controls.Add( ddlTimeCompare ); var timePicker = new TimePicker(); timePicker.ID = string.Format( "{0}_timePicker", controlIdPrefix ); timePicker.AddCssClass( "js-filter-control" ); parentControl.Controls.Add( timePicker ); controls.Add( timePicker ); break; case SystemGuid.FieldType.INTEGER: case SystemGuid.FieldType.DECIMAL: var ddlNumberCompare = ComparisonControl( NumericFilterComparisonTypes ); ddlNumberCompare.ID = string.Format( "{0}_ddlNumberCompare", controlIdPrefix ); ddlNumberCompare.AddCssClass( "js-filter-compare" ); parentControl.Controls.Add( ddlNumberCompare ); controls.Add( ddlNumberCompare ); var numberBox = new NumberBox(); numberBox.ID = string.Format( "{0}_numberBox", controlIdPrefix ); numberBox.AddCssClass( "js-filter-control" ); parentControl.Controls.Add( numberBox ); controls.Add( numberBox ); numberBox.FieldName = entityField.Title; break; case SystemGuid.FieldType.MULTI_SELECT: var cblMultiSelect = new RockCheckBoxList(); cblMultiSelect.ID = string.Format( "{0}_cblMultiSelect", controlIdPrefix ); parentControl.Controls.Add( cblMultiSelect ); cblMultiSelect.RepeatDirection = RepeatDirection.Horizontal; controls.Add( cblMultiSelect ); if ( entityField.FieldKind == FieldKind.Property ) { if ( entityField.PropertyType.IsEnum ) { // Enumeration property foreach ( var value in Enum.GetValues( entityField.PropertyType ) ) { cblMultiSelect.Items.Add( new ListItem( Enum.GetName( entityField.PropertyType, value ).SplitCase() ) ); } } else if ( entityField.DefinedTypeGuid.HasValue ) { // Defined Value Properties var definedType = DefinedTypeCache.Read( entityField.DefinedTypeGuid.Value ); if ( definedType != null ) { foreach ( var definedValue in definedType.DefinedValues ) { cblMultiSelect.Items.Add( new ListItem( definedValue.Name, definedValue.Guid.ToString() ) ); } } } } else { var attribute = AttributeCache.Read( entityField.AttributeGuid.Value ); if ( attribute != null ) { switch ( attribute.FieldType.Guid.ToString().ToUpper() ) { case SystemGuid.FieldType.SINGLE_SELECT: //TODO get attribute values qualifier to populate cbl break; case SystemGuid.FieldType.MULTI_SELECT: //TODO get attribute values qualifier to populate cbl break; } } } break; case SystemGuid.FieldType.SINGLE_SELECT: var ddlSingleSelect = new RockDropDownList(); ddlSingleSelect.ID = string.Format( "{0}_ddlSingleSelect", controlIdPrefix ); parentControl.Controls.Add( ddlSingleSelect ); controls.Add( ddlSingleSelect ); if ( entityField.FieldKind == FieldKind.Property ) { if ( entityField.PropertyType == typeof( bool ) || entityField.PropertyType == typeof( bool? ) ) { ddlSingleSelect.Items.Add( new ListItem( "True", "True" ) ); ddlSingleSelect.Items.Add( new ListItem( "False", "False" ) ); } } else { var attribute = AttributeCache.Read( entityField.AttributeGuid.Value ); if ( attribute != null ) { switch ( attribute.FieldType.Guid.ToString().ToUpper() ) { case SystemGuid.FieldType.BOOLEAN: ddlSingleSelect.Items.Add( new ListItem( "True", "True" ) ); ddlSingleSelect.Items.Add( new ListItem( "False", "False" ) ); break; } } } break; case SystemGuid.FieldType.DAY_OF_WEEK: var dayOfWeekPicker = new DayOfWeekPicker(); dayOfWeekPicker.Label = string.Empty; dayOfWeekPicker.ID = string.Format( "{0}_dayOfWeekPicker", controlIdPrefix ); dayOfWeekPicker.AddCssClass( "js-filter-control" ); parentControl.Controls.Add( dayOfWeekPicker ); controls.Add( dayOfWeekPicker ); break; case SystemGuid.FieldType.TEXT: var ddlText = ComparisonControl( StringFilterComparisonTypes ); ddlText.ID = string.Format( "{0}_ddlText", controlIdPrefix ); ddlText.AddCssClass( "js-filter-compare" ); parentControl.Controls.Add( ddlText ); controls.Add( ddlText ); var tbText = new RockTextBox(); tbText.ID = string.Format( "{0}_tbText", controlIdPrefix ); tbText.AddCssClass( "js-filter-control" ); parentControl.Controls.Add( tbText ); controls.Add( tbText ); break; } }
/// <summary> /// Gets the entity field format selection. /// </summary> /// <param name="values">The values.</param> /// <param name="entityField">The entity field.</param> /// <returns></returns> public string GetEntityFieldFormatSelection( List<string> values, EntityField entityField ) { string entityFieldResult = null; if ( entityField != null ) { // If there is just one additional value then there's no comparison value if ( values.Count == 2 ) { if ( entityField.FilterFieldType == SystemGuid.FieldType.MULTI_SELECT ) { var selectedValues = JsonConvert.DeserializeObject<List<string>>( values[1] ); var selectedTexts = new List<string>(); if ( entityField.DefinedTypeGuid.HasValue ) { foreach ( string selectedValue in selectedValues ) { Guid? definedValueGuid = selectedValue.AsGuidOrNull(); if ( definedValueGuid.HasValue ) { var definedValue = DefinedValueCache.Read( definedValueGuid.Value ); if ( definedValue != null ) { selectedTexts.Add( definedValue.Name ); } } } } else { selectedTexts = selectedValues.ToList(); } entityFieldResult = string.Format( "{0} is {1}", entityField.Title, selectedTexts.Select( v => "'" + v + "'" ).ToList().AsDelimited( " or " ) ); } else if ( entityField.FilterFieldType == SystemGuid.FieldType.DAY_OF_WEEK ) { DayOfWeek dayOfWeek = (DayOfWeek)( values[1].AsInteger() ); entityFieldResult = string.Format( "{0} is {1}", entityField.Title, dayOfWeek.ConvertToString() ); } else { entityFieldResult = string.Format( "{0} is {1}", entityField.Title, values[1] ); } } else if ( values.Count == 3 ) { // If two more values, then it is a comparison and a value ComparisonType comparisonType = values[1].ConvertToEnum<ComparisonType>( ComparisonType.StartsWith ); if ( comparisonType == ComparisonType.IsBlank || comparisonType == ComparisonType.IsNotBlank ) { entityFieldResult = string.Format( "{0} {1}", entityField.Title, comparisonType.ConvertToString() ); } else { Field.IFieldType fieldType = FieldTypeCache.Read( entityField.FilterFieldType.AsGuid() ).Field; entityFieldResult = string.Format( "{0} {1} '{2}'", entityField.Title, comparisonType.ConvertToString(), fieldType.FormatValue(null, values[2], null, false) ); } } } return entityFieldResult; }
/// <summary> /// Builds an expression for a property field /// </summary> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="entityField">The property.</param> /// <param name="values">The values.</param> /// <returns></returns> public Expression GetPropertyExpression( IService serviceInstance, ParameterExpression parameterExpression, EntityField entityField, List<string> values ) { Expression trueValue = Expression.Constant( true ); MemberExpression propertyExpression = Expression.Property( parameterExpression, entityField.Name ); return entityField.FieldType.Field.PropertyFilterExpression( entityField.FieldConfig, values, parameterExpression, entityField.Name, entityField.PropertyType ); }
/// <summary> /// Builds an expression for a property field /// </summary> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="entityField">The property.</param> /// <param name="values">The values.</param> /// <returns></returns> private Expression GetPropertyExpression( IService serviceInstance, ParameterExpression parameterExpression, EntityField entityField, List<string> values ) { Expression trueValue = Expression.Constant( true ); MemberExpression propertyExpression = Expression.Property( parameterExpression, entityField.Name ); switch ( entityField.FilterFieldType ) { // Date Properties case SystemGuid.FieldType.DATE: if ( values.Count == 2 ) { ComparisonType comparisonType = values[0].ConvertToEnum<ComparisonType>( ComparisonType.EqualTo ); DateTime dateValue = values[1].AsDateTime() ?? DateTime.MinValue; ConstantExpression constantExpression = Expression.Constant( dateValue ); if ( !( ComparisonType.IsBlank | ComparisonType.IsNotBlank ).HasFlag( comparisonType ) ) { if ( entityField.PropertyType == typeof( DateTime? ) ) { // special case for Nullable Type MemberExpression hasValue = Expression.Property( propertyExpression, "HasValue" ); MemberExpression valueExpression = Expression.Property( propertyExpression, "Value" ); Expression comparisonExpression = ComparisonExpression( comparisonType, valueExpression, constantExpression ); return Expression.AndAlso( hasValue, comparisonExpression ); } } return ComparisonExpression( comparisonType, propertyExpression, constantExpression ); } break; // Number properties case SystemGuid.FieldType.INTEGER: if ( values.Count == 2 ) { ComparisonType comparisonType = values[0].ConvertToEnum<ComparisonType>( ComparisonType.EqualTo ); int intValue = values[1].AsIntegerOrNull() ?? int.MinValue; ConstantExpression constantExpression = Expression.Constant( intValue ); if ( !( ComparisonType.IsBlank | ComparisonType.IsNotBlank ).HasFlag( comparisonType ) ) { if ( entityField.PropertyType == typeof( int? ) ) { // special case for Nullable Type MemberExpression hasValue = Expression.Property( propertyExpression, "HasValue" ); MemberExpression valueExpression = Expression.Property( propertyExpression, "Value" ); Expression comparisonExpression = ComparisonExpression( comparisonType, valueExpression, constantExpression ); return Expression.AndAlso( hasValue, comparisonExpression ); } } return ComparisonExpression( comparisonType, propertyExpression, constantExpression ); } break; // Enumerations and Defined Value properties case SystemGuid.FieldType.MULTI_SELECT: if ( values.Count == 1 ) { List<string> selectedValues = JsonConvert.DeserializeObject<List<string>>( values[0] ); if ( selectedValues.Any() ) { if ( entityField.PropertyType.IsEnum ) { ConstantExpression constantExpression = Expression.Constant( Enum.Parse( entityField.PropertyType, selectedValues[0].Replace( " ", string.Empty ) ) ); Expression comparison = Expression.Equal( propertyExpression, constantExpression ); foreach ( string selectedValue in selectedValues.Skip( 1 ) ) { constantExpression = Expression.Constant( Enum.Parse( entityField.PropertyType, selectedValue.Replace( " ", string.Empty ) ) ); comparison = Expression.Or( comparison, Expression.Equal( propertyExpression, constantExpression ) ); } return comparison; } else if ( entityField.DefinedTypeGuid.HasValue ) { List<Guid> selectedValueGuids = selectedValues.Select( v => v.AsGuid() ).ToList(); List<int> selectedIds = new DefinedValueService( serviceInstance.Context as RockContext ).GetByGuids( selectedValueGuids ).Select( a => a.Id ).ToList(); ConstantExpression constantExpression = Expression.Constant( selectedIds, typeof( List<int> ) ); if ( entityField.PropertyType == typeof( int? ) ) { // special case for Nullable Type MemberExpression hasValue = Expression.Property( propertyExpression, "HasValue" ); MemberExpression valueExpression = Expression.Property( propertyExpression, "Value" ); MethodCallExpression containsExpression = Expression.Call( constantExpression, "Contains", new Type[] { }, valueExpression ); return Expression.AndAlso( hasValue, containsExpression ); } else { return Expression.Call( constantExpression, "Contains", new Type[] { }, propertyExpression ); } } } } break; // Boolean Properties case SystemGuid.FieldType.SINGLE_SELECT: if ( values.Count == 1 ) { if ( entityField.PropertyType == typeof( bool ) || entityField.PropertyType == typeof( bool? ) ) { ConstantExpression constantExpression = Expression.Constant( bool.Parse( values[0] ) ); ComparisonType comparisonType = ComparisonType.EqualTo; if ( entityField.PropertyType == typeof( bool? ) ) { // special case for Nullable Type MemberExpression hasValue = Expression.Property( propertyExpression, "HasValue" ); MemberExpression valueExpression = Expression.Property( propertyExpression, "Value" ); Expression compareExpression = ComparisonExpression( comparisonType, valueExpression, constantExpression ); return Expression.AndAlso( hasValue, compareExpression ); } else { return ComparisonExpression( comparisonType, propertyExpression, constantExpression ); } } } break; // String Properties case SystemGuid.FieldType.TEXT: if ( values.Count == 2 ) { ComparisonType comparisonType = values[0].ConvertToEnum<ComparisonType>( ComparisonType.EqualTo ); ConstantExpression constantExpression = Expression.Constant( values[1] ); return ComparisonExpression( comparisonType, propertyExpression, constantExpression ); } break; } return null; }
public EntityFieldCollection(EntityField[] val) { AddRange(val); }
private static void CreatePrincipalEntity( IProject project ) { EntityClass principal = project.GetEntity( "Principal" ); if( principal == null ) { principal = new EntityClass( "Principal", "public" ); EntityField id = new EntityField( "id" ); id.IsPrimaryKey = true; id.Type = intType; id.IsPreview = true; principal.AddField( id ); project.Model.Add( principal ); } principal.Lazy = true; if( !principal.HasField( "name" ) ) { EntityField name = new EntityField( "name" ); name.MaxSize = 200; name.IsRequired = true; name.IsPreview = true; name.Represents = true; name.Type = stringType; principal.AddField( name ); } if( !principal.HasField( "password" ) ) { EntityField password = new EntityField( "password" ); password.MaxSize = 50; password.IsRequired = true; password.Type = stringType; password.Secret = true; principal.AddField( password ); } if( !principal.HasField( "email" ) ) { EntityField mail = new EntityField( "email" ); mail.MaxSize = 200; mail.IsPreview = true; mail.IsRequired = true; mail.Type = stringType; //mail.Regex.Add( mail.Unique = true; principal.AddField( mail ); } if( !principal.HasField( "ip" ) ) { EntityField ip = new EntityField( "ip" ); ip.MaxSize = 15; ip.Type = stringType; ip.IsPreview = true; //ip.Regex.Add( principal.AddField( ip ); } if( !principal.HasField( "registDate" ) ) { EntityField registDate = new EntityField( "registDate" ); registDate.IsRequired = true; registDate.Type = dateTimeType; //principal.Regex.Add( principal.AddField( registDate ); } if( !principal.HasField( "lastLogin" ) ) { EntityField lastLogin = new EntityField( "lastLogin" ); lastLogin.IsRequired = true; lastLogin.Type = dateTimeType; //principal.Regex.Add( principal.AddField( lastLogin ); } if( !principal.HasField( "approved" ) ) { EntityField approved = new EntityField( "approved" ); approved.IsRequired = true; approved.Type = boolType; approved.Default = false; principal.AddField( approved ); } if( !principal.HasField( "isOnline" ) ) { EntityField isOnline = new EntityField( "isOnline" ); isOnline.Type = boolType; isOnline.Default = false; principal.AddField( isOnline ); } if( !principal.HasField( "locked" ) ) { EntityField locked = new EntityField( "locked" ); locked.Type = boolType; locked.Default = false; principal.AddField( locked ); } if( !principal.HasField( "locale" ) ) { EntityField locale = new EntityField( "locale" ); locale.Type = stringType; locale.IsRequired = true; locale.MaxSize = 6; principal.AddField( locale ); } if( !principal.HasField( "roles" ) ) { EntityField role = new EntityField( "roles" ); role.Type = CreateRoleEntity( project, principal ); role.Mult = Multiplicity.ManyToMany; role.Lazy = false; principal.AddField( role ); } if( !principal.HasField("confirmationCode") ) { EntityField confirmationCode = new EntityField("confirmationCode"); confirmationCode.Type = stringType; confirmationCode.IsRequired = true; principal.AddField(confirmationCode); } EntityInterface iPrincipal = new EntityInterface(); iPrincipal.Name = "System.Security.Principal.IPrincipal"; principal.Interfaces.Add( iPrincipal ); }
/// <summary> /// Builds an expression for a property field /// </summary> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="entityField">The property.</param> /// <param name="values">The values.</param> /// <returns></returns> private Expression GetPropertyExpression( object serviceInstance, Expression parameterExpression, EntityField entityField, List<string> values ) { Expression trueValue = Expression.Constant( true ); MemberExpression propertyExpression = Expression.Property( parameterExpression, entityField.Name ); Expression constantExpression = null; ComparisonType comparisonType = ComparisonType.EqualTo; switch ( entityField.FilterFieldType ) { // Date Properties case SystemGuid.FieldType.DATE: if ( values.Count == 2 ) { DateTime dateValue = DateTime.MinValue; if ( DateTime.TryParse( values[1], out dateValue ) ) { comparisonType = values[0].ConvertToEnum<ComparisonType>( ComparisonType.EqualTo); constantExpression = Expression.Constant( dateValue ); if ( entityField.PropertyType == typeof( DateTime? ) ) { Expression hasValue = Expression.Property( propertyExpression, "HasValue" ); Expression ValueExpression = Expression.Property( propertyExpression, "Value" ); Expression comparisonExpression = ComparisonExpression( comparisonType, ValueExpression, constantExpression ); return Expression.AndAlso( hasValue, comparisonExpression ); } else { return ComparisonExpression( comparisonType, propertyExpression, constantExpression ); } } } break; // Number properties case SystemGuid.FieldType.INTEGER: if ( values.Count == 2 ) { int intValue = int.MinValue; if ( int.TryParse( values[1], out intValue ) ) { comparisonType = values[0].ConvertToEnum<ComparisonType>( ComparisonType.EqualTo ); constantExpression = Expression.Constant( intValue ); if ( entityField.PropertyType == typeof( int? ) ) { Expression hasValue = Expression.Property( propertyExpression, "HasValue" ); Expression ValueExpression = Expression.Property( propertyExpression, "Value" ); Expression comparisonExpression = ComparisonExpression( comparisonType, ValueExpression, constantExpression ); return Expression.AndAlso( hasValue, comparisonExpression ); } else { return ComparisonExpression( comparisonType, propertyExpression, constantExpression ); } } } break; // Enumerations and Defined Value properties case SystemGuid.FieldType.MULTI_SELECT: if ( values.Count == 1 ) { List<string> selectedValues = JsonConvert.DeserializeObject<List<string>>( values[0] ); if ( selectedValues.Any() ) { if ( entityField.PropertyType.IsEnum ) { constantExpression = Expression.Constant( Enum.Parse( entityField.PropertyType, selectedValues[0].Replace( " ", "" ) ) ); Expression comparison = Expression.Equal( propertyExpression, constantExpression ); foreach ( string selectedValue in selectedValues.Skip( 1 ) ) { constantExpression = Expression.Constant( Enum.Parse( entityField.PropertyType, selectedValue.Replace( " ", "" ) ) ); comparison = Expression.Or( comparison, Expression.Equal( propertyExpression, constantExpression ) ); } return comparison; } else if ( entityField.DefinedTypeId.HasValue ) { List<int> selectedIds = selectedValues.Select( v => int.Parse( v ) ).ToList(); constantExpression = Expression.Constant( selectedIds, typeof( List<int> ) ); if ( entityField.PropertyType == typeof( int? ) ) { Expression hasValue = Expression.Property( propertyExpression, "HasValue" ); Expression ValueExpression = Expression.Property( propertyExpression, "Value" ); MethodCallExpression containsExpression = Expression.Call( constantExpression, "Contains", new Type[] { }, ValueExpression ); return Expression.AndAlso( hasValue, containsExpression ); } else { return Expression.Call( constantExpression, "Contains", new Type[] { }, propertyExpression ); } } } } break; // Boolean Properties case SystemGuid.FieldType.SINGLE_SELECT: if ( values.Count == 1 ) { if ( entityField.PropertyType == typeof( bool ) || entityField.PropertyType == typeof( bool? ) ) { constantExpression = Expression.Constant( bool.Parse( values[0] ) ); if ( entityField.PropertyType == typeof( bool? ) ) { Expression hasValue = Expression.Property( propertyExpression, "HasValue" ); Expression ValueExpression = Expression.Property( propertyExpression, "Value" ); Expression compareExpression = ComparisonExpression( comparisonType, ValueExpression, constantExpression ); return Expression.AndAlso( hasValue, compareExpression ); } else { return ComparisonExpression( comparisonType, propertyExpression, constantExpression ); } } } break; // String Properties case SystemGuid.FieldType.TEXT: if ( values.Count == 2 ) { comparisonType = values[0].ConvertToEnum<ComparisonType>( ComparisonType.EqualTo ); constantExpression = Expression.Constant( values[1] ); return ComparisonExpression( comparisonType, propertyExpression, constantExpression ); } break; } return null; }