public void SetCollectionProperty_CollectionTypeCannotBeInstantiated_And_SettableProperty_Throws(string propertyName)
        {
            object       value       = new SampleClassWithSettableCollectionProperties();
            IEdmProperty edmProperty = GetMockEdmProperty(propertyName, EdmPrimitiveTypeKind.Int32);

            ExceptionAssert.Throws <SerializationException>(
                () => DeserializationHelpers.SetCollectionProperty(value, edmProperty, value: new List <int> {
                1, 2, 3
            }, propertyName: edmProperty.Name),
                String.Format("The property '{0}' on type 'Microsoft.AspNet.OData.Test.Formatter.Deserialization.DeserializationHelpersTest+SampleClassWithSettableCollectionProperties' returned a null value. " +
                              "The input stream contains collection items which cannot be added if the instance is null.", propertyName));
        }
        public void SetCollectionProperty_NonSettableProperty_NonNullValue_NoAdd_Throws(string propertyName)
        {
            object       value        = new SampleClassWithNonSettableCollectionProperties();
            Type         propertyType = typeof(SampleClassWithNonSettableCollectionProperties).GetProperty(propertyName).PropertyType;
            IEdmProperty edmProperty  = GetMockEdmProperty(propertyName, EdmPrimitiveTypeKind.Int32);

            ExceptionAssert.Throws <SerializationException>(
                () => DeserializationHelpers.SetCollectionProperty(value, edmProperty, value: new List <int> {
                1, 2, 3
            }, propertyName: edmProperty.Name),
                String.Format("The type '{0}' of the property '{1}' on type 'Microsoft.AspNet.OData.Test.Formatter.Deserialization.DeserializationHelpersTest+SampleClassWithNonSettableCollectionProperties' does not have an Add method. " +
                              "Consider using a collection type that does have an Add method - for example IList<T> or ICollection<T>.", propertyType.FullName, propertyName));
        }
        public void SetCollectionProperty_NonSettableProperty_ArrayValue_FixedSize_Throws(string propertyName)
        {
            object       value        = new SampleClassWithNonSettableCollectionProperties();
            Type         propertyType = typeof(SampleClassWithNonSettableCollectionProperties).GetProperty(propertyName).PropertyType;
            IEdmProperty edmProperty  = GetMockEdmProperty(propertyName, EdmPrimitiveTypeKind.Int32);

            ExceptionAssert.Throws <SerializationException>(
                () => DeserializationHelpers.SetCollectionProperty(value, edmProperty, value: new List <int> {
                1, 2, 3
            }, propertyName: edmProperty.Name),
                String.Format("The value of the property '{0}' on type 'Microsoft.AspNet.OData.Test.Formatter.Deserialization.DeserializationHelpersTest+SampleClassWithNonSettableCollectionProperties' is an array. " +
                              "Consider adding a setter for the property.", propertyName));
        }
        public void SetCollectionProperty_CanConvertNonStandardEdmTypes()
        {
            SampleClassWithDifferentCollectionProperties value = new SampleClassWithDifferentCollectionProperties();
            IEdmProperty edmProperty = GetMockEdmProperty("UnsignedArray", EdmPrimitiveTypeKind.Int32);

            DeserializationHelpers.SetCollectionProperty(value, edmProperty, value: new List <int> {
                1, 2, 3
            }, propertyName: edmProperty.Name);

            Assert.Equal(
                new uint[] { 1, 2, 3 },
                value.UnsignedArray);
        }
        public void SetCollectionProperty_NonSettableProperty_NonNullValue_WithAddMethod(string propertyName)
        {
            object       value       = new SampleClassWithNonSettableCollectionProperties();
            IEdmProperty edmProperty = GetMockEdmProperty(propertyName, EdmPrimitiveTypeKind.Int32);

            DeserializationHelpers.SetCollectionProperty(value, edmProperty, value: new List <int> {
                1, 2, 3
            }, propertyName: edmProperty.Name);

            Assert.Equal(
                new[] { 1, 2, 3 },
                value.GetType().GetProperty(propertyName).GetValue(value, index: null) as IEnumerable <int>);
        }
        private object BuildResourceInstance()
        {
            if (EdmObject == null)
            {
                return(null);
            }

            TypedEdmStructuredObject edmStructruredObject = EdmObject as TypedEdmStructuredObject;

            if (edmStructruredObject != null)
            {
                return(edmStructruredObject.Instance);
            }

            SelectExpandWrapper selectExpandWrapper = EdmObject as SelectExpandWrapper;

            if (selectExpandWrapper != null && selectExpandWrapper.UntypedInstance != null)
            {
                return(selectExpandWrapper.UntypedInstance);
            }

            Type clrType = EdmLibHelpers.GetClrType(StructuredType, EdmModel);

            if (clrType == null)
            {
                throw new InvalidOperationException(Error.Format(SRResources.MappingDoesNotContainResourceType, StructuredType.FullTypeName()));
            }

            object resource = Activator.CreateInstance(clrType);

            foreach (IEdmStructuralProperty property in StructuredType.StructuralProperties())
            {
                object value;
                if (EdmObject.TryGetPropertyValue(property.Name, out value) && value != null)
                {
                    string propertyName = EdmLibHelpers.GetClrPropertyName(property, EdmModel);

                    if (TypeHelper.IsCollection(value.GetType()))
                    {
                        DeserializationHelpers.SetCollectionProperty(resource, property, value, propertyName);
                    }
                    else
                    {
                        DeserializationHelpers.SetProperty(resource, propertyName, value);
                    }
                }
            }

            return(resource);
        }
Beispiel #7
0
        private static object CovertResourceId(object source, ODataResource resource,
                                               IEdmEntityTypeReference entityTypeReference, ODataDeserializerContext readContext)
        {
            Contract.Assert(resource != null);
            Contract.Assert(source != null);

            if (resource.Id == null || resource.Properties.Any())
            {
                return(source);
            }

            IWebApiRequestMessage request   = readContext.InternalRequest;
            IWebApiUrlHelper      urlHelper = readContext.InternalUrlHelper;

            DefaultODataPathHandler pathHandler = new DefaultODataPathHandler();
            string serviceRoot = urlHelper.CreateODataLink(
                request.Context.RouteName,
                request.PathHandler,
                new List <ODataPathSegment>());

            IEnumerable <KeyValuePair <string, object> > keyValues = GetKeys(pathHandler, serviceRoot, resource.Id,
                                                                             request.RequestContainer);

            IList <IEdmStructuralProperty> keys = entityTypeReference.Key().ToList();

            if (keys.Count == 1 && keyValues.Count() == 1)
            {
                // TODO: make sure the enum key works
                object propertyValue = keyValues.First().Value;
                DeserializationHelpers.SetDeclaredProperty(source, EdmTypeKind.Primitive, keys[0].Name, propertyValue,
                                                           keys[0], readContext);
                return(source);
            }

            IDictionary <string, object> keyValuesDic = keyValues.ToDictionary(e => e.Key, e => e.Value);

            foreach (IEdmStructuralProperty key in keys)
            {
                object value;
                if (keyValuesDic.TryGetValue(key.Name, out value))
                {
                    // TODO: make sure the enum key works
                    DeserializationHelpers.SetDeclaredProperty(source, EdmTypeKind.Primitive, key.Name, value, key,
                                                               readContext);
                }
            }

            return(source);
        }
        public void SetCollectionProperty_OnNonCollection_ThrowsSerialization(string propertyName)
        {
            object       value        = new SampleClassWithDifferentCollectionProperties();
            Type         propertyType = typeof(SampleClassWithDifferentCollectionProperties).GetProperty(propertyName).PropertyType;
            IEdmProperty edmProperty  = GetMockEdmProperty(propertyName, EdmPrimitiveTypeKind.Int32);

            ExceptionAssert.Throws <SerializationException>(
                () => DeserializationHelpers.SetCollectionProperty(value, edmProperty, value: new List <int> {
                1, 2, 3
            }, propertyName: edmProperty.Name),
                Error.Format(
                    "The type '{0}' of the property '{1}' on type 'Microsoft.AspNet.OData.Test.Formatter.Deserialization.DeserializationHelpersTest+SampleClassWithDifferentCollectionProperties' must be a collection.",
                    propertyType.FullName,
                    propertyName));
        }
Beispiel #9
0
        public void ConvertValue_ThrowsODataException_WithInvalidValue(string rawValue)
        {
            // Arrange
            object oDataValue = new ODataUntypedValue
            {
                RawValue = rawValue
            };

            // Act
            IEdmTypeReference typeRef = null;
            Action            test    = () => DeserializationHelpers.ConvertValue(oDataValue, ref typeRef, null, null, out EdmTypeKind typeKind);

            // Assert
            ExceptionAssert.Throws <ODataException>(test,
                                                    $"The given untyped value '{rawValue}' in payload is invalid. Consider using a OData type annotation explicitly.");
        }
Beispiel #10
0
        public void ConvertValue_Works_WithODataUntypedValue_Double()
        {
            // Arrange
            object oDataValue = new ODataUntypedValue
            {
                RawValue = "-1.643e6"
            };

            // Act
            IEdmTypeReference typeRef = null;
            object            value   = DeserializationHelpers.ConvertValue(oDataValue, ref typeRef, null, null, out EdmTypeKind typeKind);

            // Assert
            Assert.Equal(EdmTypeKind.Primitive, typeKind);
            Assert.Equal((double)-1643000, value);
        }
Beispiel #11
0
        public void ConvertValue_Works_WithODataUntypedValue(string rawValue, object expected)
        {
            // Arrange
            object oDataValue = new ODataUntypedValue
            {
                RawValue = rawValue
            };

            // Act
            IEdmTypeReference typeRef = null;
            object            value   = DeserializationHelpers.ConvertValue(oDataValue, ref typeRef, null, null, out EdmTypeKind typeKind);

            // Assert
            Assert.Equal(EdmTypeKind.Primitive, typeKind);
            Assert.Equal(expected, value);
        }
        public void SetCollectionProperty_CanConvertEnumCollection()
        {
            SampleClassWithDifferentCollectionProperties value = new SampleClassWithDifferentCollectionProperties();
            IEdmProperty edmProperty = GetMockEdmProperty("FlagsEnum", EdmPrimitiveTypeKind.String);

            DeserializationHelpers.SetCollectionProperty(
                value,
                edmProperty,
                value: new List <FlagsEnum> {
                FlagsEnum.One, FlagsEnum.Four | FlagsEnum.Two | (FlagsEnum)123
            },
                propertyName: edmProperty.Name);

            Assert.Equal(
                new FlagsEnum[] { FlagsEnum.One, FlagsEnum.Four | FlagsEnum.Two | (FlagsEnum)123 },
                value.FlagsEnum);
        }
        public override void SetValue(TStructuralType instance, object value)
        {
            if (instance == null)
            {
                throw Error.ArgumentNull("instance");
            }

            if (_isCollection)
            {
                DeserializationHelpers.SetCollectionProperty(instance, _property.Name, edmPropertyType: null,
                                                             value: value, clearCollection: true);
            }
            else
            {
                _setter(instance, value);
            }
        }
        public override void SetValue(TEntityType entity, object value)
        {
            if (entity == null)
            {
                throw Error.ArgumentNull("entity");
            }

            if (_isCollection)
            {
                DeserializationHelpers.SetCollectionProperty(entity, _property.Name, edmPropertyType: null,
                                                             value: value, clearCollection: true);
            }
            else
            {
                _setter(entity, value);
            }
        }
        public void ApplyProperty_FailWithCaseInsensitiveMatchesAndDisabledCaseSensitiveRequestPropertyBinding()
        {
            const string expectedErrorMessage = "The property 'proPerty1' does not exist on type 'namespace.name'. Make sure to only use property names that are defined by the type.";
            // Arrange
            ODataProperty property = new ODataProperty {
                Name = "proPerty1", Value = "Value1"
            };
            EdmEntityType entityType = new EdmEntityType("namespace", "name");

            entityType.AddStructuralProperty("Property1", EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(typeof(string)));
            entityType.AddKeys(entityType.AddStructuralProperty("Key1",
                                                                EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(typeof(string))));

            EdmEntityTypeReference    entityTypeReference = new EdmEntityTypeReference(entityType, isNullable: false);
            ODataDeserializerProvider provider            = ODataDeserializerProviderFactory.Create();

#if NETCORE
            IRouteBuilder builder = RoutingConfigurationFactory.CreateWithDisabledCaseInsensitiveRequestPropertyBinding();

            HttpRequest request = RequestFactory.Create(builder);
#else
            HttpConfiguration configuration = RoutingConfigurationFactory.CreateWithRootContainer("OData");
            configuration.SetCompatibilityOptions(CompatibilityOptions.DisableCaseInsensitiveRequestPropertyBinding);
            HttpRequestMessage request = RequestFactory.Create(configuration);
#endif

            ODataDeserializerContext context = new ODataDeserializerContext
            {
                Model   = new EdmModel(),
                Request = request
            };

            // Act
            var exception = Assert.Throws <ODataException>(() =>
                                                           DeserializationHelpers.ApplyProperty(
                                                               property,
                                                               entityTypeReference,
                                                               resource: null,
                                                               provider,
                                                               context));

            // Assert
            Assert.Equal(expectedErrorMessage, exception.Message);
        }
Beispiel #16
0
        private object BuildEntityInstance()
        {
            if (EdmObject == null)
            {
                return(null);
            }

            TypedEdmEntityObject edmEntityObject = EdmObject as TypedEdmEntityObject;

            if (edmEntityObject != null)
            {
                return(edmEntityObject.Instance);
            }

            var  assemblyNames = Request.HttpContext.RequestServices.GetService <AssembliesResolver>();
            Type clrType       = EdmLibHelpers.GetClrType(EntityType, EdmModel, assemblyNames);

            if (clrType == null)
            {
                throw new InvalidOperationException(Error.Format(SRResources.MappingDoesNotContainEntityType, EntityType.FullName()));
            }

            object resource = Activator.CreateInstance(clrType);

            foreach (IEdmStructuralProperty property in EntityType.StructuralProperties())
            {
                object value;
                if (EdmObject.TryGetPropertyValue(property.Name, out value) && value != null)
                {
                    if (value.GetType().IsCollection())
                    {
                        DeserializationHelpers.SetCollectionProperty(resource, property, value, property.Name, assemblyNames);
                    }
                    else
                    {
                        DeserializationHelpers.SetProperty(resource, property.Name, value);
                    }
                }
            }

            return(resource);
        }
Beispiel #17
0
        private static object CovertResourceId(object source, ODataResourceBase resource,
                                               IEdmEntityTypeReference entityTypeReference, ODataDeserializerContext readContext)
        {
            Contract.Assert(resource != null);
            Contract.Assert(source != null);

            if (resource.Id == null || resource.Properties.Any())
            {
                return(source);
            }

            HttpRequest request     = readContext.Request;
            string      serviceRoot = request.CreateODataLink();

            IEnumerable <KeyValuePair <string, object> > keyValues = GetKeys(request, serviceRoot, resource.Id, request.GetSubServiceProvider());

            IList <IEdmStructuralProperty> keys = entityTypeReference.Key().ToList();

            if (keys.Count == 1 && keyValues.Count() == 1)
            {
                // TODO: make sure the enum key works
                object propertyValue = keyValues.First().Value;
                DeserializationHelpers.SetDeclaredProperty(source, EdmTypeKind.Primitive, keys[0].Name, propertyValue,
                                                           keys[0], readContext);
                return(source);
            }

            IDictionary <string, object> keyValuesDic = keyValues.ToDictionary(e => e.Key, e => e.Value);

            foreach (IEdmStructuralProperty key in keys)
            {
                object value;
                if (keyValuesDic.TryGetValue(key.Name, out value))
                {
                    // TODO: make sure the enum key works
                    DeserializationHelpers.SetDeclaredProperty(source, EdmTypeKind.Primitive, key.Name, value, key,
                                                               readContext);
                }
            }

            return(source);
        }
        public void ApplyProperty_PassesWithCaseInsensitivePropertyName()
        {
            // Arrange
            ODataProperty property = new ODataProperty {
                Name = "keY1", Value = "Value1"
            };
            EdmEntityType entityType = new EdmEntityType("namespace", "name");

            entityType.AddKeys(entityType.AddStructuralProperty("Key1",
                                                                EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(typeof(string))));

            EdmEntityTypeReference    entityTypeReference = new EdmEntityTypeReference(entityType, isNullable: false);
            ODataDeserializerProvider provider            = ODataDeserializerProviderFactory.Create();

            var  resource     = new Mock <IDelta>(MockBehavior.Strict);
            Type propertyType = typeof(string);

            resource.Setup(r => r.TryGetPropertyType("Key1", out propertyType)).Returns(true).Verifiable();
            resource.Setup(r => r.TrySetPropertyValue("Key1", "Value1")).Returns(true).Verifiable();

#if NETCORE
            IRouteBuilder builder = RoutingConfigurationFactory.Create();

            HttpRequest request = RequestFactory.Create(builder);
#else
            HttpConfiguration  configuration = RoutingConfigurationFactory.CreateWithRootContainer("OData");
            HttpRequestMessage request       = RequestFactory.Create(configuration);
#endif

            ODataDeserializerContext context = new ODataDeserializerContext
            {
                Model   = new EdmModel(),
                Request = request
            };

            // Act
            DeserializationHelpers.ApplyProperty(property, entityTypeReference, resource.Object, provider,
                                                 context);

            // Assert
            resource.Verify();
        }
Beispiel #19
0
        public void SetCollectionProperty_CanConvertDataTime_ByDefault()
        {
            // Arrange
            SampleClassWithDifferentCollectionProperties source = new SampleClassWithDifferentCollectionProperties();
            IEdmProperty           edmProperty = GetMockEdmProperty("DateTimeList", EdmPrimitiveTypeKind.DateTimeOffset);
            DateTime               dt          = new DateTime(2014, 11, 15, 1, 2, 3);
            IList <DateTimeOffset> dtos        = new List <DateTimeOffset>
            {
                new DateTimeOffset(dt, TimeSpan.Zero),
                new DateTimeOffset(dt, new TimeSpan(+7, 0, 0)),
                new DateTimeOffset(dt, new TimeSpan(-8, 0, 0))
            };

            IEnumerable <DateTime> expects = dtos.Select(e => e.LocalDateTime);

            // Act
            DeserializationHelpers.SetCollectionProperty(source, edmProperty, dtos, edmProperty.Name, timeZoneInfo: null);

            // Assert
            Assert.Equal(expects, source.DateTimeList);
        }
Beispiel #20
0
            internal static object CovertEntityId(object source, ODataEntry entry, IEdmEntityTypeReference entityTypeReference, ODataDeserializerContext readContext)
            {
                Contract.Assert(entry != null);
                Contract.Assert(source != null);

                if (entry.Id == null || entry.Properties.Any())
                {
                    return(source);
                }

                HttpRequestMessage request  = readContext.Request;
                IEdmModel          edmModel = readContext.Model;

                DefaultODataPathHandler pathHandler = new DefaultODataPathHandler();
                string serviceRoot = GetServiceRoot(request);
                IDictionary <string, string> keyValues = GetKeys(pathHandler, edmModel, serviceRoot, entry.Id);

                IList <IEdmStructuralProperty> keys = entityTypeReference.Key().ToList();

                if (keys.Count == 1 && keyValues.Count == 1)
                {
                    object propertyValue = ODataUriUtils.ConvertFromUriLiteral(keyValues.First().Value, ODataVersion.V4, edmModel, keys[0].Type);
                    DeserializationHelpers.SetDeclaredProperty(source, EdmTypeKind.Primitive, keys[0].Name, propertyValue, keys[0], readContext);
                    return(source);
                }

                foreach (IEdmStructuralProperty key in keys)
                {
                    string value;
                    if (keyValues.TryGetValue(key.Name, out value))
                    {
                        object propertyValue = ODataUriUtils.ConvertFromUriLiteral(value, ODataVersion.V4, edmModel, key.Type);

                        DeserializationHelpers.SetDeclaredProperty(source, EdmTypeKind.Primitive, key.Name, propertyValue, key, readContext);
                    }
                }

                return(source);
            }
        public void SetCollectionProperty_ClearsCollection_IfClearCollectionIsTrue(string propertyName)
        {
            // Arrange
            IEnumerable <int> value    = new int[] { 1, 2, 3 };
            object            resource = new SampleClassWithNonSettableCollectionProperties
            {
                ICollection = { 42 },
                IList       = { 42 },
                Collection  = { 42 },
                List        = { 42 },
                CustomCollectionWithNoEmptyCtor = { 42 },
                CustomCollection = { 42 }
            };

            // Act
            DeserializationHelpers.SetCollectionProperty(resource, propertyName, null, value, clearCollection: true);

            // Assert
            Assert.Equal(
                value,
                resource.GetType().GetProperty(propertyName).GetValue(resource, index: null) as IEnumerable <int>);
        }
Beispiel #22
0
        public void SetCollectionProperty_CanConvertDataTime_ByTimeZoneInfo()
        {
            // Arrange
            SampleClassWithDifferentCollectionProperties source = new SampleClassWithDifferentCollectionProperties();
            IEdmProperty edmProperty = GetMockEdmProperty("DateTimeList", EdmPrimitiveTypeKind.DateTimeOffset);

            TimeZoneInfo           tzi  = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
            DateTime               dt   = new DateTime(2014, 11, 15, 1, 2, 3);
            IList <DateTimeOffset> dtos = new List <DateTimeOffset>
            {
                new DateTimeOffset(dt, TimeSpan.Zero),
                new DateTimeOffset(dt, new TimeSpan(+7, 0, 0)),
                new DateTimeOffset(dt, new TimeSpan(-8, 0, 0))
            };

            // Act
            DeserializationHelpers.SetCollectionProperty(source, edmProperty, dtos, edmProperty.Name, timeZoneInfo: tzi);

            // Assert
            Assert.Equal(new List <DateTime> {
                dt.AddHours(-8), dt.AddHours(-15), dt
            }, source.DateTimeList);
        }
Beispiel #23
0
        internal static Uri GenerateFunctionLink(this FeedContext feedContext, string bindingParameterType,
                                                 string functionName, IEnumerable <string> parameterNames)
        {
            Contract.Assert(feedContext != null);

            if (feedContext.EntitySetBase is IEdmContainedEntitySet)
            {
                return(null);
            }

            IList <ODataPathSegment> functionPathSegments = new List <ODataPathSegment>();

            feedContext.GenerateBaseODataPathSegmentsForFeed(functionPathSegments);

            // generate link with cast if the navigation source type doesn't match the entity type the function is bound to.
            if (feedContext.EntitySetBase.Type.FullTypeName() != bindingParameterType)
            {
                string elementType = DeserializationHelpers.GetCollectionElementTypeName(bindingParameterType, isNested: false);
                Contract.Assert(elementType != null);
                functionPathSegments.Add(new CastPathSegment(elementType));
            }

            Dictionary <string, string> parametersDictionary = new Dictionary <string, string>();

            // skip the binding parameter
            foreach (string param in parameterNames.Skip(1))
            {
                parametersDictionary.Add(param, "@" + param);
            }

            functionPathSegments.Add(new BoundFunctionPathSegment(functionName, parametersDictionary));

            string functionLink = feedContext.Url.CreateODataLink(functionPathSegments);

            return(functionLink == null ? null : new Uri(functionLink));
        }
Beispiel #24
0
        public async Task <IQueryable> ExecuteOperationAsync(
            OperationContext context, CancellationToken cancellationToken)
        {
            // Authorization check
            await InvokeAuthorizers(context, cancellationToken);

            // model build does not support operation with same name
            // So method with same name but different signature is not considered.
            MethodInfo method = context.ImplementInstance.GetType().GetMethod(
                context.OperationName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);

            if (method == null)
            {
                throw new NotImplementedException(Resources.OperationNotImplemented);
            }

            var parameterArray = method.GetParameters();

            var model = context.GetApiService <IEdmModel>();

            // Parameters of method and model is exactly mapped or there is parsing error
            var parameters = new object[parameterArray.Length];

            int paraIndex = 0;

            if (context.BindingParameterValue != null)
            {
                // Add binding parameter which is first parameter of method
                parameters[0] = PrepareBindingParameter(parameterArray[0].ParameterType, context.BindingParameterValue);
                paraIndex     = 1;
            }

            for (; paraIndex < parameterArray.Length; paraIndex++)
            {
                var parameter             = parameterArray[paraIndex];
                var currentParameterValue = context.GetParameterValueFunc(parameter.Name);

                object convertedValue = null;
                if (context.IsFunction)
                {
                    var parameterTypeRef = parameter.ParameterType.GetTypeReference(model);

                    // Change to right CLR class for collection/Enum/Complex/Entity
                    convertedValue = DeserializationHelpers.ConvertValue(
                        currentParameterValue,
                        parameter.Name,
                        parameter.ParameterType,
                        parameterTypeRef,
                        model,
                        context.Request,
                        context.ServiceProvider);
                }
                else
                {
                    convertedValue = DeserializationHelpers.ConvertCollectionType(
                        currentParameterValue, parameter.ParameterType);
                }

                parameters[paraIndex] = convertedValue;
            }

            context.ParameterValues = parameters;

            // Invoke preprocessing on the operation execution
            PerformPreEvent(context, cancellationToken);

            var result = await InvokeOperation(context.ImplementInstance, method, parameters, model);

            // Invoke preprocessing on the operation execution
            PerformPostEvent(context, cancellationToken);
            return(result);
        }
 public static T WithClearedConcurrency <T>(this T facet) where T : Facet
 {
     DeserializationHelpers.SetConcurrencyToken(facet, null);
     return(facet);
 }
Beispiel #26
0
 private string OADate(DateTime date)
 {
     return(DeserializationHelpers.ConvertToPrtgDateTime(date).ToString());
 }
        /// <summary>
        /// Asynchronously executes an operation.
        /// </summary>
        /// <param name="context">
        /// The operation context.
        /// </param>
        /// <param name="cancellationToken">
        /// A cancellation token.
        /// </param>
        /// <returns>
        /// A task that represents the asynchronous
        /// operation whose result is a operation result.
        /// </returns>
        public async Task <IQueryable> ExecuteOperationAsync(OperationContext context, CancellationToken cancellationToken)
        {
            Ensure.NotNull(context, nameof(context));

            // Authorization check
#pragma warning disable CA1062 // Validate arguments of public methods. JWS: Ensure.NotNull is there. Spurious warning.
            await InvokeAuthorizers(context, cancellationToken).ConfigureAwait(false);

#pragma warning restore CA1062 // Validate arguments of public methods.

            // model build does not support operation with same name
            // So method with same name but different signature is not considered.
            var method = context.Api.GetType().GetMethod(context.OperationName,
                                                         BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);

            if (method == null)
            {
                throw new NotImplementedException(Resources.OperationNotImplemented);
            }

            var parameterArray = method.GetParameters();

            var model = await context.Api.GetModelAsync(cancellationToken).ConfigureAwait(false);

            // Parameters of method and model is exactly mapped or there is parsing error
            var parameters = new object[parameterArray.Length];

            var paraIndex = 0;
            if (context.BindingParameterValue != null)
            {
                // Add binding parameter which is first parameter of method
                parameters[0] = PrepareBindingParameter(parameterArray[0].ParameterType, context.BindingParameterValue);
                paraIndex     = 1;
            }

            for (; paraIndex < parameterArray.Length; paraIndex++)
            {
                var parameter             = parameterArray[paraIndex];
                var currentParameterValue = context.GetParameterValueFunc(parameter.Name);

                object convertedValue = null;
                if (context.IsFunction)
                {
                    var parameterTypeRef = parameter.ParameterType.GetTypeReference(model);

                    // Change to right CLR class for collection/Enum/Complex/Entity
                    convertedValue = DeserializationHelpers.ConvertValue(
                        currentParameterValue,
                        parameter.Name,
                        parameter.ParameterType,
                        parameterTypeRef,
                        model,
                        context.Request,
                        context.Request.GetRequestContainer()); // JWS: As long as OData requires the ServiceProvder,
                                                                //      we have to provide it. DI abuse smell.
                }
                else
                {
                    convertedValue = DeserializationHelpers.ConvertCollectionType(
                        currentParameterValue, parameter.ParameterType);
                }

                parameters[paraIndex] = convertedValue;
            }

            context.ParameterValues = parameters;

            // Invoke preprocessing on the operation execution
            await PerformPreEvent(context, cancellationToken).ConfigureAwait(false);

            var result = await InvokeOperation(context.Api, method, parameters, model).ConfigureAwait(false);

            // Invoke preprocessing on the operation execution
            await PerformPostEvent(context, cancellationToken).ConfigureAwait(false);

            return(result);
        }