internal static void ApplyProperty(ODataProperty property, IEdmStructuredTypeReference resourceType, object resource, ODataDeserializerProvider deserializerProvider, ODataDeserializerContext readContext)
        {
            IEdmProperty edmProperty = resourceType.FindProperty(property.Name);

            string propertyName = property.Name;
            IEdmTypeReference propertyType = edmProperty != null ? edmProperty.Type : null; // open properties have null values

            // If we are in patch mode and we are deserializing an entity object then we are updating Delta<T> and not T.
            bool isDelta = readContext.IsPatchMode && resourceType.IsEntity();

            EdmTypeKind propertyKind;
            object value = ConvertValue(property.Value, ref propertyType, deserializerProvider, readContext, out propertyKind);

            if (propertyKind == EdmTypeKind.Collection)
            {
                SetCollectionProperty(resource, propertyName, isDelta, value);
            }
            else
            {
                if (propertyKind == EdmTypeKind.Primitive)
                {
                    value = EdmPrimitiveHelpers.ConvertPrimitiveValue(value, GetPropertyType(resource, propertyName, isDelta));
                }

                SetProperty(resource, propertyName, isDelta, value);
            }
        }
        internal static void ApplyProperty(ODataProperty property, IEdmStructuredTypeReference resourceType, object resource,
            ODataDeserializerProvider deserializerProvider, ODataDeserializerContext readContext)
        {
            IEdmProperty edmProperty = resourceType.FindProperty(property.Name);

            string propertyName = property.Name;
            IEdmTypeReference propertyType = edmProperty != null ? edmProperty.Type : null; // open properties have null values

            EdmTypeKind propertyKind;
            object value = ConvertValue(property.Value, ref propertyType, deserializerProvider, readContext, out propertyKind);

            if (propertyKind == EdmTypeKind.Collection)
            {
                SetCollectionProperty(resource, edmProperty, value);
            }
            else
            {
                if (propertyKind == EdmTypeKind.Primitive && !readContext.IsUntyped)
                {
                    value = EdmPrimitiveHelpers.ConvertPrimitiveValue(value, GetPropertyType(resource, propertyName));
                }

                SetProperty(resource, propertyName, value);
            }
        }
 protected void ApplyProperty(ODataProperty property, ResourceType resourceType, object resource)
 {
     ResourceType type;
     string name = property.Name;
     ResourceProperty resourceProperty = resourceType.TryResolvePropertyName(name);
     if (resourceProperty == null)
     {
         type = null;
     }
     else
     {
         if (resourceProperty.Kind == ResourcePropertyKind.Stream)
         {
             return;
         }
         if (base.Update && resourceProperty.IsOfKind(ResourcePropertyKind.Key))
         {
             return;
         }
         type = resourceProperty.ResourceType;
     }
     object propertyValue = this.ConvertValue(property.Value, ref type);
     if (resourceProperty == null)
     {
         Deserializer.SetOpenPropertyValue(resource, name, propertyValue, base.Service);
     }
     else
     {
         Deserializer.SetPropertyValue(resourceProperty, resource, propertyValue, base.Service);
     }
 }
 private static void AddEntryProperty(IODataJsonReaderEntryState entryState, string propertyName, object propertyValue)
 {
     ODataProperty property = new ODataProperty {
         Name = propertyName,
         Value = propertyValue
     };
     entryState.DuplicatePropertyNamesChecker.CheckForDuplicatePropertyNames(property);
     ReaderUtils.AddPropertyToPropertiesList(entryState.Entry.Properties, property);
 }
        /// <summary>
        /// Validates an <see cref="ODataProperty"/> for not being null.
        /// </summary>
        /// <param name="property">The property to validate for not being null.</param>
        internal static void ValidatePropertyNotNull(ODataProperty property)
        {
            DebugUtils.CheckNoExternalCallers();

            if (property == null)
            {
                throw new ODataException(Strings.WriterValidationUtils_PropertyMustNotBeNull);
            }
        }
        /// <summary>
        /// Deserializes the primitive from the given <paramref name="primitiveProperty"/> under the given <paramref name="readContext"/>.
        /// </summary>
        /// <param name="primitiveProperty">The primitive property to deserialize.</param>
        /// <param name="readContext">The deserializer context.</param>
        /// <returns>The deserialized OData primitive value.</returns>
        public virtual object ReadPrimitive(ODataProperty primitiveProperty, ODataDeserializerContext readContext)
        {
            if (primitiveProperty == null)
            {
                throw Error.ArgumentNull("primitiveProperty");
            }

            return primitiveProperty.Value;
        }
Esempio n. 7
0
 private void AddEpmPropertyValue(List<ODataProperty> properties, string propertyName, object propertyValue, bool checkDuplicateEntryPropertyNames)
 {
     ODataProperty property = new ODataProperty {
         Name = propertyName,
         Value = propertyValue
     };
     if (checkDuplicateEntryPropertyNames)
     {
         this.entryState.DuplicatePropertyNamesChecker.CheckForDuplicatePropertyNames(property);
     }
     properties.Add(property);
 }
        /// <summary>
        /// Validates an <see cref="ODataProperty"/> to ensure all required information is specified.
        /// </summary>
        /// <param name="property">The property to validate (must not be null, call ValidatePropertyNotNull before).</param>
        internal static void ValidateProperty(ODataProperty property)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(property != null, "property != null");

            // Properties must have a non-empty name
            string propertyName = property.Name;
            if (string.IsNullOrEmpty(propertyName))
            {
                throw new ODataException(Strings.WriterValidationUtils_PropertiesMustHaveNonEmptyName);
            }

            ValidationUtils.ValidatePropertyName(propertyName);
        }
 internal void CheckForDuplicatePropertyNames(ODataProperty property)
 {
     DuplicationRecord record;
     string name = property.Name;
     DuplicationKind duplicationKind = GetDuplicationKind(property);
     if (!this.TryGetDuplicationRecord(name, out record))
     {
         this.propertyNameCache.Add(name, new DuplicationRecord(duplicationKind));
     }
     else if ((((record.DuplicationKind == DuplicationKind.Prohibited) || (duplicationKind == DuplicationKind.Prohibited)) || ((record.DuplicationKind == DuplicationKind.NavigationProperty) && record.AssociationLinkFound)) || !this.allowDuplicateProperties)
     {
         throw new ODataException(Strings.DuplicatePropertyNamesChecker_DuplicatePropertyNamesNotAllowed(name));
     }
 }
        public void ReadInline_Calls_ReadPrimitive()
        {
            // Arrange
            IEdmPrimitiveTypeReference primitiveType = EdmCoreModel.Instance.GetInt32(isNullable: true);
            Mock<ODataPrimitiveDeserializer> deserializer = new Mock<ODataPrimitiveDeserializer>();
            ODataProperty property = new ODataProperty();
            ODataDeserializerContext readContext = new ODataDeserializerContext();

            deserializer.Setup(d => d.ReadPrimitive(property, readContext)).Returns(42).Verifiable();

            // Act
            var result = deserializer.Object.ReadInline(property, primitiveType, readContext);

            // Assert
            deserializer.Verify();
            Assert.Equal(42, result);
        }
        /// <summary>
        /// Validates a stream reference property.
        /// </summary>
        /// <param name="streamProperty">The stream property to check.</param>
        /// <param name="structuredType">The owning type of the stream property or null if no metadata is available.</param>
        /// <param name="streamEdmProperty">The stream property defined by the model.</param>
        internal static void ValidateStreamReferenceProperty(ODataProperty streamProperty, IEdmStructuredType structuredType, IEdmProperty streamEdmProperty)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(streamProperty != null, "streamProperty != null");

            ValidationUtils.ValidateStreamReferenceProperty(streamProperty, streamEdmProperty);

            if (structuredType != null && structuredType.IsOpen)
            {
                // If no property match was found in the metadata and an error wasn't raised, 
                // it is an open property (which is not supported for streams).
                if (streamEdmProperty == null)
                {
                    // Fails with the correct error message.
                    ValidationUtils.ValidateOpenPropertyValue(streamProperty.Name, streamProperty.Value);
                }
            }
        }
        internal static void ApplyProperty(ODataProperty property, IEdmStructuredTypeReference resourceType, object resource, ODataDeserializerProvider deserializerProvider, ODataDeserializerReadContext readContext)
        {
            IEdmProperty edmProperty = resourceType.FindProperty(property.Name);

            string propertyName = property.Name;
            IEdmTypeReference propertyType = edmProperty != null ? edmProperty.Type : null; // open properties have null values

            object value = ConvertValue(property.Value, ref propertyType, deserializerProvider, readContext);

            // If we are in patch mode and we are deserializing an entity object then we are updating Delta<T> and not T.
            if (!readContext.IsPatchMode || !resourceType.IsEntity())
            {
                resource.GetType().GetProperty(propertyName).SetValue(resource, value, index: null);
            }
            else
            {
                (resource as IDelta).TrySetPropertyValue(propertyName, value);
            }
        }
        /// <summary>
        /// Writes a single property in ATOM format.
        /// </summary>
        /// <param name="property">The property to write out.</param>
        internal void WriteTopLevelProperty(ODataProperty property)
        {
            DebugUtils.CheckNoExternalCallers();

            this.WritePayloadStart();
            this.AssertRecursionDepthIsZero();
            this.WriteProperty(
                property,
                null  /* owningType */,
                true  /* isTopLevel */,
                false /* isWritingCollection */,
                null  /* beforePropertyAction */,
                null  /* epmValueCache */,
                null  /* epmParentSourcePathSegment */,
                this.CreateDuplicatePropertyNamesChecker(),
                null  /* projectedProperties */);
            this.AssertRecursionDepthIsZero();
            this.WritePayloadEnd();
        }
        /// <summary>
        /// Check the <paramref name="property"/> for duplicate property names in an entry or complex value.
        /// If not explicitly allowed throw when duplicate properties are detected.
        /// If duplicate properties are allowed see the comment on ODataWriterBehavior.AllowDuplicatePropertyNames
        /// or ODataReaderBehavior.AllowDuplicatePropertyNames for further details.
        /// </summary>
        /// <param name="property">The property to be checked.</param>
        internal void CheckForDuplicatePropertyNames(ODataProperty property)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(property != null, "property != null");
#if DEBUG
            Debug.Assert(this.startNavigationLinkName == null, "CheckForDuplicatePropertyNamesOnNavigationLinkStart was followed by a CheckForDuplicatePropertyNames(ODataProperty).");
#endif

            string            propertyName    = property.Name;
            DuplicationKind   duplicationKind = GetDuplicationKind(property);
            DuplicationRecord existingDuplicationRecord;
            if (!this.TryGetDuplicationRecord(propertyName, out existingDuplicationRecord))
            {
                this.propertyNameCache.Add(propertyName, new DuplicationRecord(duplicationKind));
            }
            else if (existingDuplicationRecord.DuplicationKind == DuplicationKind.PropertyAnnotationSeen)
            {
                existingDuplicationRecord.DuplicationKind = duplicationKind;
            }
            else
            {
                // If either of them prohibits duplication, fail
                // If the existing one is an association link, fail (association links don't allow duplicates with simple properties)
                // If we don't allow duplication in the first place, fail, since there is no valid case where a simple property coexists with anything else with the same name.
                if (existingDuplicationRecord.DuplicationKind == DuplicationKind.Prohibited ||
                    duplicationKind == DuplicationKind.Prohibited ||
                    (existingDuplicationRecord.DuplicationKind == DuplicationKind.NavigationProperty && existingDuplicationRecord.AssociationLink != null) ||
                    !this.allowDuplicateProperties)
                {
                    throw new ODataException(Strings.DuplicatePropertyNamesChecker_DuplicatePropertyNamesNotAllowed(propertyName));
                }
                else
                {
                    // Otherwise allow the duplicate.
                    // Note that we don't modify the existing duplication record in any way if the new property is a simple property.
                    // This is because if the existing one is a simple property which allows duplication as well, there's nothing to change.
                    // and if the existing one is a navigation property the navigation property information is more important than the simple property one.
                }
            }
        }
Esempio n. 15
0
 protected static void ApplyCollectionDataValues(ODataProperty collectionProperty, bool ignoreMissingProperties, System.Data.Services.Client.ResponseInfo responseInfo, object collectionInstance, Type collectionItemType, Action<object, object> AddValueToBackingICollectionInstance)
 {
     ODataCollectionValue value2 = collectionProperty.Value as ODataCollectionValue;
     if (value2.Items != null)
     {
         bool flag = PrimitiveType.IsKnownNullableType(collectionItemType);
         ClientEdmModel model = ClientEdmModel.GetModel(responseInfo.MaxProtocolVersion);
         foreach (object obj2 in value2.Items)
         {
             if (obj2 == null)
             {
                 throw System.Data.Services.Client.Error.InvalidOperation(System.Data.Services.Client.Strings.Collection_NullCollectionItemsNotSupported);
             }
             if (flag)
             {
                 object obj3;
                 if ((obj2 is ODataComplexValue) || (obj2 is ODataCollectionValue))
                 {
                     throw System.Data.Services.Client.Error.InvalidOperation(System.Data.Services.Client.Strings.Collection_ComplexTypesInCollectionOfPrimitiveTypesNotAllowed);
                 }
                 MaterializePrimitiveDataValue(collectionItemType, value2.TypeName, obj2, responseInfo, () => System.Data.Services.Client.Strings.Collection_NullCollectionItemsNotSupported, out obj3);
                 AddValueToBackingICollectionInstance(collectionInstance, ConvertPrimitiveValue(obj2, collectionItemType));
             }
             else
             {
                 ODataComplexValue value3 = obj2 as ODataComplexValue;
                 if (value3 == null)
                 {
                     throw System.Data.Services.Client.Error.InvalidOperation(System.Data.Services.Client.Strings.Collection_PrimitiveTypesInCollectionOfComplexTypesNotAllowed);
                 }
                 ClientTypeAnnotation clientTypeAnnotation = model.GetClientTypeAnnotation(model.GetOrCreateEdmType(collectionItemType));
                 object instance = clientTypeAnnotation.CreateInstance();
                 ApplyDataValues(clientTypeAnnotation, value3.Properties, ignoreMissingProperties, responseInfo, instance);
                 AddValueToBackingICollectionInstance(collectionInstance, instance);
             }
         }
     }
     collectionProperty.SetMaterializedValue(collectionInstance);
 }
        public override ODataProperty CreateProperty(object graph, string elementName, ODataSerializerWriteContext writeContext)
        {
            if (String.IsNullOrWhiteSpace(elementName))
            {
                throw Error.ArgumentNullOrEmpty("elementName");
            }

            string value = null;

            if (graph != null)
            {
                // TODO: Bug 453831: [OData] Figure out how OData serializes enum flags
                value = graph.ToString();
            }

            ODataProperty property = new ODataProperty()
            {
                Name = elementName,
                Value = value
            };

            return property;
        }
        /// <summary>
        /// Write an <see cref="ODataProperty" /> to the given stream. This method creates an
        /// async buffered stream and writes the property to it.
        /// </summary>
        /// <param name="property">The property to write.</param>
        internal void WriteTopLevelProperty(ODataProperty property)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(property != null, "property != null");
            Debug.Assert(!(property.Value is ODataStreamReferenceValue), "!(property.Value is ODataStreamReferenceValue)");

            this.WriteTopLevelPayload(
                () =>
                {
                    this.JsonWriter.StartObjectScope();

                    // Note we do not allow named stream properties to be written as top level property.
                    this.AssertRecursionDepthIsZero();
                    this.WriteProperty(
                        property,
                        null /* owningType */,
                        false /* allowStreamProperty */,
                        this.CreateDuplicatePropertyNamesChecker(),
                        null /* projectedProperties */);
                    this.AssertRecursionDepthIsZero();

                    this.JsonWriter.EndObjectScope();
                });
        }
        public void CreateEntry_Calls_CreateStructuralPropertyBag()
        {
            // Arrange
            ODataProperty[] properties = new ODataProperty[] { new ODataProperty(), new ODataProperty() };
            EntityInstanceContext entityInstanceContext = new EntityInstanceContext();
            Mock<ODataEntityTypeSerializer> serializer = new Mock<ODataEntityTypeSerializer>(_serializer.EdmType, new DefaultODataSerializerProvider());

            serializer.CallBase = true;
            serializer.Setup(s => s.CreateODataActions(entityInstanceContext, _writeContext)).Returns(Enumerable.Empty<ODataAction>());
            serializer.Setup(s => s.CreateStructuralPropertyBag(entityInstanceContext, _writeContext)).Returns(properties).Verifiable();

            // Act
            ODataEntry entry = serializer.Object.CreateEntry(entityInstanceContext, _writeContext);

            // Assert
            serializer.Verify();
            Assert.Same(properties, entry.Properties);
        }
Esempio n. 19
0
 internal virtual Task WritePropertyAsync(ODataProperty property)
 {
     throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Property);
 }
        /// <summary>
        /// Reads a complex value.
        /// </summary>
        /// <param name="complexValueTypeReference">The expected type reference of the value.</param>
        /// <param name="payloadTypeName">The type name read from the payload.</param>
        /// <param name="serializationTypeNameAnnotation">The serialization type name for the collection value (possibly null).</param>
        /// <param name="duplicatePropertyNamesChecker">The duplicate property names checker to use - if null the method should create a new one if necessary.</param>
        /// <returns>The value of the complex value.</returns>
        /// <remarks>
        /// Pre-Condition:  Fails if the current node is not a JsonNodeType.StartObject or JsonNodeType.PrimitiveValue (with null value)
        /// Post-Condition: almost anything - the node after the complex value (after the EndObject)
        /// </remarks>
        private ODataComplexValue ReadComplexValueImplementation(
            IEdmComplexTypeReference complexValueTypeReference, 
            string payloadTypeName,
            SerializationTypeNameAnnotation serializationTypeNameAnnotation,
            DuplicatePropertyNamesChecker duplicatePropertyNamesChecker)
        {
            this.JsonReader.AssertNotBuffering();

            this.IncreaseRecursionDepth();

            // Read over the start object
            this.JsonReader.ReadStartObject();

            ODataComplexValue complexValue = new ODataComplexValue();

            complexValue.TypeName = complexValueTypeReference != null ? complexValueTypeReference.ODataFullName() : payloadTypeName; 
            if (serializationTypeNameAnnotation != null)
            {
                complexValue.SetAnnotation(serializationTypeNameAnnotation);
            }

            if (duplicatePropertyNamesChecker == null)
            {
                duplicatePropertyNamesChecker = this.CreateDuplicatePropertyNamesChecker();
            }
            else
            {
                duplicatePropertyNamesChecker.Clear();
            }

            List<ODataProperty> properties = new List<ODataProperty>();
            bool metadataPropertyFound = false;
            while (this.JsonReader.NodeType == JsonNodeType.Property)
            {
                string propertyName = this.JsonReader.ReadPropertyName();
                if (string.CompareOrdinal(JsonConstants.ODataMetadataName, propertyName) == 0)
                {
                    // __metadata property.
                    if (metadataPropertyFound)
                    {
                        throw new ODataException(o.Strings.ODataJsonPropertyAndValueDeserializer_MultipleMetadataPropertiesInComplexValue);
                    }

                    metadataPropertyFound = true;

                    this.JsonReader.SkipValue();
                }
                else
                {
                    if (!ValidationUtils.IsValidPropertyName(propertyName))
                    {
                        // We ignore properties with an invalid name since these are extension points for the future.
                        this.JsonReader.SkipValue();
                    }
                    else
                    {
                        // Any other property is data
                        ODataProperty property = new ODataProperty();
                        property.Name = propertyName;

                        // Lookup the property in metadata
                        IEdmProperty edmProperty = null;
                        bool ignoreProperty = false;
                        if (complexValueTypeReference != null)
                        {
                            edmProperty = ReaderValidationUtils.ValidateValuePropertyDefined(propertyName, complexValueTypeReference.ComplexDefinition(), this.MessageReaderSettings, out ignoreProperty);
                        }

                        if (ignoreProperty)
                        {
                            this.JsonReader.SkipValue();
                        }
                        else
                        {
                            ODataNullValueBehaviorKind nullValueReadBehaviorKind = this.ReadingResponse || edmProperty == null
                                ? ODataNullValueBehaviorKind.Default
                                : this.Model.NullValueReadBehaviorKind(edmProperty);

                            // Read the property value
                            object propertyValue = this.ReadNonEntityValueImplementation(
                                edmProperty == null ? null : edmProperty.Type,
                                /*duplicatePropertyNamesChecker*/ null,
                                /*collectionValidator*/ null,
                                nullValueReadBehaviorKind == ODataNullValueBehaviorKind.Default);

                            if (nullValueReadBehaviorKind != ODataNullValueBehaviorKind.IgnoreValue || propertyValue != null)
                            {
                                duplicatePropertyNamesChecker.CheckForDuplicatePropertyNames(property);
                                property.Value = propertyValue;
                                properties.Add(property);
                            }
                        }
                    }
                }
            }

            Debug.Assert(this.JsonReader.NodeType == JsonNodeType.EndObject, "After all the properties of a complex value are read the EndObject node is expected.");
            this.JsonReader.ReadEndObject();

            complexValue.Properties = new ReadOnlyEnumerable<ODataProperty>(properties);

            this.JsonReader.AssertNotBuffering();
            this.DecreaseRecursionDepth();

            return complexValue;
        }
 internal void WriteStreamProperty(ODataProperty streamProperty, IEdmEntityType owningType, DuplicatePropertyNamesChecker duplicatePropertyNamesChecker, ProjectedPropertiesAnnotation projectedProperties)
 {
     WriterValidationUtils.ValidatePropertyNotNull(streamProperty);
     string name = streamProperty.Name;
     if (!projectedProperties.ShouldSkipProperty(name))
     {
         WriterValidationUtils.ValidateProperty(streamProperty);
         duplicatePropertyNamesChecker.CheckForDuplicatePropertyNames(streamProperty);
         IEdmProperty edmProperty = WriterValidationUtils.ValidatePropertyDefined(streamProperty.Name, owningType);
         WriterValidationUtils.ValidateStreamReferenceProperty(streamProperty, edmProperty, base.Version, base.WritingResponse);
         ODataStreamReferenceValue value2 = (ODataStreamReferenceValue) streamProperty.Value;
         if (((owningType != null) && owningType.IsOpen) && (edmProperty == null))
         {
             ValidationUtils.ValidateOpenPropertyValue(streamProperty.Name, value2);
         }
         AtomStreamReferenceMetadata annotation = value2.GetAnnotation<AtomStreamReferenceMetadata>();
         string contentType = value2.ContentType;
         string title = streamProperty.Name;
         Uri readLink = value2.ReadLink;
         if (readLink != null)
         {
             string relation = AtomUtils.ComputeStreamPropertyRelation(streamProperty, false);
             AtomLinkMetadata metadata = (annotation == null) ? null : annotation.SelfLink;
             AtomLinkMetadata linkMetadata = ODataAtomWriterMetadataUtils.MergeLinkMetadata(metadata, relation, readLink, title, contentType);
             this.atomEntryMetadataSerializer.WriteAtomLink(linkMetadata, null);
         }
         Uri editLink = value2.EditLink;
         if (editLink != null)
         {
             string str5 = AtomUtils.ComputeStreamPropertyRelation(streamProperty, true);
             AtomLinkMetadata metadata4 = (annotation == null) ? null : annotation.EditLink;
             AtomLinkMetadata metadata5 = ODataAtomWriterMetadataUtils.MergeLinkMetadata(metadata4, str5, editLink, title, contentType);
             this.atomEntryMetadataSerializer.WriteAtomLink(metadata5, value2.ETag);
         }
     }
 }
        /// <summary>
        /// Returns an existing stream property value if it already exists in the list of OData properties otherwise creates a new 
        /// ODataProperty for the stream property and returns the value of that property.
        /// </summary>
        /// <param name="entryState">The reader entry state for the entry being read.</param>
        /// <param name="streamPropertyName">The name of the stream property to return.</param>
        /// <returns>A new or an existing stream property value.</returns>
        private ODataStreamReferenceValue GetNewOrExistingStreamPropertyValue(IODataAtomReaderEntryState entryState, string streamPropertyName)
        {
            Debug.Assert(entryState != null, "entryState != null");
            Debug.Assert(streamPropertyName != null, "streamPropertyName != null");

            List<ODataProperty> properties = ReaderUtils.GetPropertiesList(entryState.Entry.Properties);

            // Property names are case sensitive, so compare in a case sensitive way.
            ODataProperty streamProperty = properties.FirstOrDefault(p => String.CompareOrdinal(p.Name, streamPropertyName) == 0);

            ODataStreamReferenceValue streamReferenceValue;
            if (streamProperty == null)
            {
                // The ValidateLinkPropertyDefined will fail if a stream property is not defined and the reader settings don't allow
                // reporting undeclared link properties. So if the method returns null, it means report the undeclared property anyway.
                IEdmProperty streamEdmProperty = ReaderValidationUtils.ValidateLinkPropertyDefined(streamPropertyName, entryState.EntityType, this.MessageReaderSettings);

                streamReferenceValue = new ODataStreamReferenceValue();
                streamProperty = new ODataProperty
                {
                    Name = streamPropertyName,
                    Value = streamReferenceValue
                };

                ReaderValidationUtils.ValidateStreamReferenceProperty(streamProperty, entryState.EntityType, streamEdmProperty);
                entryState.DuplicatePropertyNamesChecker.CheckForDuplicatePropertyNames(streamProperty);
                properties.Add(streamProperty);
            }
            else
            {
                streamReferenceValue = streamProperty.Value as ODataStreamReferenceValue;
                if (streamReferenceValue == null)
                {
                    throw new ODataException(o.Strings.ODataAtomEntryAndFeedDeserializer_StreamPropertyDuplicatePropertyName(streamPropertyName));
                }
            }

            return streamReferenceValue;
        }
Esempio n. 23
0
 /// <summary>
 /// Adds a property to the Properties collection which must have been previously populated by CreateNewEntry.
 /// </summary>
 /// <param name="properties">The value of the Properties property to add the property to.</param>
 /// <param name="propertyToAdd">The property to add.</param>
 internal static void AddPropertyToPropertiesList(IEnumerable <ODataProperty> properties, ODataProperty propertyToAdd)
 {
     DebugUtils.CheckNoExternalCallers();
     Debug.Assert(propertyToAdd != null, "propertyToAdd != null");
     ReaderUtils.GetPropertiesList(properties).Add(propertyToAdd);
 }
        public void ApplyStructuralProperty_SetsProperty()
        {
            // Arrange
            var deserializer = new ODataEntityDeserializer(_productEdmType, _deserializerProvider);
            Product product = new Product();
            ODataProperty property = new ODataProperty { Name = "ID", Value = 42 };

            // Act
            deserializer.ApplyStructuralProperty(product, property, _readContext);

            // Assert
            Assert.Equal(42, product.ID);
        }
Esempio n. 25
0
 /// <summary>
 /// Asynchronously writes an <see cref="ODataProperty"/> as message payload.
 /// </summary>
 /// <param name="property">The property to write</param>
 /// <returns>A task representing the asynchronous operation of writing the property.</returns>
 /// <remarks>It is the responsibility of this method to flush the output before the task finishes.</remarks>
 internal virtual Task WritePropertyAsync(ODataProperty property)
 {
     DebugUtils.CheckNoExternalCallers();
     throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Property);
 }
        internal static void ApplyProperty(ODataProperty property, IEdmStructuredTypeReference resourceType, object resource, ODataDeserializerProvider deserializerProvider, ODataDeserializerContext readContext)
        {
            IEdmProperty edmProperty = resourceType.FindProperty(property.Name);

            string propertyName = property.Name;
            IEdmTypeReference propertyType = edmProperty != null ? edmProperty.Type : null; // open properties have null values

            bool isDelta = readContext.IsPatchMode && resourceType.IsEntity();

            if (isDelta && resourceType.AsEntity().Key().Select(key => key.Name).Contains(propertyName))
            {
                // we are patching a key property.
                if (readContext.PatchKeyMode == PatchKeyMode.Ignore)
                {
                    return;
                }
                else if (readContext.PatchKeyMode == PatchKeyMode.Throw)
                {
                    throw Error.InvalidOperation(SRResources.CannotPatchKeyProperty, propertyName, resourceType.FullName(), typeof(PatchKeyMode).Name, PatchKeyMode.Throw);
                }
            }

            EdmTypeKind propertyKind;
            object value = ConvertValue(property.Value, ref propertyType, deserializerProvider, readContext, out propertyKind);

            if (propertyKind == EdmTypeKind.Primitive)
            {
                value = ConvertPrimitiveValue(value, GetPropertyType(resource, propertyName, isDelta), propertyName, resource.GetType().FullName);
            }

            SetProperty(resource, propertyName, isDelta, value);
        }
Esempio n. 27
0
 public void WriteProperty(ODataProperty property)
 {
     this.VerifyCanWriteProperty(property);
     this.WriteToOutput(ODataPayloadKind.Property, null, context => context.WriteProperty(property));
 }
        /// <summary>
        /// Deserializes the given <paramref name="structuralProperty"/> into <paramref name="entityResource"/>.
        /// </summary>
        /// <param name="entityResource">The object into which the structural property should be read.</param>
        /// <param name="structuralProperty">The entry object containing the structural properties.</param>
        /// <param name="entityType">The entity type of the entity resource.</param>
        /// <param name="readContext">The deserializer context.</param>
        public virtual void ApplyStructuralProperty(object entityResource, ODataProperty structuralProperty,
            IEdmEntityTypeReference entityType, ODataDeserializerContext readContext)
        {
            if (entityResource == null)
            {
                throw Error.ArgumentNull("entityResource");
            }

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

            DeserializationHelpers.ApplyProperty(structuralProperty, entityType, entityResource, DeserializerProvider, readContext);
        }
Esempio n. 29
0
        private ODataEntry CreateODataEntry(IGraph resultsGraph, string entryResource, string entryType)
        {
            var idPrefix = _map.GetResourceUriPrefix(entryType);
            if (!entryResource.StartsWith(idPrefix))
            {
                // Now we have a problem
                throw new Exception("Cannot create entry feed for resource " + entryResource +
                                    ". Resource URI does not start with the expected prefix " + idPrefix);
            }
            var resourceId = entryResource.Substring(idPrefix.Length);
            var odataLink = _baseUri + _map.GetTypeSet(entryType) + "('" + resourceId + "')";
            var entry = new ODataEntry
                {
                    TypeName = entryType,
                    ReadLink = new Uri(odataLink),
                    Id = odataLink
                };
            var subject = resultsGraph.CreateUriNode(UriFactory.Create(entryResource));
            var properties = new List<ODataProperty>();

            var identifierPropertyMapping = _map.GetIdentifierPropertyMapping(entryType);
            if (identifierPropertyMapping != null)
            {
                properties.Add(new ODataProperty{Name=identifierPropertyMapping.Name, Value=resourceId});
            }

            foreach (var propertyMapping in _map.GetStructuralPropertyMappings(entryType))
            {
                var predicate = resultsGraph.CreateUriNode(UriFactory.Create(propertyMapping.Uri));
                var match = resultsGraph.GetTriplesWithSubjectPredicate(subject, predicate).FirstOrDefault();
                if (match != null)
                {
                    if (match.Object is LiteralNode)
                    {
                        var newProperty = new ODataProperty
                            {
                                Name = propertyMapping.Name,
                                Value = GetValue(match.Object, propertyMapping.PropertyType)
                            };
                        properties.Add(newProperty);
                    }
                    else if (match.Object is UriNode && propertyMapping.PropertyType.IsPrimitive())
                    {
                        var newProperty = new ODataProperty()
                            {
                                Name = propertyMapping.Name,
                                Value = GetValue(match.Object, propertyMapping.PropertyType)
                            };
                        properties.Add(newProperty);
                    }
                }
            }

            

            if (_writerSettings.Version == null ||  _writerSettings.Version >= ODataVersion.V3)
            {
                var associationLinks = new List<ODataAssociationLink>();
                foreach (var assocMap in _map.GetAssociationPropertyMappings(entryType))
                {
                    var predicate = resultsGraph.CreateUriNode(UriFactory.Create(assocMap.Uri));
                    bool hasMatch = false;
                    if (assocMap.IsInverse)
                    {
                        hasMatch = resultsGraph.GetTriplesWithPredicateObject(predicate, subject).Any();
                    }
                    else
                    {
                        hasMatch = resultsGraph.GetTriplesWithSubjectPredicate(subject, predicate).Any();
                    }
                    // TODO: May need to be more specific here to catch inverse/forward versions of the same
                    // RDF property being mapped to two different OData properties (e.g. broader and narrower on a category)
                    // This quick hack will work for now though:
                    //bool hasMatch = resultsGraph.GetTriplesWithPredicate(resultsGraph.CreateUriNode(UriFactory.Create(assocMap.Uri))).Any();
                    if (hasMatch)
                    {
                        associationLinks.Add(new ODataAssociationLink
                            {
                                Name = assocMap.Name,
                                Url = new Uri(odataLink + "/$links/" + assocMap.Name)
                            });
                    }
                }
                entry.AssociationLinks = associationLinks;
            }

            entry.Properties = properties;
            return entry;
        }
        public void CreateEntry_Calls_CreateStructuralProperty_ForEachSelectedStructuralProperty()
        {
            // Arrange
            SelectExpandNode selectExpandNode = new SelectExpandNode
            {
                SelectedStructuralProperties = { new Mock<IEdmStructuralProperty>().Object, new Mock<IEdmStructuralProperty>().Object }
            };
            ODataProperty[] properties = new ODataProperty[] { new ODataProperty(), new ODataProperty() };
            Mock<ODataEntityTypeSerializer> serializer = new Mock<ODataEntityTypeSerializer>(_serializer.EdmType, _serializerProvider);
            serializer.CallBase = true;

            serializer
                .Setup(s => s.CreateStructuralProperty(selectExpandNode.SelectedStructuralProperties.ElementAt(0), _entityInstanceContext))
                .Returns(properties[0])
                .Verifiable();
            serializer
                .Setup(s => s.CreateStructuralProperty(selectExpandNode.SelectedStructuralProperties.ElementAt(1), _entityInstanceContext))
                .Returns(properties[1])
                .Verifiable();

            // Act
            ODataEntry entry = serializer.Object.CreateEntry(selectExpandNode, _entityInstanceContext);

            // Assert
            serializer.Verify();
            Assert.Equal(properties, entry.Properties);
        }
Esempio n. 31
0
 internal override void WriteProperty(ODataProperty property)
 {
     this.WritePropertyImplementation(property);
     this.Flush();
 }
Esempio n. 32
0
 internal static void AddPropertyToPropertiesList(IEnumerable <ODataProperty> properties, ODataProperty propertyToAdd)
 {
     GetPropertiesList(properties).Add(propertyToAdd);
 }
Esempio n. 33
0
 internal override Task WritePropertyAsync(ODataProperty property)
 {
     return TaskUtils.GetTaskForSynchronousOperationReturningTask(delegate {
         this.WritePropertyImplementation(property);
         return this.FlushAsync();
     });
 }
 private ODataComplexValue ReadComplexValueImplementation(IEdmComplexTypeReference complexValueTypeReference, string payloadTypeName, SerializationTypeNameAnnotation serializationTypeNameAnnotation, DuplicatePropertyNamesChecker duplicatePropertyNamesChecker)
 {
     this.IncreaseRecursionDepth();
     base.JsonReader.ReadStartObject();
     ODataComplexValue value2 = new ODataComplexValue {
         TypeName = (complexValueTypeReference != null) ? complexValueTypeReference.ODataFullName() : payloadTypeName
     };
     if (serializationTypeNameAnnotation != null)
     {
         value2.SetAnnotation<SerializationTypeNameAnnotation>(serializationTypeNameAnnotation);
     }
     if (duplicatePropertyNamesChecker == null)
     {
         duplicatePropertyNamesChecker = base.CreateDuplicatePropertyNamesChecker();
     }
     else
     {
         duplicatePropertyNamesChecker.Clear();
     }
     List<ODataProperty> sourceList = new List<ODataProperty>();
     bool flag = false;
     while (base.JsonReader.NodeType == JsonNodeType.Property)
     {
         string strB = base.JsonReader.ReadPropertyName();
         if (string.CompareOrdinal("__metadata", strB) == 0)
         {
             if (flag)
             {
                 throw new ODataException(Microsoft.Data.OData.Strings.ODataJsonPropertyAndValueDeserializer_MultipleMetadataPropertiesInComplexValue);
             }
             flag = true;
             base.JsonReader.SkipValue();
         }
         else if (!ValidationUtils.IsValidPropertyName(strB))
         {
             base.JsonReader.SkipValue();
         }
         else
         {
             ODataProperty property = new ODataProperty {
                 Name = strB
             };
             IEdmProperty property2 = null;
             bool ignoreProperty = false;
             if (complexValueTypeReference != null)
             {
                 property2 = ReaderValidationUtils.ValidateValuePropertyDefined(strB, complexValueTypeReference.ComplexDefinition(), base.MessageReaderSettings, out ignoreProperty);
             }
             if (ignoreProperty)
             {
                 base.JsonReader.SkipValue();
                 continue;
             }
             ODataNullValueBehaviorKind kind = (base.ReadingResponse || (property2 == null)) ? ODataNullValueBehaviorKind.Default : base.Model.NullValueReadBehaviorKind(property2);
             object obj2 = this.ReadNonEntityValueImplementation((property2 == null) ? null : property2.Type, null, null, kind == ODataNullValueBehaviorKind.Default);
             if ((kind != ODataNullValueBehaviorKind.IgnoreValue) || (obj2 != null))
             {
                 duplicatePropertyNamesChecker.CheckForDuplicatePropertyNames(property);
                 property.Value = obj2;
                 sourceList.Add(property);
             }
         }
     }
     base.JsonReader.ReadEndObject();
     value2.Properties = new ReadOnlyEnumerable<ODataProperty>(sourceList);
     this.DecreaseRecursionDepth();
     return value2;
 }
Esempio n. 35
0
 private void WritePropertyImplementation(ODataProperty property)
 {
     new ODataJsonPropertyAndValueSerializer(this).WriteTopLevelProperty(property);
 }
Esempio n. 36
0
 public Task WritePropertyAsync(ODataProperty property)
 {
     this.VerifyCanWriteProperty(property);
     return(this.WriteToOutputAsync(ODataPayloadKind.Property, null, context => context.WritePropertyAsync(property)));
 }
Esempio n. 37
0
 internal IEnumerable<ODataProperty> PopulateProperties(ClientTypeAnnotation type, object resource, List<object> visitedComplexTypeObjects)
 {
     List<ODataProperty> list = new List<ODataProperty>();
     foreach (ClientPropertyAnnotation annotation in from p in type.Properties()
         orderby p.PropertyName
         select p)
     {
         if (((!annotation.IsDictionary && (annotation != type.MediaDataMember)) && !annotation.IsStreamLinkProperty) && ((type.MediaDataMember == null) || (type.MediaDataMember.MimeTypeProperty != annotation)))
         {
             object propertyValue = annotation.GetValue(resource);
             if (annotation.IsKnownType)
             {
                 ODataProperty item = new ODataProperty {
                     Name = annotation.EdmProperty.Name,
                     Value = GetPrimitiveValue(propertyValue, annotation.PropertyType)
                 };
                 list.Add(item);
             }
             else if (annotation.IsPrimitiveOrComplexCollection)
             {
                 ODataProperty property2 = new ODataProperty {
                     Name = annotation.EdmProperty.Name,
                     Value = this.CreateODataCollectionPropertyValue(annotation, propertyValue, visitedComplexTypeObjects)
                 };
                 list.Add(property2);
             }
             else if (!annotation.IsEntityCollection && !ClientTypeUtil.TypeIsEntity(annotation.PropertyType, this.requestInfo.MaxProtocolVersion))
             {
                 ODataProperty property3 = new ODataProperty {
                     Name = annotation.EdmProperty.Name,
                     Value = this.CreateODataComplexPropertyValue(annotation, propertyValue, visitedComplexTypeObjects)
                 };
                 list.Add(property3);
             }
         }
     }
     return list;
 }