/// <summary> /// Checks if the given path corresponds to some open property on the <paramref name="baseEntityType"/> /// </summary> /// <param name="baseEntityType">Type to check the path for</param> /// <param name="sourcePath">Input property path</param> /// <returns>true if there is some open property corresponding to the path, false otherwise</returns> bool IsOpenPropertyOnPath(StructuralType baseEntityType, String sourcePath) { Debug.Assert(baseEntityType != null, "Expecting non-null entity type"); if (String.IsNullOrEmpty(sourcePath)) { return(false); } String[] propertyPath = sourcePath.Split('/'); EdmMember entityProperty = baseEntityType.Members.SingleOrDefault(p => p.Name == propertyPath[0]); if (entityProperty == null) { if (baseEntityType.BaseType != null) { return(IsOpenPropertyOnPath(baseEntityType.BaseType as StructuralType, sourcePath)); } else { return(IsOpenType(baseEntityType)); } } else { StructuralType entityPropertyType = entityProperty.TypeUsage.EdmType as StructuralType; if (entityPropertyType != null) { return(IsOpenPropertyOnPath(entityPropertyType, String.Join("/", propertyPath, 1, propertyPath.Length - 1))); } else { return(false); } } }
/// <summary> /// Constructs a named stream segment for a property with the given name on the given type /// </summary> /// <param name="type">The metadata for the type</param> /// <param name="propertyName">The property name</param> /// <returns>A named streamsegment</returns> public static ODataUriSegment NamedStream(StructuralType type, string propertyName) { ExceptionUtilities.CheckArgumentNotNull(type, "type"); ExceptionUtilities.CheckStringArgumentIsNotNullOrEmpty(propertyName, "propertyName"); return(new NamedStreamSegment(propertyName)); }
/// <summary> /// Returns all complex types that are in the namedstructuraltype provided /// Ex, if a ComplexType1 has ComplexType2, and Collection(ComplexType3), then all three are returned /// </summary> /// <param name="structuralType">structuralType to search</param> /// <returns>a List of all ComplexTypes</returns> public static IEnumerable <ComplexType> AllComplexTypes(this StructuralType structuralType) { ExceptionUtilities.CheckArgumentNotNull(structuralType, "structuralType"); List <ComplexDataType> foundComplexTypes = new List <ComplexDataType>(); List <StructuralType> typesLeftToProcess = new List <StructuralType>(); typesLeftToProcess.Add(structuralType); while (typesLeftToProcess.Count > 0) { List <ComplexDataType> newTypesToProcess = new List <ComplexDataType>(); foreach (StructuralType unprocessedNamedStructuralType in typesLeftToProcess) { List <ComplexDataType> complexTypes = unprocessedNamedStructuralType.Properties.ComplexProperties().Select(p => p.PropertyType).OfType <ComplexDataType>().Where(dt => !foundComplexTypes.Contains(dt)).ToList(); foundComplexTypes.AddRange(complexTypes); newTypesToProcess.AddRange(complexTypes); List <ComplexDataType> complexTypesFromBags = unprocessedNamedStructuralType.Properties.MultiValue(MultiValueType.Complex).Select(p => p.PropertyType).OfType <CollectionDataType>().Select(ct => ct.ElementDataType).OfType <ComplexDataType>().Where(dt => !foundComplexTypes.Contains(dt)).ToList(); foundComplexTypes.AddRange(complexTypesFromBags); newTypesToProcess.AddRange(complexTypesFromBags); } typesLeftToProcess.Clear(); typesLeftToProcess.AddRange(newTypesToProcess.Select(cdt => cdt.Definition).Cast <StructuralType>()); } return(foundComplexTypes.Select(cdt => cdt.Definition).ToList()); }
/// <summary> /// Constructs a segment for a property with the given name on the given type, or an unknown segment if one cannot be found /// </summary> /// <param name="type">The metadata for the type</param> /// <param name="propertyName">The property name</param> /// <returns>A property, navigation, named stream, or unknown segment</returns> public static ODataUriSegment Property(StructuralType type, string propertyName) { ExceptionUtilities.CheckArgumentNotNull(type, "type"); ExceptionUtilities.CheckStringArgumentIsNotNullOrEmpty(propertyName, "propertyName"); MemberProperty property; var entityType = type as EntityType; if (entityType != null) { var navigation = entityType.AllNavigationProperties.SingleOrDefault(p => p.Name == propertyName); if (navigation != null) { return(new NavigationSegment(navigation)); } property = entityType.AllProperties.SingleOrDefault(p => p.Name == propertyName); } else { var complexType = type as ComplexType; ExceptionUtilities.CheckObjectNotNull(complexType, "Structural type was neither an entity type nor a complex type"); property = complexType.Properties.SingleOrDefault(p => p.Name == propertyName); } if (property != null) { return(new PropertySegment(property)); } return(new UnrecognizedSegment(propertyName)); }
/// <summary> /// Family instance parameter. /// </summary> /// <param name="location"></param> /// <param name="symbol"></param> /// <param name="lvl"></param> /// <param name="type"></param> public FamilyInstanceParameter(XYZ location, FamilySymbol symbol, Level lvl, StructuralType type) { Location = location ?? throw new ArgumentNullException(nameof(location)); Symbol = symbol ?? throw new ArgumentNullException(nameof(symbol)); Level = lvl ?? throw new ArgumentNullException(nameof(lvl)); Type = type; }
private void WriteProperties(TreeNode currentTreeNode, StructuralType item, OrderITEntities ctx, DataSpace space) { var node = currentTreeNode.Nodes.Add((space == DataSpace.CSpace) ? "Properties" : "Columns"); foreach (var prop in item.Members) { var propNode = node.Nodes.Add(GetElementNameWithType(prop.Name, prop.TypeUsage, space)); var entityItem = item as EntityType; if (entityItem != null) { if (entityItem.KeyMembers.Any(p => p.Name == prop.Name)) { propNode.NodeFont = new Font(this.Font, FontStyle.Bold); } if (ctx.MetadataWorkspace.GetItems <AssociationType>(space).Where(a => a.IsForeignKey).Any(a => a.ReferentialConstraints[0].ToProperties[0].Name == prop.Name && a.ReferentialConstraints[0].ToRole.Name == item.Name)) { propNode.NodeFont = new Font(this.Font, FontStyle.Bold); propNode.ForeColor = Color.Red; } } foreach (var facet in prop.TypeUsage.Facets) { propNode.Nodes.Add(facet.Name + ": " + facet.Value); } var metaNode = propNode.Nodes.Add("Metadata Properties"); foreach (var meta in prop.MetadataProperties) { metaNode.Nodes.Add(meta.Name + ": " + meta.Value); } } }
/// <summary> /// Obtains the entity property corresponding to a given sourcePath /// </summary> /// <param name="baseEntityType">Entity type in which to look for property</param> /// <param name="sourcePath">Source Path</param> /// <returns>EdmMember object corresponding to the property given through source path</returns> private static EdmMember GetEntityPropertyFromEpmPath(StructuralType baseEntityType, String sourcePath) { Debug.Assert(baseEntityType != null, "Expecting non-null entity type"); String[] propertyPath = sourcePath.Split('/'); if (!baseEntityType.Members.Any(p => p.Name == propertyPath[0])) { return(baseEntityType.BaseType != null?GetEntityPropertyFromEpmPath(baseEntityType.BaseType as StructuralType, sourcePath) : null); } else { EdmMember entityProperty = null; foreach (var pathSegment in propertyPath) { if (baseEntityType == null) { return(null); } entityProperty = baseEntityType.Members.SingleOrDefault(p => p.Name == pathSegment); if (entityProperty == null) { return(null); } baseEntityType = entityProperty.TypeUsage.EdmType as StructuralType; } return(entityProperty); } }
internal static Type GetClrType(MetadataWorkspace ocWorkspace, StructuralType edmType) { var oSpaceType = (StructuralType)ocWorkspace.GetObjectSpaceType(edmType); var objectItemCollection = (ObjectItemCollection)(ocWorkspace.GetItemCollection(DataSpace.OSpace)); return(objectItemCollection.GetClrType(oSpaceType)); }
/// <summary> /// Constructor taking a metadata context, an structural type, and a parent custom type descriptor /// </summary> /// <param name="typeDescriptionContext">The <see cref="LinqToEntitiesTypeDescriptionContext"/> context.</param> /// <param name="edmType">The <see cref="StructuralType"/> type (can be an entity or complex type).</param> /// <param name="parent">The parent custom type descriptor.</param> public LinqToEntitiesTypeDescriptor(LinqToEntitiesTypeDescriptionContext typeDescriptionContext, StructuralType edmType, ICustomTypeDescriptor parent) : base(parent) { _typeDescriptionContext = typeDescriptionContext; _edmType = edmType; EdmMember[] timestampMembers = _edmType.Members.Where(p => ObjectContextUtilities.IsConcurrencyTimestamp(p)).ToArray(); if (timestampMembers.Length == 1) { _timestampMember = timestampMembers[0]; } if (edmType.BuiltInTypeKind == BuiltInTypeKind.EntityType) { // if any FK member of any association is also part of the primary key, then the key cannot be marked // Editable(false) EntityType entityType = (EntityType)edmType; _foreignKeyMembers = new HashSet<EdmMember>(entityType.NavigationProperties.SelectMany(p => p.GetDependentProperties())); foreach (EdmProperty foreignKeyMember in _foreignKeyMembers) { if (entityType.KeyMembers.Contains(foreignKeyMember)) { _keyIsEditable = true; break; } } } }
/// <summary> /// Given the <paramref name="member"/> and one of its <paramref name="possibleType"/>s, determine the attributes that are relevant /// for this <paramref name="possibleType"/> and return a <see cref="MemberPath"/> signature corresponding to the <paramref name="possibleType"/> and the attributes. /// If <paramref name="needKeysOnly"/>=true, collect the key fields only. /// </summary> /// <param name="possibleType">the <paramref name="member"/>'s type or one of its subtypes</param> private static void GatherSignatureFromTypeStructuralMembers(MemberProjectionIndex index, EdmItemCollection edmItemCollection, MemberPath member, StructuralType possibleType, bool needKeysOnly) { // For each child member of this type, collect all the relevant scalar fields foreach (EdmMember structuralMember in Helper.GetAllStructuralMembers(possibleType)) { if (MetadataHelper.IsNonRefSimpleMember(structuralMember)) { if (!needKeysOnly || MetadataHelper.IsPartOfEntityTypeKey(structuralMember)) { MemberPath nonStructuredMember = new MemberPath(member, structuralMember); // Note: scalarMember's parent has already been added to the projectedSlotMap index.CreateIndex(nonStructuredMember); } } else { Debug.Assert(structuralMember.TypeUsage.EdmType is ComplexType || structuralMember.TypeUsage.EdmType is RefType, // for association ends "Only non-scalars expected - complex types, association ends"); MemberPath structuredMember = new MemberPath(member, structuralMember); GatherPartialSignature(index, edmItemCollection, structuredMember, // Only keys are required for entities referenced by association ends of an association. needKeysOnly || Helper.IsAssociationEndMember(structuralMember)); } } }
private Type GetClrType(string edmTypeName) { StructuralType structuralType = GetStructuralType(edmTypeName); Type clrType = objectContextMetadata.GetClrType(structuralType); return(clrType); }
/// <summary> /// Starting at the <paramref name="member"/>, recursively generates <see cref="MemberPath"/>s for the fields embedded in it. /// </summary> /// <param name="member">corresponds to a value of an Entity or Complex or Association type</param> /// <param name="needKeysOnly">indicates whether we need to only collect members that are keys</param> private static void GatherPartialSignature(MemberProjectionIndex index, EdmItemCollection edmItemCollection, MemberPath member, bool needKeysOnly) { EdmType memberType = member.EdmType; ComplexType complexTypemember = memberType as ComplexType; Debug.Assert(complexTypemember != null || memberType is EntityType || // for entity sets memberType is AssociationType || // For association sets memberType is RefType, // for association ends "GatherPartialSignature can be called only for complex types, entity sets, association ends"); if (memberType is ComplexType && needKeysOnly) { // Check if the complex type needs to be traversed or not. If not, just return // from here. Else we need to continue to the code below. Right now, we do not // allow keys inside complex types return; } // Make sure that this member is in the slot map before any of its embedded objects. index.CreateIndex(member); // Consider each possible type value -- each type value conributes to a tuple in the result. // For that possible type, add all the type members into the signature. foreach (EdmType possibleType in MetadataHelper.GetTypeAndSubtypesOf(memberType, edmItemCollection, false /*includeAbstractTypes*/)) { StructuralType possibleStructuralType = possibleType as StructuralType; Debug.Assert(possibleStructuralType != null, "Non-structural subtype?"); GatherSignatureFromTypeStructuralMembers(index, edmItemCollection, member, possibleStructuralType, needKeysOnly); } }
/// <summary> /// Given default values for children members, produces a new default expression for the requested (parent) member. /// </summary> /// <param name="node">Parent member</param> /// <returns>Default value for parent member</returns> internal PropagatorResult Visit(EdmMember node) { PropagatorResult result; TypeUsage nodeType = Helper.GetModelTypeUsage(node); if (Helper.IsScalarType(nodeType.EdmType)) { GetPropagatorResultForPrimitiveType(Helper.AsPrimitive(nodeType.EdmType), out result); } else { // Construct a new 'complex type' (really any structural type) member. StructuralType structuralType = (StructuralType)nodeType.EdmType; IBaseList <EdmMember> members = TypeHelpers.GetAllStructuralMembers(structuralType); PropagatorResult[] args = new PropagatorResult[members.Count]; for (int ordinal = 0; ordinal < members.Count; ordinal++) // foreach (EdmMember member in members) { args[ordinal] = Visit(members[ordinal]); } result = PropagatorResult.CreateStructuralValue(args, structuralType, false); } return(result); }
/// <summary> /// Constructor taking a metadata context, an structural type, and a parent custom type descriptor /// </summary> /// <param name="typeDescriptionContext">The <see cref="LinqToEntitiesTypeDescriptionContext"/> context.</param> /// <param name="edmType">The <see cref="StructuralType"/> type (can be an entity or complex type).</param> /// <param name="parent">The parent custom type descriptor.</param> public LinqToEntitiesTypeDescriptor(LinqToEntitiesTypeDescriptionContext typeDescriptionContext, StructuralType edmType, ICustomTypeDescriptor parent) : base(parent) { _typeDescriptionContext = typeDescriptionContext; _edmType = edmType; EdmMember[] timestampMembers = _edmType.Members.Where(p => ObjectContextUtilities.IsConcurrencyTimestamp(p)).ToArray(); if (timestampMembers.Length == 1) { _timestampMember = timestampMembers[0]; } if (edmType.BuiltInTypeKind == BuiltInTypeKind.EntityType) { // if any FK member of any association is also part of the primary key, then the key cannot be marked // Editable(false) EntityType entityType = (EntityType)edmType; _foreignKeyMembers = new HashSet <EdmMember>(entityType.NavigationProperties.SelectMany(p => p.GetDependentProperties())); foreach (EdmProperty foreignKeyMember in _foreignKeyMembers) { if (entityType.KeyMembers.Contains(foreignKeyMember)) { _keyIsEditable = true; break; } } } }
public override string ClientPropertyNameToServer(string serverName, StructuralType parentType) { if (parentType.Namespace == "Model.Edmunds") { return serverName.Substring(0, 1).ToLower() + serverName.Substring(1); } else { return base.ClientPropertyNameToServer(serverName, parentType); } }
/// <summary> /// Given the type in the target space and the member name in the source space, /// get the corresponding member in the target space /// For e.g. consider a Conceptual Type 'Foo' with a member 'Bar' and a CLR type /// 'XFoo' with a member 'YBar'. If one has a reference to Foo one can /// invoke GetMember(Foo,"YBar") to retrieve the member metadata for bar /// </summary> /// <param name="type">The type in the target perspective</param> /// <param name="memberName">the name of the member in the source perspective</param> /// <param name="ignoreCase">Whether to do case-sensitive member look up or not</param> /// <param name="outMember">returns the member in target space, if a match is found</param> internal virtual bool TryGetMember(StructuralType type, String memberName, bool ignoreCase, out EdmMember outMember) { EntityUtil.CheckArgumentNull(type, "type"); EntityUtil.CheckStringArgument(memberName, "memberName"); outMember = null; return type.Members.TryGetValue(memberName, ignoreCase, out outMember); }
/// <summary> /// Returns a custom type descriptor for the specified type (either an entity or complex type). /// </summary> /// <param name="objectType">Type of object for which we need the descriptor</param> /// <param name="parent">The parent type descriptor</param> /// <returns>Custom type description for the specified type</returns> public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, ICustomTypeDescriptor parent) { // No need to deal with concurrency... Worst case scenario we have multiple // instances of this thing. ICustomTypeDescriptor td = null; if (!this._descriptors.TryGetValue(objectType, out td)) { // call into base so the TDs are chained parent = base.GetTypeDescriptor(objectType, parent); StructuralType edmType = this._typeDescriptionContext.GetEdmType(objectType); if (edmType != null && (edmType.BuiltInTypeKind == BuiltInTypeKind.EntityType || edmType.BuiltInTypeKind == BuiltInTypeKind.ComplexType)) { // only add an LTE TypeDescriptor if the type is an EF Entity or ComplexType td = new LinqToEntitiesTypeDescriptor(this._typeDescriptionContext, edmType, parent); } else { td = parent; } this._descriptors[objectType] = td; } return(td); }
private FunctionImportReturnTypeStructuralTypeColumn GetRename(StructuralType typeForRename) { var ofTypecolumn = _columnListForType.FirstOrDefault(t => t.Type == typeForRename); if (null != ofTypecolumn) { return ofTypecolumn; } // if there are duplicate istypeof mapping defined rename for the same column, the last one wins var isOfTypeColumn = _columnListForIsTypeOfType.Where(t => t.Type == typeForRename).LastOrDefault(); if (null != isOfTypeColumn) { return isOfTypeColumn; } else { // find out all the tyes that is isparent type of this lookup type var nodesInBaseHierachy = _columnListForIsTypeOfType.Where(t => t.Type.IsAssignableFrom(typeForRename)); if (nodesInBaseHierachy.Count() == 0) { // non of its parent is renamed, so it will take the default one return new FunctionImportReturnTypeStructuralTypeColumn(_defaultMemberName, typeForRename, false, null); } else { // we will guarantee that there will be some mapping for us on this column // find out which one is lowest on the link return GetLowestParentInHierachy(nodesInBaseHierachy); } } }
// <summary> // Given the type in the target space and the member name in the source space, // get the corresponding member in the target space // For e.g. consider a Conceptual Type 'Abc' with a member 'Def' and a CLR type // 'XAbc' with a member 'YDef'. If one has a reference to Abc one can // invoke GetMember(Abc,"YDef") to retrieve the member metadata for Def // </summary> // <param name="type"> The type in the target perspective </param> // <param name="memberName"> the name of the member in the source perspective </param> // <param name="ignoreCase"> Whether to do case-sensitive member look up or not </param> // <param name="outMember"> returns the member in target space, if a match is found </param> internal virtual bool TryGetMember(StructuralType type, String memberName, bool ignoreCase, out EdmMember outMember) { DebugCheck.NotNull(type); Check.NotEmpty(memberName, "memberName"); outMember = null; return type.Members.TryGetValue(memberName, ignoreCase, out outMember); }
internal FunctionImportReturnTypeStructuralTypeColumn(string columnName, StructuralType type, bool isTypeOf, LineInfo lineInfo) { ColumnName = columnName; IsTypeOf = isTypeOf; Type = type; LineInfo = lineInfo; }
public override TypeCode GetTypeCode() { StructuralType type = this.vtable.structuralView; switch (type) { case StructuralType.Int8: return(TypeCode.SByte); case StructuralType.Int16: return(TypeCode.Int16); case StructuralType.Int32: return(TypeCode.Int32); case StructuralType.Int64: return(TypeCode.Int64); case StructuralType.UInt8: return(TypeCode.Byte); case StructuralType.UInt16: return(TypeCode.UInt16); case StructuralType.UInt32: return(TypeCode.UInt32); case StructuralType.UInt64: return(TypeCode.UInt64); default: VTable.NotReached("bad enum in InternalGetValue"); return(TypeCode.Object); } }
private FunctionImportReturnTypeStructuralTypeColumn GetRename(StructuralType typeForRename) { var ofTypecolumn = _columnListForType.FirstOrDefault(t => t.Type == typeForRename); if (null != ofTypecolumn) { return(ofTypecolumn); } // if there are duplicate istypeof mapping defined rename for the same column, the last one wins var isOfTypeColumn = _columnListForIsTypeOfType.Where(t => t.Type == typeForRename).LastOrDefault(); if (null != isOfTypeColumn) { return(isOfTypeColumn); } else { // find out all the tyes that is isparent type of this lookup type var nodesInBaseHierarchy = _columnListForIsTypeOfType.Where(t => t.Type.IsAssignableFrom(typeForRename)); if (nodesInBaseHierarchy.Count() == 0) { // non of its parent is renamed, so it will take the default one return(new FunctionImportReturnTypeStructuralTypeColumn(_defaultMemberName, typeForRename, false, null)); } else { // we will guarantee that there will be some mapping for us on this column // find out which one is lowest on the link return(GetLowestParentInHierarchy(nodesInBaseHierarchy)); } } }
private IEnumerable <XElement> GenerateProperties(StructuralType structuralType, XNamespace xmlNamespace) { var content = from prop in structuralType.Properties select this.GenerateProperty(xmlNamespace, prop); return(content); }
internal FunctionImportReturnTypeStructuralTypeColumn(string columnName, StructuralType type, bool isTypeOf, LineInfo lineInfo) { this.ColumnName = columnName; this.IsTypeOf = isTypeOf; this.Type = type; this.LineInfo = lineInfo; }
FamilyInstance CreateBeam( FamilySymbol familySymbol, Level level, XYZ startPt, XYZ endPt) { StructuralType structuralType = StructuralType.Beam; //Line line = _doc.Application.Create.NewLineBound( startPt, endPt ); // 2013 Line line = Line.CreateBound(startPt, endPt); // 2014 FamilyInstance beam = _doc.Create .NewFamilyInstance(startPt, familySymbol, level, structuralType); LocationCurve beamCurve = beam.Location as LocationCurve; if (null != beamCurve) { beamCurve.Curve = line; } return(beam); }
internal FunctionColumnMapGenerator(FunctionImportMappingNonComposable mapping, int resultSetIndex, EntitySet entitySet, StructuralType baseStructuralType) { _mapping = mapping; _entitySet = entitySet; _baseStructuralType = baseStructuralType; _resultSetIndex = resultSetIndex; }
private DbExpression GenerateStructuralTypeMappingView(StructuralType structuralType, List <StoragePropertyMapping> propertyMappings, DbExpression row, IList <EdmSchemaError> errors) { // Generate property views. var properties = TypeHelpers.GetAllStructuralMembers(structuralType); Debug.Assert(properties.Count == propertyMappings.Count, "properties.Count == propertyMappings.Count"); var constructorArgs = new List <DbExpression>(properties.Count); for (int i = 0; i < propertyMappings.Count; ++i) { var propertyMapping = propertyMappings[i]; Debug.Assert(properties[i].EdmEquals(propertyMapping.EdmProperty), "properties[i].EdmEquals(propertyMapping.EdmProperty)"); var propertyMappingView = GeneratePropertyMappingView(propertyMapping, row, new List <string>() { propertyMapping.EdmProperty.Name }, errors); if (propertyMappingView != null) { constructorArgs.Add(propertyMappingView); } } if (constructorArgs.Count != propertyMappings.Count) { Debug.Assert(errors.Count > 0, "errors.Count > 0"); return(null); } else { // Return the structural type constructor. return(TypeUsage.Create(structuralType).New(constructorArgs)); } }
public override ViewValidator.DbExpressionEntitySetInfo Visit( DbNewInstanceExpression expression) { Check.NotNull <DbNewInstanceExpression>(expression, nameof(expression)); ViewValidator.DbExpressionMemberCollectionEntitySetInfo collectionEntitySetInfo = this.VisitExpressionList(expression.Arguments); StructuralType edmType = expression.ResultType.EdmType as StructuralType; if (collectionEntitySetInfo == null || edmType == null) { return((ViewValidator.DbExpressionEntitySetInfo)null); } ViewValidator.DbExpressionStructuralTypeEntitySetInfo setInfos = new ViewValidator.DbExpressionStructuralTypeEntitySetInfo(); int index = 0; foreach (ViewValidator.DbExpressionEntitySetInfo entitySetInfo in collectionEntitySetInfo.entitySetInfos) { setInfos.Add(edmType.Members[index].Name, entitySetInfo); ++index; } if (expression.ResultType.EdmType.BuiltInTypeKind == BuiltInTypeKind.AssociationType) { this.ValidateEntitySetsMappedForAssociationSetMapping(setInfos); } return((ViewValidator.DbExpressionEntitySetInfo)setInfos); }
/// <summary> /// Adds scalar and complex properties to the generated type class. /// </summary> /// <param name="codeClass">The <see cref="CodeTypeDeclaration"/> to which to add the properties.</param> /// <param name="type">The <see cref="StructuralType"/> from which to find properties.</param> protected virtual void AddProperties(CodeTypeDeclaration codeClass, StructuralType type) { foreach (var prop in type.Properties) { CodeTypeReference propertyType = null; var genericPropertyTypeAnnotation = prop.Annotations.OfType <GenericPropertyTypeAnnotation>().FirstOrDefault(); if (genericPropertyTypeAnnotation != null) { propertyType = Code.TypeRef(genericPropertyTypeAnnotation.GenericTypeParameterName); } else { propertyType = codeTypeReferenceResolver.Resolve(prop.PropertyType); } var codeProp = codeClass.AddAutoImplementedProperty(propertyType, prop.Name); ApplyPropertyAccessModifier(codeProp, prop.Annotations.OfType <PropertyAccessModifierAnnotation>().SingleOrDefault()); if (prop.Annotations.Any(a => a is VirtualAnnotation)) { codeProp.SetVirtual(); } if (prop.Annotations.Any(a => a is CodeAttributeAnnotation)) { this.AddCodeAttributeAnnotationAsCustomAttribute(codeProp, prop.Annotations.OfType <CodeAttributeAnnotation>()); } } }
public static StructuralType GetEdmType(MetadataWorkspace workspace, Type clrType) { if (workspace == null) { throw new ArgumentNullException("workspace"); } if (clrType == null) { throw new ArgumentNullException("clrType"); } if (clrType.IsPrimitive || clrType == typeof(object)) { return(null); } EdmType edmType = null; do { if (!workspace.TryGetType(clrType.Name, clrType.Namespace, DataSpace.OSpace, out edmType)) { workspace.LoadFromAssembly(clrType.Assembly); workspace.TryGetType(clrType.Name, clrType.Namespace, DataSpace.OSpace, out edmType); } }while (edmType == null && (clrType = clrType.BaseType) != typeof(object) && clrType != null); StructuralType result = null; if (edmType != null && (edmType.BuiltInTypeKind == BuiltInTypeKind.EntityType || edmType.BuiltInTypeKind == BuiltInTypeKind.ComplexType)) { workspace.TryGetEdmSpaceType((StructuralType)edmType, out result); } return(result); }
private static List <TypeUsage> GetStructuralMemberTypes(TypeUsage instanceType) { StructuralType edmType = instanceType.EdmType as StructuralType; if (edmType == null) { throw new ArgumentException(Strings.Cqt_NewInstance_StructuralTypeRequired, nameof(instanceType)); } if (edmType.Abstract) { throw new ArgumentException(Strings.Cqt_NewInstance_CannotInstantiateAbstractType((object)instanceType.ToString()), nameof(instanceType)); } IBaseList <EdmMember> structuralMembers = TypeHelpers.GetAllStructuralMembers((EdmType)edmType); if (structuralMembers == null || structuralMembers.Count < 1) { throw new ArgumentException(Strings.Cqt_NewInstance_CannotInstantiateMemberlessType((object)instanceType.ToString()), nameof(instanceType)); } List <TypeUsage> typeUsageList = new List <TypeUsage>(structuralMembers.Count); for (int index = 0; index < structuralMembers.Count; ++index) { typeUsageList.Add(Helper.GetModelTypeUsage(structuralMembers[index])); } return(typeUsageList); }
/// <summary> /// Create an instance of the specified family, located at the origin /// </summary> /// <param name="symbol"></param> /// <param name="structuralType"></param> /// <param name="document"></param> /// <returns></returns> public static FamilyInstance CreateFamilyInstance(FamilySymbol symbol, StructuralType structuralType) { if (!symbol.IsActive) { symbol.Activate(); } return(Document.Create.NewFamilyInstance(new XYZ(0, 0, 0), symbol, structuralType)); }
public override string ClientPropertyNameToServer(string clientPropertyName, StructuralType parentType) { String serverPropertyName; if (_clientServerPropNameMap.TryGetValue(clientPropertyName, out serverPropertyName)) { serverPropertyName = clientPropertyName; } return serverPropertyName; }
internal ExtractorMetadata( EntitySetBase entitySetBase, StructuralType type, UpdateTranslator translator) { this.m_type = type; this.m_translator = translator; EntityType entityType = (EntityType)null; Set <EdmMember> set1; Set <EdmMember> set2; switch (type.BuiltInTypeKind) { case BuiltInTypeKind.EntityType: entityType = (EntityType)type; set1 = new Set <EdmMember>((IEnumerable <EdmMember>)entityType.KeyMembers).MakeReadOnly(); set2 = new Set <EdmMember>((IEnumerable <EdmMember>)((EntitySet)entitySetBase).ForeignKeyDependents.SelectMany <Tuple <AssociationSet, ReferentialConstraint>, EdmProperty>((Func <Tuple <AssociationSet, ReferentialConstraint>, IEnumerable <EdmProperty> >)(fk => (IEnumerable <EdmProperty>)fk.Item2.ToProperties))).MakeReadOnly(); break; case BuiltInTypeKind.RowType: set1 = new Set <EdmMember>((IEnumerable <EdmMember>)((RowType)type).Properties).MakeReadOnly(); set2 = Set <EdmMember> .Empty; break; default: set1 = Set <EdmMember> .Empty; set2 = Set <EdmMember> .Empty; break; } IBaseList <EdmMember> structuralMembers = TypeHelpers.GetAllStructuralMembers((EdmType)type); this.m_memberMap = new ExtractorMetadata.MemberInformation[structuralMembers.Count]; for (int ordinal = 0; ordinal < structuralMembers.Count; ++ordinal) { EdmMember edmMember = structuralMembers[ordinal]; PropagatorFlags flags = PropagatorFlags.NoFlags; int? entityKeyOrdinal = new int?(); if (set1.Contains(edmMember)) { flags |= PropagatorFlags.Key; if (entityType != null) { entityKeyOrdinal = new int?(entityType.KeyMembers.IndexOf(edmMember)); } } if (set2.Contains(edmMember)) { flags |= PropagatorFlags.ForeignKey; } if (MetadataHelper.GetConcurrencyMode(edmMember) == ConcurrencyMode.Fixed) { flags |= PropagatorFlags.ConcurrencyValue; } bool isServerGenerated = this.m_translator.ViewLoader.IsServerGen(entitySetBase, this.m_translator.MetadataWorkspace, edmMember); bool isNullConditionMember = this.m_translator.ViewLoader.IsNullConditionMember(entitySetBase, this.m_translator.MetadataWorkspace, edmMember); this.m_memberMap[ordinal] = new ExtractorMetadata.MemberInformation(ordinal, entityKeyOrdinal, flags, edmMember, isServerGenerated, isNullConditionMember); } }
/// <summary> /// According to the selected element create corresponding Boundary Conditions. /// Add it into m_bCsDictionary. /// </summary> public bool CreateBoundaryConditions() { CreateBCHandler createBCH = null; // judge the type of the HostElement if (m_hostElement is FamilyInstance) { FamilyInstance familyInstance = m_hostElement as FamilyInstance; StructuralType structuralType = familyInstance.StructuralType; if (structuralType == StructuralType.Beam) { // create Line BC for beam createBCH = new CreateBCHandler(CreateLineBC); } else if (structuralType == StructuralType.Brace || structuralType == StructuralType.Column || structuralType == StructuralType.Footing) { // create point BC for Column/brace createBCH = new CreateBCHandler(CreatePointBC); } } else if (m_hostElement is Wall) { // create line BC for wall createBCH = new CreateBCHandler(CreateLineBC); } else if (m_hostElement is Floor) { // create area BC for Floor createBCH = new CreateBCHandler(CreateAreaBC); } else if (m_hostElement is ContFooting) { // create line BC for WallFoundation createBCH = new CreateBCHandler(CreateLineBC); } // begin create Autodesk.Revit.DB.BoundaryConditions NewBC = null; try { NewBC = createBCH(m_hostElement); if (null == NewBC) { return(false); } } catch (Exception) { return(false); } // add the created Boundary Conditions into m_bCsDictionary m_bCsDictionary.Add(NewBC.Id.IntegerValue, NewBC); return(true); }
/// <summary> /// Determines the expected shape of store results. We expect a column for every property /// of the mapped type (or types) and a column for every discriminator column. We make no /// assumptions about the order of columns: the provider is expected to determine appropriate /// types by looking at the names of the result columns, not the order of columns, which is /// different from the typical handling of row types in the EF. /// </summary> /// <remarks> /// Requires that the given function import mapping refers to a Collection(Entity) or Collection(ComplexType) CSDL /// function. /// </remarks> /// <returns>Row type.</returns> internal TypeUsage GetExpectedTargetResultType(MetadataWorkspace workspace, int resultSetIndex) { FunctionImportStructuralTypeMappingKB resultMapping = this.GetResultMapping(resultSetIndex); // Collect all columns as name-type pairs. Dictionary <string, TypeUsage> columns = new Dictionary <string, TypeUsage>(); // Figure out which entity types we expect to yield from the function. IEnumerable <StructuralType> structuralTypes; if (0 == resultMapping.NormalizedEntityTypeMappings.Count) { // No explicit type mappings; just use the type specified in the ReturnType attribute on the function. StructuralType structuralType; MetadataHelper.TryGetFunctionImportReturnType <StructuralType>(this.FunctionImport, resultSetIndex, out structuralType); Debug.Assert(null != structuralType, "this method must be called only for entity/complextype reader function imports"); structuralTypes = new StructuralType[] { structuralType }; } else { // Types are explicitly mapped. structuralTypes = resultMapping.MappedEntityTypes.Cast <StructuralType>(); } // Gather columns corresponding to all properties. foreach (StructuralType structuralType in structuralTypes) { foreach (EdmProperty property in TypeHelpers.GetAllStructuralMembers(structuralType)) { // NOTE: if a complex type is encountered, the column map generator will // throw. For now, we just let them through. // We expect to see each property multiple times, so we use indexer rather than // .Add. columns[property.Name] = property.TypeUsage; } } // Gather discriminator columns. foreach (string discriminatorColumn in this.GetDiscriminatorColumns(resultSetIndex)) { if (!columns.ContainsKey(discriminatorColumn)) { // TypeUsage type = TypeUsage.CreateStringTypeUsage(workspace.GetModelPrimitiveType(PrimitiveTypeKind.String), true, false); columns.Add(discriminatorColumn, type); } } // Expected type is a collection of rows RowType rowType = new RowType(columns.Select(c => new EdmProperty(c.Key, c.Value))); TypeUsage result = TypeUsage.Create(new CollectionType(TypeUsage.Create(rowType))); return(result); }
public string Escape(StructuralType type) { if (type == null) { return(null); } return(Escape(type.Name)); }
public override String ServerPropertyNameToClient(String serverPropertyName, StructuralType parentType) { if (serverPropertyName.IndexOf("_", StringComparison.InvariantCulture) != -1) { var clientPropertyName = serverPropertyName.Replace("_", ""); _clientServerPropNameMap[clientPropertyName] = serverPropertyName; return clientPropertyName; } else { return base.ServerPropertyNameToClient(serverPropertyName, parentType); } }
private bool TryCreateStructuralType(Type type, StructuralType cspaceType, out EdmType newOSpaceType) { DebugCheck.NotNull(type); DebugCheck.NotNull(cspaceType); var referenceResolutionListForCurrentType = new List<Action>(); newOSpaceType = null; StructuralType ospaceType; if (Helper.IsEntityType(cspaceType)) { ospaceType = new ClrEntityType(type, cspaceType.NamespaceName, cspaceType.Name); } else { Debug.Assert(Helper.IsComplexType(cspaceType), "Invalid type attribute encountered"); ospaceType = new ClrComplexType(type, cspaceType.NamespaceName, cspaceType.Name); } if (cspaceType.BaseType != null) { if (TypesMatchByConvention(type.BaseType(), cspaceType.BaseType)) { TrackClosure(type.BaseType()); referenceResolutionListForCurrentType.Add( () => ospaceType.BaseType = ResolveBaseType((StructuralType)cspaceType.BaseType, type)); } else { var message = Strings.Validator_OSpace_Convention_BaseTypeIncompatible( type.BaseType().FullName, type.FullName, cspaceType.BaseType.FullName); LogLoadMessage(message, cspaceType); return false; } } // Load the properties for this type if (!TryCreateMembers(type, cspaceType, ospaceType, referenceResolutionListForCurrentType)) { return false; } // Add this to the known type map so we won't try to load it again LoadedTypes.Add(type.FullName, ospaceType); // we only add the referenceResolution to the list unless we structrually matched this type foreach (var referenceResolution in referenceResolutionListForCurrentType) { ReferenceResolutions.Add(referenceResolution); } newOSpaceType = ospaceType; return true; }
internal Type Map(StructuralType objectSpaceType) { Type type; if (!lookup.TryGetValue(objectSpaceType.FullName, out type)) { // For some reason the type wasn't in the typeLookup we built when we // constructed this class. If we encountered any errors building that lookup // they will be in the typeLoadErrors collection we pass to the exception. throw new UnknownTypeException(objectSpaceType.FullName, typeLoadErrors); } return type; }
/// <summary> /// Creates a column map for the given reader and function mapping. /// </summary> internal virtual CollectionColumnMap CreateFunctionImportStructuralTypeColumnMap( DbDataReader storeDataReader, FunctionImportMappingNonComposable mapping, int resultSetIndex, EntitySet entitySet, StructuralType baseStructuralType) { var resultMapping = mapping.GetResultMapping(resultSetIndex); Debug.Assert(resultMapping != null); if (resultMapping.NormalizedEntityTypeMappings.Count == 0) // no explicit mapping; use default non-polymorphic reader { // if there is no mapping, create default mapping to root entity type or complex type Debug.Assert(!baseStructuralType.Abstract, "mapping loader must verify abstract types have explicit mapping"); return CreateColumnMapFromReaderAndType( storeDataReader, baseStructuralType, entitySet, resultMapping.ReturnTypeColumnsRenameMapping); } // the section below deals with the polymorphic entity type mapping for return type var baseEntityType = baseStructuralType as EntityType; Debug.Assert(null != baseEntityType, "We should have entity type here"); // Generate column maps for all discriminators var discriminatorColumns = CreateDiscriminatorColumnMaps(storeDataReader, mapping, resultSetIndex); // Generate default maps for all mapped entity types var mappedEntityTypes = new HashSet<EntityType>(resultMapping.MappedEntityTypes); mappedEntityTypes.Add(baseEntityType); // make sure the base type is represented var typeChoices = new Dictionary<EntityType, TypedColumnMap>(mappedEntityTypes.Count); ColumnMap[] baseTypeColumnMaps = null; foreach (var entityType in mappedEntityTypes) { var propertyColumnMaps = GetColumnMapsForType(storeDataReader, entityType, resultMapping.ReturnTypeColumnsRenameMapping); var entityColumnMap = CreateEntityTypeElementColumnMap( storeDataReader, entityType, entitySet, propertyColumnMaps, resultMapping.ReturnTypeColumnsRenameMapping); if (!entityType.Abstract) { typeChoices.Add(entityType, entityColumnMap); } if (entityType == baseStructuralType) { baseTypeColumnMaps = propertyColumnMaps; } } // NOTE: We don't have a null sentinel here, because the stored proc won't // return one anyway; we'll just presume the data's always there. var polymorphicMap = new MultipleDiscriminatorPolymorphicColumnMap( TypeUsage.Create(baseStructuralType), baseStructuralType.Name, baseTypeColumnMaps, discriminatorColumns, typeChoices, (object[] discriminatorValues) => mapping.Discriminate(discriminatorValues, resultSetIndex)); CollectionColumnMap collection = new SimpleCollectionColumnMap( baseStructuralType.GetCollectionType().TypeUsage, baseStructuralType.Name, polymorphicMap, null, null); return collection; }
/// <summary> /// Given the type in the target space and the member name in the source space, /// get the corresponding member in the target space /// For e.g. consider a Conceptual Type Foo with a member bar and a CLR type /// XFoo with a member YBar. If one has a reference to Foo one can /// invoke GetMember(Foo,"YBar") to retrieve the member metadata for bar /// </summary> /// <param name="type"> The type in the target perspective </param> /// <param name="memberName"> the name of the member in the source perspective </param> /// <param name="ignoreCase"> true for case-insensitive lookup </param> /// <param name="outMember"> returns the edmMember if a match is found </param> /// <returns> true if a match is found, otherwise false </returns> internal override bool TryGetMember(StructuralType type, String memberName, bool ignoreCase, out EdmMember outMember) { outMember = null; Map map = null; if (MetadataWorkspace.TryGetMap(type, DataSpace.OCSpace, out map)) { var objectTypeMap = map as ObjectTypeMapping; if (objectTypeMap != null) { var objPropertyMapping = objectTypeMap.GetMemberMapForClrMember(memberName, ignoreCase); if (null != objPropertyMapping) { outMember = objPropertyMapping.EdmMember; return true; } } } return false; }
public virtual Type GetClrType(StructuralType item) { return _objectItemCollection.GetClrType(item); }
/// <summary> /// Tries and get the mapping ospace member for the given edmMember and the ospace type /// </summary> /// <param name="edmMember"></param> /// <param name="objectType"></param> /// <returns></returns private static EdmMember GetObjectMember(EdmMember edmMember, StructuralType objectType) { // Assuming that we will have a single member in O-space for a member in C space EdmMember objectMember; if (!objectType.Members.TryGetValue(edmMember.Name, false /*ignoreCase*/, out objectMember)) { throw new MappingException( Strings.Mapping_Default_OCMapping_Clr_Member( edmMember.Name, edmMember.DeclaringType.FullName, objectType.FullName)); } return objectMember; }
private static void ValidateAllMembersAreMapped(StructuralType cdmStructuralType, StructuralType objectStructuralType) { Debug.Assert(cdmStructuralType.BuiltInTypeKind == objectStructuralType.BuiltInTypeKind, "the types must be the same"); // error if they don't have the same required members, or if // some object concepts don't exist in cspace (it is ok if the ospace is missing some cspace concepts) if (cdmStructuralType.Members.Count != objectStructuralType.Members.Count) { throw new MappingException( Strings.Mapping_Default_OCMapping_Member_Count_Mismatch( cdmStructuralType.FullName, objectStructuralType.FullName)); } foreach (var member in objectStructuralType.Members) { if (!cdmStructuralType.Members.Contains(member.Identity)) { throw new MappingException( Strings.Mapping_Default_OCMapping_Clr_Member2( member.Name, objectStructuralType.FullName, cdmStructuralType.FullName)); } } }
private void CreateAndAddNavigationProperty( StructuralType cspaceType, StructuralType ospaceType, NavigationProperty cspaceProperty) { EdmType ospaceRelationship; if (CspaceToOspace.TryGetValue(cspaceProperty.RelationshipType, out ospaceRelationship)) { Debug.Assert(ospaceRelationship is StructuralType, "Structural type expected."); var foundTarget = false; EdmType targetType = null; if (Helper.IsCollectionType(cspaceProperty.TypeUsage.EdmType)) { EdmType findType; foundTarget = CspaceToOspace.TryGetValue( ((CollectionType)cspaceProperty.TypeUsage.EdmType).TypeUsage.EdmType, out findType); if (foundTarget) { Debug.Assert(findType is StructuralType, "Structural type expected."); targetType = findType.GetCollectionType(); } } else { EdmType findType; foundTarget = CspaceToOspace.TryGetValue(cspaceProperty.TypeUsage.EdmType, out findType); if (foundTarget) { Debug.Assert(findType is StructuralType, "Structural type expected."); targetType = findType; } } Debug.Assert( foundTarget, "Since the relationship will only be created if it can find the types for both ends, we will never fail to find one of the ends"); var navigationProperty = new NavigationProperty(cspaceProperty.Name, TypeUsage.Create(targetType)); var relationshipType = (RelationshipType)ospaceRelationship; navigationProperty.RelationshipType = relationshipType; // we can use First because o-space relationships are created directly from // c-space relationship navigationProperty.ToEndMember = (RelationshipEndMember)relationshipType.Members.First(e => e.Name == cspaceProperty.ToEndMember.Name); navigationProperty.FromEndMember = (RelationshipEndMember)relationshipType.Members.First(e => e.Name == cspaceProperty.FromEndMember.Name); ospaceType.AddMember(navigationProperty); } else { var missingType = cspaceProperty.RelationshipType.RelationshipEndMembers.Select(e => ((RefType)e.TypeUsage.EdmType).ElementType).First( e => e != cspaceType); LogError( Strings.Validator_OSpace_Convention_RelationshipNotLoaded( cspaceProperty.RelationshipType.FullName, missingType.FullName), missingType); } }
public Type GetClrType(StructuralType edmType) { throw new NotImplementedException(); }
/// <summary> /// Change the declaring type without doing fixup in the member collection /// </summary> internal void ChangeDeclaringTypeWithoutCollectionFixup(StructuralType newDeclaringType) { _declaringType = newDeclaringType; }
// <summary> // Creates an Enum property based on <paramref name="clrProperty" /> and adds it to the parent structural type. // </summary> // <param name="type"> // CLR type owning <paramref name="clrProperty" /> . // </param> // <param name="ospaceType"> OSpace type the created property will be added to. </param> // <param name="cspaceProperty"> Corresponding property from CSpace. </param> // <param name="clrProperty"> CLR property used to build an Enum property. </param> private void CreateAndAddEnumProperty(Type type, StructuralType ospaceType, EdmProperty cspaceProperty, PropertyInfo clrProperty) { EdmType propertyType; if (CspaceToOspace.TryGetValue(cspaceProperty.TypeUsage.EdmType, out propertyType)) { if (clrProperty.CanRead && clrProperty.CanWriteExtended()) { AddScalarMember(type, clrProperty, ospaceType, cspaceProperty, propertyType); } else { LogError( Strings.Validator_OSpace_Convention_ScalarPropertyMissginGetterOrSetter( clrProperty.Name, type.FullName, type.Assembly().FullName), cspaceProperty.TypeUsage.EdmType); } } else { LogError( Strings.Validator_OSpace_Convention_MissingOSpaceType(cspaceProperty.TypeUsage.EdmType.FullName), cspaceProperty.TypeUsage.EdmType); } }
internal static IEnumerable<EpmPropertyInformation> GetEpmInformationFromType(StructuralType structuralType) { return GetEpmPropertyInformation(structuralType, structuralType.Name, null); }
private static void AddScalarMember( Type type, PropertyInfo clrProperty, StructuralType ospaceType, EdmProperty cspaceProperty, EdmType propertyType) { DebugCheck.NotNull(type); DebugCheck.NotNull(clrProperty); Debug.Assert(clrProperty.CanRead && clrProperty.CanWriteExtended(), "The clr property has to have a setter and a getter."); DebugCheck.NotNull(ospaceType); DebugCheck.NotNull(cspaceProperty); DebugCheck.NotNull(propertyType); Debug.Assert(Helper.IsScalarType(propertyType), "Property has to be primitive or enum."); var cspaceType = cspaceProperty.DeclaringType; var isKeyMember = Helper.IsEntityType(cspaceType) && ((EntityType)cspaceType).KeyMemberNames.Contains(clrProperty.Name); // the property is nullable only if it is not a key and can actually be set to null (i.e. is not a value type or is a nullable value type) var nullableFacetValue = !isKeyMember && (!clrProperty.PropertyType.IsValueType() || Nullable.GetUnderlyingType(clrProperty.PropertyType) != null); var ospaceProperty = new EdmProperty( cspaceProperty.Name, TypeUsage.Create( propertyType, new FacetValues { Nullable = nullableFacetValue }), clrProperty, type); if (isKeyMember) { ((EntityType)ospaceType).AddKeyMember(ospaceProperty); } else { ospaceType.AddMember(ospaceProperty); } }
private void CreateAndAddComplexType(Type type, StructuralType ospaceType, EdmProperty cspaceProperty, PropertyInfo clrProperty) { EdmType propertyType; if (CspaceToOspace.TryGetValue(cspaceProperty.TypeUsage.EdmType, out propertyType)) { Debug.Assert(propertyType is StructuralType, "Structural type expected."); var property = new EdmProperty( cspaceProperty.Name, TypeUsage.Create( propertyType, new FacetValues { Nullable = false }), clrProperty, type); ospaceType.AddMember(property); } else { LogError( Strings.Validator_OSpace_Convention_MissingOSpaceType(cspaceProperty.TypeUsage.EdmType.FullName), cspaceProperty.TypeUsage.EdmType); } }
private EdmType ResolveBaseType(StructuralType baseCSpaceType, Type type) { EdmType ospaceType; var foundValue = CspaceToOspace.TryGetValue(baseCSpaceType, out ospaceType); if (!foundValue) { LogError(Strings.Validator_OSpace_Convention_BaseTypeNotLoaded(type, baseCSpaceType), baseCSpaceType); } Debug.Assert(!foundValue || ospaceType is StructuralType, "Structural type expected (if found)."); return ospaceType; }
internal static bool IsNameAlreadyAMemberName(StructuralType type, string generatedPropertyName, StringComparison comparison) { foreach (EdmMember member in type.Members) { if (member.DeclaringType == type && member.Name.Equals(generatedPropertyName, comparison)) { return true; } } return false; }
private bool TryFindAndCreatePrimitiveProperties( Type type, StructuralType cspaceType, StructuralType ospaceType, IEnumerable<PropertyInfo> clrProperties) { foreach ( var cspaceProperty in cspaceType.GetDeclaredOnlyMembers<EdmProperty>().Where(p => Helper.IsPrimitiveType(p.TypeUsage.EdmType))) { var clrProperty = clrProperties.FirstOrDefault(p => MemberMatchesByConvention(p, cspaceProperty)); if (clrProperty != null) { PrimitiveType propertyType; if (TryGetPrimitiveType(clrProperty.PropertyType, out propertyType)) { if (clrProperty.CanRead && clrProperty.CanWriteExtended()) { AddScalarMember(type, clrProperty, ospaceType, cspaceProperty, propertyType); } else { var message = Strings.Validator_OSpace_Convention_ScalarPropertyMissginGetterOrSetter( clrProperty.Name, type.FullName, type.Assembly().FullName); LogLoadMessage(message, cspaceType); return false; } } else { var message = Strings.Validator_OSpace_Convention_NonPrimitiveTypeProperty( clrProperty.Name, type.FullName, clrProperty.PropertyType.FullName); LogLoadMessage(message, cspaceType); return false; } } else { var message = Strings.Validator_OSpace_Convention_MissingRequiredProperty(cspaceProperty.Name, type.FullName); LogLoadMessage(message, cspaceType); return false; } } return true; }
/// <summary> /// Gets the CLR type for the specified StructuralType. /// </summary> /// <param name="structuralType">StructuralType used to find the CLR type.</param> /// <returns>CLR type equivalent for <paramref name="structuralType"/></returns> public Type GetClrType(StructuralType structuralType) { return ObjectContextServiceProvider.GetClrTypeForCSpaceType(this.metadataWorkspace, structuralType); }
/// <summary> /// check if a name is reserved for a type /// </summary> /// <param name="type">the object representing the schema type being defined</param> /// <param name="name">the member name</param> /// <returns>true if the name is reserved by the type</returns> public static bool DoesTypeReserveMemberName(StructuralType type, string name, StringComparison comparison) { Type reservingType = null; if (!TryGetReservedName(name,comparison, out reservingType)) { return false; } // if reserving types is null it means the name is reserved for all types. if (reservingType == null) { return true; } return (reservingType == type.GetType()); }
private Dictionary<string, StructuralType> BuildStructuralTypeMap(List<Dictionary<string, object>> structuralTypeList) { var map = new Dictionary<string, StructuralType>(); foreach (var dt in structuralTypeList) { var st = new StructuralType(); st.fullName = (string)dt["namespace"] + '.' + (string)dt["shortName"]; st.dataProperties = new List<DataProperty>(); var dpoList = (List<Dictionary<string, object>>)dt["dataProperties"]; foreach (var dpo in dpoList) { st.dataProperties.Add(BuildDataProperty(dpo)); } map.Add(st.fullName, st); } return map; }
private bool TryFindAndCreateEnumProperties( Type type, StructuralType cspaceType, StructuralType ospaceType, IEnumerable<PropertyInfo> clrProperties, List<Action> referenceResolutionListForCurrentType) { var typeClosureToTrack = new List<KeyValuePair<EdmProperty, PropertyInfo>>(); foreach ( var cspaceProperty in cspaceType.GetDeclaredOnlyMembers<EdmProperty>().Where(p => Helper.IsEnumType(p.TypeUsage.EdmType))) { var clrProperty = clrProperties.FirstOrDefault(p => MemberMatchesByConvention(p, cspaceProperty)); if (clrProperty != null) { typeClosureToTrack.Add(new KeyValuePair<EdmProperty, PropertyInfo>(cspaceProperty, clrProperty)); } else { var message = Strings.Validator_OSpace_Convention_MissingRequiredProperty(cspaceProperty.Name, type.FullName); LogLoadMessage(message, cspaceType); return false; } } foreach (var typeToTrack in typeClosureToTrack) { TrackClosure(typeToTrack.Value.PropertyType); // prevent the lifting of these closure variables var ot = ospaceType; var cp = typeToTrack.Key; var clrp = typeToTrack.Value; referenceResolutionListForCurrentType.Add(() => CreateAndAddEnumProperty(type, ot, cp, clrp)); } return true; }