Exemple #1
0
        private List <PropertyTemplate> GetClassProperties(IEdmSchemaType ent)
        {
            //stop here for enum
            var enumType = ent as IEdmEnumType;

            if (enumType != null)
            {
                return(null);
            }

            var structuredType = ent as IEdmStructuredType;
            var properties     = structuredType.Properties();

            if (_setting.UseInheritance)
            {
                properties = properties.Where(x => ((IEdmSchemaType)x.DeclaringType).FullName() == ent.FullName());
            }

            var list = properties.Select(property => new PropertyTemplate
            {
                //ToTrace = property.ToTraceString(),
                IsNullable = property.Type.IsNullable,
                PropName   = property.Name,
                PropType   = GetClrTypeName(property.Type),
                //ToDebugString = Helper.Dump(property)
            }).ToList();

            return(list);
        }
Exemple #2
0
        public IEdmSchemaType FindDeclaredType(string qualifiedName)
        {
            IEdmSchemaType edmSchemaType = null;

            this.schemaTypeDictionary.TryGetValue(qualifiedName, out edmSchemaType);
            return(edmSchemaType);
        }
Exemple #3
0
        /// <summary>
        /// Remove the Edm. prefix from the type name if it is primitive type.
        /// </summary>
        /// <param name="typeName">The type name to remove the Edm. prefix</param>
        /// <returns>The type name without the Edm. Prefix</returns>
        internal static string RemoveEdmPrefixFromTypeName(string typeName)
        {
            if (!string.IsNullOrEmpty(typeName))
            {
                string itemTypeName = EdmLibraryExtensions.GetCollectionItemTypeName(typeName);
                if (itemTypeName == null)
                {
                    IEdmSchemaType primitiveType = EdmLibraryExtensions.ResolvePrimitiveTypeName(typeName);
                    if (primitiveType != null)
                    {
                        return(primitiveType.ShortQualifiedName());
                    }
                }
                else
                {
                    IEdmSchemaType primitiveType = EdmLibraryExtensions.ResolvePrimitiveTypeName(itemTypeName);
                    if (primitiveType != null)
                    {
                        return(EdmLibraryExtensions.GetCollectionTypeName(primitiveType.ShortQualifiedName()));
                    }
                }
            }

            return(typeName);
        }
Exemple #4
0
        public static Type GetClrType(IEdmType edmType, IEdmModel edmModel, IAssembliesResolver assembliesResolver)
        {
            IEdmSchemaType edmSchemaType = edmType as IEdmSchemaType;

            Contract.Assert(edmSchemaType != null);

            ClrTypeAnnotation annotation = edmModel.GetAnnotationValue <ClrTypeAnnotation>(edmSchemaType);

            if (annotation != null)
            {
                return(annotation.ClrType);
            }

            string             typeName      = edmSchemaType.FullName();
            IEnumerable <Type> matchingTypes = GetMatchingTypes(typeName, assembliesResolver);

            if (matchingTypes.Count() > 1)
            {
                throw Error.Argument("edmTypeReference", SRResources.MultipleMatchingClrTypesForEdmType,
                                     typeName, String.Join(",", matchingTypes.Select(type => type.AssemblyQualifiedName)));
            }

            edmModel.SetAnnotationValue <ClrTypeAnnotation>(edmSchemaType, new ClrTypeAnnotation(matchingTypes.SingleOrDefault()));

            return(matchingTypes.SingleOrDefault());
        }
Exemple #5
0
        private static object ConvertCollectionValue(ODataCollectionValue collection,
                                                     ref IEdmTypeReference propertyType, IODataDeserializerProvider deserializerProvider,
                                                     ODataDeserializerContext readContext)
        {
            IEdmCollectionTypeReference collectionType;

            if (propertyType == null)
            {
                // dynamic collection property
                Contract.Assert(!String.IsNullOrEmpty(collection.TypeName),
                                "ODataLib should have verified that dynamic collection value has a type name " +
                                "since we provided metadata.");

                string         elementTypeName = GetCollectionElementTypeName(collection.TypeName, isNested: false);
                IEdmModel      model           = readContext.Model;
                IEdmSchemaType elementType     = model.FindType(elementTypeName);
                Contract.Assert(elementType != null);
                collectionType =
                    new EdmCollectionTypeReference(
                        new EdmCollectionType(elementType.ToEdmTypeReference(isNullable: false)));
                propertyType = collectionType;
            }
            else
            {
                collectionType = propertyType as IEdmCollectionTypeReference;
                Contract.Assert(collectionType != null, "The type for collection must be a IEdmCollectionType.");
            }

            IODataEdmTypeDeserializer deserializer = deserializerProvider.GetEdmTypeDeserializer(collectionType);

            return(deserializer.ReadInline(collection, collectionType, readContext));
        }
        public static Object GetValue(IEdmModel edmModel, ODataEnumValue odataValue)
        {
            IEdmSchemaType schemaType = edmModel.FindType(odataValue.TypeName);
            Type           clrType    = edmModel.GetClrType((IEdmEnumType)schemaType.AsElementType());

            return(Enum.Parse(clrType, odataValue.Value));
        }
        private static IEdmModel GetEdmModel(HttpConfiguration configuration)
        {
            var builder = new ODataConventionModelBuilder(configuration);

            EntitySetConfiguration <SelectCustomer> customers = builder.EntitySet <SelectCustomer>("SelectCustomer");

            customers.EntityType.Action("CreditRating").Returns <double>();
            customers.EntityType.Collection.Action("PremiumCustomers").ReturnsCollectionFromEntitySet <SelectCustomer>("SelectCustomer");

            builder.EntitySet <EFSelectCustomer>("EFSelectCustomers");
            builder.EntitySet <EFSelectOrder>("EFSelectOrders");
            builder.EntitySet <SelectOrderDetail>("SelectOrderDetail");
            builder.EntityType <SelectPremiumCustomer>();
            builder.EntitySet <SelectOrder>("SelectOrder");
            builder.EntitySet <SelectBonus>("SelectBonus");
            builder.EntitySet <EFWideCustomer>("EFWideCustomers");
            builder.Action("ResetDataSource");
            builder.Action("ResetDataSource-Order");

            IEdmModel model = builder.GetEdmModel();

            for (int idx = 1; idx <= 5; idx++)
            {
                IEdmSchemaType nestedType = model.FindDeclaredType("WebStack.QA.Test.OData.QueryComposition.CustomProperties" + idx);
                model.SetAnnotationValue(nestedType, new System.Web.OData.Query.ModelBoundQuerySettings()
                {
                    DefaultSelectType = SelectExpandType.Automatic
                });
            }

            return(model);
        }
Exemple #8
0
        /// <summary>
        /// Searches for a type with the given name in this model and creates a new type if no such type exists.
        /// </summary>
        /// <param name="qualifiedName">The qualified name of the type being found.</param>
        /// <returns>The requested type, or the new type created if no such type exists.</returns>
        IEdmSchemaType IEdmModel.FindDeclaredType(string qualifiedName)
        {
            CommonUtility.AssertNotNullOrEmpty("qualifiedName", qualifiedName);

            if (qualifiedName.StartsWith(Constants.Edm, StringComparison.Ordinal))
            {
                // Primitive type, let the core model handle it.
                return(null);
            }

            IEdmSchemaType schemaType = FindDeclaredType(qualifiedName);

            if (schemaType == null)
            {
                string name;
                string namespaceName;
                SplitFullTypeName(qualifiedName, out name, out namespaceName);

                // If no type is found with the given name, assume it is an open entity type with the normal set of properties.
                schemaType = CreateEntityType(namespaceName, name);
                this.AddElement(schemaType);
            }

            return(schemaType);
        }
Exemple #9
0
        private List <string> GetEnumElements(IEdmSchemaType type, out bool isFlags)
        {
            var enumList = new List <string>();

            isFlags = false;
            if (type.TypeKind == EdmTypeKind.Enum)
            {
                if (type is IEdmEnumType enumType)
                {
                    var list2 = enumType.Members;
                    isFlags = enumType.IsFlags;
                    foreach (var item in list2)
                    {
#if odataV3
                        var enumValue   = ((EdmIntegerConstant)item.Value).Value;
                        var enumElement = $"\t\t{item.Name}={enumValue}";
#else
#if EDM7
                        //issue12 reserved keyword
                        var enumElement = $"\t\t{item.Name.ChangeReservedWord()}={item.Value.Value}";
                        //var enumElement = $"\t\t{item.Name}={item.Value.Value}";
#else
                        var enumValue   = ((EdmIntegerConstant)item.Value).Value;
                        var enumElement = $"\t\t{item.Name.ChangeReservedWord()}={enumValue}";
                        //var  enumElement = $"\t\t{item.Name}={enumValue}";
#endif
#endif
                        //enumList.Add(item.Name); // v2.3.0
                        enumList.Add(enumElement); //issue #7 complete enum name /value
                    }
                }
            }

            return(enumList);
        }
        private static IEdmEntitySet FindEntitySet(IEdmModel model, IEdmSchemaType entityType)
        {
            var entitySets = model.EntityContainer.EntitySets().Where(s => entityType.IsOrInheritsFrom(s.EntityType()));

            ExceptionUtilities.Assert(entitySets.Count() == 1, "Expected one entity set for entity type {0}. Found: {1}", entityType.Name, entitySets.Count());
            return(entitySets.Single());
        }
        public static IEdmSchemaType ResolveType(this IEdmModel model, string typeName, bool enableCaseInsensitive = false)
        {
            IEdmSchemaType type = model.FindType(typeName);

            if (type != null || !enableCaseInsensitive)
            {
                return(type);
            }

            var types = model.SchemaElements.OfType <IEdmSchemaType>()
                        .Where(e => string.Equals(typeName, e.FullName(), enableCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal));

            foreach (var refModels in model.ReferencedModels)
            {
                var refedTypes = refModels.SchemaElements.OfType <IEdmSchemaType>()
                                 .Where(e => string.Equals(typeName, e.FullName(), enableCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal));

                types = types.Concat(refedTypes);
            }

            if (types.Count() > 1)
            {
                throw new Exception($"Multiple type found from the model for '{typeName}'.");
            }

            return(types.SingleOrDefault());
        }
Exemple #12
0
        /// <summary>
        /// Searches for a schema type with the given name in this model and returns null if no such schema element exists.
        /// </summary>
        /// <param name="qualifiedName">The qualified name of the schema element being found.</param>
        /// <returns>The requested schema element, or null if no such schema element exists.</returns>
        public IEdmSchemaType FindDeclaredType(string qualifiedName)
        {
            // NOTE: we only support entity types, complex types and primitive types
            //       (no association types)
            IEdmSchemaType coreType = EdmCoreModel.Instance.FindDeclaredType(qualifiedName);

            if (coreType != null)
            {
                return(null);
            }

            IEdmEntityType entityType;

            if (this.entityTypes.TryGetValue(qualifiedName, out entityType))
            {
                return(entityType);
            }

            IEdmComplexType complexType;

            if (this.complexTypes.TryGetValue(qualifiedName, out complexType))
            {
                return(complexType);
            }

            return(null);
        }
Exemple #13
0
        /// <summary>
        /// Add the Edm. prefix to the primitive type if there isn't.
        /// </summary>
        /// <param name="typeName">The type name which may be not prefixed (Edm.).</param>
        /// <returns>The type name with Edm. prefix</returns>
        internal static string AddEdmPrefixOfTypeName(string typeName)
        {
            if (!string.IsNullOrEmpty(typeName))
            {
                string itemTypeName = EdmLibraryExtensions.GetCollectionItemTypeName(typeName);
                if (itemTypeName == null)
                {
                    // This is the primitive type
                    IEdmSchemaType primitiveType = EdmLibraryExtensions.ResolvePrimitiveTypeName(typeName);
                    if (primitiveType != null)
                    {
                        return(primitiveType.FullName());
                    }
                }
                else
                {
                    // This is the collection type
                    IEdmSchemaType primitiveType = EdmLibraryExtensions.ResolvePrimitiveTypeName(itemTypeName);
                    if (primitiveType != null)
                    {
                        return(EdmLibraryExtensions.GetCollectionTypeName(primitiveType.FullName()));
                    }
                }
            }

            // Return the origin type name
            return(typeName);
        }
Exemple #14
0
        private List <PropertyTemplate> GetClassProperties(IEdmSchemaType ent)
        {
            //stop here if enum
            if (ent is IEdmEnumType)
            {
                return(Enumerable.Empty <PropertyTemplate>().ToList());                    //null;
            }
            var structuredType = ent as IEdmStructuredType;
            var properties     = structuredType.Properties();

            if (_setting != null && _setting.UseInheritance)
            {
#if odataV3
                properties = properties.Where(x => ((IEdmSchemaType)x.DeclaringType).FullName() == ent.FullName());
#else
                properties = properties.Where(x => x.DeclaringType.FullTypeName() == ent.FullTypeName());
#endif
            }

            //add serial for properties to support protbuf v3.0
            var serial = 1;
            var list   = properties.Select(property => new PropertyTemplate
            {
                IsNullable     = property.Type.IsNullable,
                PropName       = property.Name,
                PropType       = GetClrTypeName(property.Type),
                Serial         = serial++,
                ClassNameSpace = ent.Namespace,
                MaxLength      = GetMaxLength(property),
                IsReadOnly     = Model.IsReadOnly(property),
                //OriginalType = property.VocabularyAnnotations(Model),
            }).ToList();

            return(list);
        }
        public static string ToTraceString(this IEdmType type)
        {
            EdmUtil.CheckArgumentNull <IEdmType>(type, "type");
            EdmTypeKind typeKind = type.TypeKind;

            switch (typeKind)
            {
            case EdmTypeKind.Row:
            {
                return(((IEdmRowType)type).ToTraceString());
            }

            case EdmTypeKind.Collection:
            {
                return(((IEdmCollectionType)type).ToTraceString());
            }

            case EdmTypeKind.EntityReference:
            {
                return(((IEdmEntityReferenceType)type).ToTraceString());
            }

            default:
            {
                IEdmSchemaType edmSchemaType = type as IEdmSchemaType;
                if (edmSchemaType == null)
                {
                    break;
                }
                return(edmSchemaType.ToTraceString());
            }
            }
            return("UnknownType");
        }
Exemple #16
0
        /// <summary>
        /// Prepare the type name for writing.
        /// 1) If it is primitive type, remove the Edm. prefix.
        /// 2) If it is a non-primitive type or 4.0, prefix with #.
        /// </summary>
        /// <param name="typeName">The type name to write</param>
        /// <param name="version">OData Version of payload being written</param>
        /// <returns>The type name for writing</returns>
        internal static string PrefixTypeNameForWriting(string typeName, ODataVersion version)
        {
            if (!string.IsNullOrEmpty(typeName))
            {
                string itemTypeName = EdmLibraryExtensions.GetCollectionItemTypeName(typeName);
                if (itemTypeName == null)
                {
                    IEdmSchemaType primitiveType = EdmLibraryExtensions.ResolvePrimitiveTypeName(typeName);
                    if (primitiveType != null)
                    {
                        typeName = primitiveType.ShortQualifiedName();
                        return(version < ODataVersion.V401 ? PrefixTypeName(typeName) : typeName);
                    }
                }
                else
                {
                    IEdmSchemaType primitiveType = EdmLibraryExtensions.ResolvePrimitiveTypeName(itemTypeName);
                    if (primitiveType != null)
                    {
                        typeName = EdmLibraryExtensions.GetCollectionTypeName(primitiveType.ShortQualifiedName());
                        return(version < ODataVersion.V401 ? PrefixTypeName(typeName) : typeName);
                    }
                }
            }

            return(PrefixTypeName(typeName));
        }
Exemple #17
0
        private List <PropertyTemplate> GetClassProperties(IEdmSchemaType ent)
        {
            //stop here if enum
            if (ent is IEdmEnumType)
            {
                return(null);
            }
            var structuredType = ent as IEdmStructuredType;
            var properties     = structuredType.Properties();

            if (_setting.UseInheritance)
            {
#if odataV3
                properties = properties.Where(x => ((IEdmSchemaType)x.DeclaringType).FullName() == ent.FullName());
#else
                properties = properties.Where(x => x.DeclaringType.FullTypeName() == ent.FullTypeName());
#endif
            }

            //add serial for properties to support protbuf v3.0
            var serial = 1;
            var list   = properties.Select(property => new PropertyTemplate
            {
                IsNullable = property.Type.IsNullable,
                PropName   = property.Name,
                PropType   = GetClrTypeName(property.Type),
                Serial     = serial++
            }).ToList();

            return(list);
        }
Exemple #18
0
        protected string RemoveEdmPrefixFromTypeName(string typeName)
        {
            string itemTypeName = GetCollectionItemTypeName(typeName);

            if (itemTypeName == null)
            {
                // This is not a collection type
                IEdmSchemaType edmType = EdmCoreModel.Instance.FindDeclaredType(typeName);
                if (edmType != null)
                {
                    return(edmType.ShortQualifiedName());
                }
            }
            else
            {
                // This is a collection type
                IEdmSchemaType edmType = EdmCoreModel.Instance.FindDeclaredType(itemTypeName);
                if (edmType != null)
                {
                    return(CollectionTypeQualifier + String.Format("({0})", edmType.ShortQualifiedName()));
                }
            }

            return(typeName);
        }
Exemple #19
0
        public void WriteToStreamAsync_SetsMetadataUriWithSelectClause_OnODataWriterSettings()
        {
            // Arrange
            MemoryStream  stream  = new MemoryStream();
            StreamContent content = new StreamContent(stream);

            content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

            IEdmModel              model      = CreateModel();
            IEdmSchemaType         entityType = model.FindDeclaredType("System.Net.Http.Formatting.SampleType");
            IEdmStructuralProperty property   =
                ((IEdmStructuredType)entityType).FindProperty("Number") as IEdmStructuralProperty;
            HttpRequestMessage request = CreateFakeODataRequest(model);

            request.RequestUri = new Uri("http://localhost/sampleTypes?$select=Number");
            request.ODataProperties().SelectExpandClause =
                new SelectExpandClause(
                    new Collection <SelectItem>
            {
                new PathSelectItem(new ODataSelectPath(new PropertySegment(property))),
            },
                    allSelected: false);

            ODataMediaTypeFormatter formatter = CreateFormatter(model, request, ODataPayloadKind.Resource);

            // Act
            formatter.WriteToStreamAsync(typeof(SampleType[]), new SampleType[0], stream, content, transportContext: null);

            // Assert
            stream.Seek(0, SeekOrigin.Begin);
            string  result = content.ReadAsStringAsync().Result;
            JObject obj    = JObject.Parse(result);

            Assert.Equal("http://localhost/$metadata#sampleTypes(Number)", obj["@odata.context"]);
        }
Exemple #20
0
        /// <summary>
        /// Resolve the <see cref="IEdmSchemaType"/> using the type name. This method supports the type name case insensitive.
        /// </summary>
        /// <param name="model">The Edm model.</param>
        /// <param name="typeName">The type name.</param>
        /// <returns>The Edm schema type.</returns>
        public static IEdmSchemaType ResolveType(this IEdmModel model, string typeName)
        {
            IEdmSchemaType type = model.FindType(typeName);

            if (type != null)
            {
                return(type);
            }

            var types = model.SchemaElements.OfType <IEdmSchemaType>()
                        .Where(e => string.Equals(typeName, e.FullName(), StringComparison.OrdinalIgnoreCase));

            foreach (var refModels in model.ReferencedModels)
            {
                var refedTypes = refModels.SchemaElements.OfType <IEdmSchemaType>()
                                 .Where(e => string.Equals(typeName, e.FullName(), StringComparison.OrdinalIgnoreCase));

                types = types.Concat(refedTypes);
            }

            if (types.Count() > 1)
            {
                throw new ODataException(Error.Format(SRResources.AmbiguousTypeNameFound, typeName));
            }

            return(types.SingleOrDefault());
        }
Exemple #21
0
        /// <summary>
        /// Binds a DottedIdentifierToken and it's parent node (if needed).
        /// </summary>
        /// <param name="dottedIdentifierToken">Token to bind to metadata.</param>
        /// <param name="state">State of the Binding.</param>
        /// <returns>A bound node representing the cast.</returns>
        internal QueryNode BindDottedIdentifier(DottedIdentifierToken dottedIdentifierToken, BindingState state)
        {
            DebugUtils.CheckNoExternalCallers();
            ExceptionUtils.CheckArgumentNotNull(dottedIdentifierToken, "castToken");
            ExceptionUtils.CheckArgumentNotNull(state, "state");

            QueryNode parent;
            IEdmType  parentType;

            if (dottedIdentifierToken.NextToken == null)
            {
                parent     = NodeFactory.CreateRangeVariableReferenceNode(state.ImplicitRangeVariable);
                parentType = state.ImplicitRangeVariable.TypeReference.Definition;
            }
            else
            {
                parent     = this.bindMethod(dottedIdentifierToken.NextToken);
                parentType = parent.GetEdmType();
            }

            SingleEntityNode parentAsSingleValue = parent as SingleEntityNode;

            IEdmSchemaType childType       = UriEdmHelpers.FindTypeFromModel(state.Model, dottedIdentifierToken.Identifier);
            IEdmEntityType childEntityType = childType as IEdmEntityType;

            if (childEntityType == null)
            {
                FunctionCallBinder functionCallBinder = new FunctionCallBinder(bindMethod);
                QueryNode          functionCallNode;
                if (functionCallBinder.TryBindDottedIdentifierAsFunctionCall(dottedIdentifierToken, parentAsSingleValue, state, out functionCallNode))
                {
                    return(functionCallNode);
                }
                else
                {
                    throw new ODataException(ODataErrorStrings.CastBinder_ChildTypeIsNotEntity(dottedIdentifierToken.Identifier));
                }
            }

            // Check whether childType is a derived type of the type of its parent node
            UriEdmHelpers.CheckRelatedTo(parentType, childType);

            EntityCollectionNode parentAsCollection = parent as EntityCollectionNode;

            if (parentAsCollection != null)
            {
                return(new EntityCollectionCastNode(parentAsCollection, childEntityType));
            }

            // parent can be null for casts on the implicit parameter; this is OK
            if (parent == null)
            {
                return(new SingleEntityCastNode(null, childEntityType));
            }

            Debug.Assert(parentAsSingleValue != null, "If parent of the cast node was not collection, it should be a single value.");
            return(new SingleEntityCastNode(parentAsSingleValue, childEntityType));
        }
Exemple #22
0
        private string ProcessComplexType(IEdmSchemaType complexType)
        {
            StringBuilder str            = new StringBuilder();
            var           structuredType = complexType as IEdmStructuredType;
            var           properties     = structuredType.Properties();

            str.Append(complexType.Name);
            return(str.ToString());
        }
Exemple #23
0
        internal static string FullyQualifiedName(IEdmVocabularyAnnotatable element)
        {
            IEdmSchemaElement schemaElement = element as IEdmSchemaElement;

            if (schemaElement != null)
            {
                IEdmOperation operation = schemaElement as IEdmOperation;
                if (operation != null)
                {
                    return(ParameterizedName(operation));
                }
                else
                {
                    return(schemaElement.FullName());
                }
            }
            else
            {
                IEdmEntityContainerElement containerElement = element as IEdmEntityContainerElement;
                if (containerElement != null)
                {
                    return(containerElement.Container.FullName() + "/" + containerElement.Name);
                }
                else
                {
                    IEdmProperty property = element as IEdmProperty;
                    if (property != null)
                    {
                        IEdmSchemaType declaringSchemaType = property.DeclaringType as IEdmSchemaType;
                        if (declaringSchemaType != null)
                        {
                            string propertyOwnerName = FullyQualifiedName(declaringSchemaType);
                            if (propertyOwnerName != null)
                            {
                                return(propertyOwnerName + "/" + property.Name);
                            }
                        }
                    }
                    else
                    {
                        IEdmOperationParameter parameter = element as IEdmOperationParameter;
                        if (parameter != null)
                        {
                            string parameterOwnerName = FullyQualifiedName(parameter.DeclaringOperation);
                            if (parameterOwnerName != null)
                            {
                                return(parameterOwnerName + "/" + parameter.Name);
                            }
                        }
                    }
                }
            }

            return(null);
        }
Exemple #24
0
        /// <summary>
        /// Get the item type full name if it's the primitive type
        /// </summary>
        /// <param name="typeName">the original type name</param>
        /// <returns>the item type full name if it's the primitive type</returns>
        private static string GetItemTypeFullName(string typeName)
        {
            IEdmSchemaType knownType = EdmCoreModel.Instance.FindDeclaredType(typeName);

            if (knownType != null)
            {
                return(knownType.FullName());
            }

            return(typeName);
        }
Exemple #25
0
        public static Type GetClrType(IEdmType edmType, IEdmModel edmModel, IAssemblyProvider assemblyProvider)
        {
            IEdmSchemaType edmSchemaType = edmType as IEdmSchemaType;

            Contract.Assert(edmSchemaType != null);

            string             typeName      = edmSchemaType.FullName();
            IEnumerable <Type> matchingTypes = GetMatchingTypes(typeName, assemblyProvider);

            return(matchingTypes.FirstOrDefault());
        }
 public IEdmSchemaType FindDeclaredType(string qualifiedName)
 {
     foreach (var innerContainer in _innerContainers)
     {
         IEdmSchemaType edmType = innerContainer.EdmModel.FindDeclaredType(qualifiedName);
         if (edmType != null)
         {
             return(edmType);
         }
     }
     return(null);
 }
Exemple #27
0
        private static EdmTypeKind ComputeExpectedTypeKind(string typeName, out IEdmPrimitiveType primitiveItemType)
        {
            IEdmSchemaType type = EdmCoreModel.Instance.FindDeclaredType(typeName);

            if (type != null)
            {
                primitiveItemType = (IEdmPrimitiveType)type;
                return(EdmTypeKind.Primitive);
            }
            primitiveItemType = null;
            return(EdmTypeKind.Complex);
        }
Exemple #28
0
        private List <string> GetNavigation(IEdmSchemaType ent)
        {
            var list = new List <string>();

            if (ent is IEdmEntityType entityType)
            {
                var nav = entityType.DeclaredNavigationProperties().ToList();
                list.AddRange(nav.Select(key => key.Name));
            }

            return(list);
        }
		public static IEntitySetMetadata GetEntitySetFor(this IContainerMetadata containerMetadata, IEdmSchemaType edmSchemaType)
		{
			Contract.Requires<ArgumentNullException>(containerMetadata != null);
			Contract.Requires<ArgumentNullException>(edmSchemaType != null);

			IEntityTypeMetadata entityType = GetEntityType(containerMetadata, edmSchemaType);
			if (entityType == null)
			{
				return null;
			}
			return containerMetadata.EntitySets.SingleOrDefault(es => es.ElementTypeHierarchyMetadata.Contains(entityType));
		}
Exemple #30
0
        internal static IEdmSchemaType CreateAmbiguousTypeBinding(IEdmSchemaType first, IEdmSchemaType second)
        {
            var ambiguous = first as AmbiguousTypeBinding;

            if (ambiguous != null)
            {
                ambiguous.AddBinding(second);
                return(ambiguous);
            }

            return(new AmbiguousTypeBinding(first, second));
        }
Exemple #31
0
        protected string GetCyclicBaseTypeName(string baseTypeName)
        {
            IEdmSchemaType edmSchemaType = this.context.FindType(baseTypeName);

            if (edmSchemaType != null)
            {
                return(edmSchemaType.FullName());
            }
            else
            {
                return(baseTypeName);
            }
        }
		public static IEntityTypeMetadata GetEntityType(this IContainerMetadata containerMetadata, IEdmSchemaType edmSchemaType)
		{
			Contract.Requires<ArgumentNullException>(containerMetadata != null);
			Contract.Requires<ArgumentNullException>(edmSchemaType != null);
			
			return containerMetadata.EntityTypes.SingleOrDefault(et =>
			{
				IEdmEntityType edmType = et.EdmType;
				return edmType.TypeKind == edmSchemaType.TypeKind
					   && edmType.Name == edmSchemaType.Name
					   && ((edmType.Namespace == edmSchemaType.Namespace) || (containerMetadata.Namespace == edmSchemaType.Namespace) || (et.ClrType.Namespace == edmSchemaType.Namespace));
			});
		}
Exemple #33
0
        private List<string> GetEnumElements(IEdmSchemaType type)
        {
            List<string> enumList = new List<string>();

            if (type.TypeKind == EdmTypeKind.Enum)
            {
                var enumType = type as IEdmEnumType;
                if (enumType != null)
                {
                    var list2 = enumType.Members;

                    foreach (var item in list2)
                    {
                        Debug.WriteLine("GetEnumElements- name: [{0}] ", (object)item.Name);
                        enumList.Add(item.Name);
                    }

                }

            }
            return enumList;
        }
Exemple #34
0
        private ClassTemplate GeneratePocoClass(IEdmSchemaType ent)
        {

            if (ent == null) return null;
            //for debuging
           // var debugString = Helper.Dump(ent);
            //v1.0.0-rc3 , enum support
            var enumType = ent as IEdmEnumType;
            ClassTemplate classTemplate = new ClassTemplate
               {
                   Name = ent.Name,
                 //  ToDebugString = debugString,
                   IsEnum = (enumType != null)

               };

            //for enum type , stop here , no more information needed
            if (classTemplate.IsEnum) return classTemplate;

            //fill setname
            //v1.4
            classTemplate.EntitySetName = GetEntitySetName(ent.Name);

            //fill keys 
            var list = GetKeys(ent);
            if (list != null) classTemplate.Keys.AddRange(list);

            //fill navigation properties
            var list2 = GetNavigation(ent);
            if (list2 != null) classTemplate.Navigation.AddRange(list2);

            var entityProperties = GetClassProperties(ent);

            //set the key ,comment
            foreach (var property in entityProperties)
            {
                //@@@ v1.0.0-rc3  
                if (classTemplate.Navigation.Exists(x => x == property.PropName)) property.IsNavigate = true;

                if (classTemplate.Keys.Exists(x => x == property.PropName)) property.IsKey = true;
                var comment = (property.IsKey ? "PrimaryKey" : String.Empty)
                                + (property.IsNullable ? String.Empty : " not null");
                if (!string.IsNullOrEmpty(comment)) property.PropComment = "//" + comment;

            }
            classTemplate.Properties.AddRange(entityProperties);
            return classTemplate;
        }
        /// <summary>
        /// Adds a schema type to the internal caches of the model.
        /// </summary>
        /// <param name="schemaType">The <see cref="IEdmSchemaType"/> to cache.</param>
        /// <remarks>
        /// Materialization state: none required. No change in materialization state.
        /// Cache state: none required. No change in cache state.
        /// </remarks>
        private void CacheSchemaType(IEdmSchemaType schemaType)
        {
            Debug.Assert(schemaType != null, "schemaType != null");

            // first add the schema element to the schema element cache
            string fullName = schemaType.FullName();
            Debug.Assert(!this.schemaTypeCache.ContainsKey(fullName), "Schema type cache already contains an element with name " + fullName + ".");
            this.schemaTypeCache.Add(fullName, schemaType);
            IEdmStructuredType structuredType = schemaType as IEdmStructuredType;
            if (structuredType != null && structuredType.BaseType != null)
            {
                List<IEdmStructuredType> derivedTypes;
                if (!this.derivedTypeMappings.TryGetValue(structuredType.BaseType, out derivedTypes))
                {
                    derivedTypes = new List<IEdmStructuredType>();
                    this.derivedTypeMappings[structuredType.BaseType] = derivedTypes;
                }

                derivedTypes.Add(structuredType);
            }
        }
Exemple #36
0
        private List<string> GetNavigation(IEdmSchemaType ent)
        {
            var list = new List<string>();
            var entityType = ent as IEdmEntityType;
            if (entityType != null)
            {
                var nav = entityType.DeclaredNavigationProperties().ToList();
                list.AddRange(nav.Select(key => key.Name));
            }

            return list;
        }
Exemple #37
0
        private List<string> GetKeys(IEdmSchemaType ent)
        {
            var list = new List<string>();
            var entityType = ent as IEdmEntityType;
            if (entityType != null)
            {
                var keys = entityType.DeclaredKey;
                if (keys != null)
                    list.AddRange(keys.Select(key => key.Name));
            }

            return list;
        }
 private void CacheSchemaType(IEdmSchemaType schemaType)
 {
     string key = schemaType.FullName();
     this.schemaTypeCache.Add(key, schemaType);
     IEdmStructuredType item = schemaType as IEdmStructuredType;
     if ((item != null) && (item.BaseType != null))
     {
         List<IEdmStructuredType> list;
         if (!this.derivedTypeMappings.TryGetValue(item.BaseType, out list))
         {
             list = new List<IEdmStructuredType>();
             this.derivedTypeMappings[item.BaseType] = list;
         }
         list.Add(item);
     }
 }
Exemple #39
0
        private List<PropertyTemplate> GetClassProperties(IEdmSchemaType ent)
        {

            //stop here for enum
            var enumType = ent as IEdmEnumType;
            if (enumType != null) return null;

            var structuredType = ent as IEdmStructuredType;
            var properties = structuredType.Properties();

            var list = properties.Select(property => new PropertyTemplate
            {
                //ToTrace = property.ToTraceString(),
                IsNullable = property.Type.IsNullable,
                PropName = property.Name,
                PropType = GetClrTypeName(property.Type),
                //ToDebugString = Helper.Dump(property)
            }).ToList();

            return list;
        }
 private static bool IsEquivalentTo(this IEdmSchemaType thisType, IEdmSchemaType otherType)
 {
     return Object.ReferenceEquals(thisType, otherType);
 }
 private static void CheckForUnreacheableTypeError(ValidationContext context, IEdmSchemaType type, EdmLocation location)
 {
     IEdmType foundType = context.Model.FindType(type.FullName());
     if (foundType is AmbiguousTypeBinding)
     {
         context.AddError(
             location,
             EdmErrorCode.BadAmbiguousElementBinding,
             Strings.EdmModel_Validator_Semantic_AmbiguousType(type.FullName()));
     }
     else if (!foundType.IsEquivalentTo(type))
     {
         context.AddError(
             location,
             EdmErrorCode.BadUnresolvedType,
             Strings.EdmModel_Validator_Semantic_InaccessibleType(type.FullName()));
     }
 }
 private void AnnotateElement(IEdmSchemaType schemaElement, Uri elementId)
 {
     _annotationsManager.SetAnnotationValue(schemaElement, AnnotationNamespace, AnnotationAttribute, elementId);
 }
 private static IEdmEntitySet FindEntitySet(IEdmModel model, IEdmSchemaType entityType)
 {
     var entitySets = model.EntityContainer.EntitySets().Where(s => entityType.IsOrInheritsFrom(s.EntityType()));
     ExceptionUtilities.Assert(entitySets.Count() == 1, "Expected one entity set for entity type {0}. Found: {1}", entityType.Name, entitySets.Count());
     return entitySets.Single();
 }