static ODataAtomPropertyAndValueDeserializerTests()
 {
     EdmModel = new EdmModel();
     ComplexType = new EdmComplexType("TestNamespace", "TestComplexType");
     StringProperty = ComplexType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
     EdmModel.AddElement(ComplexType);
 }
        /// <summary>
        /// This method creates and reads the property from the input and 
        /// returns an <see cref="ODataProperty"/> representing the read property.
        /// </summary>
        /// <param name="expectedProperty">The <see cref="IEdmProperty"/> producing the property to be read.</param>
        /// <param name="expectedPropertyTypeReference">The expected type of the property to read.</param>
        /// <returns>An <see cref="ODataProperty"/> representing the read property.</returns>
        internal ODataProperty ReadTopLevelProperty(IEdmStructuralProperty expectedProperty, IEdmTypeReference expectedPropertyTypeReference)
        {
            Debug.Assert(
                expectedPropertyTypeReference == null || !expectedPropertyTypeReference.IsODataEntityTypeKind(),
                "If the expected type is specified it must not be an entity type.");
            Debug.Assert(this.XmlReader != null, "this.xmlReader != null");

            this.ReadPayloadStart();
            Debug.Assert(this.XmlReader.NodeType == XmlNodeType.Element, "The XML reader must be positioned on an Element.");

            // For compatibility with WCF DS Server we need to be able to read the property element in any namespace, not just the OData namespace.
            if (!this.UseServerFormatBehavior && !this.XmlReader.NamespaceEquals(this.XmlReader.ODataMetadataNamespace))
            {
                throw new ODataException(ODataErrorStrings.ODataAtomPropertyAndValueDeserializer_TopLevelPropertyElementWrongNamespace(this.XmlReader.NamespaceURI, this.XmlReader.ODataMetadataNamespace));
            }

            // this is a top level property so EPM does not apply hence it is safe to say that EPM is not present
            this.AssertRecursionDepthIsZero();
            string expectedPropertyName = ReaderUtils.GetExpectedPropertyName(expectedProperty);
            ODataProperty property = this.ReadProperty(
                true,
                expectedPropertyName,
                expectedPropertyTypeReference,
                /*nullValueReadBehaviorKind*/ ODataNullValueBehaviorKind.Default);
            this.AssertRecursionDepthIsZero();
        
            Debug.Assert(property != null, "If we don't ignore null values the property must not be null.");

            this.ReadPayloadEnd();

            return property;
        }
        /// <summary>
        /// Initializes a new instance of <see cref="EdmReferentialConstraintPropertyPair"/>.
        /// </summary>
        /// <param name="dependentProperty">The local or dependent property in the referential constraint property pair. A null value is not allowed.</param>
        /// <param name="principalProperty">The foreign or principal property in the referential constraint property pair. A null value is not allowed.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if either of the properties given are null.</exception>
        public EdmReferentialConstraintPropertyPair(IEdmStructuralProperty dependentProperty, IEdmStructuralProperty principalProperty)
        {
            EdmUtil.CheckArgumentNull(dependentProperty, "dependentProperty");
            EdmUtil.CheckArgumentNull(principalProperty, "principalProperty");

            this.DependentProperty = dependentProperty;
            this.PrincipalProperty = principalProperty;
        }
Пример #4
0
        public override ODataProperty ReadProperty(IEdmStructuralProperty property, IEdmTypeReference expectedPropertyTypeReference)
        {
            if (!this.AvroReader.MoveNext())
            {
                throw new ApplicationException("Error Reader state");
            }

            return new ODataProperty { Value = ODataAvroConvert.ToODataValue(this.AvroReader.Current) };
        }
Пример #5
0
        /// <inheritdoc />
        public override bool TryTranslate(ODataTemplateTranslateContext context)
        {
            if (context == null)
            {
                throw Error.ArgumentNull(nameof(context));
            }

            RouteValueDictionary routeValues = context.RouteValues;

            // the request should have the navigation property
            if (!routeValues.TryGetValue(ParameterName, out object rawValue))
            {
                return(false);
            }

            string navigationProperty = rawValue as string;

            if (navigationProperty == null)
            {
                return(false);
            }

            // Find the navigation property
            IEdmNavigationProperty edmNavProperty = DeclaringType.ResolveProperty(navigationProperty) as IEdmNavigationProperty;

            if (edmNavProperty == null)
            {
                return(false);
            }

            IEdmNavigationSource targetNavigationSource = NavigationSource.FindNavigationTarget(edmNavProperty);

            // ODL implementation is complex, here i just use the NavigationPropertyLinkSegment
            context.Segments.Add(new NavigationPropertyLinkSegment(edmNavProperty, targetNavigationSource));

            if (RelatedKey != null)
            {
                IEdmEntityType entityType = edmNavProperty.ToEntityType();

                // only handle the single key
                IEdmStructuralProperty keyProperty = entityType.Key().SingleOrDefault();
                Contract.Assert(entityType.Key().Count() == 1);
                Contract.Assert(keyProperty != null);

                IDictionary <string, string> keyValuePairs = new Dictionary <string, string>
                {
                    { keyProperty.Name, $"{{{RelatedKey}}}" }
                };

                KeySegmentTemplate keySegment = new KeySegmentTemplate(keyValuePairs, entityType, targetNavigationSource);
                return(keySegment.TryTranslate(context));
            }

            return(true);
        }
 /// <summary>
 /// Reads an <see cref="ODataProperty"/> as message payload.
 /// </summary>
 /// <param name="property">The metadata of the property to read.</param>
 /// <returns>The property read from the payload.</returns>
 public ODataProperty ReadProperty(IEdmStructuralProperty property)
 {
     if (this.testConfiguration.Synchronous)
     {
         return(this.messageReader.ReadProperty(property));
     }
     else
     {
         return(this.messageReader.ReadPropertyAsync(property).WaitForResult());
     }
 }
Пример #7
0
        internal override void WriteStructuralPropertyElementHeader(IEdmStructuralProperty property, bool inlineType)
        {
            this.xmlWriter.WriteStartElement(CsdlConstants.Element_Property);
            this.WriteRequiredAttribute(CsdlConstants.Attribute_Name, property.Name, EdmValueWriter.StringAsXml);
            if (inlineType)
            {
                this.WriteRequiredAttribute(CsdlConstants.Attribute_Type, property.Type, this.TypeReferenceAsXml);
            }

            this.WriteOptionalAttribute(CsdlConstants.Attribute_DefaultValue, property.DefaultValueString, EdmValueWriter.StringAsXml);
        }
Пример #8
0
        public override ODataProperty ReadProperty(IEdmStructuralProperty property, IEdmTypeReference expectedPropertyTypeReference)
        {
            if (!this.AvroReader.MoveNext())
            {
                throw new ApplicationException("Error Reader state");
            }

            return(new ODataProperty {
                Value = ODataAvroConvert.ToODataValue(this.AvroReader.Current)
            });
        }
Пример #9
0
        public void CreatePropertyValueExpression_DerivedNonNullableProperty_ReturnsPropertyAccessExpressionCastToNullable()
        {
            Expression             customer = Expression.Constant(new Customer());
            IEdmStructuralProperty specialCustomerProperty = _model.SpecialCustomer.DeclaredStructuralProperties().Single();

            Expression property = _binder.CreatePropertyValueExpression(_model.Customer, specialCustomerProperty, customer);

            Assert.Equal(
                String.Format("Convert(({0} As SpecialCustomer).SpecialCustomerProperty)", customer.ToString()),
                property.ToString());
        }
        protected override void ProcessStructuralProperty(IEdmStructuralProperty element)
        {
            bool inlineType = IsInlineType(element.Type);

            this.BeginElement <IEdmStructuralProperty>(element, t => this.schemaWriter.WriteStructuralPropertyElementHeader(t, inlineType), new Action <IEdmStructuralProperty>[] { e => this.ProcessFacets(e.Type, inlineType) });
            if (!inlineType)
            {
                base.VisitTypeReference(element.Type);
            }
            this.EndElement(element);
        }
Пример #11
0
        internal static string GetExpectedPropertyName(IEdmStructuralProperty expectedProperty)
        {
            DebugUtils.CheckNoExternalCallers();

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

            return(expectedProperty.Name);
        }
Пример #12
0
 internal void WriteStructuralPropertyElementHeader(IEdmStructuralProperty property, bool inlineType)
 {
     this.xmlWriter.WriteStartElement("Property");
     this.WriteRequiredAttribute <string>("Name", property.Name, new Func <string, string>(EdmValueWriter.StringAsXml));
     if (inlineType)
     {
         this.WriteRequiredAttribute <IEdmTypeReference>("Type", property.Type, new Func <IEdmTypeReference, string>(this.TypeReferenceAsXml));
     }
     this.WriteOptionalAttribute <EdmConcurrencyMode>("ConcurrencyMode", property.ConcurrencyMode, EdmConcurrencyMode.None, new Func <EdmConcurrencyMode, string>(EdmModelCsdlSchemaWriter.ConcurrencyModeAsXml));
     this.WriteOptionalAttribute <string>("DefaultValue", property.DefaultValueString, new Func <string, string>(EdmValueWriter.StringAsXml));
 }
Пример #13
0
        public static bool TryMatch(this KeySegment keySegment, IDictionary <string, string> mapping, IDictionary <string, object> values)
        {
            Contract.Assert(keySegment != null);
            Contract.Assert(mapping != null);
            Contract.Assert(values != null);

            if (keySegment.Keys.Count() != mapping.Count)
            {
                return(false);
            }

            IEdmEntityType entityType = keySegment.EdmType as IEdmEntityType;

            Dictionary <string, object> routeData = new Dictionary <string, object>();

            foreach (KeyValuePair <string, object> key in keySegment.Keys)
            {
                string mappingName;
                if (!mapping.TryGetValue(key.Key, out mappingName))
                {
                    // mapping name is not found. it's not a match.
                    return(false);
                }

                IEdmTypeReference typeReference;
                // get the key property from the entity type
                if (entityType != null)
                {
                    IEdmStructuralProperty keyProperty = entityType.Key().FirstOrDefault(k => k.Name == key.Key);
                    if (keyProperty == null)
                    {
                        // If it's an alternate key
                        keyProperty = entityType.Properties().OfType <IEdmStructuralProperty>().FirstOrDefault(p => p.Name == key.Key);
                    }

                    Contract.Assert(keyProperty != null);
                    typeReference = keyProperty.Type;
                }
                else
                {
                    typeReference = EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(key.Value.GetType());
                }

                AddKeyValues(mappingName, key.Value, typeReference, routeData, routeData);
            }

            foreach (KeyValuePair <string, object> kvp in routeData)
            {
                values[kvp.Key] = kvp.Value;
            }

            return(true);
        }
Пример #14
0
        protected override void ProcessStructuralProperty(IEdmStructuralProperty element)
        {
            bool inlineType = IsInlineType(element.Type);

            this.BeginElement(element, (IEdmStructuralProperty t) => { this.schemaWriter.WriteStructuralPropertyElementHeader(t, inlineType); }, e => { this.ProcessFacets(e.Type, inlineType); });
            if (!inlineType)
            {
                VisitTypeReference(element.Type);
            }

            this.EndElement(element);
        }
Пример #15
0
        public static IEdmModel GetModelFunctionsOnNonEntityTypes()
        {
            EdmComplexType colorInfoType = new EdmComplexType("Test", "ColorInfo");

            colorInfoType.AddProperty(new EdmStructuralProperty(colorInfoType, "Red", EdmCoreModel.Instance.GetInt32(false)));
            colorInfoType.AddProperty(new EdmStructuralProperty(colorInfoType, "Green", EdmCoreModel.Instance.GetInt32(false)));
            colorInfoType.AddProperty(new EdmStructuralProperty(colorInfoType, "Blue", EdmCoreModel.Instance.GetInt32(false)));

            EdmEntityType          vegetableType = new EdmEntityType("Test", "Vegetable");
            IEdmStructuralProperty id            = vegetableType.AddStructuralProperty("ID", EdmCoreModel.Instance.GetInt32(false));

            vegetableType.AddKeys(id);
            vegetableType.AddStructuralProperty("Color", new EdmComplexTypeReference(colorInfoType, false));

            EdmEntityContainer container = new EdmEntityContainer("Test", "Container");
            var set = container.AddEntitySet("Vegetables", vegetableType);

            var function1 = new EdmFunction("Test", "IsPrime", EdmCoreModel.Instance.GetBoolean(false), true, null, true);

            function1.AddParameter("integer", EdmCoreModel.Instance.GetInt32(false));
            container.AddFunctionImport("IsPrime", function1);

            var action = new EdmAction("Test", "Subtract", EdmCoreModel.Instance.GetInt32(false), true /*isBound*/, null /*entitySetPath*/);

            action.AddParameter("integer", EdmCoreModel.Instance.GetInt32(false));
            container.AddActionImport(action);

            var function2 = new EdmFunction("Test", "IsDark", EdmCoreModel.Instance.GetBoolean(false), true, null, true);

            function2.AddParameter("color", new EdmComplexTypeReference(colorInfoType, false));
            container.AddFunctionImport("IsDark", function2);

            var function3 = new EdmFunction("Test", "IsDarkerThan", EdmCoreModel.Instance.GetBoolean(false), true, null, true);

            function3.AddParameter("color", new EdmComplexTypeReference(colorInfoType, false));
            function3.AddParameter("other", new EdmComplexTypeReference(colorInfoType, true));
            container.AddFunctionImport("IsDarkerThan", function3);

            var function4 = new EdmFunction("Test", "GetMostPopularVegetableWithThisColor", new EdmEntityTypeReference(vegetableType, true), true, new EdmPathExpression("color"), true);

            function4.AddParameter("color", new EdmComplexTypeReference(colorInfoType, false));

            EdmModel model = new EdmModel();

            model.AddElement(container);
            model.AddElement(vegetableType);
            model.AddElement(action);
            model.AddElement(function1);
            model.AddElement(function2);
            model.AddElement(function3);
            model.AddElement(function4);
            return(model);
        }
Пример #16
0
        public static IEnumerable <IEdmStructuralProperty> GetConcurrencyProperties(this IEdmModel model, IEdmNavigationSource navigationSource)
        {
            Contract.Assert(model != null);
            Contract.Assert(navigationSource != null);

            IEnumerable <IEdmStructuralProperty> cachedProperties;

            if (_concurrencyProperties != null && _concurrencyProperties.TryGetValue(navigationSource, out cachedProperties))
            {
                return(cachedProperties);
            }

            IList <IEdmStructuralProperty> results = new List <IEdmStructuralProperty>();
            IEdmEntityType            entityType   = navigationSource.EntityType();
            IEdmVocabularyAnnotatable annotatable  = navigationSource as IEdmVocabularyAnnotatable;

            if (annotatable != null)
            {
                var annotations = model.FindVocabularyAnnotations <IEdmVocabularyAnnotation>(annotatable, CoreVocabularyModel.ConcurrencyTerm);
                IEdmVocabularyAnnotation annotation = annotations.FirstOrDefault();
                if (annotation != null)
                {
                    IEdmCollectionExpression properties = annotation.Value as IEdmCollectionExpression;
                    if (properties != null)
                    {
                        foreach (var property in properties.Elements)
                        {
                            IEdmPathExpression pathExpression = property as IEdmPathExpression;
                            if (pathExpression != null)
                            {
                                // So far, we only consider the single path, because only the direct properties from declaring type are used.
                                // However we have an issue tracking on: https://github.com/OData/WebApi/issues/472
                                string                 propertyName       = pathExpression.PathSegments.First();
                                IEdmProperty           edmProperty        = entityType.FindProperty(propertyName);
                                IEdmStructuralProperty structuralProperty = edmProperty as IEdmStructuralProperty;
                                if (structuralProperty != null)
                                {
                                    results.Add(structuralProperty);
                                }
                            }
                        }
                    }
                }
            }

            if (_concurrencyProperties == null)
            {
                _concurrencyProperties = new ConcurrentDictionary <IEdmNavigationSource, IEnumerable <IEdmStructuralProperty> >();
            }

            _concurrencyProperties[navigationSource] = results;
            return(results);
        }
Пример #17
0
        public void EdmStructuralTypeInfo_IsStructuralPropertyDefined_ReturnsCorrectBoolean()
        {
            // Assert
            var structuralTypeInfo = new SelectExpandNode.EdmStructuralTypeInfo(_model.Model, _model.Customer);

            IEdmStructuralProperty property        = _model.Customer.DeclaredStructuralProperties().FirstOrDefault();
            IEdmStructuralProperty addressProperty = _model.Address.DeclaredStructuralProperties().FirstOrDefault();

            // Act & Assert
            Assert.True(structuralTypeInfo.IsStructuralPropertyDefined(property));
            Assert.False(structuralTypeInfo.IsStructuralPropertyDefined(addressProperty));
        }
Пример #18
0
        private OdcmProperty FindProperty(OdcmClass odcmClass, IEdmStructuralProperty keyProperty)
        {
            foreach (OdcmProperty property in odcmClass.Properties)
            {
                if (property.Name.Equals(keyProperty.Name, StringComparison.OrdinalIgnoreCase))
                {
                    return(property);
                }
            }

            return(null);
        }
Пример #19
0
        private OdcmField FindField(OdcmClass odcmClass, IEdmStructuralProperty keyProperty)
        {
            foreach (OdcmField field in odcmClass.Fields)
            {
                if (field.Name.Equals("_" + keyProperty.Name, StringComparison.OrdinalIgnoreCase))
                {
                    return(field);
                }
            }

            return(null);
        }
Пример #20
0
        public static void AddKeyValueToRouteData(this RouteContext routeContext, KeySegment segment, ActionDescriptor actionDescriptor, string keyName = "key")
        {
            Contract.Assert(routeContext != null);
            Contract.Assert(segment != null);

            HttpRequest request = routeContext.HttpContext.Request;
            IDictionary <string, object> routingConventionsStore = request.ODataFeature().RoutingConventionsStore;

            IEdmEntityType entityType = segment.EdmType as IEdmEntityType;

            Contract.Assert(entityType != null);

            int keyCount = segment.Keys.Count();

            foreach (var keyValuePair in segment.Keys)
            {
                bool alternateKey = false;
                // get the key property from the entity type
                IEdmStructuralProperty keyProperty = entityType.Key().FirstOrDefault(k => k.Name == keyValuePair.Key);
                if (keyProperty == null)
                {
                    // If it's alternate key.
                    keyProperty  = entityType.Properties().OfType <IEdmStructuralProperty>().FirstOrDefault(p => p.Name == keyValuePair.Key);
                    alternateKey = true;
                }
                Contract.Assert(keyProperty != null);

                // if there's only one key, just use the given key name, for example: "key, relatedKey"
                // otherwise, to append the key name after the given key name.
                // so for multiple keys, the parameter name is "keyId1, keyId2..."
                // for navigation property, the parameter name is "relatedKeyId1, relatedKeyId2 ..."
                string newKeyName;
                if (alternateKey || keyCount > 1)
                {
                    newKeyName = keyName + keyValuePair.Key;
                }
                else
                {
                    newKeyName = keyName;
                }

                // If we only have one parameter in our action which matches the type of the key required
                // then use the action's parameter, so if the action parameter is "productId", for example
                // it will still just work.
                if (actionDescriptor != null && keyCount == 1 && actionDescriptor.Parameters.Count == 1 &&
                    actionDescriptor.Parameters.Single().ParameterType == keyValuePair.Value.GetType())
                {
                    newKeyName = actionDescriptor.Parameters.Single().Name;
                }

                AddKeyValues(keyValuePair.Key, newKeyName, keyValuePair.Value, keyProperty.Type, routeContext.RouteData.Values, routingConventionsStore);
            }
        }
Пример #21
0
        private static void AddSelector(string httpMethod, ODataControllerActionContext context, ActionModel action,
                                        IEdmNavigationSource navigationSource,
                                        IEdmStructuralProperty edmProperty,
                                        IEdmType cast, IEdmEntityType declaringType, bool dollarValue, bool dollarCount)
        {
            IEdmEntitySet  entitySet  = navigationSource as IEdmEntitySet;
            IEdmEntityType entityType = navigationSource.EntityType();

            IList <ODataSegmentTemplate> segments = new List <ODataSegmentTemplate>();

            if (entitySet != null)
            {
                segments.Add(new EntitySetSegmentTemplate(entitySet));
                segments.Add(KeySegmentTemplate.CreateKeySegment(entityType, navigationSource));
            }
            else
            {
                segments.Add(new SingletonSegmentTemplate(navigationSource as IEdmSingleton));
            }

            if (declaringType != null && declaringType != entityType)
            {
                segments.Add(new CastSegmentTemplate(declaringType, entityType, navigationSource));
            }

            segments.Add(new PropertySegmentTemplate(edmProperty));

            if (cast != null)
            {
                if (edmProperty.Type.IsCollection())
                {
                    cast = new EdmCollectionType(cast.ToEdmTypeReference(edmProperty.Type.IsNullable));
                }

                // TODO: maybe create the collection type for the collection????
                segments.Add(new CastSegmentTemplate(cast, edmProperty.Type.Definition, navigationSource));
            }

            if (dollarValue)
            {
                segments.Add(new ValueSegmentTemplate(edmProperty.Type.Definition));
            }

            if (dollarCount)
            {
                segments.Add(CountSegmentTemplate.Instance);
            }

            ODataPathTemplate template = new ODataPathTemplate(segments);

            action.AddSelector(httpMethod.NormalizeHttpMethod(), context.Prefix, context.Model, template, context.Options?.RouteOptions);
        }
Пример #22
0
        public void PropertyCommonPropertiesReturnsAsExpected()
        {
            // Assert
            EdmEntityType           entityType      = new EdmEntityType("NS", "Customer");
            IEdmStructuralProperty  property        = entityType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            PropertySegmentTemplate propertySegment = new PropertySegmentTemplate(property);

            // Act & Assert
            Assert.Equal("Name", propertySegment.Literal);
            Assert.Equal(ODataSegmentKind.Property, propertySegment.Kind);
            Assert.True(propertySegment.IsSingle);
            Assert.Equal("Edm.String", propertySegment.EdmType.FullTypeName());
        }
Пример #23
0
        /// <summary>Adds a key property to the specified <paramref name="structuredType"/>.</summary>
        /// <param name="structuredType">The entity type to add the property to.</param>
        /// <param name="name">The name of the property to add.</param>
        /// <param name="propertyType">The CLR type of the property to add. This can be only a primitive type.</param>
        /// <param name="etag">true if the property should be part of the ETag</param>
        public void AddKeyProperty(IEdmStructuredType structuredType, string name, Type propertyType, bool etag = false)
        {
            EdmEntityType entityType = structuredType as EdmEntityType;

            if (entityType == null)
            {
                throw new InvalidOperationException("Expected an EdmEntityType instance.");
            }

            IEdmStructuralProperty keyProperty = this.AddPrimitiveProperty(entityType, name, propertyType, etag ? EdmConcurrencyMode.Fixed : EdmConcurrencyMode.None);

            AddKeyFragment(entityType, keyProperty);
        }
Пример #24
0
        private static bool HasAutoExpandProperty(this IEdmModel edmModel, IEdmStructuredType structuredType, IEdmProperty pathProperty, ISet <IEdmStructuredType> visited)
        {
            if (visited.Contains(structuredType))
            {
                return(false);
            }
            visited.Add(structuredType);

            List <IEdmStructuredType> structuredTypes = new List <IEdmStructuredType>();

            structuredTypes.Add(structuredType);
            structuredTypes.AddRange(edmModel.FindAllDerivedTypes(structuredType));

            foreach (IEdmStructuredType edmStructuredType in structuredTypes)
            {
                // for top type, let's retrieve its properties and the properties from base type of top type if has.
                // for derived type, let's retrieve the declared properties.
                IEnumerable <IEdmProperty> properties = edmStructuredType == structuredType
                        ? edmStructuredType.Properties()
                        : edmStructuredType.DeclaredProperties;

                foreach (IEdmProperty property in properties)
                {
                    switch (property.PropertyKind)
                    {
                    case EdmPropertyKind.Structural:
                        IEdmStructuralProperty structuralProperty = (IEdmStructuralProperty)property;
                        IEdmTypeReference      typeRef            = property.Type.GetElementTypeOrSelf();
                        if (typeRef.IsComplex() && edmModel.CanExpand(typeRef.AsComplex().ComplexDefinition(), structuralProperty))
                        {
                            IEdmStructuredType subStrucutredType = typeRef.AsStructured().StructuredDefinition();
                            if (edmModel.HasAutoExpandProperty(subStrucutredType, structuralProperty, visited))
                            {
                                return(true);
                            }
                        }
                        break;

                    case EdmPropertyKind.Navigation:
                        IEdmNavigationProperty navigationProperty = (IEdmNavigationProperty)property;
                        if (IsAutoExpand(navigationProperty, pathProperty, edmStructuredType, edmModel))
                        {
                            return(true);    // find an auto-expand navigation property path
                        }
                        break;
                    }
                }
            }

            return(false);
        }
Пример #25
0
        /// <summary>
        /// Translates at V3 PropertySegment (e.g. "/Boxes(1)/Name") into a V4 PropertySegment
        /// </summary>
        /// <param name="segment">OData V3 PropertySegment</param>
        /// <returns>OData V4 PropertySegment</returns>
        public override ODataPathSegment Translate(Data.OData.Query.SemanticAst.PropertySegment segment)
        {
            // Look up equivalent declaring type in V4 model
            IEdmStructuredType v4Type = v4model.GetV4Definition(segment.Property.DeclaringType) as IEdmStructuredType;

            ExceptionUtil.IfNullThrowException(v4Type, "Unable to locate equivalent v4 type for " + segment.Property.DeclaringType.GetFullTypeName());

            // Look up corresponding Property in V4 Type by name
            IEdmStructuralProperty v4Property = v4Type.FindProperty(segment.Property.Name) as IEdmStructuralProperty;

            ExceptionUtil.IfNullThrowException(v4Property, "Unable to locate equivalent v4 property for " + segment.Property.Name);

            return(new PropertySegment(v4Property));
        }
Пример #26
0
        private MemberProperty ConvertToTaupoProperty(IEdmStructuralProperty edmProperty)
        {
            var taupoProperty = new MemberProperty(edmProperty.Name);

            taupoProperty.PropertyType = this.ConvertToTaupoDataType(edmProperty.Type);

            if (!string.IsNullOrEmpty(edmProperty.DefaultValueString))
            {
                taupoProperty.DefaultValue = edmProperty.DefaultValueString;
            }

            this.ConvertAnnotationsIntoTaupo(edmProperty, taupoProperty);
            return(taupoProperty);
        }
        public void TestReadProperty_InJsonLight_WithStructuralProperty_DoesNotThrow()
        {
            // Arrange
            IODataRequestMessage       request  = CreateJsonLightRequest("{\"value\":1}");
            ODataMessageReaderSettings settings = CreateSettings();
            IEdmModel model = CreateModel();
            IEdmStructuralProperty property = model.EntityContainer.EntitySets().First().EntityType().StructuralProperties().First();

            using (ODataMessageReader reader = new ODataMessageReader(request, settings, model))
            {
                // Act & Assert
                Assert.DoesNotThrow(() => reader.ReadProperty(property));
            }
        }
Пример #28
0
        /// <summary>
        /// Creates an EdmModel based on the source table
        /// </summary>
        /// <param name="sourceTable"></param>
        /// <returns></returns>
        public static Tuple <IEdmModel, IEdmType> BuildEdmModel(this DataTable sourceTable, String entityName = null, String entitySetName = null)
        {
            String Namespace = "Dynamic";
            String TypeName  = sourceTable.TableName;

            if (!String.IsNullOrWhiteSpace(entityName))
            {
                TypeName = entityName;
            }

            EdmModel Output = new EdmModel();

            EdmEntityType DataSourceModel = new EdmEntityType(Namespace, TypeName);
            List <IEdmStructuralProperty> KeyProperties = new List <IEdmStructuralProperty>();

            foreach (DataColumn SourceColumn in sourceTable.Columns)
            {
                String ColumnName = SourceColumn.ColumnName;
                Type   ColumnType = SourceColumn.DataType;
                EdmPrimitiveTypeKind?MappedType = ConvertType(ColumnType);

                if (!MappedType.HasValue)
                {
                    continue;
                }

                IEdmStructuralProperty NewColumn = DataSourceModel.AddStructuralProperty(ColumnName, MappedType.Value);

                if (sourceTable.PrimaryKey != null && sourceTable.PrimaryKey.Any(x => String.Equals(x.ColumnName, ColumnName, StringComparison.InvariantCultureIgnoreCase)))
                {
                    KeyProperties.Add(NewColumn);
                }
            }

            if (KeyProperties.Count > 0)
            {
                DataSourceModel.AddKeys(KeyProperties);
            }

            Output.AddElement(DataSourceModel);

            if (!String.IsNullOrWhiteSpace(entitySetName))
            {
                EdmEntityContainer OutputContainer = Output.AddEntityContainer("Dynamic", "Test");

                OutputContainer.AddEntitySet(entitySetName, DataSourceModel);
            }

            return(new Tuple <IEdmModel, IEdmType>(Output, DataSourceModel));
        }
        public override ODataProperty CreateStructuralProperty(IEdmStructuralProperty structuralProperty, ResourceContext resourceContext)
        {
            ODataProperty property = base.CreateStructuralProperty(structuralProperty, resourceContext);

            var instance = resourceContext.ResourceInstance;
            var parent   = resourceContext.SerializerContext.ExpandedResource;

            if (parent != null)
            {
                var parentInstance = parent.ResourceInstance;
            }

            return(property);
        }
Пример #30
0
            public override ODataProperty CreateStructuralProperty(IEdmStructuralProperty structuralProperty, EntityInstanceContext entityInstanceContext)
            {
                ODataProperty property = base.CreateStructuralProperty(structuralProperty, entityInstanceContext);

                // instance annotation on property
                if (property.Name == "Age")
                {
                    ODataPrimitiveValue dateValue = new ODataPrimitiveValue(new DateTimeOffset(new DateTime(2010, 1, 2)));
                    property.InstanceAnnotations.Add(new ODataInstanceAnnotation("Property.BirthdayAnnotation",
                                                                                 dateValue));
                }

                return(property);
            }
Пример #31
0
        public static void AddKeyValueToRouteData(this IWebApiControllerContext controllerContext, KeySegment segment, string keyName = "key")
        {
            Contract.Assert(controllerContext != null);
            Contract.Assert(segment != null);

            IDictionary <string, object> routingConventionsStore = controllerContext.Request.Context.RoutingConventionsStore;

            IEdmEntityType entityType = segment.EdmType as IEdmEntityType;

            Contract.Assert(entityType != null);

            int keyCount = segment.Keys.Count();

            foreach (var keyValuePair in segment.Keys)
            {
                bool alternateKey = false;
                // get the key property from the entity type
                IEdmStructuralProperty keyProperty = entityType.Key().FirstOrDefault(k => k.Name == keyValuePair.Key);
                if (keyProperty == null)
                {
                    // If it's alternate key.
                    keyProperty  = entityType.Properties().OfType <IEdmStructuralProperty>().FirstOrDefault(p => p.Name == keyValuePair.Key);
                    alternateKey = true;
                }
                Contract.Assert(keyProperty != null);

                // if there's only one key, provide two paramters, one using the given key name, e.g., "key, relatedKey"
                // and the other appending the property name to the given key name: "keyId, relatedKeyId"
                // in other cases, just append the property names to the given key name
                // so for multiple keys, the parameter name is "keyId1, keyId2..."
                // for navigation property, the parameter name is "relatedKeyId1, relatedKeyId2 ..."
                if (alternateKey || keyCount > 1)
                {
                    var newKeyName = keyName + keyValuePair.Key;
                    AddKeyValues(newKeyName, keyValuePair.Value, keyProperty.Type, controllerContext.RouteData, routingConventionsStore);
                }
                else
                {
                    AddKeyValues(keyName, keyValuePair.Value, keyProperty.Type, controllerContext.RouteData, routingConventionsStore);
                    if (keyCount == 1)
                    {
                        var anotherKeyName = keyName + keyValuePair.Key;
                        AddKeyValues(anotherKeyName, keyValuePair.Value, keyProperty.Type, controllerContext.RouteData, routingConventionsStore);
                    }
                }

                IncrementKeyCount(routingConventionsStore);
            }
        }
        private static bool IsEquivalentTo(this IEdmStructuralProperty thisProp, IEdmStructuralProperty otherProp)
        {
            if (thisProp == otherProp)
            {
                return(true);
            }

            if (thisProp == null || otherProp == null)
            {
                return(false);
            }

            return(thisProp.Name == otherProp.Name &&
                   thisProp.Type.IsEquivalentTo(otherProp.Type));
        }
Пример #33
0
        public void ExpandedNavigationPropertiesAreImplicitlyAddedAsPathSelectionItemsIfSelectIsPopulated()
        {
            IEdmNavigationProperty navigationProperty = ModelBuildingHelpers.BuildValidNavigationProperty();
            IEdmStructuralProperty structuralProperty = ModelBuildingHelpers.BuildValidPrimitiveProperty();
            SelectExpandClause     clause             = new SelectExpandClause(new SelectItem[]
            {
                new PathSelectItem(new ODataSelectPath(new PropertySegment(structuralProperty))),
                new ExpandedNavigationSelectItem(new ODataExpandPath(new NavigationPropertySegment(navigationProperty, ModelBuildingHelpers.BuildValidEntitySet())), ModelBuildingHelpers.BuildValidEntitySet(), new SelectExpandClause(new List <SelectItem>(), false)),
            },
                                                                               false /*allSelected*/);

            SelectExpandClauseFinisher.AddExplicitNavPropLinksWhereNecessary(clause);
            clause.SelectedItems.Should().HaveCount(2)
            .And.Contain(x => x is PathSelectItem && x.As <PathSelectItem>().SelectedPath.LastSegment is PropertySegment && x.As <PathSelectItem>().SelectedPath.LastSegment.As <PropertySegment>().Property.Name == structuralProperty.Name);
        }
        private EdmReferentialConstraintPropertyPair ComputeReferentialConstraintPropertyPair(CsdlReferentialConstraint csdlConstraint)
        {
            // <EntityType Name="Product">
            //   ...
            //   <Property Name="CategoryID" Type="Edm.String" Nullable="false"/>
            //  <NavigationProperty Name="Category" Type="Self.Category" Nullable="false">
            //     <ReferentialConstraint Property="CategoryID" ReferencedProperty="ID" />
            //   </NavigationProperty>
            // </EntityType>
            // the above CategoryID is DependentProperty, ID is PrincipalProperty.
            IEdmStructuralProperty dependentProperty = this.declaringType.FindProperty(csdlConstraint.PropertyName) as IEdmStructuralProperty ?? new UnresolvedProperty(this.declaringType, csdlConstraint.PropertyName, csdlConstraint.Location);
            IEdmStructuralProperty principalProperty = this.TargetEntityType.FindProperty(csdlConstraint.ReferencedPropertyName) as IEdmStructuralProperty ?? new UnresolvedProperty(this.ToEntityType(), csdlConstraint.ReferencedPropertyName, csdlConstraint.Location);

            return(new EdmReferentialConstraintPropertyPair(dependentProperty, principalProperty));
        }
Пример #35
0
 public override Task<ODataProperty> ReadPropertyAsync(IEdmStructuralProperty property, IEdmTypeReference expectedPropertyTypeReference)
 {
     return Task<ODataProperty>.Factory.StartNew(this.ReadPropertyImplementation);
 }
Пример #36
0
        private static void SetCoreChangeTrackingAnnotation(this EdmModel model, EdmEntitySet entitySet, IEdmStructuralProperty[] filterableProperties, IEdmNavigationProperty[] expandableProperties)
        {
            IEdmModel termModel = ReadTermModel("CoreCapabilities.csdl");
            IEdmValueTerm changeTracking = termModel.FindDeclaredValueTerm("Core.ChangeTracking");
            var exp = new EdmRecordExpression(
                new EdmPropertyConstructor("Supported", new EdmBooleanConstant(true)),

                new EdmPropertyConstructor("FilterableProperties", new EdmCollectionExpression(filterableProperties.Select(p => new EdmPropertyPathExpression(p.Name)))),
                new EdmPropertyConstructor("ExpandableProperties", new EdmCollectionExpression(expandableProperties.Select(p => new EdmPropertyPathExpression(p.Name)))));

            EdmAnnotation annotation = new EdmAnnotation(entitySet, changeTracking, exp);
            annotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
            model.AddVocabularyAnnotation(annotation);
        }
        /// <summary>
        /// Reads an <see cref="ODataProperty"/> as message payload.
        /// </summary>
        /// <param name="property">The metadata of the property to read.</param>
        /// <returns>The property read from the payload.</returns>
        public ODataProperty ReadProperty(IEdmStructuralProperty property)
        {
            if (this.testConfiguration.Synchronous)
            {
                return this.messageReader.ReadProperty(property);
            }
            else
            {
#if SILVERLIGHT || WINDOWS_PHONE
                throw new PlatformNotSupportedException("Asynchronous reading is only supported on desktop");
#else
                return this.messageReader.ReadPropertyAsync(property).WaitForResult();
#endif
            }
        }
            /// <summary>
            /// Constructor
            /// </summary>
            /// <param name="model">The model used to resolve the metadata.</param>
            /// <param name="payloadElement">The payload element to get the reader metadata for.</param>
            public ReaderMetadata(IEdmModel model, ODataPayloadElement payloadElement)
            {
                var expectedTypeAnnotation = payloadElement.GetAnnotation<ExpectedTypeODataPayloadElementAnnotation>();

                // NOTE: we don't require a model for the computation of the expected type (since the expected one might be a primitive type).
                this.expectedType = GetExpectedType(expectedTypeAnnotation, model);

                // We need a model for all the other expected reader metadata
                if (model == null)
                {
                    // If the annotation specified some model dependent data (basically anything but primitive expected type)
                    // and we don't have a model, we wouldn't be able to correctly represent it here (since we need the model to resolve these)
                    // and thus we should not pass in the expected type alone, as that would be changing the intent of the annotation.
                    if (expectedTypeAnnotation != null &&
                        (expectedTypeAnnotation.EntitySet != null ||
                         expectedTypeAnnotation.EdmEntitySet != null ||
                         expectedTypeAnnotation.FunctionImport != null ||
                         expectedTypeAnnotation.ProductFunctionImport != null ||
                         expectedTypeAnnotation.MemberProperty != null ||
                         expectedTypeAnnotation.EdmProperty != null ||
                         expectedTypeAnnotation.NavigationProperty != null ||
                         expectedTypeAnnotation.EdmNavigationProperty != null ||
                         expectedTypeAnnotation.OpenMemberPropertyName != null ||
                         expectedTypeAnnotation.OwningType != null ||
                         expectedTypeAnnotation.EdmOwningType != null))
                    {
                        this.expectedType = null;
                    }

                    return;
                }

                ODataPayloadElementType elementType = payloadElement.ElementType;
                switch (elementType)
                {
                    case ODataPayloadElementType.EntityInstance:    // fall through
                    case ODataPayloadElementType.EntitySetInstance:
                        this.entitySet = GetExpectedEntitySet(expectedTypeAnnotation, model, payloadElement);
                        break;

                    case ODataPayloadElementType.DeferredLink:      // fall through
                    case ODataPayloadElementType.LinkCollection:
                        this.navigationProperty = GetExpectedNavigationProperty(expectedTypeAnnotation, model);
                        break;

                    case ODataPayloadElementType.PrimitiveMultiValueProperty:   // fall through
                    case ODataPayloadElementType.PrimitiveProperty:             // fall through
                    case ODataPayloadElementType.ComplexProperty:               // fall through
                    case ODataPayloadElementType.ComplexMultiValueProperty:     // fall through
                    case ODataPayloadElementType.EmptyCollectionProperty:
                        this.structuralProperty = GetExpectedStructuralProperty(expectedTypeAnnotation, model);
                        this.functionImport = GetExpectedFunctionImport(expectedTypeAnnotation, model);
                        break;

                    case ODataPayloadElementType.ComplexInstanceCollection:     // fall through
                    case ODataPayloadElementType.PrimitiveCollection:           // fall through
                    case ODataPayloadElementType.EmptyUntypedCollection:
                        this.functionImport = GetExpectedFunctionImport(expectedTypeAnnotation, model);
                        break;

                    case ODataPayloadElementType.ComplexInstance:
                        // NOTE: this is how we model parameter payloads
                        this.functionImport = GetExpectedFunctionImport(expectedTypeAnnotation, model);
                        break;
                }
            }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="structuralProperty">The expected structural property reader metadata.</param>
 public ReaderMetadata(IEdmStructuralProperty structuralProperty)
 {
     this.expectedType = structuralProperty.Type;
     this.structuralProperty = structuralProperty;
 }
Пример #40
0
        /// <summary>
        /// Creates the <see cref="ODataProperty"/> to be written for the given entity and the structural property.
        /// </summary>
        /// <param name="structuralProperty">The EDM structural property being written.</param>
        /// <param name="entityInstanceContext">The context for the entity instance being written.</param>
        /// <returns>The <see cref="ODataProperty"/> to write.</returns>
        public virtual ODataProperty CreateStructuralProperty(IEdmStructuralProperty structuralProperty, EntityInstanceContext entityInstanceContext)
        {
            if (structuralProperty == null)
            {
                throw Error.ArgumentNull("structuralProperty");
            }
            if (entityInstanceContext == null)
            {
                throw Error.ArgumentNull("entityInstanceContext");
            }

            ODataSerializerContext writeContext = entityInstanceContext.SerializerContext;

            ODataEdmTypeSerializer serializer = SerializerProvider.GetEdmTypeSerializer(structuralProperty.Type);
            if (serializer == null)
            {
                throw new SerializationException(
                    Error.Format(SRResources.TypeCannotBeSerialized, structuralProperty.Type.FullName(), typeof(ODataMediaTypeFormatter).Name));
            }

            object propertyValue = entityInstanceContext.GetPropertyValue(structuralProperty.Name);

            IEdmTypeReference propertyType = structuralProperty.Type;
            if (propertyValue != null)
            {
                IEdmTypeReference actualType = writeContext.GetEdmType(propertyValue, propertyValue.GetType());
                if (propertyType != null && propertyType != actualType)
                {
                    propertyType = actualType;
                }
            }

            return serializer.CreateProperty(propertyValue, propertyType, structuralProperty.Name, writeContext);
        }
        /// <summary>
        /// Creates the <see cref="ODataProperty"/> to be written for the given entity and the structural property.
        /// </summary>
        /// <param name="structuralProperty">The EDM structural property being written.</param>
        /// <param name="entityInstance">The entity being written.</param>
        /// <param name="writeContext">The serializer context.</param>
        /// <returns>The <see cref="ODataProperty"/> to write.</returns>
        public virtual ODataProperty CreateStructuralProperty(IEdmStructuralProperty structuralProperty, object entityInstance, ODataSerializerContext writeContext)
        {
            if (structuralProperty == null)
            {
                throw Error.ArgumentNull("structuralProperty");
            }

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

            ODataEdmTypeSerializer serializer = SerializerProvider.GetEdmTypeSerializer(structuralProperty.Type);
            if (serializer == null)
            {
                throw new SerializationException(
                    Error.Format(SRResources.TypeCannotBeSerialized, structuralProperty.Type.FullName(), typeof(ODataMediaTypeFormatter).Name));
            }

            object propertyValue = entityInstance.GetType().GetProperty(structuralProperty.Name).GetValue(entityInstance, index: null);
            return serializer.CreateProperty(propertyValue, structuralProperty.Name, writeContext);
        }
Пример #42
0
        private IEdmStructuralProperty ConvertToStockStructuralProperty(IEdmStructuralProperty edmProperty, IEdmModel edmModel, EdmModel stockModel)
        {
            var stockPropertyDeclaringType = stockModel.FindType(GetFullName(edmProperty.DeclaringType)) as IEdmStructuredType;

            var stockProperty = new EdmStructuralProperty(
                                        stockPropertyDeclaringType,
                                        edmProperty.Name,
                                        ConvertToStockTypeReference(edmProperty.Type, stockModel),
                                        edmProperty.DefaultValueString,
                                        edmProperty.ConcurrencyMode
                                     );
            ((EdmStructuredType)stockPropertyDeclaringType).AddProperty(stockProperty);

            // TODO: Documentation
            this.SetImmediateAnnotations(edmProperty, stockProperty, edmModel, stockModel);

            return stockProperty;
        }
Пример #43
0
            public override ODataProperty CreateStructuralProperty(IEdmStructuralProperty structuralProperty, EntityInstanceContext entityInstanceContext)
            {
                ODataProperty property = base.CreateStructuralProperty(structuralProperty, entityInstanceContext);

                // instance annotation on property
                if (property.Name == "Age")
                {
                    ODataPrimitiveValue dateValue = new ODataPrimitiveValue(new Date(2010, 1, 2));
                    property.InstanceAnnotations.Add(new ODataInstanceAnnotation("Property.BirthdayAnnotation",
                        dateValue));
                }

                return property;
            }
Пример #44
0
 public override ODataProperty ReadProperty(IEdmStructuralProperty property, IEdmTypeReference expectedPropertyTypeReference)
 {
     return this.ReadPropertyImplementation();
 }
Пример #45
0
 /// <summary>
 /// Set the key (conveniece method)
 /// </summary>
 /// <param name="keyProperty">The first key property</param>
 /// <param name="additionalKeys">The rest key properties</param>
 public void SetKey(IEdmStructuralProperty keyProperty, params IEdmStructuralProperty[] additionalKeys)
 {
     this.SetKey(new[] { keyProperty }.Concat(additionalKeys));
 }
        /// <summary>
        /// Asynchronously read the property from the input and 
        /// return an <see cref="ODataProperty"/> representing the read property.
        /// </summary>
        /// <param name="property">The <see cref="IEdmProperty"/> producing the property to be read.</param>
        /// <param name="expectedPropertyTypeReference">The expected type reference of the property to read.</param>
        /// <returns>Task which when completed returns an <see cref="ODataProperty"/> representing the read property.</returns>
        public override Task<ODataProperty> ReadPropertyAsync(IEdmStructuralProperty property, IEdmTypeReference expectedPropertyTypeReference)
        {
            this.AssertAsynchronous();
            this.VerifyCanReadProperty();

            ODataJsonLightPropertyAndValueDeserializer jsonLightPropertyAndValueDeserializer = new ODataJsonLightPropertyAndValueDeserializer(this);
            return jsonLightPropertyAndValueDeserializer.ReadTopLevelPropertyAsync(expectedPropertyTypeReference);
        }
Пример #47
0
        internal static string GetExpectedPropertyName(IEdmStructuralProperty expectedProperty)
        {
            if (expectedProperty == null)
            {
                return null;
            }

            return expectedProperty.Name;
        }
Пример #48
0
        private static ExplorerItem GetStructuralChildItem(IEdmEntityType parentType, IEdmStructuralProperty property)
        {
            var icon = parentType.HasDeclaredKeyProperty(property)
                                                    ? ExplorerIcon.Key
                                                    : ExplorerIcon.Column;

            var name = $"{property.Name} ({property.Type.GetTypeName()})";
            var item = new ExplorerItem(name, ExplorerItemKind.Property, icon)
                                    {
                                        DragText = property.Name
                                    };

            return item;
        }
        private MemberProperty ConvertToTaupoProperty(IEdmStructuralProperty edmProperty)
        {
            var taupoProperty = new MemberProperty(edmProperty.Name);
            taupoProperty.PropertyType = this.ConvertToTaupoDataType(edmProperty.Type);

            if (edmProperty.ConcurrencyMode == EdmConcurrencyMode.Fixed)
            {
                taupoProperty.Add(new ConcurrencyTokenAnnotation());
            }

            if (!string.IsNullOrEmpty(edmProperty.DefaultValueString))
            {
                taupoProperty.DefaultValue = edmProperty.DefaultValueString;
            }

            this.ConvertAnnotationsIntoTaupo(edmProperty, taupoProperty);
            return taupoProperty;
        }
Пример #50
0
 /// <summary>
 /// Adds a key fragment to the key of the specified entity type.
 /// </summary>
 /// <param name="entityType">The entity type to add the key fragment to.</param>
 /// <param name="keyProperty">The key property to add.</param>
 private static void AddKeyFragment(EdmEntityType entityType, IEdmStructuralProperty keyProperty)
 {
     Debug.Assert(entityType != null, "entityType != null");
     Debug.Assert(keyProperty != null, "keyProperty != null");
     entityType.AddKeys(keyProperty);
 }
Пример #51
0
		public void AddKeys(IEdmStructuralProperty[] keyProperties)
		{
			this.AddKeys((IEnumerable<IEdmStructuralProperty>)keyProperties);
		}
Пример #52
0
 /// <summary>
 /// This method creates and reads the property from the input and 
 /// returns an <see cref="ODataProperty"/> representing the read property.
 /// </summary>
 /// <param name="property">The <see cref="IEdmProperty"/> producing the property to be read.</param>
 /// <param name="expectedPropertyTypeReference">The expected type reference of the property to read.</param>
 /// <returns>An <see cref="ODataProperty"/> representing the read property.</returns>
 private ODataProperty ReadPropertyImplementation(IEdmStructuralProperty property, IEdmTypeReference expectedPropertyTypeReference)
 {
     ODataAtomPropertyAndValueDeserializer atomPropertyAndValueDeserializer = new ODataAtomPropertyAndValueDeserializer(this);
     return atomPropertyAndValueDeserializer.ReadTopLevelProperty(property, expectedPropertyTypeReference);
 }
Пример #53
0
        private static bool IsEquivalentTo(this IEdmStructuralProperty thisProp, IEdmStructuralProperty otherProp)
        {
            if (thisProp == otherProp)
            {
                return true;
            }

            if (thisProp == null || otherProp == null)
            {
                return false;
            }

            return thisProp.Name == otherProp.Name &&
                   thisProp.Type.IsEquivalentTo(otherProp.Type);
        }
Пример #54
0
        /// <summary>
        /// Asynchronously read the property from the input and 
        /// return an <see cref="ODataProperty"/> representing the read property.
        /// </summary>
        /// <param name="property">The <see cref="IEdmProperty"/> or <see cref="IEdmOperationImport"/> producing the property to be read.</param>
        /// <param name="expectedPropertyTypeReference">The expected type reference of the property to read.</param>
        /// <returns>Task which when completed returns an <see cref="ODataProperty"/> representing the read property.</returns>
        public override Task<ODataProperty> ReadPropertyAsync(IEdmStructuralProperty property, IEdmTypeReference expectedPropertyTypeReference)
        {
            this.AssertAsynchronous();

            // Note that the reading is actually synchronous since we buffer the entire input when getting the stream from the message.
            return TaskUtils.GetTaskForSynchronousOperation(() => this.ReadPropertyImplementation(property, expectedPropertyTypeReference));
        }
Пример #55
0
        /// <summary>
        /// This method creates an reads the property from the input and 
        /// returns an <see cref="ODataProperty"/> representing the read property.
        /// </summary>
        /// <param name="property">The <see cref="IEdmProperty"/> producing the property to be read.</param>
        /// <param name="expectedPropertyTypeReference">The expected type reference of the property to read.</param>
        /// <returns>An <see cref="ODataProperty"/> representing the read property.</returns>
        public override ODataProperty ReadProperty(IEdmStructuralProperty property, IEdmTypeReference expectedPropertyTypeReference)
        {
            this.AssertSynchronous();

            return this.ReadPropertyImplementation(property, expectedPropertyTypeReference);
        }
Пример #56
0
            private bool TryFindProperty(OdcmClass odcmClass, IEdmStructuralProperty keyProperty, out OdcmProperty odcmProperty)
            {
                if (odcmClass == null)
                {
                    odcmProperty = null;
                    return false;
                }

                foreach (OdcmProperty property in odcmClass.Properties)
                {
                    if (property.Name.Equals(keyProperty.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        odcmProperty = property;
                        return true;
                    }
                }

                return TryFindProperty(odcmClass.Base, keyProperty, out odcmProperty);
            }
Пример #57
0
 /// <summary>
 /// Adds a structural property
 /// </summary>
 /// <param name="structuralProperty">The structural property</param>
 public void Add(IEdmStructuralProperty structuralProperty)
 {
     this.declaredProperties.Add(structuralProperty);
     StubEdmStructuralProperty stubStructuralProperty = structuralProperty as StubEdmStructuralProperty;
     if (stubStructuralProperty != null)
     {
         stubStructuralProperty.DeclaringType = this;
     }
 }
Пример #58
0
 /// <summary>
 /// Asynchronously read the property from the input and 
 /// return an <see cref="ODataProperty"/> representing the read property.
 /// </summary>
 /// <param name="property">The <see cref="IEdmProperty"/> producing the property to be read.</param>
 /// <param name="expectedPropertyTypeReference">The expected type reference of the property to read.</param>
 /// <returns>Task which when completed returns an <see cref="ODataProperty"/> representing the read property.</returns>
 public virtual Task<ODataProperty> ReadPropertyAsync(IEdmStructuralProperty property, IEdmTypeReference expectedPropertyTypeReference)
 {
     throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Property);
 }