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

            string propertyName = property.Name;
            if (edmProperty != null)
            {
                propertyName = EdmLibHelpers.GetClrPropertyName(edmProperty, readContext.Model);
            }
            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, propertyName);
            }
            else
            {
                if (propertyKind == EdmTypeKind.Primitive && !readContext.IsUntyped)
                {
                    value = EdmPrimitiveHelpers.ConvertPrimitiveValue(value, GetPropertyType(resource, propertyName));
                }

                SetProperty(resource, propertyName, value);
            }
        }
Exemplo n.º 2
0
 public override void WriteProperty(ODataProperty property)
 {
     var schema = this.AvroWriter.UpdateSchema(property.Value, null);
     var obj = ODataAvroConvert.FromODataObject(property.Value, schema);
     this.AvroWriter.Write(obj);
     this.Flush();
 }
Exemplo n.º 3
0
        internal static void ApplyProperty(ODataProperty property, IEdmStructuredTypeReference resourceType, object resource,
            ODataDeserializerProvider deserializerProvider, ODataDeserializerContext readContext, AssembliesResolver assembliesResolver)
        {
            IEdmProperty edmProperty = resourceType.FindProperty(property.Name);

            bool isDynamicProperty = false;
            string propertyName = property.Name;
            if (edmProperty != null)
            {
                propertyName = EdmLibHelpers.GetClrPropertyName(edmProperty, readContext.Model);
            }
            else
            {
                IEdmStructuredType structuredType = resourceType.StructuredDefinition();
                isDynamicProperty = structuredType != null && structuredType.IsOpen;
            }

            // dynamic properties have null values
            IEdmTypeReference propertyType = edmProperty != null ? edmProperty.Type : null;

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

            if (isDynamicProperty)
            {
                SetDynamicProperty(resource, resourceType, propertyKind, propertyName, value, propertyType,
                    readContext, assembliesResolver);
            }
            else
            {
                SetDeclaredProperty(resource, propertyKind, propertyName, value, edmProperty, readContext, assembliesResolver);
            }
        }
Exemplo n.º 4
0
        public override void WriteProperty(ODataProperty property)
        {
            var val = property.Value as ODataComplexValue;
            if (val == null)
            {
                throw new ApplicationException("only support write complex type property.");
            }

            this.writer.WriteStart();
            foreach (ODataProperty prop in val.Properties)
            {
                string name = null;
                string @params = string.Empty;

                int idx = prop.Name.IndexOf('_');
                if (idx < 0)
                {
                    name = prop.Name;
                }
                else
                {
                    name = prop.Name.Substring(0, idx);
                    @params = string.Join(";", prop.Name.Substring(idx + 1).Split('_'));
                }

                foreach (ODataInstanceAnnotation anns in prop.InstanceAnnotations)
                {
                    @params += ";" + anns.Name.Substring(6) /*VCARD.*/ + "=" + ((ODataPrimitiveValue)anns.Value).Value;
                }

                this.writer.WriteItem(null, name, @params, (string)prop.Value);
            }

            this.writer.WriteEnd();
        }
 /// <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)
 {
     if (property == null)
     {
         throw new ODataException(Strings.WriterValidationUtils_PropertyMustNotBeNull);
     }
 }
 public void ShouldBeAbleToSetThePropertySerializationInfo()
 {
     ODataProperty property = new ODataProperty();
     ODataPropertySerializationInfo serializationInfo = new ODataPropertySerializationInfo();
     property.SetSerializationInfo(serializationInfo);
     property.SerializationInfo.Should().BeSameAs(serializationInfo);
 }
 public void ShouldBeAbleToClearThePropertySerializationInfo()
 {
     ODataProperty property = new ODataProperty();
     ODataPropertySerializationInfo serializationInfo = new ODataPropertySerializationInfo();
     property.SerializationInfo = serializationInfo;
     property.SetSerializationInfo(null);
     property.SerializationInfo.Should().BeNull();
 }
        public void ApplyNonExistantPropertyWithIgnoreMissingPropertiesShouldNotError()
        {
            TestMaterializerContext context = new TestMaterializerContext() {IgnoreMissingProperties = true};
            CollectionValueMaterializationPolicyTests.Point point = new CollectionValueMaterializationPolicyTests.Point();
            ODataProperty property = new ODataProperty() {Name = "Z", Value = 10};

            this.CreatePrimitiveValueMaterializationPolicy(context).ApplyDataValue(context.ResolveTypeForMaterialization(typeof(CollectionValueMaterializationPolicyTests.Point), null), property, point);
        }
        /// <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;
        }
        public void ApplyODataComplexValueForCollectionPropertyShouldError()
        {
            TestMaterializerContext context = new TestMaterializerContext();
            ComplexTypeWithPrimitiveCollection complexInstance = new ComplexTypeWithPrimitiveCollection();
            ODataProperty property = new ODataProperty() { Name = "Strings", Value = new ODataComplexValue() };

            Action test = () => this.CreatePrimitiveValueMaterializationPolicy(context).ApplyDataValue(context.ResolveTypeForMaterialization(typeof(ComplexTypeWithPrimitiveCollection), null), property, complexInstance);
            test.ShouldThrow<InvalidOperationException>().WithMessage(DSClient.Strings.AtomMaterializer_InvalidCollectionItem(property.Name));
        }
 private static ODataProperty CreateProperty(string name, object value)
 {
     ODataProperty prop = new ODataProperty()
     {
         Name = name,
         Value = value,
     };
     return prop;
 }
        public void ComplexTypeRoundtripAtomTest()
        {
            var age = new ODataProperty() { Name = "Age", Value = (Int16)18 };
            var email = new ODataProperty() { Name = "Email", Value = "*****@*****.**" };
            var tel = new ODataProperty() { Name = "Tel", Value = "0123456789" };
            var id = new ODataProperty() { Name = "ID", Value = Guid.Empty };

            ODataComplexValue complexValue = new ODataComplexValue() { TypeName = "NS.PersonalInfo", Properties = new[] { age, email, tel, id } };

            this.VerifyComplexTypeRoundtrip(complexValue, "NS.PersonalInfo");
        }
        /// <summary>
        /// Materializes the enum data value.
        /// </summary>
        /// <param name="valueType">Type of the collection item.</param>
        /// <param name="property">The ODataProperty.</param>
        /// <returns>Materialized enum data CLR value.</returns>
        public object MaterializeEnumTypeProperty(Type valueType, ODataProperty property)
        {
            object materializedValue = null;
            ODataEnumValue value = property.Value as ODataEnumValue;
            this.MaterializeODataEnumValue(valueType, value.TypeName, value.Value, () => "TODO: Is this reachable?", out materializedValue);
            if (!property.HasMaterializedValue())
            {
                property.SetMaterializedValue(materializedValue);
            }

            return materializedValue;
        }
 public void ShouldBeAbleToWriteInstanceAnnotationsInResponse()
 {
     ODataProperty property = new ODataProperty()
     {
         Name = "Prop",
         Value = Guid.Empty,
         InstanceAnnotations = new Collection<ODataInstanceAnnotation>
         {
             new ODataInstanceAnnotation("Annotation.1", new ODataPrimitiveValue(true)),
             new ODataInstanceAnnotation("Annotation.2", new ODataPrimitiveValue(123))
         }
     };
     WriteAndValidate(outputContext => outputContext.WriteProperty(property), "{\"@odata.context\":\"http://odata.org/test/$metadata#Edm.Guid\",\"@Annotation.1\":true,\"@Annotation.2\":123,\"value\":\"00000000-0000-0000-0000-000000000000\"}");
 }
        internal static void ApplyProperty(ODataProperty property, IEdmStructuredTypeReference resourceType, object resource,
            ODataDeserializerProvider deserializerProvider, ODataDeserializerContext readContext)
        {
            IEdmProperty edmProperty = resourceType.FindProperty(property.Name);

            // try to deserializer the dynamic properties for open type.
            if (edmProperty == null)
            {
                // the logic here works for open complex type and open entity type.
                IEdmStructuredType structuredType = resourceType.StructuredDefinition();
                if (structuredType != null && structuredType.IsOpen)
                {
                    if (ApplyDynamicProperty(property, structuredType, resource, deserializerProvider, readContext))
                    {
                        return;
                    }
                }
            }

            string propertyName = property.Name;
            if (edmProperty != null)
            {
                propertyName = EdmLibHelpers.GetClrPropertyName(edmProperty, readContext.Model);
            }
            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, propertyName);
            }
            else
            {
                if (!readContext.IsUntyped)
                {
                    if (propertyKind == EdmTypeKind.Primitive)
                    {
                        value = EdmPrimitiveHelpers.ConvertPrimitiveValue(value, GetPropertyType(resource, propertyName));
                    }
                    else if (propertyKind == EdmTypeKind.Enum)
                    {
                        value = EnumDeserializationHelpers.ConvertEnumValue(value, GetPropertyType(resource, propertyName));
                    }
                }

                SetProperty(resource, propertyName, value);
            }
        }
Exemplo n.º 16
0
        public void PropertyGettersAndSettersTest()
        {
            string name1 = "ODataPrimitiveProperty";
            object value1 = "Hello world";

            ODataProperty primitiveProperty = new ODataProperty()
            {
                Name = name1,
                Value = value1,
            };

            this.Assert.AreEqual(name1, primitiveProperty.Name, "Expected equal name values.");
            this.Assert.AreSame(value1, primitiveProperty.Value, "Expected reference equal values for property 'Value'.");

            string name2 = "ODataComplexProperty";
            ODataComplexValue value2 = new ODataComplexValue()
            {
                Properties = new[]
                {
                    new ODataProperty() { Name = "One", Value = 1 },
                    new ODataProperty() { Name = "Two", Value = 2 },
                }
            };

            ODataProperty complexProperty = new ODataProperty()
            {
                Name = name2,
                Value = value2,
            };

            this.Assert.AreEqual(name2, complexProperty.Name, "Expected equal name values.");
            this.Assert.AreSame(value2, complexProperty.Value, "Expected reference equal values for property 'Value'.");

            string name3 = "ODataCollectionProperty";
            ODataCollectionValue value3 = new ODataCollectionValue()
            {
                Items = new[] { 1, 2, 3 }
            };

            ODataProperty multiValueProperty = new ODataProperty()
            {
                Name = name3,
                Value = value3,
            };

            this.Assert.AreEqual(name3, multiValueProperty.Name, "Expected equal name values.");
            this.Assert.AreSame(value3, multiValueProperty.Value, "Expected reference equal values for property 'Value'.");
        }
Exemplo n.º 17
0
        /// <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>
        /// <param name="messageReaderSettings">The message reader settings being used.</param>
        internal static void ValidateStreamReferenceProperty(ODataProperty streamProperty, IEdmStructuredType structuredType, IEdmProperty streamEdmProperty, ODataMessageReaderSettings messageReaderSettings)
        {
            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 && !messageReaderSettings.ReportUndeclaredLinkProperties)
                {
                    // Fails with the correct error message.
                    ValidationUtils.ValidateOpenPropertyValue(streamProperty.Name, streamProperty.Value);
                }
            }
        }
        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);
        }
        private void EntryStarting(WritingEntryArgs ea)
        {
            var odataProps = ea.Entry.Properties as List<ODataProperty>;

            var entityState = contextWrapper.Context.Entities.First(e => e.Entity == ea.Entity).State;

            // Send up an undeclared property on an Open Type.
            if (entityState == EntityStates.Modified || entityState == EntityStates.Added)
            {
                if (ea.Entity.GetType() == typeof(Row))
                {
                    // In practice, the data from this undeclared property would probably be stored in a transient property of the partial companion class to the client proxy.
                    var undeclaredOdataProperty = new ODataProperty() { Name = "dynamicPropertyKey", Value = "dynamicPropertyValue" };
                    odataProps.Add(undeclaredOdataProperty);
                }
            }
        }
Exemplo n.º 20
0
        public void PropertyGettersAndSettersTest()
        {
            string etag = "ETag";
            Uri id = new Uri("http://odatalib.org/id");
            Uri readlink = new Uri("http://odatalib.org/readlink");
            Uri editlink = new Uri("http://odatalib.org/editlink");
            ODataStreamReferenceValue mediaResource = new ODataStreamReferenceValue();

            ODataProperty primitiveProperty = new ODataProperty();
            ODataProperty complexProperty = new ODataProperty();
            ODataProperty multiValueProperty = new ODataProperty();
            ODataProperty namedStreamProperty = new ODataProperty();
            List<ODataProperty> properties = new List<ODataProperty>()
            {
                primitiveProperty,
                complexProperty,
                multiValueProperty,
                namedStreamProperty
            };

            string typeName = "ODataLibSample.DummyType";

            ODataEntry entry = new ODataEntry()
            {
                ETag = etag,
                Id = id,
                EditLink = editlink,
                Properties = properties,
                TypeName = typeName,
                MediaResource = mediaResource
            };

            this.Assert.IsNull(entry.ReadLink, "Expect ReadLink to be null if it was not set.");

            entry.ReadLink = readlink;

            this.Assert.AreSame(etag, entry.ETag, "Expected reference equal values for property 'ETag'.");
            this.Assert.AreSame(id, entry.Id, "Expected reference equal values for property 'Id'.");
            this.Assert.AreSame(readlink, entry.ReadLink, "Expected reference equal values for property 'ReadLink'.");
            this.Assert.AreSame(editlink, entry.EditLink, "Expected reference equal values for property 'EditLink'.");
            this.Assert.AreSame(properties, entry.Properties, "Expected reference equal values for property 'Properties'.");
            this.Assert.AreSame(typeName, entry.TypeName, "Expected reference equal values for property 'TypeName'.");
            this.Assert.AreSame(mediaResource, entry.MediaResource, "Expected reference equals for property 'MediaResource'.");
        }
Exemplo n.º 21
0
        public void JsonPaddingEnabledWithUserSpecifiedContentType()
        {
            var settings = new ODataMessageWriterSettings {JsonPCallback = "functionName", DisableMessageStreamDisposal = true};
            settings.SetServiceDocumentUri(new Uri("http://stuff"));
            IODataResponseMessage message = new InMemoryMessage {StatusCode = 200, Stream = new MemoryStream()};
            message.SetHeader("Content-Type", "application/json");
            var property = new ODataProperty {Name = "PropertyName", Value = "value"};
            
            using (var writer = new ODataMessageWriter(message, settings))
            {
                writer.WriteProperty(property);
            }

            var responseStream = message.GetStream();
            responseStream.Position = 0;
            var responseString = new StreamReader(responseStream).ReadToEnd();
            responseString.Should().Be("functionName({\"@odata.context\":\"http://stuff/$metadata#Edm.String\",\"value\":\"value\"})");
            message.GetHeader("Content-Type").Should().StartWith("text/javascript");
        }
        public void NullValueShouldBeAppliedToSubComplexValueProperty()
        {
            TestMaterializerContext context = new TestMaterializerContext();
            ComplexTypeWithChildComplexType complexInstance = new ComplexTypeWithChildComplexType();
            complexInstance.InnerComplexProperty = new ChildComplexType();
            ODataProperty property = new ODataProperty() { Name = "InnerComplexProperty", Value = null };

            this.CreatePrimitiveValueMaterializationPolicy(context).ApplyDataValue(context.ResolveTypeForMaterialization(typeof(ComplexTypeWithChildComplexType), null), property, complexInstance);
            Assert.IsNull(complexInstance.InnerComplexProperty);
        }
        public void ValueShouldBeAppliedRegardlessIfPropertyStartsNullOrNot()
        {
            foreach (var startingPropertyState in new ChildComplexType[] {null, new ChildComplexType()})
            {
                TestMaterializerContext context = new TestMaterializerContext();
                ComplexTypeWithChildComplexType complexInstance = new ComplexTypeWithChildComplexType();
                complexInstance.InnerComplexProperty = startingPropertyState;
                ODataProperty property = new ODataProperty() {Name = "InnerComplexProperty", Value = new ODataComplexValue() {Properties = new ODataProperty[] {new ODataProperty() {Name = "Prop", Value = 1}}}};

                this.CreatePrimitiveValueMaterializationPolicy(context).ApplyDataValue(context.ResolveTypeForMaterialization(typeof(ComplexTypeWithChildComplexType), null), property, complexInstance);
                complexInstance.InnerComplexProperty.Prop.Should().Be(1);
            }
        }
        public void ApplyODataCollectionValueToNullCollectionProperty()
        {
            TestMaterializerContext context = new TestMaterializerContext();
            ComplexTypeWithPrimitiveCollection complexInstance = new ComplexTypeWithPrimitiveCollection();
            complexInstance.Strings = null;
            ODataProperty property = new ODataProperty() { Name = "Strings", Value = new ODataCollectionValue() { Items = new string[] { "foo" }, TypeName = typeof(ComplexTypeWithPrimitiveCollection).FullName } };

            this.CreatePrimitiveValueMaterializationPolicy(context).ApplyDataValue(context.ResolveTypeForMaterialization(typeof(ComplexTypeWithPrimitiveCollection), null), property, complexInstance);
            complexInstance.Strings.Should().HaveCount(1);
            complexInstance.Strings[0].Should().Be("foo");
        }
        public void ApplyODataCollectionValueToNonNullExistingCollectionProperty()
        {
            TestMaterializerContext context = new TestMaterializerContext();
            ComplexTypeWithPrimitiveCollection complexInstance = new ComplexTypeWithPrimitiveCollection();
            complexInstance.Strings.Add("ShouldBeCleared");
            ODataProperty property = new ODataProperty() { Name = "Strings", Value = new ODataCollectionValue() };

            this.CreatePrimitiveValueMaterializationPolicy(context).ApplyDataValue(context.ResolveTypeForMaterialization(typeof(ComplexTypeWithPrimitiveCollection), null), property, complexInstance);
            complexInstance.Strings.Should().HaveCount(0);
        }
        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>(_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);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Validates a named stream property to ensure it's not null and it's name if correct.
        /// </summary>
        /// <param name="streamProperty">The stream reference property to validate.</param>
        /// <param name="edmProperty">Property metadata to validate against.</param>
        /// <param name="writingResponse">true when writing a response; otherwise false.</param>
        /// <param name="bypassValidation">Bypass the validation if it is true.</param>
        /// <remarks>This does NOT validate the value of the stream property, just the property itself.</remarks>
        internal static void ValidateStreamReferenceProperty(ODataProperty streamProperty, IEdmProperty edmProperty, bool writingResponse, bool bypassValidation = false)
        {
            Debug.Assert(streamProperty != null, "streamProperty != null");
            if (bypassValidation)
            {
                return;
            }

            ValidationUtils.ValidateStreamReferenceProperty(streamProperty, edmProperty);

            if (!writingResponse)
            {
                // Stream properties are only valid in responses; writers fail if they encounter them in requests.
                throw new ODataException(Strings.WriterValidationUtils_StreamPropertyInRequest(streamProperty.Name));
            }
        }
 /// <summary>
 /// Provide additional serialization information to the <see cref="ODataWriter"/> for <paramref name="property"/>.
 /// </summary>
 /// <param name="property">The instance to set the serialization info.</param>
 /// <param name="serializationInfo">The serialization info to set.</param>
 public static void SetSerializationInfo(this ODataProperty property, ODataPropertySerializationInfo serializationInfo)
 {
     ExceptionUtils.CheckArgumentNotNull(property, "property");
     property.SerializationInfo = serializationInfo;
 }
Exemplo n.º 29
0
 /// <summary>
 /// Validates a named stream property to ensure it's not null and it's name if correct.
 /// </summary>
 /// <param name="streamProperty">The stream reference property to validate.</param>
 /// <param name="edmProperty">Property metadata to validate against.</param>
 /// <param name="writingResponse">true when writing a response; otherwise false.</param>
 /// <remarks>This does NOT validate the value of the stream property, just the property itself.</remarks>
 public void ValidateStreamReferenceProperty(ODataProperty streamProperty, IEdmProperty edmProperty, bool writingResponse)
 {
 }
Exemplo n.º 30
0
 /// <summary>
 /// Writes an <see cref="ODataProperty"/> as message payload.
 /// </summary>
 /// <param name="property">The property to write.</param>
 /// <remarks>It is the responsibility of this method to flush the output before the method returns.</remarks>
 internal virtual void WriteProperty(ODataProperty property)
 {
     throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Property);
 }
Exemplo n.º 31
0
 /// <summary>
 /// Validates an <see cref="ODataProperty"/> for not being null.
 /// </summary>
 /// <param name="property">The property to validate for not being null.</param>
 public void ValidatePropertyNotNull(ODataProperty property)
 {
     WriterValidationUtils.ValidatePropertyNotNull(property);
 }
        public void ApplyODataDerivedComplexValueForBaseComplexTypeProperty()
        {
            TestMaterializerContext context = new TestMaterializerContext();
            ComplexTypeWithChildComplexType complexInstance = new ComplexTypeWithChildComplexType();
            complexInstance.InnerComplexProperty = new DerivedComplexType {DerivedProp = 1};

            //In a true client, a TypeResolver will be used to resolve derived property type.
            context.ResolveTypeForMaterializationOverrideFunc = (Type type, string name) =>
            {
                if (name == "DerivedComplexType")
                {
                    var edmType = context.Model.GetOrCreateEdmType(typeof(DerivedComplexType));
                    return new ClientTypeAnnotation(edmType, typeof(DerivedComplexType), "DerivedComplexType", context.Model);
                }
                else
                {
                    var edmType = context.Model.GetOrCreateEdmType(typeof(ComplexTypeWithChildComplexType));
                    return new ClientTypeAnnotation(edmType, typeof(ComplexTypeWithChildComplexType), "ComplexTypeWithChildComplexType", context.Model);
                }
            };

            IEdmType t = context.Model.GetOrCreateEdmType(typeof(DerivedComplexType));
            ODataProperty property = new ODataProperty() { Name = "InnerComplexProperty", Value = new ODataComplexValue { TypeName = "DerivedComplexType", Properties = new ODataProperty[] { new ODataProperty { Name = "DerivedProp", Value = 1 } } } };

            Action test = () => this.CreatePrimitiveValueMaterializationPolicy(context).ApplyDataValue(context.ResolveTypeForMaterialization(typeof(ComplexTypeWithChildComplexType), null), property, complexInstance);
            test.ShouldNotThrow();
        }
        /// <summary>
        /// Applies collectionValue item to the provided <paramref name="collectionInstance"/>. 
        /// </summary>
        /// <param name="collectionProperty">Atom property containing materialized Collection items.</param>
        /// <param name="collectionInstance">Collection instance. Must implement ICollection&lt;T&gt; where T is either primitive or complex type (not an entity).</param>
        /// <param name="collectionItemType">Type of items in the Collection. Note: this could be calculated from collectionInstance but we already have it in upstream methods.</param>
        /// <param name="addValueToBackingICollectionInstance">Action called actually add a Collection item to <paramref name="collectionInstance" /></param>
        /// <param name="isElementNullable">If element type is nullable.</param>
        internal void ApplyCollectionDataValues(
            ODataProperty collectionProperty,
            object collectionInstance,
            Type collectionItemType,
            Action<object, object> addValueToBackingICollectionInstance,
            bool isElementNullable)
        {
            Debug.Assert(collectionProperty != null, "property != null");
            Debug.Assert(collectionProperty.Value != null, "Collection should have already been checked for nullness");
            Debug.Assert(collectionInstance != null, "collectionInstance != null");
            Debug.Assert(WebUtil.IsCLRTypeCollection(collectionInstance.GetType(), this.materializerContext.Model), "collectionInstance must be a CollectionValue");
            Debug.Assert(collectionItemType.IsAssignableFrom(
                ClientTypeUtil.GetImplementationType(collectionInstance.GetType(), typeof(ICollection<>)).GetGenericArguments()[0]),
                "collectionItemType has to match the collectionInstance generic type.");
            Debug.Assert(!ClientTypeUtil.TypeIsEntity(collectionItemType, this.materializerContext.Model), "CollectionValues cannot contain entities");
            Debug.Assert(addValueToBackingICollectionInstance != null, "AddValueToBackingICollectionInstance != null");

            ODataCollectionValue collectionValue = collectionProperty.Value as ODataCollectionValue;
            this.ApplyCollectionDataValues(
                collectionValue.Items,
                collectionValue.TypeName,
                collectionInstance,
                collectionItemType,
                addValueToBackingICollectionInstance,
                isElementNullable);

            collectionProperty.SetMaterializedValue(collectionInstance);
        }
Exemplo n.º 34
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>
 public virtual Task WritePropertyAsync(ODataProperty property)
 {
     throw this.CreatePayloadKindNotSupportedException(ODataPayloadKind.Property);
 }
        /// <summary>
        /// Creates Collection instance of store Collection items.
        /// </summary>
        /// <param name="collectionProperty">ODataProperty instance representing the Collection as seen in the atom payload.</param>
        /// <param name="userCollectionType">CLR type of the Collection as defined by the user.</param>
        /// <returns>Newly created Collection instance. Never null.</returns>
        internal object CreateCollectionPropertyInstance(ODataProperty collectionProperty, Type userCollectionType)
        {
            Debug.Assert(collectionProperty != null, "collectionProperty != null");
            Debug.Assert(collectionProperty.Value != null, "Collection should have already been checked for nullness");
            Debug.Assert(userCollectionType != null, "userCollectionType != null");
            Debug.Assert(ClientTypeUtil.GetImplementationType(userCollectionType, typeof(ICollection<>)) != null, "Not a Collection - Collection types must implement ICollection<> interface.");
            Debug.Assert(
                !ClientTypeUtil.TypeIsEntity(ClientTypeUtil.GetImplementationType(userCollectionType, typeof(ICollection<>)).GetGenericArguments()[0], this.materializerContext.Model),
                "Not a Collection - Collections cannot contain entities");
            Debug.Assert(!(collectionProperty.Value is ODataFeed) && !(collectionProperty.Value is ODataEntry), "Collection properties should never materialized from entry or feed payload");

            ODataCollectionValue collectionValue = collectionProperty.Value as ODataCollectionValue;

            // get a ClientType instance for the Collection property. This determines what type will be used later when creating the actual Collection instance
            ClientTypeAnnotation collectionClientType = this.materializerContext.ResolveTypeForMaterialization(userCollectionType, collectionValue.TypeName);

            return this.CreateCollectionInstance(collectionClientType.EdmTypeReference as IEdmCollectionTypeReference, collectionClientType.ElementType, () => DSClient.Strings.AtomMaterializer_NoParameterlessCtorForCollectionProperty(collectionProperty.Name, collectionClientType.ElementTypeName));
        }
Exemplo n.º 36
0
 /// <summary>
 /// Validates an <see cref="ODataProperty"/> for not being null.
 /// </summary>
 /// <param name="property">The property to validate for not being null.</param>
 public void ValidatePropertyNotNull(ODataProperty property)
 {
 }
Exemplo n.º 37
0
 /// <summary>
 /// Validates a named stream property to ensure it's not null and it's name if correct.
 /// </summary>
 /// <param name="streamProperty">The stream reference property to validate.</param>
 /// <param name="edmProperty">Property metadata to validate against.</param>
 /// <param name="writingResponse">true when writing a response; otherwise false.</param>
 /// <remarks>This does NOT validate the value of the stream property, just the property itself.</remarks>
 public void ValidateStreamReferenceProperty(ODataProperty streamProperty, IEdmProperty edmProperty, bool writingResponse)
 {
     WriterValidationUtils.ValidateStreamReferenceProperty(streamProperty, edmProperty, writingResponse);
 }