Пример #1
0
 /// <summary>
 /// Creates an <see cref="EntitySetNode"/>
 /// </summary>
 /// <param name="entitySet">The entity set this node represents</param>
 /// <exception cref="System.ArgumentNullException">Throws if the input entitySet is null.</exception>
 public EntitySetNode(IEdmEntitySet entitySet)
 {
     ExceptionUtils.CheckArgumentNotNull(entitySet, "entitySet");
     this.entitySet = entitySet;
     this.entityType = new EdmEntityTypeReference(this.NavigationSource.EntityType(), false);
     this.collectionTypeReference = EdmCoreModel.GetCollection(this.entityType);
 }
Пример #2
0
 private void WriteElementEpm(XmlWriter writer, EpmTargetPathSegment targetSegment, EntryPropertiesValueCache epmValueCache, IEdmEntityTypeReference entityType, ref string alreadyDeclaredPrefix)
 {
     string prefix = targetSegment.SegmentNamespacePrefix ?? string.Empty;
     writer.WriteStartElement(prefix, targetSegment.SegmentName, targetSegment.SegmentNamespaceUri);
     if (prefix.Length > 0)
     {
         WriteNamespaceDeclaration(writer, targetSegment, ref alreadyDeclaredPrefix);
     }
     foreach (EpmTargetPathSegment segment in targetSegment.SubSegments)
     {
         if (segment.IsAttribute)
         {
             this.WriteAttributeEpm(writer, segment, epmValueCache, entityType, ref alreadyDeclaredPrefix);
         }
     }
     if (targetSegment.HasContent)
     {
         string str2 = this.GetEntryPropertyValueAsText(targetSegment, epmValueCache, entityType);
         ODataAtomWriterUtils.WriteString(writer, str2);
     }
     else
     {
         foreach (EpmTargetPathSegment segment2 in targetSegment.SubSegments)
         {
             if (!segment2.IsAttribute)
             {
                 this.WriteElementEpm(writer, segment2, epmValueCache, entityType, ref alreadyDeclaredPrefix);
             }
         }
     }
     writer.WriteEndElement();
 }
 public static void Get(
     string dataSourceName,
     IEdmEntityTypeReference entityType,
     EdmEntityObjectCollection collection)
 {
     GetDataSource(dataSourceName).Get(entityType, collection);
 }
Пример #4
0
 /// <summary>
 /// Constructs a KeyLookupNode.
 /// </summary>
 /// <param name="source">The collection that this key is referring to.</param>
 /// <param name="keyPropertyValues">List of the properties and their values that we use to look up our return value.</param>
 /// <exception cref="System.ArgumentNullException">Throws if the input source is null.</exception>
 public KeyLookupNode(EntityCollectionNode source, IEnumerable<KeyPropertyValue> keyPropertyValues)
 {
     ExceptionUtils.CheckArgumentNotNull(source, "source");
     this.source = source;
     this.navigationSource = source.NavigationSource;
     this.entityTypeReference = source.EntityItemType;
     this.keyPropertyValues = keyPropertyValues;
 }
		protected override async Task CreatingEntityInstanceContextAsync(object entity, IEdmEntityTypeReference entityType, object graph, ODataSerializerContext writeContext)
		{
			if (entity is Customer)
			{
				await PreProcessCustomerAsync(entity as Customer);
			}
			await base.CreatingEntityInstanceContextAsync(entity, entityType, graph, writeContext);
		}
Пример #6
0
 /// <summary>
 /// Creates a <see cref="EntityRangeVariable"/>.
 /// </summary>
 /// <param name="name"> The name of the associated any/all parameter (null if none)</param>
 /// <param name="entityType">The entity type of each item in the collection that this range variable iterates over.</param>
 /// <param name="navigationSource">The navigation source of the collection this node iterates over.</param>
 /// <exception cref="System.ArgumentNullException">Throws if the input name or entityType is null.</exception>
 public EntityRangeVariable(string name, IEdmEntityTypeReference entityType, IEdmNavigationSource navigationSource)
 {
     ExceptionUtils.CheckArgumentNotNull(name, "name");
     ExceptionUtils.CheckArgumentNotNull(entityType, "entityType");
     this.name = name;
     this.entityTypeReference = entityType;
     this.entityCollectionNode = null;
     this.navigationSource = navigationSource;
 }
Пример #7
0
 private string GetEntryPropertyValueAsText(EpmTargetPathSegment targetSegment, EntryPropertiesValueCache epmValueCache, IEdmEntityTypeReference entityType)
 {
     object propertyValue = base.ReadEntryPropertyValue(targetSegment.EpmInfo, epmValueCache, entityType);
     if (propertyValue == null)
     {
         return string.Empty;
     }
     return EpmWriterUtils.GetPropertyValueAsText(propertyValue);
 }
Пример #8
0
 private void WriteAttributeEpm(XmlWriter writer, EpmTargetPathSegment targetSegment, EntryPropertiesValueCache epmValueCache, IEdmEntityTypeReference entityType, ref string alreadyDeclaredPrefix)
 {
     string str = this.GetEntryPropertyValueAsText(targetSegment, epmValueCache, entityType);
     string prefix = targetSegment.SegmentNamespacePrefix ?? string.Empty;
     writer.WriteAttributeString(prefix, targetSegment.AttributeName, targetSegment.SegmentNamespaceUri, str);
     if (prefix.Length > 0)
     {
         WriteNamespaceDeclaration(writer, targetSegment, ref alreadyDeclaredPrefix);
     }
 }
        private EntityInstanceContext(ODataSerializerContext serializerContext, IEdmEntityTypeReference entityType, IEdmStructuredObject edmObject)
        {
            if (serializerContext == null)
            {
                throw Error.ArgumentNull("serializerContext");
            }

            SerializerContext = serializerContext;
            EntityType = entityType.EntityDefinition();
            EdmObject = edmObject;
        }
Пример #10
0
        /// <summary>
        /// Validates that the <paramref name="payloadEntityTypeReference"/> is assignable to the <paramref name="expectedEntityTypeReference"/>
        /// and fails if it's not.
        /// </summary>
        /// <param name="expectedEntityTypeReference">The expected entity type reference, the base type of the entities expected.</param>
        /// <param name="payloadEntityTypeReference">The payload entity type reference to validate.</param>
        internal static void ValidateEntityTypeIsAssignable(IEdmEntityTypeReference expectedEntityTypeReference, IEdmEntityTypeReference payloadEntityTypeReference)
        {
            Debug.Assert(expectedEntityTypeReference != null, "expectedEntityTypeReference != null");
            Debug.Assert(payloadEntityTypeReference != null, "payloadEntityTypeReference != null");

            // Entity types must be assignable
            if (!EdmLibraryExtensions.IsAssignableFrom(expectedEntityTypeReference.EntityDefinition(), payloadEntityTypeReference.EntityDefinition()))
            {
                throw new ODataException(Strings.ValidationUtils_EntryTypeNotAssignableToExpectedType(payloadEntityTypeReference.ODataFullName(), expectedEntityTypeReference.ODataFullName()));
            }
        }
Пример #11
0
 public void Get(IEdmEntityTypeReference entityType, EdmEntityObjectCollection collection)
 {
     EdmEntityObject entity = new EdmEntityObject(entityType);
     entity.TrySetPropertyValue("Name", "Foo");
     entity.TrySetPropertyValue("ID", 100);
     collection.Add(entity);
     entity = new EdmEntityObject(entityType);
     entity.TrySetPropertyValue("Name", "Bar");
     entity.TrySetPropertyValue("ID", 101);
     collection.Add(entity);
 }
Пример #12
0
        private EntityInstanceContext(ODataSerializerContext serializerContext, IEdmEntityTypeReference entityType, IEdmEntityObject edmObject, string assemblyName)
        {
            if (serializerContext == null)
            {
                throw Error.ArgumentNull("serializerContext");
            }

	        AssemblyName = assemblyName;
            SerializerContext = serializerContext;
            EntityType = entityType.EntityDefinition();
            EdmObject = edmObject;
        }
Пример #13
0
 private void WriteEntryEpm(XmlWriter writer, EpmTargetTree epmTargetTree, EntryPropertiesValueCache epmValueCache, IEdmEntityTypeReference entityType)
 {
     EpmTargetPathSegment nonSyndicationRoot = epmTargetTree.NonSyndicationRoot;
     if (nonSyndicationRoot.SubSegments.Count != 0)
     {
         foreach (EpmTargetPathSegment segment2 in nonSyndicationRoot.SubSegments)
         {
             string alreadyDeclaredPrefix = null;
             this.WriteElementEpm(writer, segment2, epmValueCache, entityType, ref alreadyDeclaredPrefix);
         }
     }
 }
Пример #14
0
        /// <summary>
        /// Writes the custom mapped EPM properties to an XML writer which is expected to be positioned such to write
        /// a child element of the entry element.
        /// </summary>
        /// <param name="writer">The XmlWriter to write to.</param>
        /// <param name="epmTargetTree">The EPM target tree to use.</param>
        /// <param name="epmValueCache">The entry properties value cache to use to access the properties.</param>
        /// <param name="entityType">The type of the entry.</param>
        /// <param name="atomOutputContext">The output context currently in use.</param>
        internal static void WriteEntryEpm(
            XmlWriter writer,
            EpmTargetTree epmTargetTree,
            EntryPropertiesValueCache epmValueCache,
            IEdmEntityTypeReference entityType,
            ODataAtomOutputContext atomOutputContext)
        {
            DebugUtils.CheckNoExternalCallers();

            EpmCustomWriter epmWriter = new EpmCustomWriter(atomOutputContext);
            epmWriter.WriteEntryEpm(writer, epmTargetTree, epmValueCache, entityType);
        }
 public ODataEntityDeserializerTests()
 {
     _edmModel = EdmTestHelpers.GetModel();
     IEdmEntitySet entitySet = _edmModel.EntityContainers().Single().FindEntitySet("Products");
     _readContext = new ODataDeserializerContext
     {
         Path = new ODataPath(new EntitySetPathSegment(entitySet)),
         Model = _edmModel
     };
     _productEdmType = _edmModel.GetEdmTypeReference(typeof(Product)).AsEntity();
     _supplierEdmType = _edmModel.GetEdmTypeReference(typeof(Supplier)).AsEntity();
     _deserializerProvider = new DefaultODataDeserializerProvider();
 }
Пример #16
0
        /// <summary>
        /// Writes the syndication part of EPM for an entry into ATOM metadata OM.
        /// </summary>
        /// <param name="epmTargetTree">The EPM target tree to use.</param>
        /// <param name="epmValueCache">The entry properties value cache to use to access the properties.</param>
        /// <param name="type">The type of the entry.</param>
        /// <param name="atomOutputContext">The output context currently in use.</param>
        /// <returns>The ATOM metadata OM with the EPM values populated.</returns>
        internal static AtomEntryMetadata WriteEntryEpm(
            EpmTargetTree epmTargetTree,
            EntryPropertiesValueCache epmValueCache,
            IEdmEntityTypeReference type,
            ODataAtomOutputContext atomOutputContext)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(epmTargetTree != null, "epmTargetTree != null");
            Debug.Assert(epmValueCache != null, "epmValueCache != null");
            Debug.Assert(type != null, "For any EPM to exist the metadata must be available.");

            EpmSyndicationWriter epmWriter = new EpmSyndicationWriter(epmTargetTree, atomOutputContext);
            return epmWriter.WriteEntryEpm(epmValueCache, type);
        }
        /// <summary>
        /// Deserializes the given <paramref name="feed"/> under the given <paramref name="readContext"/>.
        /// </summary>
        /// <param name="feed">The feed to deserialize.</param>
        /// <param name="readContext">The deserializer context.</param>
        /// <param name="elementType">The element type of the feed being read.</param>
        /// <returns>The deserialized feed object.</returns>
        public virtual IEnumerable ReadFeed(ODataFeedWithEntries feed, IEdmEntityTypeReference elementType, ODataDeserializerContext readContext)
        {
            ODataEdmTypeDeserializer deserializer = DeserializerProvider.GetEdmTypeDeserializer(elementType);
            if (deserializer == null)
            {
                throw new SerializationException(
                    Error.Format(SRResources.TypeCannotBeDeserialized, elementType.FullName(), typeof(ODataMediaTypeFormatter).Name));
            }

            foreach (ODataEntryWithNavigationLinks entry in feed.Entries)
            {
                yield return deserializer.ReadInline(entry, elementType, readContext);
            }
        }
        public void Get(IEdmEntityTypeReference entityType, EdmEntityObjectCollection collection)
        {
            EdmEntityObject entity = new EdmEntityObject(entityType);
            entity.TrySetPropertyValue("Name", "Foo");
            entity.TrySetPropertyValue("ID", 100);
            entity.TrySetPropertyValue("School", Createchool(99, new DateTimeOffset(2016, 1, 19, 1, 2, 3, TimeSpan.Zero), entity.ActualEdmType));
            collection.Add(entity);

            entity = new EdmEntityObject(entityType);
            entity.TrySetPropertyValue("Name", "Bar");
            entity.TrySetPropertyValue("ID", 101);
            entity.TrySetPropertyValue("School", Createchool(99, new DateTimeOffset(1978, 11, 15, 1, 2, 3, TimeSpan.Zero), entity.ActualEdmType));

            collection.Add(entity);
        }
Пример #19
0
        public void Get(IEdmEntityTypeReference entityType, EdmEntityObjectCollection collection)
        {
            EdmEntityObject entity = new EdmEntityObject(entityType);
            entity.TrySetPropertyValue("Name", "abc");
            entity.TrySetPropertyValue("ID", 1);
            entity.TrySetPropertyValue("DetailInfo", CreateDetailInfo(88, "abc_detailinfo", entity.ActualEdmType));

            collection.Add(entity);
            entity = new EdmEntityObject(entityType);
            entity.TrySetPropertyValue("Name", "def");
            entity.TrySetPropertyValue("ID", 2);
            entity.TrySetPropertyValue("DetailInfo", CreateDetailInfo(99, "def_detailinfo", entity.ActualEdmType));

            collection.Add(entity);
        }
Пример #20
0
        internal static IEdmValue CreateStructuredEdmValue(ODataEntry entry, IEdmEntitySet entitySet, IEdmEntityTypeReference entityType)
        {
            if (entitySet != null)
            {
                object typeAnnotation = ReflectionUtils.CreateInstance(
                    odataTypeAnnotationType,
                    new Type[] { typeof(IEdmEntitySet), typeof(IEdmEntityTypeReference) },
                    entitySet, entityType);
                entry.SetAnnotation(typeAnnotation);
            }

            return (IEdmValue)ReflectionUtils.CreateInstance(
                odataEdmStructuredValueType, 
                new Type[] { typeof(ODataEntry) },
                entry);
        }
Пример #21
0
        /// <summary>
        /// Reads a property value starting on an entry.
        /// </summary>
        /// <param name="epmInfo">The EPM info which describes the mapping for which to read the property value.</param>
        /// <param name="epmValueCache">The EPM value cache for the entry to read from.</param>
        /// <param name="entityType">The type of the entry.</param>
        /// <returns>The value of the property (may be null), or null if the property itself was not found due to one of its parent properties being null.</returns>
        protected object ReadEntryPropertyValue(
            EntityPropertyMappingInfo epmInfo,
            EntryPropertiesValueCache epmValueCache,
            IEdmEntityTypeReference entityType)
        {
            Debug.Assert(epmInfo != null, "epmInfo != null");
            Debug.Assert(epmInfo.PropertyValuePath != null, "The PropertyValuePath should have been initialized by now.");
            Debug.Assert(epmInfo.PropertyValuePath.Length > 0, "The PropertyValuePath must not be empty for an entry property.");
            Debug.Assert(entityType != null, "entityType != null");

            // TODO - It might be possible to avoid the "value" type checks below if we do property value validation based on the type
            return this.ReadPropertyValue(
                epmInfo,
                epmValueCache.EntryProperties,
                0,
                entityType,
                epmValueCache);
        }
        public EdmLibraryExtensionsTests()
        {
            this.model = TestModel.BuildDefaultTestModel();
            this.defaultContainer = (EdmEntityContainer)this.model.FindEntityContainer("Default");
            this.productsSet = this.defaultContainer.FindEntitySet("Products");
            this.productType = (IEdmEntityType)this.model.FindDeclaredType("TestModel.Product");
            this.productTypeReference = new EdmEntityTypeReference(this.productType, false);

            EdmComplexType complexType = new EdmComplexType("TestModel", "MyComplexType");

            this.operationWithNoOverload = new EdmFunction("TestModel", "FunctionImportWithNoOverload", EdmCoreModel.Instance.GetInt32(true));
            this.operationWithNoOverload.AddParameter("p1", EdmCoreModel.Instance.GetInt32(false));
            this.model.AddElement(operationWithNoOverload);
            this.operationImportWithNoOverload = this.defaultContainer.AddFunctionImport("FunctionImportWithNoOverload", operationWithNoOverload);

            this.operationWithOverloadAnd0Param = new EdmFunction("TestModel", "FunctionImportWithNoOverload", EdmCoreModel.Instance.GetInt32(true));
            this.model.AddElement(operationWithOverloadAnd0Param);
            this.operationImportWithOverloadAnd0Param = defaultContainer.AddFunctionImport("FunctionImportWithOverload", operationWithOverloadAnd0Param);

            this.operationWithOverloadAnd1Param = new EdmFunction("TestModel", "FunctionImportWithNoOverload", EdmCoreModel.Instance.GetInt32(true));
            this.operationWithOverloadAnd1Param.AddParameter("p1", EdmCoreModel.Instance.GetInt32(false));
            this.model.AddElement(operationWithOverloadAnd1Param);
            this.operationImportWithOverloadAnd1Param = defaultContainer.AddFunctionImport("FunctionImportWithOverload", operationWithOverloadAnd1Param);

            this.operationWithOverloadAnd2Params = new EdmFunction("TestModel", "FunctionImportWithNoOverload", EdmCoreModel.Instance.GetInt32(true));
            var productTypeReference = new EdmEntityTypeReference(productType, isNullable: false);
            this.operationWithOverloadAnd2Params.AddParameter("p1", productTypeReference);
            this.operationWithOverloadAnd2Params.AddParameter("p2", EdmCoreModel.Instance.GetString(true));
            this.model.AddElement(operationWithOverloadAnd2Params);
            this.operationImportWithOverloadAnd2Params = defaultContainer.AddFunctionImport("FunctionImportWithOverload", operationWithOverloadAnd2Params);

            this.operationWithOverloadAnd5Params = new EdmFunction("TestModel", "FunctionImportWithNoOverload", EdmCoreModel.Instance.GetInt32(true));
            this.operationWithOverloadAnd5Params.AddParameter("p1", new EdmCollectionTypeReference(new EdmCollectionType(productTypeReference)));
            this.operationWithOverloadAnd5Params.AddParameter("p2", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetString(isNullable: false))));
            this.operationWithOverloadAnd5Params.AddParameter("p3", EdmCoreModel.Instance.GetString(isNullable: true));
            EdmComplexTypeReference complexTypeReference = new EdmComplexTypeReference(complexType, isNullable: false);
            this.operationWithOverloadAnd5Params.AddParameter("p4", complexTypeReference);
            this.operationWithOverloadAnd5Params.AddParameter("p5", new EdmCollectionTypeReference(new EdmCollectionType(complexTypeReference)));
            this.model.AddElement(operationWithOverloadAnd5Params);
            this.operationImportWithOverloadAnd5Params = defaultContainer.AddFunctionImport("FunctionImportWithOverload", operationWithOverloadAnd5Params);
        }
        /// <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="selectExpandClause"/>.
        /// </summary>
        /// <param name="selectExpandClause">The parsed $select and $expand query options.</param>
        /// <param name="entityType">The entity type of the entry that would be written.</param>
        /// <param name="model">The <see cref="IEdmModel"/> that contains the given entity type.</param>
        public SelectExpandNode(SelectExpandClause selectExpandClause, IEdmEntityTypeReference entityType, IEdmModel model)
            : this()
        {
            if (entityType == null)
            {
                throw Error.ArgumentNull("entityType");
            }
            if (model == null)
            {
                throw Error.ArgumentNull("model");
            }

            HashSet<IEdmStructuralProperty> allStructuralProperties = new HashSet<IEdmStructuralProperty>(entityType.StructuralProperties());
            HashSet<IEdmNavigationProperty> allNavigationProperties = new HashSet<IEdmNavigationProperty>(entityType.NavigationProperties());
            HashSet<IEdmFunctionImport> allActions = new HashSet<IEdmFunctionImport>(model.GetAvailableProcedures(entityType.EntityDefinition()));

            if (selectExpandClause == null)
            {
                SelectedStructuralProperties = allStructuralProperties;
                SelectedNavigationProperties = allNavigationProperties;
                SelectedActions = allActions;
            }
            else
            {
                if (selectExpandClause.AllSelected)
                {
                    SelectedStructuralProperties = allStructuralProperties;
                    SelectedNavigationProperties = allNavigationProperties;
                    SelectedActions = allActions;
                }
                else
                {
                    BuildSelections(selectExpandClause, allStructuralProperties, allNavigationProperties, allActions);
                }

                BuildExpansions(selectExpandClause, allNavigationProperties);

                // remove expanded navigation properties from the selected navigation properties.
                SelectedNavigationProperties.ExceptWith(ExpandedNavigationProperties.Keys);
            }
        }
        public ODataEntityTypeSerializerTests()
        {
            _model = SerializationTestsHelpers.SimpleCustomerOrderModel();

            _model.SetAnnotationValue<ClrTypeAnnotation>(_model.FindType("Default.Customer"), new ClrTypeAnnotation(typeof(Customer)));
            _model.SetAnnotationValue<ClrTypeAnnotation>(_model.FindType("Default.Order"), new ClrTypeAnnotation(typeof(Order)));

            _customerSet = _model.FindDeclaredEntityContainer("Default.Container").FindEntitySet("Customers");
            _customer = new Customer()
            {
                FirstName = "Foo",
                LastName = "Bar",
                ID = 10,
            };

            _serializerProvider = new DefaultODataSerializerProvider();
            _customerType = _model.GetEdmTypeReference(typeof(Customer)).AsEntity();
            _serializer = new ODataEntityTypeSerializer(_serializerProvider);
            _writeContext = new ODataSerializerContext() { EntitySet = _customerSet, Model = _model };
            _entityInstanceContext = new EntityInstanceContext(_writeContext, _customerSet.ElementType.AsReference(), _customer);
        }
        public ODataEntityTypeSerializerTests()
        {
            _model = SerializationTestsHelpers.SimpleCustomerOrderModel();

            _model.SetAnnotationValue<ClrTypeAnnotation>(_model.FindType("Default.Customer"), new ClrTypeAnnotation(typeof(Customer)));
            _model.SetAnnotationValue<ClrTypeAnnotation>(_model.FindType("Default.Order"), new ClrTypeAnnotation(typeof(Order)));
            _model.SetAnnotationValue(
                _model.FindType("Default.SpecialCustomer"),
                new ClrTypeAnnotation(typeof(SpecialCustomer)));
            _model.SetAnnotationValue(
                _model.FindType("Default.SpecialOrder"),
                new ClrTypeAnnotation(typeof(SpecialOrder)));

            _customerSet = _model.EntityContainer.FindEntitySet("Customers");
            _customer = new Customer()
            {
                FirstName = "Foo",
                LastName = "Bar",
                ID = 10,
            };

            _orderSet = _model.EntityContainer.FindEntitySet("Orders");
            _order = new Order
            {
                ID = 20,
            };

            _serializerProvider = new DefaultODataSerializerProvider();
            _customerType = _model.GetEdmTypeReference(typeof(Customer)).AsEntity();
            _orderType = _model.GetEdmTypeReference(typeof(Order)).AsEntity();
            _specialCustomerType = _model.GetEdmTypeReference(typeof(SpecialCustomer)).AsEntity();
            _specialOrderType = _model.GetEdmTypeReference(typeof(SpecialOrder)).AsEntity();
            _serializer = new ODataEntityTypeSerializer(_serializerProvider);
            _path = new ODataPath(new EntitySetPathSegment(_customerSet));
            _writeContext = new ODataSerializerContext() { NavigationSource = _customerSet, Model = _model, Path = _path };
            _entityInstanceContext = new EntityInstanceContext(_writeContext, _customerSet.EntityType().AsReference(), _customer);
        }
Пример #26
0
        /// <summary>
        /// Builds the <see cref="SelectExpandNode"/> describing the set of structural properties and navigation properties and actions to select
        /// and navigation properties to expand while writing an entry of type <paramref name="entityType"/> for the given 
        /// <paramref name="selectExpandClause"/>.
        /// </summary>
        /// <param name="selectExpandClause">The parsed $select and $expand query options.</param>
        /// <param name="entityType">The entity type of the entry that would be written.</param>
        /// <param name="model">The <see cref="IEdmModel"/> that contains the given entity type.</param>
        /// <returns>The built <see cref="SelectExpandNode"/>.</returns>
        public static SelectExpandNode BuildSelectExpandNode(SelectExpandClause selectExpandClause, IEdmEntityTypeReference entityType, IEdmModel model)
        {
            if (entityType == null)
            {
                throw Error.ArgumentNull("entityType");
            }
            if (model == null)
            {
                throw Error.ArgumentNull("model");
            }

            SelectExpandNode selectExpandNode = new SelectExpandNode();
            if (selectExpandClause != null && selectExpandClause.Expansion != null)
            {
                selectExpandNode.BuildExpansions(selectExpandClause.Expansion, entityType);
            }
            selectExpandNode.BuildSelections(selectExpandClause == null ? null : selectExpandClause.Selection, entityType, model);

            // remove expanded navigation properties from the selected navigation properties.
            IEnumerable<IEdmNavigationProperty> expandedNavigationProperties = selectExpandNode.ExpandedNavigationProperties.Keys;
            selectExpandNode.SelectedNavigationProperties.ExceptWith(expandedNavigationProperties);

            return selectExpandNode;
        }
Пример #27
0
 protected object ReadEntryPropertyValue(EntityPropertyMappingInfo epmInfo, EntryPropertiesValueCache epmValueCache, IEdmEntityTypeReference entityType)
 {
     return(this.ReadPropertyValue(epmInfo, epmValueCache.EntryProperties, 0, entityType, epmValueCache));
 }
Пример #28
0
 public FakeSingleEntityNode(IEdmEntityTypeReference type, IEdmEntitySetBase set)
 {
     this.typeReference = type;
     this.set           = set;
 }
Пример #29
0
        private async Task <EntityInstanceContext> CreateEntityInstanceContextAsync(object graph, ODataSerializerContext writeContext, IEdmEntityTypeReference entityType)
        {
            var entity = graph;

            if (graph is ISelectExpandWrapper)
            {
                entity = (graph as ISelectExpandWrapper).Instance;
            }
            await CreatingEntityInstanceContextAsync(entity, entityType, graph, writeContext);

            return(new EntityInstanceContext(writeContext, entityType, graph, null));
        }
Пример #30
0
 public ServiceApiEdmEntityObject(IEdmEntityTypeReference edmType)
     : this(edmType.EntityDefinition(), edmType.IsNullable)
 {
 }
Пример #31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EdmDeltaDeletedLink"/> class.
 /// </summary>
 /// <param name="entityTypeReference">The <see cref="IEdmEntityTypeReference"/> of this DeltaDeletedLink.</param>
 public EdmDeltaDeletedLink(IEdmEntityTypeReference entityTypeReference)
     : this(entityTypeReference.EntityDefinition(), entityTypeReference.IsNullable)
 {
 }
Пример #32
0
 protected virtual Task CreatingEntityInstanceContextAsync(object entity, IEdmEntityTypeReference entityType, object graph, ODataSerializerContext writeContext)
 {
     return(Task.FromResult(true));
 }
Пример #33
0
 protected virtual void ProcessEntityTypeReference(IEdmEntityTypeReference reference)
 {
     this.ProcessStructuredTypeReference(reference);
 }
Пример #34
0
 public IODataEntityObject CreateODataEntityObject(IEdmEntityTypeReference edmType)
 {
     return(new ServiceApiEdmEntityObject(edmType));
 }
        private static IEdmStructuredObject AsEdmStructuredObject(object entityInstance, IEdmEntityTypeReference entityType)
        {
            if (entityType == null)
            {
                throw Error.ArgumentNull("entityType");
            }

            IEdmStructuredObject edmObject = entityInstance as IEdmStructuredObject;
            if (edmObject != null)
            {
                return edmObject;
            }
            else
            {
                return new EdmStructuredObject(entityInstance, entityType);
            }
        }
 private void ApplyEntityProperties(object entityResource, ODataEntryWithNavigationLinks entryWrapper,
                                    IEdmEntityTypeReference entityType, ODataDeserializerContext readContext)
 {
     ApplyStructuralProperties(entityResource, entryWrapper, entityType, readContext);
     ApplyNavigationProperties(entityResource, entryWrapper, entityType, readContext);
 }
Пример #37
0
 protected object ReadEntryPropertyValue(EntityPropertyMappingInfo epmInfo, EntryPropertiesValueCache epmValueCache, IEdmEntityTypeReference entityType)
 {
     return this.ReadPropertyValue(epmInfo, epmValueCache.EntryProperties, 0, entityType, epmValueCache);
 }
Пример #38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EntityInstanceContext"/> class.
 /// </summary>
 /// <param name="serializerContext">The backing <see cref="ODataSerializerContext"/>.</param>
 /// <param name="entityType">The EDM entity type of this instance context.</param>
 /// <param name="entityInstance">The object representing the instance of this context.</param>
 public EntityInstanceContext(ODataSerializerContext serializerContext, IEdmEntityTypeReference entityType, object entityInstance)
     : this(serializerContext, entityType, AsEdmEntityObject(entityInstance, entityType))
 {
 }
Пример #39
0
        private EdmEntityObject GetEdmEntityObject(Dictionary <string, object> keyValuePairs, IEdmEntityTypeReference edmEntityType)
        {
            var obj = new EdmEntityObject(edmEntityType);

            foreach (var kvp in keyValuePairs)
            {
                obj.TrySetPropertyValue(kvp.Key, kvp.Value);
            }
            return(obj);
        }
        /// <summary>
        /// Validates that the <paramref name="payloadEntityTypeReference"/> is assignable to the <paramref name="expectedEntityTypeReference"/>
        /// and fails if it's not.
        /// </summary>
        /// <param name="expectedEntityTypeReference">The expected entity type reference, the base type of the entities expected.</param>
        /// <param name="payloadEntityTypeReference">The payload entity type reference to validate.</param>
        internal static void ValidateEntityTypeIsAssignable(IEdmEntityTypeReference expectedEntityTypeReference, IEdmEntityTypeReference payloadEntityTypeReference)
        {
            Debug.Assert(expectedEntityTypeReference != null, "expectedEntityTypeReference != null");
            Debug.Assert(payloadEntityTypeReference != null, "payloadEntityTypeReference != null");

            // Entity types must be assignable
            if (!EdmLibraryExtensions.IsAssignableFrom(expectedEntityTypeReference.EntityDefinition(), payloadEntityTypeReference.EntityDefinition()))
            {
                throw new ODataException(Strings.ValidationUtils_EntryTypeNotAssignableToExpectedType(payloadEntityTypeReference.ODataFullName(), expectedEntityTypeReference.ODataFullName()));
            }
        }
 public EdmDeltaDeletedResourceObject(IEdmEntityTypeReference entityTypeReference)
     : this(entityTypeReference.EntityDefinition(), entityTypeReference.IsNullable)
 {
 }
Пример #42
0
        public void ReadResource_CanReadDynamicPropertiesForOpenEntityType()
        {
            // Arrange
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

            builder.EntityType <SimpleOpenCustomer>();
            builder.EnumType <SimpleEnum>();
            IEdmModel model = builder.GetEdmModel();

            IEdmEntityTypeReference customerTypeReference = model.GetEdmTypeReference(typeof(SimpleOpenCustomer)).AsEntity();

            var deserializer = new ODataResourceDeserializer(_deserializerProvider);

            ODataEnumValue enumValue = new ODataEnumValue("Third", typeof(SimpleEnum).FullName);

            ODataResource[] complexResources =
            {
                new ODataResource
                {
                    TypeName   = typeof(SimpleOpenAddress).FullName,
                    Properties = new[]
                    {
                        // declared properties
                        new ODataProperty {
                            Name = "Street", Value = "Street 1"
                        },
                        new ODataProperty {
                            Name = "City", Value = "City 1"
                        },

                        // dynamic properties
                        new ODataProperty
                        {
                            Name  = "DateTimeProperty",
                            Value = new DateTimeOffset(new DateTime(2014, 5, 6))
                        }
                    }
                },
                new ODataResource
                {
                    TypeName   = typeof(SimpleOpenAddress).FullName,
                    Properties = new[]
                    {
                        // declared properties
                        new ODataProperty {
                            Name = "Street", Value = "Street 2"
                        },
                        new ODataProperty {
                            Name = "City", Value = "City 2"
                        },

                        // dynamic properties
                        new ODataProperty
                        {
                            Name  = "ArrayProperty",
                            Value = new ODataCollectionValue{
                                TypeName = "Collection(Edm.Int32)", Items = new[]{                                         1, 2, 3, 4 }.Cast <object>()
                            }
                        }
                    }
                }
            };

            ODataResource odataResource = new ODataResource
            {
                Properties = new[]
                {
                    // declared properties
                    new ODataProperty {
                        Name = "CustomerId", Value = 991
                    },
                    new ODataProperty {
                        Name = "Name", Value = "Name #991"
                    },

                    // dynamic properties
                    new ODataProperty {
                        Name = "GuidProperty", Value = new Guid("181D3A20-B41A-489F-9F15-F91F0F6C9ECA")
                    },
                    new ODataProperty {
                        Name = "EnumValue", Value = enumValue
                    },
                },
                TypeName = typeof(SimpleOpenCustomer).FullName
            };

            ODataDeserializerContext readContext = new ODataDeserializerContext()
            {
                Model = model
            };

            ODataResourceWrapper topLevelResourceWrapper = new ODataResourceWrapper(odataResource);

            ODataNestedResourceInfo resourceInfo = new ODataNestedResourceInfo
            {
                IsCollection = true,
                Name         = "CollectionProperty"
            };
            ODataNestedResourceInfoWrapper resourceInfoWrapper = new ODataNestedResourceInfoWrapper(resourceInfo);
            ODataResourceSetWrapper        resourceSetWrapper  = new ODataResourceSetWrapper(new ODataResourceSet
            {
                TypeName = String.Format("Collection({0})", typeof(SimpleOpenAddress).FullName)
            });

            foreach (var complexResource in complexResources)
            {
                resourceSetWrapper.Resources.Add(new ODataResourceWrapper(complexResource));
            }
            resourceInfoWrapper.NestedItems.Add(resourceSetWrapper);
            topLevelResourceWrapper.NestedResourceInfos.Add(resourceInfoWrapper);

            // Act
            SimpleOpenCustomer customer = deserializer.ReadResource(topLevelResourceWrapper, customerTypeReference, readContext)
                                          as SimpleOpenCustomer;

            // Assert
            Assert.NotNull(customer);

            // Verify the declared properties
            Assert.Equal(991, customer.CustomerId);
            Assert.Equal("Name #991", customer.Name);

            // Verify the dynamic properties
            Assert.NotNull(customer.CustomerProperties);
            Assert.Equal(3, customer.CustomerProperties.Count());
            Assert.Equal(new Guid("181D3A20-B41A-489F-9F15-F91F0F6C9ECA"), customer.CustomerProperties["GuidProperty"]);
            Assert.Equal(SimpleEnum.Third, customer.CustomerProperties["EnumValue"]);

            // Verify the dynamic collection property
            var collectionValues = Assert.IsType <List <SimpleOpenAddress> >(customer.CustomerProperties["CollectionProperty"]);

            Assert.NotNull(collectionValues);
            Assert.Equal(2, collectionValues.Count());

            Assert.Equal(new DateTimeOffset(new DateTime(2014, 5, 6)), collectionValues[0].Properties["DateTimeProperty"]);
            Assert.Equal(new List <int> {
                1, 2, 3, 4
            }, collectionValues[1].Properties["ArrayProperty"]);
        }
        private void WriteFeed(IEnumerable enumerable, IEdmTypeReference feedType, ODataDeltaWriter writer,
                               ODataSerializerContext writeContext)
        {
            Contract.Assert(writer != null);
            Contract.Assert(writeContext != null);
            Contract.Assert(enumerable != null);
            Contract.Assert(feedType != null);

            ODataDeltaResourceSet deltaFeed = CreateODataDeltaFeed(enumerable, feedType.AsCollection(), writeContext);

            if (deltaFeed == null)
            {
                throw new SerializationException(Error.Format(SRResources.CannotSerializerNull, DeltaFeed));
            }

            // save this for later to support JSON odata.streaming.
            Uri nextPageLink = deltaFeed.NextPageLink;

            deltaFeed.NextPageLink = null;

            //Start writing of the Delta Feed
            writer.WriteStart(deltaFeed);

            //Iterate over all the entries present and select the appropriate write method.
            //Write method creates ODataDeltaDeletedEntry / ODataDeltaDeletedLink / ODataDeltaLink or ODataEntry.
            foreach (object entry in enumerable)
            {
                if (entry == null)
                {
                    throw new SerializationException(SRResources.NullElementInCollection);
                }

                IEdmChangedObject edmChangedObject = entry as IEdmChangedObject;
                if (edmChangedObject == null)
                {
                    throw new SerializationException(Error.Format(SRResources.CannotWriteType, GetType().Name, enumerable.GetType().FullName));
                }

                switch (edmChangedObject.DeltaKind)
                {
                case EdmDeltaEntityKind.DeletedEntry:
                    WriteDeltaDeletedEntry(entry, writer, writeContext);
                    break;

                case EdmDeltaEntityKind.DeletedLinkEntry:
                    WriteDeltaDeletedLink(entry, writer, writeContext);
                    break;

                case EdmDeltaEntityKind.LinkEntry:
                    WriteDeltaLink(entry, writer, writeContext);
                    break;

                case EdmDeltaEntityKind.Entry:
                {
                    IEdmEntityTypeReference elementType     = GetEntityType(feedType);
                    ODataResourceSerializer entrySerializer = SerializerProvider.GetEdmTypeSerializer(writeContext.Context, elementType) as ODataResourceSerializer;
                    if (entrySerializer == null)
                    {
                        throw new SerializationException(
                                  Error.Format(SRResources.TypeCannotBeSerialized, elementType.FullName(), typeof(ODataOutputFormatter).Name));
                    }
                    entrySerializer.WriteDeltaObjectInline(entry, elementType, writer, writeContext);
                    break;
                }

                default:
                    break;
                }
            }

            // Subtle and surprising behavior: If the NextPageLink property is set before calling WriteStart(feed),
            // the next page link will be written early in a manner not compatible with odata.streaming=true. Instead, if
            // the next page link is not set when calling WriteStart(feed) but is instead set later on that feed
            // object before calling WriteEnd(), the next page link will be written at the end, as required for
            // odata.streaming=true support.
            if (nextPageLink != null)
            {
                deltaFeed.NextPageLink = nextPageLink;
            }

            //End Writing of the Delta Feed
            writer.WriteEnd();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="EntityInstanceContext"/> class.
 /// </summary>
 /// <param name="serializerContext">The backing <see cref="ODataSerializerContext"/>.</param>
 /// <param name="entityType">The EDM entity type of this instance context.</param>
 /// <param name="entityInstance">The object representing the instance of this context.</param>
 public EntityInstanceContext(ODataSerializerContext serializerContext, IEdmEntityTypeReference entityType, object entityInstance)
     : this(serializerContext, entityType, AsEdmStructuredObject(entityInstance, entityType))
 {
 }
Пример #45
0
        /// <summary>
        /// Binds a <see cref="InnerPathToken"/>.
        /// This includes more than just navigations - it includes complex property access and primitive collections.
        /// </summary>
        /// <param name="segmentToken">The segment token to bind.</param>
        /// <returns>The bound node.</returns>
        internal QueryNode BindInnerPathSegment(InnerPathToken segmentToken)
        {
            FunctionCallBinder functionCallBinder = new FunctionCallBinder(this.bindMethod, state);

            // First we get the parent node
            QueryNode parent = this.DetermineParentNode(segmentToken, state);

            Debug.Assert(parent != null, "parent should never be null");

            SingleValueNode singleValueParent = parent as SingleValueNode;

            if (singleValueParent == null)
            {
                QueryNode boundFunction;
                if (functionCallBinder.TryBindInnerPathAsFunctionCall(segmentToken, parent, out boundFunction))
                {
                    return(boundFunction);
                }

                CollectionNavigationNode collectionParent = parent as CollectionNavigationNode;

                if (collectionParent != null)
                {
                    IEdmEntityTypeReference parentType         = collectionParent.EntityItemType;
                    IEdmProperty            collectionProperty = this.Resolver.ResolveProperty(parentType.StructuredDefinition(), segmentToken.Identifier);
                    if (collectionProperty != null && collectionProperty.PropertyKind == EdmPropertyKind.Structural)
                    {
                        return(new AggregatedCollectionPropertyNode(collectionParent, collectionProperty));
                    }
                }

                throw new ODataException(ODataErrorStrings.MetadataBinder_PropertyAccessSourceNotSingleValue(segmentToken.Identifier));
            }

            // Using the parent and name of this token, we try to get the IEdmProperty it represents
            IEdmProperty property = BindProperty(singleValueParent.TypeReference, segmentToken.Identifier, this.Resolver);

            if (property == null)
            {
                QueryNode boundFunction;
                if (functionCallBinder.TryBindInnerPathAsFunctionCall(segmentToken, parent, out boundFunction))
                {
                    return(boundFunction);
                }

                if (singleValueParent.TypeReference != null && !singleValueParent.TypeReference.Definition.IsOpen())
                {
                    throw new ODataException(
                              ODataErrorStrings.MetadataBinder_PropertyNotDeclared(
                                  parent.GetEdmTypeReference().FullName(), segmentToken.Identifier));
                }

                return(new SingleValueOpenPropertyAccessNode(singleValueParent, segmentToken.Identifier));
            }

            IEdmStructuralProperty structuralProperty = property as IEdmStructuralProperty;

            if (property.Type.IsComplex())
            {
                // Generate a segment to parsed segments for the parsed token
                state.ParsedSegments.Add(new PropertySegment(structuralProperty));
                return(new SingleComplexNode(singleValueParent as SingleResourceNode, property));
            }
            else if (property.Type.IsPrimitive())
            {
                return(new SingleValuePropertyAccessNode(singleValueParent, property));
            }

            // Note - this means nonentity collection (primitive or complex)
            if (property.Type.IsNonEntityCollectionType())
            {
                if (property.Type.IsStructuredCollectionType())
                {
                    // Generate a segment to parsed segments for the parsed token
                    state.ParsedSegments.Add(new PropertySegment(structuralProperty));
                    return(new CollectionComplexNode(singleValueParent as SingleResourceNode, property));
                }

                return(new CollectionPropertyAccessNode(singleValueParent, property));
            }

            IEdmNavigationProperty navigationProperty = property as IEdmNavigationProperty;

            if (navigationProperty == null)
            {
                throw new ODataException(ODataErrorStrings.MetadataBinder_IllegalSegmentType(property.Name));
            }

            SingleResourceNode parentResource = EnsureParentIsResourceForNavProp(singleValueParent);

            IEdmNavigationSource navigationSource;
            QueryNode            node = GetNavigationNode(navigationProperty, parentResource, segmentToken.NamedValues, state,
                                                          new KeyBinder(this.bindMethod), out navigationSource);

            // Generate a segment to parsed segments for the parsed token
            state.ParsedSegments.Add(new NavigationPropertySegment(navigationProperty, navigationSource));

            return(node);
        }
 public ODataFeedDeserializerTest()
 {
     _model         = GetEdmModel();
     _customerType  = _model.GetEdmTypeReference(typeof(Customer)).AsEntity();
     _customersType = new EdmCollectionTypeReference(new EdmCollectionType(_customerType), isNullable: false);
 }
Пример #47
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ODataEntityDeserializer"/> class.
 /// </summary>
 /// <param name="edmType">The entity type that this serializer handles.</param>
 /// <param name="deserializerProvider">The deserializer provider to use to read inner objects.</param>
 public ODataEntityDeserializer(IEdmEntityTypeReference edmType, ODataDeserializerProvider deserializerProvider)
     : base(edmType, ODataPayloadKind.Entry, deserializerProvider)
 {
     EntityType = edmType;
 }
 /// <inheritdoc />
 public ODataEntityTypeSerializer(IEdmEntityTypeReference edmType, ODataSerializerProvider serializerProvider)
     : base(edmType, ODataPayloadKind.Entry, serializerProvider)
 {
     Contract.Assert(edmType != null);
     EntityType = edmType;
 }
Пример #49
0
 protected override void ProcessEntityTypeReference(IEdmEntityTypeReference element)
 {
     this.CheckSchemaElementReference(element.EntityDefinition());
 }