public CsdlSemanticsRecordExpression(CsdlRecordExpression expression, IEdmEntityType bindingContext, CsdlSemanticsSchema schema) : base(schema, expression)
		{
			this.declaredTypeCache = new Cache<CsdlSemanticsRecordExpression, IEdmStructuredTypeReference>();
			this.propertiesCache = new Cache<CsdlSemanticsRecordExpression, IEnumerable<IEdmPropertyConstructor>>();
			this.expression = expression;
			this.bindingContext = bindingContext;
		}
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="outputContext">The output context to write to.</param>
        /// <param name="navigationSource">The navigation source we are going to write entities for.</param>
        /// <param name="entityType">The entity type for the entries in the feed to be written (or null if the entity set base type should be used).</param>
        /// <param name="writingFeed">True if the writer is created for writing a feed; false when it is created for writing an entry.</param>
        /// <param name="listener">If not null, the writer will notify the implementer of the interface of relevant state changes in the writer.</param>
        protected ODataWriterCore(
            ODataOutputContext outputContext,
            IEdmNavigationSource navigationSource,
            IEdmEntityType entityType,
            bool writingFeed,
            IODataReaderWriterListener listener = null)
        {
            Debug.Assert(outputContext != null, "outputContext != null");

            this.outputContext = outputContext;
            this.writingFeed = writingFeed;

            // create a collection validator when writing a top-level feed and a user model is present
            if (this.writingFeed && this.outputContext.Model.IsUserModel())
            {
                this.feedValidator = new FeedWithoutExpectedTypeValidator();
            }

            if (navigationSource != null && entityType == null)
            {
                entityType = this.outputContext.EdmTypeResolver.GetElementType(navigationSource);
            }

            ODataUri odataUri = outputContext.MessageWriterSettings.ODataUri.Clone();

            // Remove key for top level entry
            if (!writingFeed && odataUri != null && odataUri.Path != null)
            {
                odataUri.Path = odataUri.Path.TrimEndingKeySegment();
            }

            this.listener = listener;

            this.scopes.Push(new Scope(WriterState.Start, /*item*/null, navigationSource, entityType, /*skipWriting*/false, outputContext.MessageWriterSettings.SelectedProperties, odataUri));
        }
		public CsdlSemanticsCollectionExpression(CsdlCollectionExpression expression, IEdmEntityType bindingContext, CsdlSemanticsSchema schema) : base(schema, expression)
		{
			this.declaredTypeCache = new Cache<CsdlSemanticsCollectionExpression, IEdmTypeReference>();
			this.elementsCache = new Cache<CsdlSemanticsCollectionExpression, IEnumerable<IEdmExpression>>();
			this.expression = expression;
			this.bindingContext = bindingContext;
		}
Esempio n. 4
0
 public static bool HasDefaultStream(this IEdmModel model, IEdmEntityType entityType)
 {
     bool flag;
     ExceptionUtils.CheckArgumentNotNull<IEdmModel>(model, "model");
     ExceptionUtils.CheckArgumentNotNull<IEdmEntityType>(entityType, "entityType");
     return (TryGetBooleanAnnotation(model, entityType, "HasStream", true, out flag) && flag);
 }
Esempio n. 5
0
 public override IEnumerable<KeyValuePair<string, object>> ResolveKeys(
     IEdmEntityType type,
     IList<string> positionalValues,
     Func<IEdmTypeReference, string, object> convertFunc)
 {
     return stringAsEnum.ResolveKeys(type, positionalValues, convertFunc);
 }
        public void GetModel(EdmModel model, EdmEntityContainer container)
        {
            EdmEntityType student = new EdmEntityType("ns", "Student");
            student.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            EdmStructuralProperty key = student.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32);
            student.AddKeys(key);
            model.AddElement(student);
            EdmEntitySet students = container.AddEntitySet("Students", student);

            EdmEntityType school = new EdmEntityType("ns", "School");
            school.AddKeys(school.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
            school.AddStructuralProperty("CreatedDay", EdmPrimitiveTypeKind.DateTimeOffset);
            model.AddElement(school);
            EdmEntitySet schools = container.AddEntitySet("Schools", student);

            EdmNavigationProperty schoolNavProp = student.AddUnidirectionalNavigation(
                new EdmNavigationPropertyInfo
                {
                    Name = "School",
                    TargetMultiplicity = EdmMultiplicity.One,
                    Target = school
                });
            students.AddNavigationTarget(schoolNavProp, schools);

            _school = school;
        }
        /// <summary>
        /// Validates the type of an entry in a top-level feed.
        /// </summary>
        /// <param name="entityType">The type of the entry.</param>
        internal void ValidateEntry(IEdmEntityType entityType)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(entityType != null, "entityType != null");

            // If we don't have a type, store the type of the first item.
            if (this.itemType == null)
            {
                this.itemType = entityType;
            }

            // Validate the expected and actual types.
            if (this.itemType.IsEquivalentTo(entityType))
            {
                return;
            }

            // If the types are not equivalent, make sure they have a common base type.
            IEdmType commonBaseType = EdmLibraryExtensions.GetCommonBaseType(this.itemType, entityType);
            if (commonBaseType == null)
            {
                throw new ODataException(Strings.FeedWithoutExpectedTypeValidator_IncompatibleTypes(entityType.ODataFullName(), this.itemType.ODataFullName()));
            }

            this.itemType = (IEdmEntityType)commonBaseType;
        }
Esempio n. 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EdmEntitySetBase"/> class.
        /// </summary>
        /// <param name="name">Name of the entity set base.</param>
        /// <param name="elementType">The entity type of the elements in this entity set base.</param>
        protected EdmEntitySetBase(string name, IEdmEntityType elementType)
            : base(name)
        {
            EdmUtil.CheckArgumentNull(elementType, "elementType");

            this.type = new EdmCollectionType(new EdmEntityTypeReference(elementType, false));
        }
        public ParameterAliasNodeTranslatorTest()
        {
            var builder = new ODataConventionModelBuilder();
            builder.EntitySet<ParameterAliasCustomer>("Customers");
            builder.EntitySet<ParameterAliasOrder>("Orders");

            builder.EntityType<ParameterAliasCustomer>().Function("CollectionFunctionCall")
                .ReturnsCollection<int>().Parameter<int>("p1");

            builder.EntityType<ParameterAliasCustomer>().Function("EntityCollectionFunctionCall")
                .ReturnsCollectionFromEntitySet<ParameterAliasCustomer>("Customers").Parameter<int>("p1");

            builder.EntityType<ParameterAliasCustomer>().Function("SingleEntityFunctionCall")
                .Returns<ParameterAliasCustomer>().Parameter<int>("p1");

            builder.EntityType<ParameterAliasCustomer>().Function("SingleEntityFunctionCallWithoutParameters")
                .Returns<ParameterAliasCustomer>();

            builder.EntityType<ParameterAliasCustomer>().Function("SingleValueFunctionCall")
                .Returns<int>().Parameter<int>("p1");

            _model = builder.GetEdmModel();
            _customersEntitySet = _model.FindDeclaredEntitySet("Customers");
            _customerEntityType = _customersEntitySet.EntityType();
            _parameterAliasMappedNode = new ConstantNode(123);
        }
		public CsdlSemanticsPropertyReferenceExpression(CsdlPropertyReferenceExpression expression, IEdmEntityType bindingContext, CsdlSemanticsSchema schema) : base(schema, expression)
		{
			this.baseCache = new Cache<CsdlSemanticsPropertyReferenceExpression, IEdmExpression>();
			this.elementCache = new Cache<CsdlSemanticsPropertyReferenceExpression, IEdmProperty>();
			this.expression = expression;
			this.bindingContext = bindingContext;
		}
Esempio n. 11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CastPathSegment" /> class.
        /// </summary>
        /// <param name="previous">The previous segment in the path.</param>
        /// <param name="castType">The type of the cast.</param>
        public CastPathSegment(ODataPathSegment previous, IEdmEntityType castType)
            : base(previous)
        {
            if (castType == null)
            {
                throw Error.ArgumentNull("cast");
            }

            IEdmType previousEdmType = previous.EdmType;

            if (previousEdmType == null)
            {
                throw Error.InvalidOperation(SRResources.PreviousSegmentEdmTypeCannotBeNull);
            }

            if (previousEdmType.TypeKind == EdmTypeKind.Collection)
            {
                EdmType = castType.GetCollection();
            }
            else
            {
                EdmType = castType;
            }
            EntitySet = previous.EntitySet;
            CastType = castType;
        }
Esempio n. 12
0
		public EdmEntityType(string namespaceName, string name, IEdmEntityType baseType, bool isAbstract, bool isOpen) : base(isAbstract, isOpen, baseType)
		{
			EdmUtil.CheckArgumentNull<string>(namespaceName, "namespaceName");
			EdmUtil.CheckArgumentNull<string>(name, "name");
			this.namespaceName = namespaceName;
			this.name = name;
		}
Esempio n. 13
0
 private string GetIdentifierPrefix(IEdmEntityType entityType)
 {
     if (entityType.BaseEntityType() != null)
     {
         return GetIdentifierPrefix(entityType.BaseEntityType());
     }
     TypeMapping existingMapping;
     if (_typeUriMap.TryGetValue(entityType.FullName(), out existingMapping))
     {
         return existingMapping.IdentifierPrefix;
     }
     var keyList = entityType.DeclaredKey.ToList();
     if (keyList.Count != 1)
     {
         // Ignore this entity
         // TODO: Log an error
         return null;
     }
     var identifierPrefix = GetStringAnnotationValue(keyList.First(), AnnotationsNamespace, "IdentifierPrefix");
     if (identifierPrefix == null)
     {
         // TODO: Log an error
     }
     return identifierPrefix;
 }
		public CsdlSemanticsAssertTypeExpression(CsdlAssertTypeExpression expression, IEdmEntityType bindingContext, CsdlSemanticsSchema schema) : base(schema, expression)
		{
			this.operandCache = new Cache<CsdlSemanticsAssertTypeExpression, IEdmExpression>();
			this.typeCache = new Cache<CsdlSemanticsAssertTypeExpression, IEdmTypeReference>();
			this.expression = expression;
			this.bindingContext = bindingContext;
		}
Esempio n. 15
0
        /// <summary>
        /// Creates a new ODataEntry from the specified entity set, instance, and type.
        /// </summary>
        /// <param name="entitySet">Entity set for the new entry.</param>
        /// <param name="value">Entity instance for the new entry.</param>
        /// <param name="entityType">Entity type for the new entry.</param>
        /// <returns>New ODataEntry with the specified entity set and type, property values from the specified instance.</returns>
        internal static ODataEntry CreateODataEntry(IEdmEntitySet entitySet, IEdmStructuredValue value, IEdmEntityType entityType)
        {
            var entry = new ODataEntry();
            entry.SetAnnotation(new ODataTypeAnnotation(entitySet, entityType));
            entry.Properties = value.PropertyValues.Select(p =>
            {
                object propertyValue;
                if (p.Value.ValueKind == EdmValueKind.Null)
                {
                    propertyValue = null;
                }
                else if (p.Value is IEdmPrimitiveValue)
                {
                    propertyValue = ((IEdmPrimitiveValue)p.Value).ToClrValue();
                }
                else
                {
                    Assert.Fail("Test only currently supports creating ODataEntry from IEdmPrimitiveValue instances.");
                    return null;
                }

                return new ODataProperty() { Name = p.Name, Value = propertyValue };
            });

            return entry;
        }
 public CsdlSemanticsApplyExpression(CsdlApplyExpression expression, IEdmEntityType bindingContext, CsdlSemanticsSchema schema)
     : base(schema, expression)
 {
     this.expression = expression;
     this.bindingContext = bindingContext;
     this.schema = schema;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="SelectExpandQueryOption"/> class.
        /// </summary>
        /// <param name="select">The $select query parameter value.</param>
        /// <param name="expand">The $select query parameter value.</param>
        /// <param name="context">The <see cref="ODataQueryContext"/> which contains the <see cref="IEdmModel"/> and some type information.</param>
        public SelectExpandQueryOption(string select, string expand, ODataQueryContext context)
        {
            if (context == null)
            {
                throw Error.ArgumentNull("context");
            }

            if (String.IsNullOrEmpty(select) && String.IsNullOrEmpty(expand))
            {
                throw Error.Argument(SRResources.SelectExpandEmptyOrNull);
            }

            IEdmEntityType entityType = context.ElementType as IEdmEntityType;
            if (entityType == null)
            {
                throw Error.Argument("context", SRResources.SelectNonEntity, context.ElementType.ToTraceString());
            }

            _entityType = entityType;

            Context = context;
            RawSelect = select;
            RawExpand = expand;
            Validator = new SelectExpandQueryValidator();
        }
Esempio n. 18
0
        /// <summary>
        /// Creates a new instance of the <see cref="SelectExpandNode"/> class describing the set of structural properties,
        /// navigation properties, and actions to select and expand for the given <paramref name="writeContext"/>.
        /// </summary>
        /// <param name="entityType">The entity type of the entry that would be written.</param>
        /// <param name="writeContext">The serializer context to be used while creating the collection.</param>
        /// <remarks>The default constructor is for unit testing only.</remarks>
        public SelectExpandNode(IEdmEntityType entityType, ODataSerializerContext writeContext)
            : this(writeContext.SelectExpandClause, entityType, writeContext.Model)
        {
            var queryOptionParser = new ODataQueryOptionParser(
                  writeContext.Model,
                  entityType,
                  writeContext.NavigationSource,
                  _extraQueryParameters);

            var selectExpandClause = queryOptionParser.ParseSelectAndExpand();
            if (selectExpandClause != null)
            {
                foreach (SelectItem selectItem in selectExpandClause.SelectedItems)
                {
                    ExpandedNavigationSelectItem expandItem = selectItem as ExpandedNavigationSelectItem;
                    if (expandItem != null)
                    {
                        ValidatePathIsSupported(expandItem.PathToNavigationProperty);
                        NavigationPropertySegment navigationSegment = (NavigationPropertySegment)expandItem.PathToNavigationProperty.LastSegment;
                        IEdmNavigationProperty navigationProperty = navigationSegment.NavigationProperty;
                        if (!ExpandedNavigationProperties.ContainsKey(navigationProperty))
                        {
                            ExpandedNavigationProperties.Add(navigationProperty, expandItem.SelectAndExpand);
                        }
                    }
                }
            }
            SelectedNavigationProperties.ExceptWith(ExpandedNavigationProperties.Keys);
        }
Esempio n. 19
0
 internal EntityPropertyMappingInfo(EntityPropertyMappingAttribute attribute, IEdmEntityType definingType, IEdmEntityType actualTypeDeclaringProperty)
 {
     this.attribute = attribute;
     this.definingType = definingType;
     this.actualPropertyType = actualTypeDeclaringProperty;
     this.isSyndicationMapping = this.attribute.TargetSyndicationItem != SyndicationItemProperty.CustomProperty;
 }
Esempio n. 20
0
 public override IEnumerable<KeyValuePair<string, object>> ResolveKeys(
     IEdmEntityType type,
     IDictionary<string, string> namedValues,
     Func<IEdmTypeReference, string, object> convertFunc)
 {
     return stringAsEnum.ResolveKeys(type, namedValues, convertFunc);
 }
        public EdmDeltaModel(IEdmModel source, IEdmEntityType entityType, IEnumerable<string> propertyNames)
        {
            _source = source;
            _entityType = new EdmEntityType(entityType.Namespace, entityType.Name);

            foreach (var property in entityType.StructuralProperties())
            {
                if (propertyNames.Contains(property.Name))
                    _entityType.AddStructuralProperty(property.Name, property.Type, property.DefaultValueString, property.ConcurrencyMode);
            }

            foreach (var property in entityType.NavigationProperties())
            {
                if (propertyNames.Contains(property.Name))
                {
                    var navInfo = new EdmNavigationPropertyInfo()
                    {
                        ContainsTarget = property.ContainsTarget,
                        DependentProperties = property.DependentProperties(),
                        PrincipalProperties = property.PrincipalProperties(),
                        Name = property.Name,
                        OnDelete = property.OnDelete,
                        Target = property.Partner != null 
                            ? property.Partner.DeclaringEntityType()
                            : property.Type.TypeKind() == EdmTypeKind.Collection
                            ? (property.Type.Definition as IEdmCollectionType).ElementType.Definition as IEdmEntityType
                            : property.Type.TypeKind() == EdmTypeKind.Entity
                            ? property.Type.Definition as IEdmEntityType
                            : null,
                        TargetMultiplicity = property.TargetMultiplicity(),
                    };
                    _entityType.AddUnidirectionalNavigation(navInfo);
                }
            }
        }
		protected override void ProcessEntityType(IEdmEntityType element)
		{
			base.ProcessEntityType(element);
			if (element.BaseEntityType() != null)
			{
				this.CheckSchemaElementReference(element.BaseEntityType());
			}
		}
		public CsdlSemanticsApplyExpression(CsdlApplyExpression expression, IEdmEntityType bindingContext, CsdlSemanticsSchema schema) : base(schema, expression)
		{
			this.appliedFunctionCache = new Cache<CsdlSemanticsApplyExpression, IEdmExpression>();
			this.argumentsCache = new Cache<CsdlSemanticsApplyExpression, IEnumerable<IEdmExpression>>();
			this.expression = expression;
			this.bindingContext = bindingContext;
			this.schema = schema;
		}
		public CsdlSemanticsLabeledExpression(string name, CsdlExpressionBase element, IEdmEntityType bindingContext, CsdlSemanticsSchema schema) : base(element)
		{
			this.expressionCache = new Cache<CsdlSemanticsLabeledExpression, IEdmExpression>();
			this.name = name;
			this.sourceElement = element;
			this.bindingContext = bindingContext;
			this.schema = schema;
		}
Esempio n. 25
0
 public ParserExtModel()
 {
     Person = (IEdmEntityType)Model.FindType("TestNS.Person");
     Pet = Model.FindType("TestNS.Pet");
     Fish = Model.FindType("TestNS.Fish");
     People = Model.FindDeclaredEntitySet("People");
     PetSet = Model.FindDeclaredEntitySet("PetSet");
 }
Esempio n. 26
0
 internal static void CheckEntityPropertyMapping(ODataVersion version, IEdmEntityType entityType, IEdmModel model)
 {
     ODataEntityPropertyMappingCache epmCache = model.GetEpmCache(entityType);
     if ((epmCache != null) && (version < epmCache.EpmTargetTree.MinimumODataProtocolVersion))
     {
         throw new ODataException(Microsoft.Data.OData.Strings.ODataVersionChecker_EpmVersionNotSupported(entityType.ODataFullName(), ODataUtils.ODataVersionToString(epmCache.EpmTargetTree.MinimumODataProtocolVersion), ODataUtils.ODataVersionToString(version)));
     }
 }
Esempio n. 27
0
		public CsdlSemanticsIfExpression(CsdlIfExpression expression, IEdmEntityType bindingContext, CsdlSemanticsSchema schema) : base(schema, expression)
		{
			this.testCache = new Cache<CsdlSemanticsIfExpression, IEdmExpression>();
			this.ifTrueCache = new Cache<CsdlSemanticsIfExpression, IEdmExpression>();
			this.ifFalseCache = new Cache<CsdlSemanticsIfExpression, IEdmExpression>();
			this.expression = expression;
			this.bindingContext = bindingContext;
		}
Esempio n. 28
0
 internal EdmDeltaType(IEdmEntityType entityType, EdmDeltaEntityKind deltaKind)
 {
     if (entityType == null)
     {
         throw Error.ArgumentNull("entityType");
     }
     _entityType = entityType;
     _deltaKind = deltaKind;
 }
Esempio n. 29
0
		public EdmEntitySet(IEdmEntityContainer container, string name, IEdmEntityType elementType) : base(name)
		{
			this.navigationPropertyMappings = new Dictionary<IEdmNavigationProperty, IEdmEntitySet>();
			this.navigationTargetsCache = new Cache<EdmEntitySet, IEnumerable<IEdmNavigationTargetMapping>>();
			EdmUtil.CheckArgumentNull<IEdmEntityContainer>(container, "container");
			EdmUtil.CheckArgumentNull<IEdmEntityType>(elementType, "elementType");
			this.container = container;
			this.elementType = elementType;
		}
 private static IEnumerable<IEdmEntityType> GetTypeHierarchy(IEdmEntityType entityType)
 {
     IEdmEntityType current = entityType;
     while (current != null)
     {
         yield return current;
         current = current.BaseEntityType();
     }
 }
Esempio n. 31
0
        private void PairUpNavigationPropertyWithResourceAssociationSet(MetadataProviderEdmEntityContainer entityContainer, ResourceAssociationSet resourceAssociationSet, ResourceAssociationType resourceAssociationType, ResourceType resourceType, ResourceProperty navigationProperty)
        {
            string            associationEndName;
            EdmMultiplicity   multiplicity;
            EdmOnDeleteAction deleteBehavior;
            string            str3;
            EdmMultiplicity   multiplicity2;
            EdmOnDeleteAction none;
            string            typeNamespace;
            bool   flag          = (resourceAssociationSet.End1.ResourceProperty != null) && (resourceAssociationSet.End2.ResourceProperty != null);
            string entitySetName = MetadataProviderUtils.GetEntitySetName(resourceAssociationSet.End1.ResourceSet);
            string name          = MetadataProviderUtils.GetEntitySetName(resourceAssociationSet.End2.ResourceSet);
            bool   isPrinciple   = false;
            List <IEdmStructuralProperty> dependentProperties = null;

            if (resourceAssociationType != null)
            {
                associationEndName = resourceAssociationType.End1.Name;
                deleteBehavior     = resourceAssociationType.End1.DeleteBehavior;
                multiplicity2      = MetadataProviderUtils.ConvertMultiplicity(resourceAssociationType.End1.Multiplicity);
                str3         = resourceAssociationType.End2.Name;
                none         = resourceAssociationType.End2.DeleteBehavior;
                multiplicity = MetadataProviderUtils.ConvertMultiplicity(resourceAssociationType.End2.Multiplicity);
                ResourceReferentialConstraint referentialConstraint = resourceAssociationType.ReferentialConstraint;
                if (referentialConstraint != null)
                {
                    isPrinciple = object.ReferenceEquals(resourceAssociationType.End1, referentialConstraint.PrincipalEnd);
                    IEdmEntityType type = isPrinciple ? ((IEdmEntityType)this.EnsureSchemaType(resourceAssociationSet.End2.ResourceType)) : ((IEdmEntityType)this.EnsureSchemaType(resourceAssociationSet.End1.ResourceType));
                    dependentProperties = new List <IEdmStructuralProperty>();
                    foreach (ResourceProperty property in referentialConstraint.DependentProperties)
                    {
                        IEdmProperty property2 = type.FindProperty(property.Name);
                        dependentProperties.Add((IEdmStructuralProperty)property2);
                    }
                }
            }
            else
            {
                if (!flag)
                {
                    if (resourceAssociationSet.End1.ResourceProperty != null)
                    {
                        associationEndName = resourceType.Name;
                        str3 = navigationProperty.Name;
                    }
                    else
                    {
                        associationEndName = navigationProperty.Name;
                        str3 = resourceType.Name;
                    }
                }
                else
                {
                    associationEndName = MetadataProviderUtils.GetAssociationEndName(resourceAssociationSet.End1.ResourceType, resourceAssociationSet.End1.ResourceProperty);
                    str3 = MetadataProviderUtils.GetAssociationEndName(resourceAssociationSet.End2.ResourceType, resourceAssociationSet.End2.ResourceProperty);
                }
                multiplicity   = MetadataProviderUtils.GetMultiplicity(resourceAssociationSet.End1.ResourceProperty);
                deleteBehavior = EdmOnDeleteAction.None;
                multiplicity2  = MetadataProviderUtils.GetMultiplicity(resourceAssociationSet.End2.ResourceProperty);
                none           = EdmOnDeleteAction.None;
            }
            string associationName = (resourceAssociationType == null) ? MetadataProviderUtils.GetAssociationName(resourceAssociationSet) : resourceAssociationType.Name;

            if ((resourceAssociationType == null) || (resourceAssociationType.NamespaceName == null))
            {
                ResourceAssociationSetEnd end = (resourceAssociationSet.End1.ResourceProperty != null) ? resourceAssociationSet.End1 : resourceAssociationSet.End2;
                typeNamespace = this.GetTypeNamespace(end.ResourceType);
            }
            else
            {
                typeNamespace = resourceAssociationType.NamespaceName;
            }
            ResourceProperty resourceProperty = resourceAssociationSet.End1.ResourceProperty;
            ResourceProperty property4        = resourceAssociationSet.End2.ResourceProperty;
            MetadataProviderEdmNavigationProperty partnerProperty = null;
            MetadataProviderEdmNavigationProperty property6       = null;

            if (resourceProperty != null)
            {
                IEdmEntityType type2 = (IEdmEntityType)this.EnsureSchemaType(resourceAssociationSet.End1.ResourceType);
                partnerProperty = (MetadataProviderEdmNavigationProperty)type2.FindProperty(resourceProperty.Name);
            }
            if (property4 != null)
            {
                IEdmEntityType type3 = (IEdmEntityType)this.EnsureSchemaType(resourceAssociationSet.End2.ResourceType);
                property6 = (MetadataProviderEdmNavigationProperty)type3.FindProperty(property4.Name);
            }
            IEdmNavigationProperty property7 = (partnerProperty != null) ? ((IEdmNavigationProperty)partnerProperty) : ((IEdmNavigationProperty) new MetadataProviderEdmSilentNavigationProperty(property6, deleteBehavior, multiplicity, associationEndName));
            IEdmNavigationProperty partner   = (property6 != null) ? ((IEdmNavigationProperty)property6) : ((IEdmNavigationProperty) new MetadataProviderEdmSilentNavigationProperty(partnerProperty, none, multiplicity2, str3));

            MetadataProviderUtils.FixUpNavigationPropertyWithAssociationSetData(property7, partner, isPrinciple, dependentProperties, deleteBehavior, multiplicity);
            MetadataProviderUtils.FixUpNavigationPropertyWithAssociationSetData(partner, property7, !isPrinciple, dependentProperties, none, multiplicity2);
            EdmEntitySet entitySet = (EdmEntitySet)entityContainer.FindEntitySet(entitySetName);
            EdmEntitySet target    = (EdmEntitySet)entityContainer.FindEntitySet(name);

            if (partnerProperty != null)
            {
                entitySet.AddNavigationTarget(partnerProperty, target);
                this.SetAssociationSetName(entitySet, partnerProperty, resourceAssociationSet.Name);
                this.SetAssociationSetAnnotations(entitySet, partnerProperty, MetadataProviderUtils.ConvertCustomAnnotations(this, resourceAssociationSet.CustomAnnotations), MetadataProviderUtils.ConvertCustomAnnotations(this, resourceAssociationSet.End1.CustomAnnotations), MetadataProviderUtils.ConvertCustomAnnotations(this, resourceAssociationSet.End2.CustomAnnotations));
            }
            if (property6 != null)
            {
                target.AddNavigationTarget(property6, entitySet);
                this.SetAssociationSetName(target, property6, resourceAssociationSet.Name);
                if (partnerProperty == null)
                {
                    this.SetAssociationSetAnnotations(entitySet, property6, MetadataProviderUtils.ConvertCustomAnnotations(this, resourceAssociationSet.CustomAnnotations), MetadataProviderUtils.ConvertCustomAnnotations(this, resourceAssociationSet.End1.CustomAnnotations), MetadataProviderUtils.ConvertCustomAnnotations(this, resourceAssociationSet.End2.CustomAnnotations));
                }
            }
            this.SetAssociationNamespace(property7, typeNamespace);
            this.SetAssociationName(property7, associationName);
            this.SetAssociationEndName(property7, associationEndName);
            this.SetAssociationNamespace(partner, typeNamespace);
            this.SetAssociationName(partner, associationName);
            this.SetAssociationEndName(partner, str3);
            if (resourceAssociationType != null)
            {
                this.SetAssociationAnnotations(property7, MetadataProviderUtils.ConvertCustomAnnotations(this, resourceAssociationType.CustomAnnotations), MetadataProviderUtils.ConvertCustomAnnotations(this, (property7.GetPrimary() == property7) ? resourceAssociationType.End1.CustomAnnotations : resourceAssociationType.End2.CustomAnnotations), MetadataProviderUtils.ConvertCustomAnnotations(this, (property7.GetPrimary() == property7) ? resourceAssociationType.End2.CustomAnnotations : resourceAssociationType.End1.CustomAnnotations), MetadataProviderUtils.ConvertCustomAnnotations(this, (resourceAssociationType.ReferentialConstraint != null) ? resourceAssociationType.ReferentialConstraint.CustomAnnotations : null));
            }
        }
Esempio n. 32
0
 /// <summary>
 /// Asynchronously creates an <see cref="ODataDeltaReader" /> to read a resource set.
 /// </summary>
 /// <param name="entitySet">The entity set we are going to read entities for.</param>
 /// <param name="expectedBaseEntityType">The expected base entity type for the entries in the delta response.</param>
 /// <returns>Task which when completed returns the newly created <see cref="ODataDeltaReader"/>.</returns>
 internal virtual Task <ODataDeltaReader> CreateDeltaReaderAsync(IEdmEntitySetBase entitySet, IEdmEntityType expectedBaseEntityType)
 {
     throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.ResourceSet);
 }
Esempio n. 33
0
 public EntityTypeFrame(IEdmEntityType entityType, bool isCollection)
 {
     EntityType   = entityType;
     IsCollection = isCollection;
 }
Esempio n. 34
0
        /// <summary>
        /// Creates a new ODataEntry from the specified entity set, instance, and type.
        /// </summary>
        /// <param name="entitySet">Entity set for the new entry.</param>
        /// <param name="value">Entity instance for the new entry.</param>
        /// <param name="entityType">Entity type for the new entry.</param>
        /// <returns>New ODataEntry with the specified entity set and type, property values from the specified instance.</returns>
        internal static ODataEntry CreateODataEntry(IEdmEntitySet entitySet, IEdmStructuredValue value, IEdmEntityType entityType)
        {
            var entry = new ODataEntry();

            entry.SetAnnotation(new ODataTypeAnnotation(entitySet, entityType));
            entry.Properties = value.PropertyValues.Select(p =>
            {
                object propertyValue;
                if (p.Value.ValueKind == EdmValueKind.Null)
                {
                    propertyValue = null;
                }
                else if (p.Value is IEdmPrimitiveValue)
                {
                    propertyValue = ((IEdmPrimitiveValue)p.Value).ToClrValue();
                }
                else
                {
                    Assert.True(false, "Test only currently supports creating ODataEntry from IEdmPrimitiveValue instances.");
                    return(null);
                }

                return(new ODataProperty()
                {
                    Name = p.Name, Value = propertyValue
                });
            });

            return(entry);
        }
Esempio n. 35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EdmEntityType"/> class.
 /// </summary>
 /// <param name="namespaceName">Namespace the entity belongs to.</param>
 /// <param name="name">Name of the entity.</param>
 /// <param name="baseType">The base type of this entity type.</param>
 public EdmEntityType(string namespaceName, string name, IEdmEntityType baseType)
     : this(namespaceName, name, baseType, false, false)
 {
 }
 public CsdlSemanticsFunctionReferenceExpression(CsdlFunctionReferenceExpression expression, IEdmEntityType bindingContext, CsdlSemanticsSchema schema) : base(schema, expression)
 {
     this.referencedCache = new Cache <CsdlSemanticsFunctionReferenceExpression, IEdmFunction>();
     this.expression      = expression;
     this.bindingContext  = bindingContext;
 }
Esempio n. 37
0
        internal static IEdmExpression WrapExpression(CsdlExpressionBase expression, IEdmEntityType bindingContext, CsdlSemanticsSchema schema)
        {
            if (expression != null)
            {
                switch (expression.ExpressionKind)
                {
                case EdmExpressionKind.Cast:
                    return(new CsdlSemanticsCastExpression((CsdlCastExpression)expression, bindingContext, schema));

                case EdmExpressionKind.BinaryConstant:
                    return(new CsdlSemanticsBinaryConstantExpression((CsdlConstantExpression)expression, schema));

                case EdmExpressionKind.BooleanConstant:
                    return(new CsdlSemanticsBooleanConstantExpression((CsdlConstantExpression)expression, schema));

                case EdmExpressionKind.Collection:
                    return(new CsdlSemanticsCollectionExpression((CsdlCollectionExpression)expression, bindingContext, schema));

                case EdmExpressionKind.DateTimeOffsetConstant:
                    return(new CsdlSemanticsDateTimeOffsetConstantExpression((CsdlConstantExpression)expression, schema));

                case EdmExpressionKind.DecimalConstant:
                    return(new CsdlSemanticsDecimalConstantExpression((CsdlConstantExpression)expression, schema));

                case EdmExpressionKind.EnumMember:
                    return(new CsdlSemanticsEnumMemberExpression((CsdlEnumMemberExpression)expression, bindingContext, schema));

                case EdmExpressionKind.FloatingConstant:
                    return(new CsdlSemanticsFloatingConstantExpression((CsdlConstantExpression)expression, schema));

                case EdmExpressionKind.Null:
                    return(new CsdlSemanticsNullExpression((CsdlConstantExpression)expression, schema));

                case EdmExpressionKind.FunctionApplication:
                    return(new CsdlSemanticsApplyExpression((CsdlApplyExpression)expression, bindingContext, schema));

                case EdmExpressionKind.GuidConstant:
                    return(new CsdlSemanticsGuidConstantExpression((CsdlConstantExpression)expression, schema));

                case EdmExpressionKind.If:
                    return(new CsdlSemanticsIfExpression((CsdlIfExpression)expression, bindingContext, schema));

                case EdmExpressionKind.IntegerConstant:
                    return(new CsdlSemanticsIntConstantExpression((CsdlConstantExpression)expression, schema));

                case EdmExpressionKind.IsType:
                    return(new CsdlSemanticsIsTypeExpression((CsdlIsTypeExpression)expression, bindingContext, schema));

                case EdmExpressionKind.LabeledExpressionReference:
                    return(new CsdlSemanticsLabeledExpressionReferenceExpression((CsdlLabeledExpressionReferenceExpression)expression, bindingContext, schema));

                case EdmExpressionKind.Labeled:
                    return(schema.WrapLabeledElement((CsdlLabeledExpression)expression, bindingContext));

                case EdmExpressionKind.Path:
                    return(new CsdlSemanticsPathExpression((CsdlPathExpression)expression, bindingContext, schema));

                case EdmExpressionKind.PropertyPath:
                    return(new CsdlSemanticsPropertyPathExpression((CsdlPropertyPathExpression)expression, bindingContext, schema));

                case EdmExpressionKind.NavigationPropertyPath:
                    return(new CsdlSemanticsNavigationPropertyPathExpression((CsdlNavigationPropertyPathExpression)expression, bindingContext, schema));

                case EdmExpressionKind.Record:
                    return(new CsdlSemanticsRecordExpression((CsdlRecordExpression)expression, bindingContext, schema));

                case EdmExpressionKind.StringConstant:
                    return(new CsdlSemanticsStringConstantExpression((CsdlConstantExpression)expression, schema));

                case EdmExpressionKind.DurationConstant:
                    return(new CsdlSemanticsDurationConstantExpression((CsdlConstantExpression)expression, schema));

                case EdmExpressionKind.DateConstant:
                    return(new CsdlSemanticsDateConstantExpression((CsdlConstantExpression)expression, schema));

                case EdmExpressionKind.TimeOfDayConstant:
                    return(new CsdlSemanticsTimeOfDayConstantExpression((CsdlConstantExpression)expression, schema));

                case EdmExpressionKind.AnnotationPath:
                    return(new CsdlSemanticsAnnotationPathExpression((CsdlAnnotationPathExpression)expression, bindingContext, schema));
                }
            }

            return(null);
        }
Esempio n. 38
0
 public override IEnumerable <KeyValuePair <string, object> > ResolveKeys(IEdmEntityType type, IList <string> positionalValues, Func <IEdmTypeReference, string, object> convertFunc)
 {
     return(this.stringAsEnum.ResolveKeys(type, positionalValues, convertFunc));
 }
Esempio n. 39
0
        /// <summary>
        /// Resolves the specified entity model schema type and returns the Edm model type for it.
        /// </summary>
        /// <param name="model">The model to get the type from.</param>
        /// <param name="schemaType">The entity model schema type to resolve.</param>
        /// <returns>The resolved type for the specified <paramref name="schemaType"/>.</returns>
        public static IEdmTypeReference ResolveEntityModelSchemaType(IEdmModel model, DataType schemaType)
        {
            if (schemaType == null)
            {
                return(null);
            }

            PrimitiveDataType primitiveDataType = schemaType as PrimitiveDataType;

            if (primitiveDataType != null)
            {
                return(GetPrimitiveTypeReference(primitiveDataType));
            }

            if (model == null)
            {
                return(null);
            }

            EntityDataType entityDataType = schemaType as EntityDataType;

            if (entityDataType != null)
            {
                IEdmNamedElement edmType = model.FindType(entityDataType.Definition.FullName);
                ExceptionUtilities.Assert(
                    edmType != null,
                    "The expected entity type '{0}' was not found in the entity model for this test.",
                    entityDataType.Definition.FullName);

                IEdmEntityType entityType = edmType as IEdmEntityType;
                ExceptionUtilities.Assert(
                    entityType != null,
                    "The expected entity type '{0}' is not defined as entity type in the test's metadata.",
                    entityDataType.Definition.FullName);
                return(entityType.ToTypeReference());
            }

            ComplexDataType complexDataType = schemaType as ComplexDataType;

            if (complexDataType != null)
            {
                return(GetComplexType(model, complexDataType));
            }

            CollectionDataType collectionDataType = schemaType as CollectionDataType;

            if (collectionDataType != null)
            {
                DataType          collectionElementType = collectionDataType.ElementDataType;
                PrimitiveDataType primitiveElementType  = collectionElementType as PrimitiveDataType;
                if (primitiveElementType != null)
                {
                    IEdmPrimitiveTypeReference primitiveElementTypeReference = GetPrimitiveTypeReference(primitiveElementType);
                    return(primitiveElementTypeReference.ToCollectionTypeReference());
                }

                ComplexDataType complexElementType = collectionElementType as ComplexDataType;
                if (complexElementType != null)
                {
                    IEdmComplexTypeReference complexElementTypeReference = GetComplexType(model, complexElementType);
                    return(complexElementTypeReference.ToCollectionTypeReference());
                }

                EntityDataType entityElementType = collectionElementType as EntityDataType;
                if (entityElementType != null)
                {
                    IEdmEntityTypeReference entityElementTypeReference = GetEntityType(model, entityElementType);
                    return(entityElementTypeReference.ToCollectionTypeReference());
                }

                throw new NotSupportedException("Collection types only support primitive, complex, and entity element types.");
            }

            StreamDataType streamType = schemaType as StreamDataType;

            if (streamType != null)
            {
                Type systemType = streamType.GetFacet <PrimitiveClrTypeFacet>().Value;
                ExceptionUtilities.Assert(systemType == typeof(Stream), "Expected the system type 'System.IO.Stream' for a stream reference property.");
                return(MetadataUtils.GetPrimitiveTypeReference(systemType));
            }

            throw new NotImplementedException("Unrecognized schema type " + schemaType.GetType().Name + ".");
        }
Esempio n. 40
0
        static ExtensionTestBase()
        {
            var model = new EdmModel();

            Model = model;

            var person   = new EdmEntityType("TestNS", "Person");
            var personId = person.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32);

            PersonNameProp = person.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            PersonPen      = person.AddStructuralProperty("pen", EdmPrimitiveTypeKind.Binary);
            person.AddKeys(personId);
            PersonType = person;

            var address = new EdmComplexType("TestNS", "Address");

            AddrType        = address;
            ZipCodeProperty = address.AddStructuralProperty("ZipCode", EdmPrimitiveTypeKind.String);
            AddrProperty    = person.AddStructuralProperty("Addr", new EdmComplexTypeReference(address, false));

            var pencil   = new EdmEntityType("TestNS", "Pencil");
            var pencilId = pencil.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32);

            PencilId = pencilId;
            var pid = pencil.AddStructuralProperty("Pid", EdmPrimitiveTypeKind.Int32);

            pencil.AddKeys(pencilId);

            var starPencil = new EdmEntityType("TestNS", "StarPencil", pencil);

            model.AddElement(starPencil);
            var starPencilUpper = new EdmEntityType("TestNS", "STARPENCIL");

            model.AddElement(starPencilUpper);
            StarPencil = starPencil;

            var navInfo = new EdmNavigationPropertyInfo()
            {
                Name               = "Pen",
                ContainsTarget     = false,
                Target             = pencil,
                TargetMultiplicity = EdmMultiplicity.One
            };

            PersonNavPen = person.AddUnidirectionalNavigation(navInfo);

            var navInfo2 = new EdmNavigationPropertyInfo()
            {
                Name               = "Pen2",
                ContainsTarget     = true,
                Target             = pencil,
                TargetMultiplicity = EdmMultiplicity.One
            };

            PersonNavPen2 = person.AddUnidirectionalNavigation(navInfo2);

            var container = new EdmEntityContainer("Default", "Con1");
            var personSet = container.AddEntitySet("People", person);

            PencilSet  = container.AddEntitySet("PencilSet", pencil);
            Boss       = container.AddSingleton("Boss", person);
            Bajie      = container.AddSingleton("Bajie", pencil);
            BajieUpper = container.AddSingleton("BAJIE", pencil);
            personSet.AddNavigationTarget(PersonNavPen, PencilSet);
            PeopleSet = personSet;

            var pencilSetUpper = container.AddEntitySet("PENCILSET", pencil);

            PencilSetUpper = pencilSetUpper;

            var         pencilRef   = new EdmEntityTypeReference(pencil, false);
            EdmFunction findPencil1 = new EdmFunction("TestNS", "FindPencil", pencilRef, true, null, false);

            findPencil1.AddParameter("qid", new EdmEntityTypeReference(PersonType, false));
            model.AddElement(findPencil1);
            FindPencil1P = findPencil1;

            EdmFunction findPencil = new EdmFunction("TestNS", "FindPencil", pencilRef, true, null, false);

            findPencil.AddParameter("qid", new EdmEntityTypeReference(PersonType, false));
            findPencil.AddParameter("pid", EdmCoreModel.Instance.GetInt32(false));
            model.AddElement(findPencil);
            FindPencil2P = findPencil;

            EdmFunction findPencils = new EdmFunction("TestNS", "FindPencils", new EdmCollectionTypeReference(new EdmCollectionType(pencilRef)), true, null, false);

            findPencils.AddParameter("qid", new EdmEntityTypeReference(PersonType, false));
            model.AddElement(findPencils);
            FindPencils = findPencils;

            EdmFunction findPencilsCon = new EdmFunction("TestNS", "FindPencilsCon", new EdmCollectionTypeReference(new EdmCollectionType(pencilRef)), true, null, false);

            FindPencilsCon = findPencilsCon;
            findPencilsCon.AddParameter("qid", new EdmEntityTypeReference(PersonType, false));
            model.AddElement(findPencilsCon);

            EdmFunction findPencilsConUpper = new EdmFunction("TestNS", "FindPencilsCON", new EdmCollectionTypeReference(new EdmCollectionType(pencilRef)), true, null, false);

            FindPencilsConUpper = findPencilsConUpper;
            findPencilsConUpper.AddParameter("qid", new EdmEntityTypeReference(PersonType, false));
            model.AddElement(findPencilsConUpper);

            EdmFunction findPencilsConNT = new EdmFunction("TestNT", "FindPencilsCon", new EdmCollectionTypeReference(new EdmCollectionType(pencilRef)), true, null, false);

            FindPencilsConNT = findPencilsConNT;
            findPencilsConNT.AddParameter("qid", new EdmEntityTypeReference(PersonType, false));
            model.AddElement(findPencilsConNT);

            ChangeZip = new EdmAction("TestNS", "ChangeZip", null, true, null);
            ChangeZip.AddParameter("address", new EdmComplexTypeReference(address, false));
            ChangeZip.AddParameter("newZip", EdmCoreModel.Instance.GetString(false));
            model.AddElement(ChangeZip);

            GetZip = new EdmFunction("TestNS", "GetZip", EdmCoreModel.Instance.GetString(false), true, null, true);
            GetZip.AddParameter("address", new EdmComplexTypeReference(address, false));
            model.AddElement(GetZip);

            model.AddElement(person);
            model.AddElement(address);
            model.AddElement(pencil);
            model.AddElement(container);

            var feed = new EdmAction("TestNS", "Feed", null);

            Feed = feed;
            feed.AddParameter("pid", EdmCoreModel.Instance.GetInt32(false));

            FeedImport         = container.AddActionImport("Feed", feed);
            FeedConImport      = container.AddActionImport("FeedCon", feed);
            FeedConUpperImport = container.AddActionImport("FeedCON", feed);

            var pet = new EdmEntityType("TestNS", "Pet");

            PetType = pet;
            model.AddElement(pet);
            var key1 = pet.AddStructuralProperty("key1", EdmCoreModel.Instance.GetInt32(false));
            var key2 = pet.AddStructuralProperty("key2", EdmCoreModel.Instance.GetString(false));

            pet.AddKeys(key1, key2);
            var petSet = container.AddEntitySet("PetSet", pet);

            var petCon = new EdmEntityType("TestNS", "PetCon");

            model.AddElement(petCon);
            var key1Con = pet.AddStructuralProperty("key", EdmCoreModel.Instance.GetInt32(false));
            var key2Con = pet.AddStructuralProperty("KEY", EdmCoreModel.Instance.GetString(false));

            petCon.AddKeys(key1Con, key2Con);
            var petSetCon = container.AddEntitySet("PetSetCon", petCon);

            EdmEnumType colorType = new EdmEnumType("TestNS", "Color");

            Color = colorType;
            colorType.AddMember("Red", new EdmIntegerConstant(1L));
            colorType.AddMember("Blue", new EdmIntegerConstant(2L));
            model.AddElement(colorType);
            var moonType = new EdmEntityType("TestNS", "Moon");

            MoonType = moonType;
            var color = moonType.AddStructuralProperty("color", new EdmEnumTypeReference(colorType, false));

            moonType.AddKeys(color);
            model.AddElement(moonType);
            container.AddEntitySet("MoonSet", moonType);

            var moonType2 = new EdmEntityType("TestNS", "Moon2");

            MoonType2 = moonType2;
            var color2 = moonType2.AddStructuralProperty("color", new EdmEnumTypeReference(colorType, false));
            var id     = moonType2.AddStructuralProperty("id", EdmCoreModel.Instance.GetInt32(false));

            moonType2.AddKeys(color2, id);
            model.AddElement(moonType2);
            container.AddEntitySet("MoonSet2", moonType2);

            EdmFunction findPencilCon = new EdmFunction("TestNS", "FindPencilCon", pencilRef, true, null, false);

            FindPencilCon = findPencilCon;
            findPencilCon.AddParameter("qid", new EdmEntityTypeReference(PersonType, false));
            findPencilCon.AddParameter("pid", EdmCoreModel.Instance.GetInt32(false));
            findPencilCon.AddParameter("PID", EdmCoreModel.Instance.GetInt32(false));
            model.AddElement(findPencilCon);

            EdmFunction getColorCmyk = new EdmFunction("TestNS", "GetColorCmyk", EdmCoreModel.Instance.GetString(false));

            getColorCmyk.AddParameter("co", new EdmEnumTypeReference(colorType, true));
            GetColorCmyk = getColorCmyk;
            model.AddElement(getColorCmyk);
            GetColorCmykImport = container.AddFunctionImport("GetColorCmykImport", getColorCmyk);

            EdmFunction getMixedColor = new EdmFunction("TestNS", "GetMixedColor", EdmCoreModel.Instance.GetString(false));

            getMixedColor.AddParameter("co", new EdmCollectionTypeReference(new EdmCollectionType(new EdmEnumTypeReference(colorType, true))));
            model.AddElement(getMixedColor);
            GetMixedColor = container.AddFunctionImport("GetMixedColorImport", getMixedColor);
        }
 /// <summary>
 /// Finds operations that can be invoked on the feed. This would include all the operations that are bound to the given
 /// type and its base types.
 /// </summary>
 /// <param name="entityType">The EDM entity type.</param>
 /// <returns>A collection of operations bound to the feed.</returns>
 public virtual IEnumerable <IEdmOperation> FindOperationsBoundToCollection(IEdmEntityType entityType)
 {
     return(GetTypeHierarchy(entityType).SelectMany(FindDeclaredOperationsBoundToCollection));
 }
Esempio n. 42
0
        internal static IEnumerable <IEdmFunctionImport> GetAvailableProcedures(this IEdmModel model, IEdmEntityType entityType)
        {
            if (model == null)
            {
                throw Error.ArgumentNull("model");
            }

            if (entityType == null)
            {
                throw Error.ArgumentNull("entityType");
            }

            BindableProcedureFinder annotation = model.GetAnnotationValue <BindableProcedureFinder>(model);

            if (annotation == null)
            {
                return(Enumerable.Empty <IEdmFunctionImport>());
            }
            else
            {
                return(annotation.FindProcedures(entityType));
            }
        }
Esempio n. 43
0
 internal virtual Task <ODataReader> CreateFeedReaderAsync(IEdmEntityType expectedBaseEntityType)
 {
     throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Feed);
 }
Esempio n. 44
0
        private IEnumerable <Tuple <ODataItem, ODataDeltaReaderState, ODataReaderState> > ReadItem(string payload, IEdmModel model = null, IEdmNavigationSource navigationSource = null, IEdmEntityType entityType = null, bool enableReadingODataAnnotationWithoutPrefix = false)
        {
            var settings = new ODataMessageReaderSettings
            {
                ShouldIncludeAnnotation = s => true,
            };

            var messageInfo = new ODataMessageInfo
            {
                IsResponse = true,
                MediaType  = new ODataMediaType("application", "json"),
                IsAsync    = false,
                Model      = model ?? new EdmModel(),
                Container  = ContainerBuilderHelper.BuildContainer(null)
            };

            using (var inputContext = new ODataJsonLightInputContext(
                       new StringReader(payload), messageInfo, settings))
            {
                inputContext.Container.GetRequiredService <ODataSimplifiedOptions>()
                .EnableReadingODataAnnotationWithoutPrefix = enableReadingODataAnnotationWithoutPrefix;
                var jsonLightReader = new ODataJsonLightDeltaReader(inputContext, navigationSource, entityType);
                while (jsonLightReader.Read())
                {
                    yield return(new Tuple <ODataItem, ODataDeltaReaderState, ODataReaderState>(jsonLightReader.Item, jsonLightReader.State, jsonLightReader.SubState));
                }
            }
        }
Esempio n. 45
0
 public CsdlSemanticsAssertTypeExpression(CsdlAssertTypeExpression expression, IEdmEntityType bindingContext, CsdlSemanticsSchema schema)
     : base(schema, expression)
 {
     this.expression     = expression;
     this.bindingContext = bindingContext;
 }
Esempio n. 46
0
        /// <summary>
        /// Determine if the query containes auto select expand property.
        /// </summary>
        /// <param name="responseValue">The response value.</param>
        /// <param name="singleResultCollection">The content as SingleResult.Queryable.</param>
        /// <param name="actionDescriptor">The action context, i.e. action and controller name.</param>
        /// <param name="request">The OData path.</param>
        /// <returns></returns>
        private static bool ContainsAutoSelectExpandProperty(
            object responseValue,
            IQueryable singleResultCollection,
            ControllerActionDescriptor actionDescriptor,
            HttpRequest request)
        {
            Type elementClrType = GetElementType(responseValue, singleResultCollection, actionDescriptor);

            IEdmModel model = GetModel(elementClrType, request, actionDescriptor);

            if (model == null)
            {
                throw Error.InvalidOperation(SRResources.QueryGetModelMustNotReturnNull);
            }
            ODataPath          path           = request.ODataFeature().Path;
            IEdmType           edmType        = model.GetTypeMappingCache().GetEdmType(elementClrType, model)?.Definition;
            IEdmEntityType     baseEntityType = edmType as IEdmEntityType;
            IEdmStructuredType structuredType = edmType as IEdmStructuredType;
            IEdmProperty       property       = null;

            if (path != null)
            {
                string name;
                EdmHelpers.GetPropertyAndStructuredTypeFromPath(path, out property, out structuredType, out name);
            }

            if (baseEntityType != null)
            {
                List <IEdmEntityType> entityTypes = new List <IEdmEntityType>();
                entityTypes.Add(baseEntityType);
                entityTypes.AddRange(EdmHelpers.GetAllDerivedEntityTypes(baseEntityType, model));
                foreach (var entityType in entityTypes)
                {
                    IEnumerable <IEdmNavigationProperty> navigationProperties = entityType == baseEntityType
                        ? entityType.NavigationProperties()
                        : entityType.DeclaredNavigationProperties();

                    if (navigationProperties != null)
                    {
                        if (navigationProperties.Any(
                                navigationProperty =>
                                EdmHelpers.IsAutoExpand(navigationProperty, property, entityType, model)))
                        {
                            return(true);
                        }
                    }

                    IEnumerable <IEdmStructuralProperty> properties = entityType == baseEntityType
                        ? entityType.StructuralProperties()
                        : entityType.DeclaredStructuralProperties();

                    if (properties != null)
                    {
                        foreach (var edmProperty in properties)
                        {
                            if (EdmHelpers.IsAutoSelect(edmProperty, property, entityType, model))
                            {
                                return(true);
                            }
                        }
                    }
                }
            }
            else if (structuredType != null)
            {
                IEnumerable <IEdmStructuralProperty> properties = structuredType.StructuralProperties();
                if (properties != null)
                {
                    foreach (var edmProperty in properties)
                    {
                        if (EdmHelpers.IsAutoSelect(edmProperty, property, structuredType, model))
                        {
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
Esempio n. 47
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EdmEntityType"/> class.
 /// </summary>
 /// <param name="namespaceName">Namespace the entity belongs to.</param>
 /// <param name="name">Name of the entity.</param>
 /// <param name="baseType">The base type of this entity type.</param>
 /// <param name="isAbstract">Denotes an entity that cannot be instantiated.</param>
 /// <param name="isOpen">Denotes if the type is open.</param>
 public EdmEntityType(string namespaceName, string name, IEdmEntityType baseType, bool isAbstract, bool isOpen)
     : this(namespaceName, name, baseType, isAbstract, isOpen, false)
 {
 }
Esempio n. 48
0
 internal virtual ODataReader CreateEntryReader(IEdmEntityType expectedEntityType)
 {
     throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Entry);
 }
        /// <inheritdoc/>
        public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup <string, HttpActionDescriptor> actionMap)
        {
            if (odataPath == null)
            {
                throw Error.ArgumentNull("odataPath");
            }

            if (controllerContext == null)
            {
                throw Error.ArgumentNull("controllerContext");
            }

            if (actionMap == null)
            {
                throw Error.ArgumentNull("actionMap");
            }

            HttpMethod method           = controllerContext.Request.Method;
            string     actionNamePrefix = GetActionMethodPrefix(method);

            if (actionNamePrefix == null)
            {
                return(null);
            }

            if (odataPath.PathTemplate == "~/entityset/key/navigation" ||
                odataPath.PathTemplate == "~/entityset/key/navigation/$count" ||
                odataPath.PathTemplate == "~/entityset/key/cast/navigation" ||
                odataPath.PathTemplate == "~/entityset/key/cast/navigation/$count" ||
                odataPath.PathTemplate == "~/singleton/navigation" ||
                odataPath.PathTemplate == "~/singleton/navigation/$count" ||
                odataPath.PathTemplate == "~/singleton/cast/navigation" ||
                odataPath.PathTemplate == "~/singleton/cast/navigation/$count")
            {
                NavigationPathSegment navigationSegment =
                    (odataPath.Segments.Last() as NavigationPathSegment) ??
                    odataPath.Segments[odataPath.Segments.Count - 2] as NavigationPathSegment;
                IEdmNavigationProperty navigationProperty = navigationSegment.NavigationProperty;
                IEdmEntityType         declaringType      = navigationProperty.DeclaringType as IEdmEntityType;

                // It is not valid to *Post* to any non-collection valued navigation property.
                if (navigationProperty.TargetMultiplicity() != EdmMultiplicity.Many &&
                    method == HttpMethod.Post)
                {
                    return(null);
                }

                // It is not valid to *Put/Patch" to any collection-valued navigation property.
                if (navigationProperty.TargetMultiplicity() == EdmMultiplicity.Many &&
                    (method == HttpMethod.Put || "PATCH" == method.Method.ToUpperInvariant()))
                {
                    return(null);
                }

                // *Get* is the only supported method for $count request.
                if (odataPath.Segments.Last() is CountPathSegment && method != HttpMethod.Get)
                {
                    return(null);
                }

                if (declaringType != null)
                {
                    // e.g. Try GetNavigationPropertyFromDeclaringType first, then fallback on GetNavigationProperty action name
                    string actionName = actionMap.FindMatchingAction(
                        actionNamePrefix + navigationProperty.Name + "From" + declaringType.Name,
                        actionNamePrefix + navigationProperty.Name);

                    if (actionName != null)
                    {
                        if (odataPath.PathTemplate.StartsWith("~/entityset/key", StringComparison.Ordinal))
                        {
                            KeyValuePathSegment keyValueSegment = odataPath.Segments[1] as KeyValuePathSegment;
                            controllerContext.RouteData.Values[ODataRouteConstants.Key] = keyValueSegment.Value;
                        }

                        return(actionName);
                    }
                }
            }

            return(null);
        }
        private static OpenApiSchema CreateStructuredTypeSchema(this ODataContext context, IEdmStructuredType structuredType, bool processBase, bool processExample)
        {
            Debug.Assert(context != null);
            Debug.Assert(structuredType != null);

            if (processBase && structuredType.BaseType != null)
            {
                // A structured type with a base type is represented as a Schema Object
                // that contains the keyword allOf whose value is an array with two items:
                return(new OpenApiSchema
                {
                    AllOf = new List <OpenApiSchema>
                    {
                        // 1. a JSON Reference to the Schema Object of the base type
                        new OpenApiSchema
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.Schema,
                                Id = structuredType.BaseType.FullTypeName()
                            }
                        },

                        // 2. a Schema Object describing the derived type
                        context.CreateStructuredTypeSchema(structuredType, false, false)
                    },

                    AnyOf = null,
                    OneOf = null,
                    Properties = null,
                    Example = CreateStructuredTypePropertiesExample(context, structuredType)
                });
            }
            else
            {
                // A structured type without a base type is represented as a Schema Object of type object
                OpenApiSchema schema = new OpenApiSchema
                {
                    Title = (structuredType as IEdmSchemaElement)?.Name,

                    Type = "object",

                    // Each structural property and navigation property is represented
                    // as a name/value pair of the standard OpenAPI properties object.
                    Properties = context.CreateStructuredTypePropertiesSchema(structuredType),

                    // make others null
                    AllOf = null,
                    OneOf = null,
                    AnyOf = null
                };

                // It optionally can contain the field description,
                // whose value is the value of the unqualified annotation Core.Description of the structured type.
                if (structuredType.TypeKind == EdmTypeKind.Complex)
                {
                    IEdmComplexType complex = (IEdmComplexType)structuredType;
                    schema.Description = context.Model.GetDescriptionAnnotation(complex);
                }
                else if (structuredType.TypeKind == EdmTypeKind.Entity)
                {
                    IEdmEntityType entity = (IEdmEntityType)structuredType;
                    schema.Description = context.Model.GetDescriptionAnnotation(entity);
                }

                if (processExample)
                {
                    schema.Example = CreateStructuredTypePropertiesExample(context, structuredType);
                }

                return(schema);
            }
        }
Esempio n. 51
0
            internal Scope(ODataReaderState state, ODataItem item, IEdmEntitySet entitySet, IEdmEntityType expectedEntityType)
            {
                Debug.Assert(
                    state == ODataReaderState.Exception && item == null ||
                    state == ODataReaderState.EntryStart && (item == null || item is ODataEntry) ||
                    state == ODataReaderState.EntryEnd && (item == null || item is ODataEntry) ||
                    state == ODataReaderState.FeedStart && item is ODataFeed ||
                    state == ODataReaderState.FeedEnd && item is ODataFeed ||
                    state == ODataReaderState.NavigationLinkStart && item is ODataNavigationLink ||
                    state == ODataReaderState.NavigationLinkEnd && item is ODataNavigationLink ||
                    state == ODataReaderState.EntityReferenceLink && item is ODataEntityReferenceLink ||
                    state == ODataReaderState.Start && item == null ||
                    state == ODataReaderState.Completed && item == null,
                    "Reader state and associated item do not match.");

                this.state      = state;
                this.item       = item;
                this.EntityType = expectedEntityType;
                this.EntitySet  = entitySet;
            }
Esempio n. 52
0
        public ITestActionResult Get()
        {
            IEdmEntityType             customerType            = Request.GetModel().FindDeclaredType("Microsoft.Test.E2E.AspNet.OData.TestCustomer") as IEdmEntityType;
            IEdmEntityType             customerWithAddressType = Request.GetModel().FindDeclaredType("Microsoft.Test.E2E.AspNet.OData.TestCustomerWithAddress") as IEdmEntityType;
            IEdmComplexType            addressType             = Request.GetModel().FindDeclaredType("Microsoft.Test.E2E.AspNet.OData.TestAddress") as IEdmComplexType;
            IEdmEntityType             orderType      = Request.GetModel().FindDeclaredType("Microsoft.Test.E2E.AspNet.OData.TestOrder") as IEdmEntityType;
            IEdmEntitySet              ordersSet      = Request.GetModel().FindDeclaredEntitySet("TestOrders") as IEdmEntitySet;
            EdmChangedObjectCollection changedObjects = new EdmChangedObjectCollection(customerType);

            EdmDeltaComplexObject a = new EdmDeltaComplexObject(addressType);

            a.TrySetPropertyValue("State", "State");
            a.TrySetPropertyValue("ZipCode", null);

            EdmDeltaEntityObject changedEntity = new EdmDeltaEntityObject(customerWithAddressType);

            changedEntity.TrySetPropertyValue("Id", 1);
            changedEntity.TrySetPropertyValue("Name", "Name");
            changedEntity.TrySetPropertyValue("Address", a);
            changedEntity.TrySetPropertyValue("PhoneNumbers", new List <String> {
                "123-4567", "765-4321"
            });
            changedEntity.TrySetPropertyValue("OpenProperty", 10);
            changedEntity.TrySetPropertyValue("NullOpenProperty", null);
            changedObjects.Add(changedEntity);

            EdmComplexObjectCollection places = new EdmComplexObjectCollection(new EdmCollectionTypeReference(new EdmCollectionType(new EdmComplexTypeReference(addressType, true))));
            EdmDeltaComplexObject      b      = new EdmDeltaComplexObject(addressType);

            b.TrySetPropertyValue("City", "City2");
            b.TrySetPropertyValue("State", "State2");
            b.TrySetPropertyValue("ZipCode", 12345);
            b.TrySetPropertyValue("OpenProperty", 10);
            b.TrySetPropertyValue("NullOpenProperty", null);
            places.Add(a);
            places.Add(b);

            var newCustomer = new EdmDeltaEntityObject(customerType);

            newCustomer.TrySetPropertyValue("Id", 10);
            newCustomer.TrySetPropertyValue("Name", "NewCustomer");
            newCustomer.TrySetPropertyValue("FavoritePlaces", places);
            changedObjects.Add(newCustomer);

            var newOrder = new EdmDeltaEntityObject(orderType);

            newOrder.NavigationSource = ordersSet;
            newOrder.TrySetPropertyValue("Id", 27);
            newOrder.TrySetPropertyValue("Amount", 100);
            changedObjects.Add(newOrder);

            var deletedCustomer = new EdmDeltaDeletedEntityObject(customerType);

            deletedCustomer.Id     = "7";
            deletedCustomer.Reason = DeltaDeletedEntryReason.Changed;
            changedObjects.Add(deletedCustomer);

            var deletedOrder = new EdmDeltaDeletedEntityObject(orderType);

            deletedOrder.NavigationSource = ordersSet;
            deletedOrder.Id     = "12";
            deletedOrder.Reason = DeltaDeletedEntryReason.Deleted;
            changedObjects.Add(deletedOrder);

            var deletedLink = new EdmDeltaDeletedLink(customerType);

            deletedLink.Source       = new Uri("http://localhost/odata/DeltaCustomers(1)");
            deletedLink.Target       = new Uri("http://localhost/odata/DeltaOrders(12)");
            deletedLink.Relationship = "Orders";
            changedObjects.Add(deletedLink);

            var addedLink = new EdmDeltaLink(customerType);

            addedLink.Source       = new Uri("http://localhost/odata/DeltaCustomers(10)");
            addedLink.Target       = new Uri("http://localhost/odata/DeltaOrders(27)");
            addedLink.Relationship = "Orders";
            changedObjects.Add(addedLink);

            return(Ok(changedObjects));
        }
Esempio n. 53
0
        public bool Read()
        {
            if (_jsonTextReader.TokenType == JsonToken.PropertyName)
            {
                if (_jsonTextReader.Value.Equals("@odata.context"))
                {
                    IEdmEntityType entityType = ReadOdataContextEntityType();
                    _entityTypes.Push(new EntityTypeFrame(entityType, true));
                    return(entityType != null);
                }
                else if (_jsonTextReader.Depth > 1)
                {
                    _property = _entityTypes.Peek().EntityType.FindProperty((String)_jsonTextReader.Value);
                    if (_property != null)
                    {
                        if (_property.Type.IsEnum())
                        {
                            if (_jsonTextReader.Read())
                            {
                                if (_jsonTextReader.Value is long longValue)
                                {
                                    _value = EnumHelper.ToStringLiteral((IEdmEnumTypeReference)_property.Type, longValue);
                                }

                                return(true);
                            }

                            return(false);
                        }
                        else if (_property.Type.IsDecimal())
                        {
                            String svalue = _jsonTextReader.ReadAsString();
                            if (svalue != null)
                            {
                                _value = Decimal.Parse(svalue, CultureInfo.InvariantCulture);
                                return(true);
                            }

                            return(false);
                        }
                        else if (_property is IEdmNavigationProperty navigationProperty)
                        {
                            _entityTypes.Push(new EntityTypeFrame(navigationProperty.ToEntityType(), navigationProperty.Type.IsCollection()));
                        }
                    }
                }
            }
            else if (_jsonTextReader.TokenType == JsonToken.EndObject && _jsonTextReader.Depth > 1)
            {
                _property = null;
                if (!_entityTypes.Peek().IsCollection)
                {
                    _entityTypes.Pop();
                }
            }
            else if (_jsonTextReader.TokenType == JsonToken.EndArray)
            {
                _property = null;
                _entityTypes.Pop();
            }

            return(_jsonTextReader.Read());
        }
        /// <summary>
        /// Deserializes the given <paramref name="resourceWrapper"/> under the given <paramref name="readContext"/>.
        /// </summary>
        /// <param name="resourceWrapper">The OData resource to deserialize.</param>
        /// <param name="structuredType">The type of the resource to deserialize.</param>
        /// <param name="readContext">The deserializer context.</param>
        /// <returns>The deserialized resource.</returns>
        public virtual object ReadResource(ODataResourceWrapper resourceWrapper, IEdmStructuredTypeReference structuredType,
                                           ODataDeserializerContext readContext)
        {
            if (resourceWrapper == null)
            {
                throw Error.ArgumentNull("resourceWrapper");
            }

            if (readContext == null)
            {
                throw Error.ArgumentNull("readContext");
            }

            if (!String.IsNullOrEmpty(resourceWrapper.Resource.TypeName) && structuredType.FullName() != resourceWrapper.Resource.TypeName)
            {
                // received a derived type in a base type deserializer. delegate it to the appropriate derived type deserializer.
                IEdmModel model = readContext.Model;

                if (model == null)
                {
                    throw Error.Argument("readContext", SRResources.ModelMissingFromReadContext);
                }

                IEdmStructuredType actualType = model.FindType(resourceWrapper.Resource.TypeName) as IEdmStructuredType;
                if (actualType == null)
                {
                    throw new ODataException(Error.Format(SRResources.ResourceTypeNotInModel, resourceWrapper.Resource.TypeName));
                }

                if (actualType.IsAbstract)
                {
                    string message = Error.Format(SRResources.CannotInstantiateAbstractResourceType, resourceWrapper.Resource.TypeName);
                    throw new ODataException(message);
                }

                IEdmTypeReference actualStructuredType;
                IEdmEntityType    actualEntityType = actualType as IEdmEntityType;
                if (actualEntityType != null)
                {
                    actualStructuredType = new EdmEntityTypeReference(actualEntityType, isNullable: false);
                }
                else
                {
                    actualStructuredType = new EdmComplexTypeReference(actualType as IEdmComplexType, isNullable: false);
                }

                ODataEdmTypeDeserializer deserializer = DeserializerProvider.GetEdmTypeDeserializer(actualStructuredType);
                if (deserializer == null)
                {
                    throw new SerializationException(
                              Error.Format(SRResources.TypeCannotBeDeserialized, actualEntityType.FullName()));
                }

                object resource = deserializer.ReadInline(resourceWrapper, actualStructuredType, readContext);

                EdmStructuredObject structuredObject = resource as EdmStructuredObject;
                if (structuredObject != null)
                {
                    structuredObject.ExpectedEdmType = structuredType.StructuredDefinition();
                }

                return(resource);
            }
            else
            {
                object resource = CreateResourceInstance(structuredType, readContext);
                ApplyResourceProperties(resource, resourceWrapper, structuredType, readContext);
                return(resource);
            }
        }
Esempio n. 55
0
 public static IEdmEntityTypeReference AsReference(this IEdmEntityType entity)
 {
     return(new EdmEntityTypeReference(entity, isNullable: false));
 }
        /// <summary>
        /// Create the <see cref="ODataResourceSet"/> to be written for the given resourceSet instance.
        /// </summary>
        /// <param name="resourceSetInstance">The instance representing the resourceSet being written.</param>
        /// <param name="resourceSetType">The EDM type of the resourceSet being written.</param>
        /// <param name="writeContext">The serializer context.</param>
        /// <returns>The created <see cref="ODataResourceSet"/> object.</returns>
        public virtual ODataResourceSet CreateResourceSet(IEnumerable resourceSetInstance, IEdmCollectionTypeReference resourceSetType,
                                                          ODataSerializerContext writeContext)
        {
            ODataResourceSet resourceSet = new ODataResourceSet
            {
                TypeName = resourceSetType.FullName()
            };

            IEdmStructuredTypeReference structuredType = GetResourceType(resourceSetType).AsStructured();

            if (writeContext.NavigationSource != null && structuredType.IsEntity())
            {
                ResourceSetContext resourceSetContext = ResourceSetContext.Create(writeContext, resourceSetInstance);
                IEdmEntityType     entityType         = structuredType.AsEntity().EntityDefinition();
                var operations      = writeContext.Model.GetAvailableOperationsBoundToCollection(entityType);
                var odataOperations = CreateODataOperations(operations, resourceSetContext, writeContext);
                foreach (var odataOperation in odataOperations)
                {
                    ODataAction action = odataOperation as ODataAction;
                    if (action != null)
                    {
                        resourceSet.AddAction(action);
                    }
                    else
                    {
                        resourceSet.AddFunction((ODataFunction)odataOperation);
                    }
                }
            }

            if (writeContext.ExpandedResource == null)
            {
                // If we have more OData format specific information apply it now, only if we are the root feed.
                PageResult odataResourceSetAnnotations = resourceSetInstance as PageResult;
                if (odataResourceSetAnnotations != null)
                {
                    resourceSet.Count        = odataResourceSetAnnotations.Count;
                    resourceSet.NextPageLink = odataResourceSetAnnotations.NextPageLink;
                }
                else if (writeContext.Request != null)
                {
                    resourceSet.NextPageLink = writeContext.InternalRequest.Context.NextLink;
                    resourceSet.DeltaLink    = writeContext.InternalRequest.Context.DeltaLink;

                    long?countValue = writeContext.InternalRequest.Context.TotalCount;
                    if (countValue.HasValue)
                    {
                        resourceSet.Count = countValue.Value;
                    }
                }
            }
            else
            {
                ICountOptionCollection countOptionCollection = resourceSetInstance as ICountOptionCollection;
                if (countOptionCollection != null && countOptionCollection.TotalCount != null)
                {
                    resourceSet.Count = countOptionCollection.TotalCount;
                }
            }

            return(resourceSet);
        }
Esempio n. 57
0
        private void CompileAndVerify(string source, bool isCSharp, IEdmModel model)
        {
            // verify that the given cs/vb code can be compiled successfully
            CompilerParameters compilerOptions = new CompilerParameters
            {
                GenerateExecutable      = false,
                GenerateInMemory        = true,
                IncludeDebugInformation = false,
                TreatWarningsAsErrors   = true,
                WarningLevel            = 4,
                ReferencedAssemblies    =
                {
                    typeof(DataServiceContext).Assembly.Location,
                    typeof(IEdmModel).Assembly.Location,
                    typeof(GeographyPoint).Assembly.Location,
                    typeof(Uri).Assembly.Location,
                    typeof(IQueryable).Assembly.Location,
                    typeof(INotifyPropertyChanged).Assembly.Location,
                    typeof(XmlReader).Assembly.Location,
                }
            };

            CodeDomProvider codeProvider = null;

            if (isCSharp)
            {
                codeProvider = new CSharpCodeProvider();
            }
            else
            {
                codeProvider = new VBCodeProvider();
            }

            var results = codeProvider.CompileAssemblyFromSource(compilerOptions, source);

            Assert.AreEqual(0, results.Errors.Count);

            // verify that the generated assembly contains entity types, complex types, and the entity container specified in the given model
            foreach (var modelElement in model.SchemaElements.Where(se => se.SchemaElementKind != EdmSchemaElementKind.Function && se.SchemaElementKind != EdmSchemaElementKind.Action))
            {
                Type t = results.CompiledAssembly.DefinedTypes.FirstOrDefault(dt => dt.Name == modelElement.Name);
                Assert.IsNotNull(t, modelElement.Name);

                IEdmEntityType      entityType      = modelElement as IEdmEntityType;
                IEdmComplexType     complexTypeType = modelElement as IEdmComplexType;
                IEdmEntityContainer container       = modelElement as IEdmEntityContainer;
                if (entityType != null)
                {
                    foreach (var edmProperty in entityType.DeclaredProperties)
                    {
                        Assert.IsNotNull(t.GetProperties().Where(p => p.Name == edmProperty.Name), "Property not found: " + edmProperty.Name + " in " + entityType.Name);
                    }
                }
                else if (complexTypeType != null)
                {
                    foreach (var edmProperty in complexTypeType.DeclaredProperties)
                    {
                        Assert.IsNotNull(t.GetProperties().Where(p => p.Name == edmProperty.Name), "Property not found: " + edmProperty.Name + " in " + complexTypeType.Name);
                    }
                }
                else if (container != null)
                {
                    foreach (var entitySet in container.EntitySets())
                    {
                        Assert.IsNotNull(t.GetProperties().Where(p => p.Name == entitySet.Name), "EntitySet not found: " + entitySet.Name);
                    }
                }
                else
                {
                    Assert.Fail("Unhandled model element " + modelElement.GetType().Name);
                }
            }
        }
Esempio n. 58
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="jsonLightOutputContext">The output context to write to.</param>
        /// <param name="navigationSource">The navigation source we are going to write entities for.</param>
        /// <param name="entityType">The entity type for the entries in the resource set to be written (or null if the entity set base type should be used).</param>
        public ODataJsonLightDeltaWriter(ODataJsonLightOutputContext jsonLightOutputContext, IEdmNavigationSource navigationSource, IEdmEntityType entityType)
        {
            Debug.Assert(jsonLightOutputContext != null, "jsonLightOutputContext != null");

            this.navigationSource       = navigationSource;
            this.entityType             = entityType;
            this.jsonLightOutputContext = jsonLightOutputContext;
            this.resourceWriter         = new ODataJsonLightWriter(jsonLightOutputContext, navigationSource, entityType, true, writingDelta: true);
            this.inStreamErrorListener  = resourceWriter;
        }
Esempio n. 59
0
 /// <summary>
 /// Creates an <see cref="ODataWriter" /> to write an entry or a feed.
 /// </summary>
 /// <param name="isFeed">Specify whether to create a writer for a feed or an entry.</param>
 /// <param name="entitySet">The entity set we are going to write entities for.</param>
 /// <param name="entityType">The entity type for the entries in the feed to be written (or null if the entity set base type should be used).</param>
 /// <returns>If <paramref name="isFeed"/> is true, return the result of CreateODataResourceSetWriter, otherwise return the result of CreateODataResourceWriter.</returns>
 internal ODataWriter CreateODataWriter(bool isFeed, IEdmEntitySet entitySet, IEdmEntityType entityType)
 {
     return(isFeed ? this.CreateODataResourceSetWriter(entitySet, entityType) : this.CreateODataResourceWriter(entitySet, entityType));
 }
Esempio n. 60
0
 public CsdlSemanticsPropertyReferenceExpression(CsdlPropertyReferenceExpression expression, IEdmEntityType bindingContext, CsdlSemanticsSchema schema)
     : base(schema, expression)
 {
     this.expression     = expression;
     this.bindingContext = bindingContext;
 }