Esempio n. 1
0
        public void ServiceActionParameterInvalidCasesTest()
        {
            ResourceType complexType           = new ResourceType(typeof(object), ResourceTypeKind.ComplexType, null, "foo", "Address", false);
            ResourceType entityType            = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "foo", "Order", false);
            ResourceSet  entitySet             = new ResourceSet("Set", entityType);
            ResourceType collectionOfPrimitive = ResourceType.GetCollectionResourceType(ResourceType.GetPrimitiveResourceType(typeof(int)));
            ResourceType collectionOfComplex   = ResourceType.GetCollectionResourceType(complexType);
            ResourceType collectionType        = ResourceType.GetEntityCollectionResourceType(entityType);

            var parameterTypes = ResourceTypeUtils.GetPrimitiveResourceTypes()
                                 .Concat(new ResourceType[] {
                complexType,
                entityType,
                collectionOfPrimitive,
                collectionOfComplex,
                collectionType
            });

            AstoriaTestNS.TestUtil.RunCombinations(parameterTypes, (parameterType) =>
            {
                Exception e = AstoriaTestNS.TestUtil.RunCatching(() => new ServiceActionParameter("p", parameterType));
                if (parameterType != ResourceType.GetPrimitiveResourceType(typeof(System.IO.Stream)))
                {
                    Assert.IsNull(e, "Service op parameter should have succeeded.");
                }
                else
                {
                    ExceptionUtils.IsExpectedException <ArgumentException>(e, "The service operation parameter 'p' of type 'Edm.Stream' is not supported.\r\nParameter name: parameterType");
                }
            });
        }
Esempio n. 2
0
        public void ServiceOperationTypes()
        {
            ResourceType complexType           = new ResourceType(typeof(object), ResourceTypeKind.ComplexType, null, "foo", "Address", false);
            ResourceType entityType            = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "foo", "Order", false);
            ResourceSet  entitySet             = new ResourceSet("Set", entityType);
            ResourceType collectionOfPrimitive = ResourceType.GetCollectionResourceType(ResourceType.GetPrimitiveResourceType(typeof(int)));
            ResourceType collectionOfComplex   = ResourceType.GetCollectionResourceType(complexType);

            var returnTypeDirectCases = ResourceTypeUtils.GetPrimitiveResourceTypes().Select(rt => new { Type = rt, Set = (ResourceSet)null, Invalid = rt.InstanceType == typeof(System.IO.Stream) ? true : false })
                                        .Concat(new[] {
                new { Type = complexType, Set = (ResourceSet)null, Invalid = false },
                new { Type = entityType, Set = entitySet, Invalid = false }
            })
                                        .Concat(new ResourceType[] { collectionOfPrimitive, collectionOfComplex }.Select(rt => new { Type = rt, Set = (ResourceSet)null, Invalid = true }));

            AstoriaTestNS.TestUtil.RunCombinations(returnTypeDirectCases, (returnTypeDirectCase) =>
            {
                Exception e = AstoriaTestNS.TestUtil.RunCatching(() =>
                                                                 new ServiceOperation("so", ServiceOperationResultKind.DirectValue, returnTypeDirectCase.Type, returnTypeDirectCase.Set, "GET", null));
                if (returnTypeDirectCase.Invalid)
                {
                    Assert.IsNotNull(e, "Service op should have failed to be constructed.");
                    Assert.IsTrue(e is ArgumentException, "Invalid exception type.");
                }
                else
                {
                    Assert.IsNull(e, "Service op should have succeeded.");
                }
            });
        }
Esempio n. 3
0
        public void VerifyVersionOfCollectionResourceTypeIsV3()
        {
            ResourceType rt = ResourceType.GetCollectionResourceType(ResourceType.GetPrimitiveResourceType(typeof(int)));

            Assert.AreEqual(v4, rt.MetadataVersion, "MetadataVersion must be 4.0");
            Assert.AreEqual(MetadataEdmSchemaVersion.Version4Dot0, rt.SchemaVersion, "Schema version must be 4.0");
        }
Esempio n. 4
0
        /// <summary>Adds a collection of complex or primitive items property.</summary>
        /// <param name="resourceType">The resource type to add the property to.</param>
        /// <param name="name">The name of the property to add.</param>
        /// <param name="itemType">The resource type of the item in the collection.</param>
        public void AddCollectionProperty(ResourceType resourceType, string name, ResourceType itemType)
        {
            var property = new ResourceProperty(
                name,
                ResourcePropertyKind.Collection,
                ResourceType.GetCollectionResourceType(itemType));

            property.CanReflectOnInstanceTypeProperty = false;
            resourceType.AddProperty(property);
        }
Esempio n. 5
0
        internal void AddComplexCollectionProperty(ResourceType resourceType, string name, ResourceType complexType)
        {
            CollectionResourceType collectionResourceType          = ResourceType.GetCollectionResourceType(complexType);
            ResourceProperty       resourcePropertyWithDescription = new ResourcePropertyWithDescription(name, ResourcePropertyKind.Collection, collectionResourceType);

            resourcePropertyWithDescription.CanReflectOnInstanceTypeProperty = false;
            PropertyCustomState propertyCustomState = new PropertyCustomState();

            resourcePropertyWithDescription.CustomState = propertyCustomState;
            resourceType.AddProperty(resourcePropertyWithDescription);
        }
Esempio n. 6
0
        internal static void AddResourcePropertyFromInstanceCollectionResourceType(this ResourceType resourceType, ResourceType propertyCollection)
        {
            var resourceProperty = new ResourceProperty(
                propertyCollection.Name,
                ResourcePropertyKind.Collection,
                ResourceType.GetCollectionResourceType(propertyCollection));

            resourceProperty.CanReflectOnInstanceTypeProperty = false;
            resourceProperty.GetAnnotation().InstanceProperty = (PropertyInfo)propertyCollection.CustomState;
            resourceType.AddProperty(resourceProperty);
        }
Esempio n. 7
0
        internal void AddPrimitiveCollectionProperty(ResourceType resourceType, string name, Type propertyType, object defaultValue)
        {
            CollectionResourceType collectionResourceType          = ResourceType.GetCollectionResourceType(ResourceType.GetPrimitiveResourceType(propertyType));
            ResourceProperty       resourcePropertyWithDescription = new ResourcePropertyWithDescription(name, ResourcePropertyKind.Collection, collectionResourceType);

            resourcePropertyWithDescription.CanReflectOnInstanceTypeProperty = false;
            PropertyCustomState propertyCustomState = new PropertyCustomState();

            propertyCustomState.DefaultValue            = defaultValue;
            resourcePropertyWithDescription.CustomState = propertyCustomState;
            resourceType.AddProperty(resourcePropertyWithDescription);
        }
        private ResourceType GetNonEntityResourceType(Type type, IBsonSerializer serializer)
        {
            ResourceType resourceType;

            if (_knownResourceTypes.TryGetValue(type, out resourceType))
            {
                if (resourceType.ResourceTypeKind == ResourceTypeKind.EntityType)
                {
                    throw new InvalidOperationException("Entity types cannot be members of another entity type in MongoDB.");
                }

                return(resourceType);
            }

            var arraySerializer = serializer as IBsonArraySerializer;

            if (arraySerializer != null)
            {
                BsonSerializationInfo options;
                if (arraySerializer.TryGetItemSerializationInfo(out options))
                {
                    var elementType           = options.NominalType;
                    var elementTypeSerializer = options.Serializer;
                    var elementResourceType   = GetNonEntityResourceType(elementType, elementTypeSerializer);
                    return(ResourceType.GetCollectionResourceType(elementResourceType));
                }
                return(null);
            }

            var primitiveResourceType = ResourceType.GetPrimitiveResourceType(type);

            if (primitiveResourceType != null)
            {
                return(primitiveResourceType);
            }

            var documentSerializer = serializer as IBsonDocumentSerializer;

            if (documentSerializer != null)
            {
                resourceType = BuildHierarchyForType(type, ResourceTypeKind.ComplexType);
                if (resourceType != null)
                {
                    return(resourceType);
                }
            }

            throw new InvalidOperationException(string.Format("Unable to determine the resource type {0}.", type));
        }
Esempio n. 9
0
        public void InvalidCasesTest()
        {
            ResourceType complexType    = new ResourceType(typeof(object), ResourceTypeKind.ComplexType, null, "foo", "Address", false);
            ResourceType primitiveType  = ResourceType.GetPrimitiveResourceType(typeof(int));
            ResourceType collectionType = ResourceType.GetCollectionResourceType(primitiveType);

            AstoriaTestNS.TestUtil.RunCombinations(
                new ResourceType[] { complexType, primitiveType, collectionType },
                (resourceType) =>
            {
                ExceptionUtils.ExpectedException <ArgumentException>(
                    () => new ResourceSet("Foo", resourceType),
                    "The ResourceTypeKind property of a ResourceType instance that is associated with a ResourceSet must have a value of 'EntityType'.",
                    "Cannot add non-entity types to container");
            });
        }
Esempio n. 10
0
        /// <summary>
        /// Gets the return type of the operation.
        /// </summary>
        /// <param name="resultType">Type of element of the method result. This is the item type of the return type if the return type is a collection type.</param>
        /// <param name="resultKind">Kind of result expected from this operation.</param>
        /// <returns>Returns the return type of the operation.</returns>
        private static ResourceType GetReturnTypeFromResultType(ResourceType resultType, ServiceOperationResultKind resultKind)
        {
            if ((resultKind == ServiceOperationResultKind.Void && resultType != null) ||
                (resultKind != ServiceOperationResultKind.Void && resultType == null))
            {
                throw new ArgumentException(Strings.ServiceOperation_ResultTypeAndKindMustMatch("resultKind", "resultType", ServiceOperationResultKind.Void));
            }

            if (resultType != null && resultType.ResourceTypeKind == ResourceTypeKind.Collection)
            {
                throw new ArgumentException(Strings.ServiceOperation_InvalidResultType(resultType.FullName));
            }

            if (resultType != null && resultType.ResourceTypeKind == ResourceTypeKind.EntityCollection)
            {
                throw new ArgumentException(Strings.ServiceOperation_InvalidResultType(resultType.FullName));
            }

            ResourceType returnType;

            if (resultType == null)
            {
                Debug.Assert(resultKind == ServiceOperationResultKind.Void, "resultKind == ServiceOperationResultKind.Void");
                returnType = null;
            }
            else if ((resultType.ResourceTypeKind == ResourceTypeKind.Primitive || resultType.ResourceTypeKind == ResourceTypeKind.ComplexType) && (resultKind == ServiceOperationResultKind.Enumeration || resultKind == ServiceOperationResultKind.QueryWithMultipleResults))
            {
                returnType = ResourceType.GetCollectionResourceType(resultType);
            }
            else if (resultType.ResourceTypeKind == ResourceTypeKind.EntityType && (resultKind == ServiceOperationResultKind.Enumeration || resultKind == ServiceOperationResultKind.QueryWithMultipleResults))
            {
                returnType = ResourceType.GetEntityCollectionResourceType(resultType);
            }
            else
            {
                Debug.Assert(
                    resultKind == ServiceOperationResultKind.DirectValue || resultKind == ServiceOperationResultKind.QueryWithSingleResult,
                    "resultKind == ServiceOperationResultKind.DirectValue || resultKind == ServiceOperationResultKind.QueryWithSingleResult");
                returnType = resultType;
            }

            return(returnType);
        }
Esempio n. 11
0
        /// <summary>
        /// Get the resource type for the given clr type.
        /// </summary>
        /// <param name="metadataProvider">An instance of the IDataServiceMetadataProvider.</param>
        /// <param name="type">Clr type in question.</param>
        /// <param name="elementTypeName">Name of the element type if <paramref name="type"/> is a
        /// <see cref="DSPResource"/> type or a collection type of <see cref="DSPResource"/>.</param>
        /// <returns>The resource type for the given clr type.</returns>
        private static ResourceType GetResourceTypeFromType(IDataServiceMetadataProvider metadataProvider, Type type, string elementTypeName)
        {
            Debug.Assert(metadataProvider != null, "metadataProvider != null");
            if (type == typeof(void))
            {
                return(null);
            }

            ResourceType resourceType;
            Type         elementType = type;

            if (!type.IsPrimitive && type.IsGenericType && typeof(IEnumerable).IsAssignableFrom(type))
            {
                elementType = type.GetGenericArguments()[0];
            }

            if (elementType == typeof(DSPResource))
            {
                metadataProvider.TryResolveResourceType(elementTypeName, out resourceType);
            }
            else
            {
                resourceType = ResourceType.GetPrimitiveResourceType(elementType);
                if (resourceType == null && !metadataProvider.TryResolveResourceType(elementType.FullName, out resourceType))
                {
                    throw new DataServiceException(string.Format("The type '{0}' is unknown to the metadata provider.", elementType.FullName));
                }
            }

            if (type != elementType)
            {
                if (resourceType.ResourceTypeKind == ResourceTypeKind.EntityType)
                {
                    resourceType = ResourceType.GetEntityCollectionResourceType(resourceType);
                }
                else
                {
                    resourceType = ResourceType.GetCollectionResourceType(resourceType);
                }
            }

            return(resourceType);
        }
Esempio n. 12
0
        protected CollectionResourceType GetCollectionTypeFromName(string typeName, string propertyName)
        {
            if (string.IsNullOrEmpty(typeName))
            {
                throw DataServiceException.CreateBadRequestError(System.Data.Services.Strings.BadRequest_InvalidTypeName(typeName));
            }
            string collectionItemTypeName = CommonUtil.GetCollectionItemTypeName(typeName, false);

            if (collectionItemTypeName == null)
            {
                throw DataServiceException.CreateBadRequestError(System.Data.Services.Strings.BadRequest_CollectionTypeExpected(typeName, propertyName));
            }
            ResourceType itemType = WebUtil.TryResolveResourceType(this.Service.Provider, collectionItemTypeName);

            if (itemType == null)
            {
                throw DataServiceException.CreateBadRequestError(System.Data.Services.Strings.BadRequest_InvalidTypeName(typeName));
            }
            return(ResourceType.GetCollectionResourceType(itemType));
        }
Esempio n. 13
0
    // Allow all types: Primitive/Complex/Entity and IQueryable<> and IEnumerable<>
    private ResourceType GetResourceType(Type type)
    {
        if (type.IsGenericType)
        {
            var typeDef = type.GetGenericTypeDefinition();
            if (typeDef.GetGenericArguments().Count() == 1)
            {
                if (typeDef == typeof(IEnumerable <>) || typeDef == typeof(IQueryable <>))
                {
                    var elementResource = GetResourceType(type.GetGenericArguments().Single());
                    if ((elementResource.ResourceTypeKind | ResourceTypeKind.EntityType) == ResourceTypeKind.EntityType)
                    {
                        return(ResourceType.GetEntityCollectionResourceType(elementResource));
                    }
                    else
                    {
                        return(ResourceType.GetCollectionResourceType(elementResource));
                    }
                }
            }

            throw new Exception($"Generic action parameter type {type} not supported");
        }

        if (ActionFactory.__primitives.Contains(type))
        {
            return(ResourceType.GetPrimitiveResourceType(type));
        }

        var resourceType = _metadata.Types.SingleOrDefault(s => s.Name == type.Name);

        if (resourceType == null)
        {
            throw new Exception($"Generic action parameter type {type} not supported");
        }

        return(resourceType);
    }
Esempio n. 14
0
        public void ServiceActionConstructorTests()
        {
            ResourceProperty id           = new ResourceProperty("ID", ResourcePropertyKind.Primitive | ResourcePropertyKind.Key, ResourceType.GetPrimitiveResourceType(typeof(int)));
            ResourceType     customerType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "Foo", "Customer", false);

            customerType.AddProperty(id);
            customerType.SetReadOnly();
            ResourceSet  customerSet = new ResourceSet("Customers", customerType);
            ResourceType orderType   = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "Foo", "Order", false);

            orderType.AddProperty(id);
            orderType.SetReadOnly();

            ResourceType complexType           = new ResourceType(typeof(object), ResourceTypeKind.ComplexType, null, "foo", "Address", false);
            ResourceType collectionOfPrimitive = ResourceType.GetCollectionResourceType(ResourceType.GetPrimitiveResourceType(typeof(int)));
            ResourceType collectionOfComplex   = ResourceType.GetCollectionResourceType(complexType);
            ResourceType collectionOfCustomer  = ResourceType.GetEntityCollectionResourceType(customerType);
            ResourceType collectionOfOrder     = ResourceType.GetEntityCollectionResourceType(orderType);

            var types = ResourceTypeUtils.GetPrimitiveResourceTypes().Concat(new ResourceType[] { null, customerType, orderType, complexType, collectionOfPrimitive, collectionOfComplex, collectionOfCustomer, collectionOfOrder });
            var resultSetsOrPathExpressions = new object[] { null, customerSet, new ResourceSetPathExpression("p1/Foo") };
            var parameters = types.Except(new[] { ResourceType.GetPrimitiveResourceType(typeof(System.IO.Stream)) }).Select(t => t != null ? new ServiceActionParameter[] { new ServiceActionParameter("p1", t) } : new ServiceActionParameter[0]);

            parameters = parameters.Concat(types.Except(new[] { ResourceType.GetPrimitiveResourceType(typeof(System.IO.Stream)), null }).ToList().Combinations(2).Select(tt => new ServiceActionParameter[] { new ServiceActionParameter("p1", tt[0]), new ServiceActionParameter("p2", tt[1]) }));
            var operationParameterBindings = new OperationParameterBindingKind[] { OperationParameterBindingKind.Never, OperationParameterBindingKind.Sometimes, OperationParameterBindingKind.Always };

            AstoriaTestNS.TestUtil.RunCombinations(
                types, resultSetsOrPathExpressions, parameters, operationParameterBindings,
                (returnType, resultSetOrPathExpression, paramList, operationParameterBindingKind) =>
            {
                ServiceAction action    = null;
                ResourceSet resourceSet = resultSetOrPathExpression as ResourceSet;
                ResourceSetPathExpression pathExpression = resultSetOrPathExpression as ResourceSetPathExpression;
                bool bindable = (operationParameterBindingKind == OperationParameterBindingKind.Always || operationParameterBindingKind == OperationParameterBindingKind.Sometimes);
                Exception e   = null;

                try
                {
                    if (pathExpression != null)
                    {
                        bindable = true;
                        action   = new ServiceAction("foo", returnType, OperationParameterBindingKind.Sometimes, paramList, pathExpression);
                    }
                    else
                    {
                        action = new ServiceAction("foo", returnType, resourceSet, operationParameterBindingKind, paramList);
                    }
                }
                catch (Exception ex)
                {
                    e = ex;
                }
                if (resourceSet != null && operationParameterBindingKind != OperationParameterBindingKind.Never)
                {
                    ExceptionUtils.IsExpectedException <ArgumentException>(e, "When 'returnType' is an entity type or an entity collection type, 'resultSetPathExpression' and 'resultSet' cannot be both null and the resource type of the result set must be assignable from 'returnType'.");
                }
                else if (returnType != null && (returnType.ResourceTypeKind == ResourceTypeKind.EntityType || returnType.ResourceTypeKind == ResourceTypeKind.EntityCollection) &&
                         (resourceSet == null && pathExpression == null ||
                          resourceSet != null && returnType.ResourceTypeKind == ResourceTypeKind.EntityType && resourceSet.ResourceType != returnType ||
                          resourceSet != null && returnType.ResourceTypeKind == ResourceTypeKind.EntityCollection && resourceSet.ResourceType != ((EntityCollectionResourceType)returnType).ItemType))
                {
                    ExceptionUtils.IsExpectedException <ArgumentException>(e, "When 'returnType' is an entity type or an entity collection type, 'resultSetPathExpression' and 'resultSet' cannot be both null and the resource type of the result set must be assignable from 'returnType'.");
                }
                else if ((returnType == null || returnType.ResourceTypeKind != ResourceTypeKind.EntityCollection && returnType.ResourceTypeKind != ResourceTypeKind.EntityType) && resourceSet != null)
                {
                    ExceptionUtils.IsExpectedException <ArgumentException>(e, "'resultSet' must be null when 'returnType' is null, not an entity type or not an entity collection type.");
                }
                else if ((returnType == null || returnType.ResourceTypeKind != ResourceTypeKind.EntityCollection && returnType.ResourceTypeKind != ResourceTypeKind.EntityType) && pathExpression != null)
                {
                    ExceptionUtils.IsExpectedException <ArgumentException>(e, "'resultSetPathExpression' must be null when 'returnType' is null, not an entity type or not an entity collection type.");
                }
                else if (returnType == ResourceType.GetPrimitiveResourceType(typeof(System.IO.Stream)))
                {
                    ExceptionUtils.IsExpectedException <ArgumentException>(e, "The resource type 'Edm.Stream' is not a type that can be returned by a function or action. A function or action can only return values of an entity type, an entity collection type, a complex type, a collection type or any primitive type, other than the stream type.\r\nParameter name: returnType");
                }
                else if (paramList.Length > 0 && paramList.Skip(bindable ? 1 : 0).Any(p => p.ParameterType.ResourceTypeKind == ResourceTypeKind.EntityType || p.ParameterType.ResourceTypeKind == ResourceTypeKind.EntityCollection))
                {
                    var param             = paramList.Skip(bindable ? 1 : 0).First(p => p.ParameterType.ResourceTypeKind == ResourceTypeKind.EntityType || p.ParameterType.ResourceTypeKind == ResourceTypeKind.EntityCollection);
                    var parameterTypeKind = param.ParameterType.ResourceTypeKind;
                    ExceptionUtils.IsExpectedException <ArgumentException>(e, string.Format("The '{0}' parameter is of resource type kind '{1}' and it is not the binding parameter. Parameter of type kind '{1}' is only supported for the binding parameter.", param.Name, parameterTypeKind));
                }
                else if (pathExpression != null && !bindable)
                {
                    ExceptionUtils.IsExpectedException <ArgumentException>(e, "The binding parameter type must be an entity type or an entity collection type when 'resultSetPathExpression' is not null.");
                }
                else if (bindable && paramList.Length == 0)
                {
                    ExceptionUtils.IsExpectedException <ArgumentException>(e, "Bindable actions or functions must have at least one parameter, where the first parameter is the binding parameter.\r\nParameter name: operationParameterBindingKind");
                }
                else if (pathExpression != null && bindable && paramList.First().ParameterType.ResourceTypeKind != ResourceTypeKind.EntityType && paramList.First().ParameterType.ResourceTypeKind != ResourceTypeKind.EntityCollection)
                {
                    ExceptionUtils.IsExpectedException <ArgumentException>(e, "The binding parameter type must be an entity type or an entity collection type when 'resultSetPathExpression' is not null.");
                }
                else if (paramList.Length > 0 && bindable && paramList[0].ParameterType.ResourceTypeKind != ResourceTypeKind.EntityType && paramList[0].ParameterType.ResourceTypeKind != ResourceTypeKind.EntityCollection)
                {
                    ExceptionUtils.IsExpectedException <ArgumentException>(e, "An action's binding parameter must be of type Entity or EntityCollection.\r\nParameter name: parameters");
                }
                else
                {
                    Assert.IsNull(e, "Received exception but expected none. Exception message: {0}", e == null ? string.Empty : e.Message);
                    Assert.IsNotNull(action, "Action should be constructed.");

                    Assert.AreEqual("foo", action.Name, "unexpected name");
                    Assert.AreEqual(returnType, action.ReturnType, "unexpected return type");
                    Assert.AreEqual(resourceSet, action.ResourceSet, "unexpected result set");
                    Assert.AreEqual(pathExpression, action.ResultSetPathExpression, "unexpected path expression");
                    Assert.IsTrue(!bindable || action.BindingParameter == action.Parameters.First(), "unexpected binding parameter");
                    Assert.IsTrue(action.Method == "POST", "HttpMethod must be POST for ServiceActions.");
                    Assert.IsTrue(action.ResourceSet == null || action.ResultSetPathExpression == null, "'resultSet' and 'resultSetPathExpression' cannot be both set by the constructor.");
                }
            });
        }
Esempio n. 15
0
        public void GetTargetSetTestsSetBindingTypeShouldPerformCorrectValidation()
        {
            ResourceType actorEntityType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "foo", "Actor", false)
            {
                CanReflectOnInstanceType = false
            };
            ResourceProperty idProperty = new ResourceProperty("ID", ResourcePropertyKind.Primitive | ResourcePropertyKind.Key, ResourceType.GetPrimitiveResourceType(typeof(int)))
            {
                CanReflectOnInstanceTypeProperty = false
            };

            actorEntityType.AddProperty(idProperty);

            ResourceType addressComplexType = new ResourceType(typeof(object), ResourceTypeKind.ComplexType, null, "foo", "Address", false)
            {
                CanReflectOnInstanceType = false
            };

            addressComplexType.AddProperty(new ResourceProperty("StreetAddress", ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(string)))
            {
                CanReflectOnInstanceTypeProperty = false
            });
            addressComplexType.AddProperty(new ResourceProperty("ZipCode", ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(int)))
            {
                CanReflectOnInstanceTypeProperty = false
            });

            actorEntityType.AddProperty(new ResourceProperty("PrimaryAddress", ResourcePropertyKind.ComplexType, addressComplexType)
            {
                CanReflectOnInstanceTypeProperty = false
            });
            actorEntityType.AddProperty(new ResourceProperty("OtherAddresses", ResourcePropertyKind.Collection, ResourceType.GetCollectionResourceType(addressComplexType))
            {
                CanReflectOnInstanceTypeProperty = false
            });

            ResourceType movieEntityType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "foo", "Movie", false)
            {
                CanReflectOnInstanceType = false
            };

            movieEntityType.AddProperty(idProperty);

            ResourceProperty moviesNavProp = new ResourceProperty("Movies", ResourcePropertyKind.ResourceSetReference, movieEntityType)
            {
                CanReflectOnInstanceTypeProperty = false
            };

            actorEntityType.AddProperty(moviesNavProp);
            ResourceProperty actorsNavProp = new ResourceProperty("Actors", ResourcePropertyKind.ResourceSetReference, actorEntityType)
            {
                CanReflectOnInstanceTypeProperty = false
            };

            movieEntityType.AddProperty(actorsNavProp);

            ResourceType derivedActorEntityType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, actorEntityType, "foo", "DerivedActor", false)
            {
                CanReflectOnInstanceType = false
            };
            ResourceType derivedMovieEntityType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, movieEntityType, "foo", "DerivedMovie", false)
            {
                CanReflectOnInstanceType = false
            };

            actorEntityType.SetReadOnly();
            derivedActorEntityType.SetReadOnly();
            movieEntityType.SetReadOnly();
            derivedMovieEntityType.SetReadOnly();
            addressComplexType.SetReadOnly();
            DataServiceProviderSimulator providerSimulator = new DataServiceProviderSimulator();

            providerSimulator.AddResourceType(actorEntityType);
            providerSimulator.AddResourceType(derivedActorEntityType);
            providerSimulator.AddResourceType(movieEntityType);
            providerSimulator.AddResourceType(derivedMovieEntityType);
            providerSimulator.AddResourceType(addressComplexType);

            ResourceSet actorSet = new ResourceSet("Actors", actorEntityType);
            ResourceSet movieSet = new ResourceSet("Movies", movieEntityType);

            actorSet.SetReadOnly();
            movieSet.SetReadOnly();
            providerSimulator.AddResourceSet(actorSet);
            providerSimulator.AddResourceSet(movieSet);

            providerSimulator.AddResourceAssociationSet(new ResourceAssociationSet("Actors_Movies", new ResourceAssociationSetEnd(actorSet, actorEntityType, moviesNavProp), new ResourceAssociationSetEnd(movieSet, movieEntityType, actorsNavProp)));

            DataServiceConfiguration config = new DataServiceConfiguration(providerSimulator);

            config.SetEntitySetAccessRule("*", EntitySetRights.All);
            config.DataServiceBehavior.MaxProtocolVersion = ODataProtocolVersion.V4;

            var dataService = new DataServiceSimulator()
            {
                OperationContext = new DataServiceOperationContext(new DataServiceHostSimulator())
            };

            dataService.ProcessingPipeline = new DataServiceProcessingPipeline();
            DataServiceStaticConfiguration staticConfiguration = new DataServiceStaticConfiguration(dataService.Instance.GetType(), providerSimulator);
            IDataServiceProviderBehavior   providerBehavior    = DataServiceProviderBehavior.CustomDataServiceProviderBehavior;

            DataServiceProviderWrapper provider = new DataServiceProviderWrapper(
                new DataServiceCacheItem(
                    config,
                    staticConfiguration),
                providerSimulator,
                providerSimulator,
                dataService,
                false);

            dataService.Provider      = provider;
            provider.ProviderBehavior = providerBehavior;

            var testCases = new[]
            {
                new
                {
                    AppendParameterName = true,
                    Path         = "",
                    BindingSet   = ResourceSetWrapper.CreateResourceSetWrapper(actorSet, provider, set => set),
                    TargetSet    = ResourceSetWrapper.CreateResourceSetWrapper(actorSet, provider, set => set),
                    ErrorMessage = default(string)
                },
                new
                {
                    AppendParameterName = true,
                    Path         = "/Movies",
                    BindingSet   = ResourceSetWrapper.CreateResourceSetWrapper(actorSet, provider, set => set),
                    TargetSet    = ResourceSetWrapper.CreateResourceSetWrapper(movieSet, provider, set => set),
                    ErrorMessage = default(string)
                },
                new
                {
                    AppendParameterName = true,
                    Path         = "/Movies/Actors/Movies",
                    BindingSet   = ResourceSetWrapper.CreateResourceSetWrapper(actorSet, provider, set => set),
                    TargetSet    = ResourceSetWrapper.CreateResourceSetWrapper(movieSet, provider, set => set),
                    ErrorMessage = default(string)
                },
                new
                {
                    AppendParameterName = true,
                    Path         = "/foo.DerivedActor/Movies/foo.DerivedMovie/Actors/foo.DerivedActor/Movies",
                    BindingSet   = ResourceSetWrapper.CreateResourceSetWrapper(actorSet, provider, set => set),
                    TargetSet    = ResourceSetWrapper.CreateResourceSetWrapper(movieSet, provider, set => set),
                    ErrorMessage = default(string)
                },
                new
                {
                    AppendParameterName = true,
                    Path         = "/",
                    BindingSet   = ResourceSetWrapper.CreateResourceSetWrapper(actorSet, provider, set => set),
                    TargetSet    = default(ResourceSetWrapper),
                    ErrorMessage = "The path expression '{0}/' is not a valid expression because it contains an empty segment or it ends with '/'."
                },
                new
                {
                    AppendParameterName = true,
                    Path         = "/Movies/",
                    BindingSet   = ResourceSetWrapper.CreateResourceSetWrapper(actorSet, provider, set => set),
                    TargetSet    = default(ResourceSetWrapper),
                    ErrorMessage = "The path expression '{0}/Movies/' is not a valid expression because it contains an empty segment or it ends with '/'."
                },
                new
                {
                    AppendParameterName = true,
                    Path         = "/Movies//Actors",
                    BindingSet   = ResourceSetWrapper.CreateResourceSetWrapper(actorSet, provider, set => set),
                    TargetSet    = ResourceSetWrapper.CreateResourceSetWrapper(movieSet, provider, set => set),
                    ErrorMessage = "The path expression '{0}/Movies//Actors' is not a valid expression because it contains an empty segment or it ends with '/'."
                },
                new
                {
                    AppendParameterName = true,
                    Path         = "/foo.DerivedActor",
                    BindingSet   = ResourceSetWrapper.CreateResourceSetWrapper(actorSet, provider, set => set),
                    TargetSet    = default(ResourceSetWrapper),
                    ErrorMessage = "The path expression '{0}/foo.DerivedActor' is not a valid expression because it ends with the type identifier 'foo.DerivedActor'. A valid path expression must not end in a type identifier."
                },
                new
                {
                    AppendParameterName = true,
                    Path         = "/Movies/foo.DerivedMovie",
                    BindingSet   = ResourceSetWrapper.CreateResourceSetWrapper(actorSet, provider, set => set),
                    TargetSet    = default(ResourceSetWrapper),
                    ErrorMessage = "The path expression '{0}/Movies/foo.DerivedMovie' is not a valid expression because it ends with the type identifier 'foo.DerivedMovie'. A valid path expression must not end in a type identifier."
                },
                new
                {
                    AppendParameterName = true,
                    Path         = "/Foo",
                    BindingSet   = ResourceSetWrapper.CreateResourceSetWrapper(actorSet, provider, set => set),
                    TargetSet    = default(ResourceSetWrapper),
                    ErrorMessage = "The path expression '{0}/Foo' is not a valid expression because the segment 'Foo' is not a type identifier or a property on the resource type 'foo.Actor'."
                },
                new
                {
                    AppendParameterName = true,
                    Path         = "/ID",
                    BindingSet   = ResourceSetWrapper.CreateResourceSetWrapper(actorSet, provider, set => set),
                    TargetSet    = default(ResourceSetWrapper),
                    ErrorMessage = "The path expression '{0}/ID' is not a valid expression because the segment 'ID' is a property of type 'Edm.Int32'. A valid path expression must only contain properties of entity type."
                },
                new
                {
                    AppendParameterName = true,
                    Path         = "/OtherAddresses",
                    BindingSet   = ResourceSetWrapper.CreateResourceSetWrapper(actorSet, provider, set => set),
                    TargetSet    = default(ResourceSetWrapper),
                    ErrorMessage = "The path expression '{0}/OtherAddresses' is not a valid expression because the segment 'OtherAddresses' is a property of type 'Collection(foo.Address)'. A valid path expression must only contain properties of entity type."
                },
                new
                {
                    AppendParameterName = true,
                    Path         = "/Movies/Actors/PrimaryAddress",
                    BindingSet   = ResourceSetWrapper.CreateResourceSetWrapper(actorSet, provider, set => set),
                    TargetSet    = default(ResourceSetWrapper),
                    ErrorMessage = "The path expression '{0}/Movies/Actors/PrimaryAddress' is not a valid expression because the segment 'PrimaryAddress' is a property of type 'foo.Address'. A valid path expression must only contain properties of entity type."
                },
                new
                {
                    AppendParameterName = false,
                    Path         = "foo",
                    BindingSet   = ResourceSetWrapper.CreateResourceSetWrapper(actorSet, provider, set => set),
                    TargetSet    = default(ResourceSetWrapper),
                    ErrorMessage = "The path expression 'foo' is not a valid path expression. A valid path expression must start with the binding parameter name '{0}'."
                },
                new
                {
                    AppendParameterName = false,
                    Path         = "abc/pqr",
                    BindingSet   = ResourceSetWrapper.CreateResourceSetWrapper(actorSet, provider, set => set),
                    TargetSet    = default(ResourceSetWrapper),
                    ErrorMessage = "The path expression 'abc/pqr' is not a valid path expression. A valid path expression must start with the binding parameter name '{0}'."
                },
                new
                {
                    AppendParameterName = false,
                    Path         = "actorParameter",
                    BindingSet   = ResourceSetWrapper.CreateResourceSetWrapper(actorSet, provider, set => set),
                    TargetSet    = default(ResourceSetWrapper),
                    ErrorMessage = "The path expression 'actorParameter' is not a valid path expression. A valid path expression must start with the binding parameter name '{0}'."
                },
                new
                {
                    AppendParameterName = false,
                    Path         = "actorsParameter",
                    BindingSet   = ResourceSetWrapper.CreateResourceSetWrapper(actorSet, provider, set => set),
                    TargetSet    = default(ResourceSetWrapper),
                    ErrorMessage = "The path expression 'actorsParameter' is not a valid path expression. A valid path expression must start with the binding parameter name '{0}'."
                },
            };

            ServiceActionParameter actorParameter  = new ServiceActionParameter("actor", actorEntityType);
            ServiceActionParameter actorsParameter = new ServiceActionParameter("actors", ResourceType.GetEntityCollectionResourceType(actorEntityType));
            var parameters = new ServiceActionParameter[] { actorParameter, actorsParameter };

            foreach (var parameter in parameters)
            {
                foreach (var testCase in testCases)
                {
                    string pathString = testCase.AppendParameterName ? parameter.Name + testCase.Path : testCase.Path;
                    var    path       = new ResourceSetPathExpression(pathString);
                    Assert.AreEqual(pathString, path.PathExpression);
                    string expectedErrorMessage = testCase.ErrorMessage == null ? null : string.Format(testCase.ErrorMessage, parameter.Name);
                    try
                    {
                        path.SetBindingParameter(parameter);
                        path.InitializePathSegments(provider);
                        var targetSet = path.GetTargetSet(provider, testCase.BindingSet);
                        Assert.IsNull(expectedErrorMessage, "Expecting exception but received none.");
                        Assert.AreEqual(targetSet.Name, testCase.TargetSet.Name);
                    }
                    catch (InvalidOperationException e)
                    {
                        Assert.AreEqual(expectedErrorMessage, e.Message);
                    }
                }
            }
        }
Esempio n. 16
0
        public void InvalidCasesTest()
        {
            ResourceType rt = (ResourceType)ResourceTypeUtils.GetTestInstance(typeof(ResourceType));

            ResourceType complexType = new ResourceType(typeof(object), ResourceTypeKind.ComplexType, null, "Namespace", "Address", false);
            ResourceType entityType  = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "Namespace", "Order", false);
            ResourceType primitiveOrComplexCollectionType = ResourceType.GetCollectionResourceType(complexType);
            ResourceType entityCollectionType             = ResourceType.GetEntityCollectionResourceType(entityType);
            ResourceType namedStreamType = ResourceType.GetPrimitiveResourceType(typeof(System.IO.Stream));

            AstoriaTestNS.TestUtil.RunCombinations(
                GetPropertyKindValues(),
                new ResourceType[] { entityType, complexType, primitiveOrComplexCollectionType, entityCollectionType }.Concat(ResourceTypeUtils.GetPrimitiveResourceTypes()),
                (kind, type) =>
            {
                bool invalidCase = true;

                if (IsValidValue(kind))
                {
                    if ((kind.HasFlag(ResourcePropertyKind.Primitive) && type.ResourceTypeKind == ResourceTypeKind.Primitive && type != namedStreamType) ||
                        (kind.HasFlag(ResourcePropertyKind.ComplexType) && type.ResourceTypeKind == ResourceTypeKind.ComplexType) ||
                        (kind.HasFlag(ResourcePropertyKind.ResourceReference) && type.ResourceTypeKind == ResourceTypeKind.EntityType) ||
                        (kind.HasFlag(ResourcePropertyKind.ResourceSetReference) && type.ResourceTypeKind == ResourceTypeKind.EntityType) ||
                        (kind.HasFlag(ResourcePropertyKind.Collection) && type.ResourceTypeKind == ResourceTypeKind.Collection) ||
                        (kind.HasFlag(ResourcePropertyKind.Stream) && type == namedStreamType))
                    {
                        invalidCase = false;
                    }

                    if ((kind & ResourcePropertyKind.Key) == ResourcePropertyKind.Key &&
                        type.InstanceType.IsGenericType && type.InstanceType.GetGenericTypeDefinition() == typeof(Nullable <>))
                    {
                        invalidCase = true;
                    }
                }

                if (invalidCase)
                {
                    ExceptionUtils.ThrowsException <ArgumentException>(
                        () => new ResourceProperty("TestProperty", kind, type),
                        string.Format("resource property constructor test case. Kind: '{0}', Type: '{1}: {2}'", kind, type.ResourceTypeKind, type.InstanceType));
                }
                else
                {
                    ResourceProperty p = new ResourceProperty("TestProperty", kind, type);
                    Assert.AreEqual("TestProperty", p.Name, "Name was not stored properly");
                    Assert.AreEqual(kind, p.Kind, "Kind was not stored properly");
                    Assert.AreEqual(type, p.ResourceType, "Type was not stored properly");
                    Assert.AreEqual(p.Kind.HasFlag(ResourcePropertyKind.Stream) ? false : true, p.CanReflectOnInstanceTypeProperty, "CanReflectOnInstanceTypeProperty should be true by default on non-NamedStreams, and false on NamedStreams.");
                    Assert.IsNull(p.MimeType, "MimeType should be null by default.");

                    if (p.Kind.HasFlag(ResourcePropertyKind.Stream))
                    {
                        ExceptionUtils.ThrowsException <InvalidOperationException>(
                            () => { p.CanReflectOnInstanceTypeProperty = false; },
                            "CanReflectOnInstanceTypeProperty should be settable on non-namedstreams, and not settable on namedstreams");
                    }
                    else
                    {
                        p.CanReflectOnInstanceTypeProperty = false;
                    }

                    Assert.AreEqual(false, p.CanReflectOnInstanceTypeProperty, "CanReflectOnInstanceTypeProperty should be false.");

                    bool shouldFail = true;
                    if ((kind & ResourcePropertyKind.Primitive) == ResourcePropertyKind.Primitive)
                    {
                        shouldFail = false;
                    }

                    if (shouldFail)
                    {
                        ExceptionUtils.ThrowsException <InvalidOperationException>(
                            () => p.MimeType = "plain/text",
                            string.Format("Setting MimeType on non-primitive property should fail. Kind: '{0}', Type: '{1}: {2}'", kind, type.ResourceTypeKind, type.InstanceType));
                    }
                    else
                    {
                        p.MimeType = "plain/text";
                    }
                }
            });
        }
Esempio n. 17
0
        internal static void AddResourcePropertyFromInstancePropertyInfo(this ResourceType resourceType, PropertyInfo property)
        {
            var resourcePropertyType      = ResourceType.GetPrimitiveResourceType(property.PropertyType);
            var innerEnumerableType       = TypeSystem.GetIEnumerableElementType(property.PropertyType);
            var innerResourcePropertyType = null != innerEnumerableType?ResourceType.GetPrimitiveResourceType(innerEnumerableType) : null;

            resourcePropertyType = null == resourcePropertyType && null != innerResourcePropertyType?ResourceType.GetCollectionResourceType(innerResourcePropertyType) : resourcePropertyType;

            if (null == resourcePropertyType)
            {
                return;
            }

            var resourcePropertyKind = null == innerResourcePropertyType ? ResourcePropertyKind.Primitive : ResourcePropertyKind.Collection;
            var resourceProperty     = new ResourceProperty(
                property.Name,
                resourcePropertyKind,
                resourcePropertyType);

            resourceProperty.CanReflectOnInstanceTypeProperty = false;
            resourceProperty.GetAnnotation().InstanceProperty = property;
            resourceType.AddProperty(resourceProperty);
        }
Esempio n. 18
0
        /// <summary>Adds a property of type collection of primitive or complex typed items.</summary>
        /// <param name="resourceType">The resource type to add the property to.</param>
        /// <param name="name">The name of the property to add.</param>
        /// <param name="collectionItemType">Primitive or complex type for items in the collection.</param>
        private void AddCollectionPropertyInner(ResourceType resourceType, string name, ResourceType collectionItemType)
        {
            PropertyInfo propertyInfo = resourceType.InstanceType.GetProperty(name);

            AddResourceProperty(resourceType, name, ResourcePropertyKind.Collection, ResourceType.GetCollectionResourceType(collectionItemType), propertyInfo);
        }
        public void CollectionTypeValidation()
        {
            ResourceType entityType   = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "foo", "Order", false);
            ResourceType complexType  = new ResourceType(typeof(object), ResourceTypeKind.ComplexType, null, "foo", "bar", false);
            ResourceType complexType2 = new ResourceType(typeof(object), ResourceTypeKind.ComplexType, null, "foo", "bar2", false);

            complexType2.AddProperty(new ResourceProperty("CollectionProperty", ResourcePropertyKind.Collection, ResourceType.GetCollectionResourceType(complexType)));

            var itemTypes = new ResourceType[] { complexType, complexType2 }.Concat(ResourceTypeUtils.GetPrimitiveResourceTypes());
            var collectionTypes = itemTypes.Except(new[] { ResourceType.GetPrimitiveResourceType(typeof(System.IO.Stream)) }).Select(it => new { ItemType = it, CollectionType = ResourceType.GetCollectionResourceType(it) });

            AstoriaTestNS.TestUtil.RunCombinations(
                collectionTypes,
                c =>
            {
                Assert.AreEqual(c.ItemType, c.CollectionType.ItemType, "The item type of the collection doesn't match the one specified upon creation.");
                Assert.AreEqual("Collection(" + c.ItemType.FullName + ")", c.CollectionType.FullName, "The full name of a collection type is wrong.");
                Assert.AreEqual("Collection(" + c.ItemType.FullName + ")", c.CollectionType.Name, "The name of a collection type is wrong.");
                Assert.AreEqual("", c.CollectionType.Namespace, "The namespace of a collection type should be empty.");
                Assert.IsTrue(c.CollectionType.IsReadOnly, "The collection type is always read-only.");
                Assert.IsFalse(c.CollectionType.IsAbstract, "Collection type is never abstract.");
                Assert.IsFalse(c.CollectionType.IsOpenType, "Collection type is never open.");
                Assert.IsFalse(c.CollectionType.IsMediaLinkEntry, "Collection type is never an MLE.");
                Assert.AreEqual(typeof(IEnumerable <>).MakeGenericType(c.ItemType.InstanceType), c.CollectionType.InstanceType, "The instance type of the collection type is wrong.");
                Assert.IsTrue(c.CollectionType.CanReflectOnInstanceType, "Collection type has CanReflectOnInstanceType always true.");
                Assert.IsNull(c.CollectionType.BaseType, "Collection type has never a base type.");
                Assert.AreEqual(ResourceTypeKind.Collection, c.CollectionType.ResourceTypeKind, "The kind of a collection type is always Collection.");
                Assert.AreEqual(0, c.CollectionType.PropertiesDeclaredOnThisType.Count(), "Collection type has no properties.");
                Assert.AreEqual(0, c.CollectionType.Properties.Count(), "Collection type has no properties.");
                Assert.AreEqual(0, c.CollectionType.KeyProperties.Count(), "Collection type has no properties.");
                Assert.AreEqual(0, c.CollectionType.ETagProperties.Count(), "Collection type has no properties.");
                Assert.IsNull(c.CollectionType.CustomState, "Custom state should be null by default.");

                ExceptionUtils.ThrowsException <InvalidOperationException>(
                    () => c.CollectionType.IsMediaLinkEntry = true,
                    "Setting MLE on collection type should fail.");
                ExceptionUtils.ThrowsException <InvalidOperationException>(
                    () => c.CollectionType.IsOpenType = true,
                    "Setting IsOpenType on collection type should fail.");
                ExceptionUtils.ThrowsException <InvalidOperationException>(
                    () => c.CollectionType.CanReflectOnInstanceType = false,
                    "Setting CanReflectOnInstanceType on collection type should fail.");
                // Setting a custom state should still work
                c.CollectionType.CustomState = "some value";
                Assert.AreEqual("some value", c.CollectionType.CustomState, "Custom state doesn't persist its value.");

                ExceptionUtils.ThrowsException <InvalidOperationException>(
                    () => c.CollectionType.AddProperty(new ResourceProperty("ID", ResourcePropertyKind.ComplexType, complexType)),
                    "Adding a property on collection type should fail.");

                c.CollectionType.SetReadOnly();
                Assert.IsTrue(c.CollectionType.IsReadOnly, "The collection type is always read-only.");
            });

            // Verify that only primitive and complex types are allowed as items in a collection
            ResourceType collectionType = ResourceType.GetCollectionResourceType(complexType);

            foreach (var t in new ResourceType[] { entityType, collectionType })
            {
                Exception exception = AstoriaTestNS.TestUtil.RunCatching(() => ResourceType.GetCollectionResourceType(t));
                Assert.IsTrue(exception is ArgumentException, "Exception of a wrong type");
                Assert.AreEqual(
                    "Only collection properties that contain primitive types or complex types are supported.",
                    exception.Message, "Wrong exception message.");
            }
        }
        protected override IEnumerable <ServiceAction> LoadServiceActions(IDataServiceMetadataProvider dataServiceMetadataProvider)
        {
            ResourceType employeeType;

            dataServiceMetadataProvider.TryResolveResourceType("Microsoft.Test.OData.Services.AstoriaDefaultService.Employee", out employeeType);
            ResourceType computerDetailType;

            dataServiceMetadataProvider.TryResolveResourceType("Microsoft.Test.OData.Services.AstoriaDefaultService.ComputerDetail", out computerDetailType);
            ResourceType computerType;

            dataServiceMetadataProvider.TryResolveResourceType("Microsoft.Test.OData.Services.AstoriaDefaultService.Computer", out computerType);
            ResourceType customerType;

            dataServiceMetadataProvider.TryResolveResourceType("Microsoft.Test.OData.Services.AstoriaDefaultService.Customer", out customerType);
            ResourceType auditInfoType;

            dataServiceMetadataProvider.TryResolveResourceType("Microsoft.Test.OData.Services.AstoriaDefaultService.AuditInfo", out auditInfoType);
            ResourceSet computerSet;

            dataServiceMetadataProvider.TryResolveResourceSet("Computer", out computerSet);
            var increaseSalaryAction = new ServiceAction(
                "IncreaseSalaries",
                null,
                null,
                OperationParameterBindingKind.Always,
                new[]
            {
                new ServiceActionParameter("employees", ResourceType.GetEntityCollectionResourceType(employeeType)),
                new ServiceActionParameter("n", ResourceType.GetPrimitiveResourceType(typeof(int))),
            });

            increaseSalaryAction.SetReadOnly();

            yield return(increaseSalaryAction);

            var sackEmployeeAction = new ServiceAction(
                "Sack",
                null,
                null,
                OperationParameterBindingKind.Always,
                new[]
            {
                new ServiceActionParameter("employee", employeeType),
            });

            sackEmployeeAction.SetReadOnly();

            yield return(sackEmployeeAction);

            var getComputerAction = new ServiceAction(
                "GetComputer",
                computerType,
                OperationParameterBindingKind.Always,
                new[]
            {
                new ServiceActionParameter("computer", computerType)
            },
                new ResourceSetPathExpression("computer"));

            getComputerAction.SetReadOnly();

            yield return(getComputerAction);

            var changeCustomerAuditInfoAction = new ServiceAction(
                "ChangeCustomerAuditInfo",
                null,
                null,
                OperationParameterBindingKind.Always,
                new[]
            {
                new ServiceActionParameter("customer", customerType),
                new ServiceActionParameter("auditInfo", auditInfoType),
            });

            changeCustomerAuditInfoAction.SetReadOnly();

            yield return(changeCustomerAuditInfoAction);

            var resetComputerDetailsSpecificationsAction = new ServiceAction(
                "ResetComputerDetailsSpecifications",
                null,
                null,
                OperationParameterBindingKind.Always,
                new[]
            {
                new ServiceActionParameter("computerDetail", computerDetailType),
                new ServiceActionParameter("specifications", ResourceType.GetCollectionResourceType(ResourceType.GetPrimitiveResourceType(typeof(string)))),
                new ServiceActionParameter("purchaseTime", ResourceType.GetPrimitiveResourceType(typeof(DateTimeOffset)))
            });

            resetComputerDetailsSpecificationsAction.SetReadOnly();

            yield return(resetComputerDetailsSpecificationsAction);
        }
Esempio n. 21
0
        public NodeToExpressionTranslatorTests()
        {
            this.functionExpressionBinder = new FunctionExpressionBinder(t => { throw new Exception(); });

            this.customerResourceType = new ResourceType(typeof(Customer), ResourceTypeKind.EntityType, null, "Fake", "Customer", false)
            {
                IsOpenType = true
            };
            var derivedCustomerResourceType = new ResourceType(typeof(DerivedCustomer), ResourceTypeKind.EntityType, this.customerResourceType, "Fake", "DerivedCustomer", false);

            this.weaklyBackedDerivedType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, derivedCustomerResourceType, "Fake", "WeaklyBackedCustomer", false)
            {
                CanReflectOnInstanceType = false
            };
            var nameResourceProperty = new ResourceProperty("Name", ResourcePropertyKind.Key | ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(string)));

            this.customerResourceType.AddProperty(nameResourceProperty);
            var addressResourceType     = new ResourceType(typeof(Address), ResourceTypeKind.ComplexType, null, "Fake", "Address", false);
            var addressResourceProperty = new ResourceProperty("Address", ResourcePropertyKind.ComplexType, addressResourceType);

            this.customerResourceType.AddProperty(addressResourceProperty);

            var namesResourceProperty = new ResourceProperty("Names", ResourcePropertyKind.Collection, ResourceType.GetCollectionResourceType(ResourceType.GetPrimitiveResourceType(typeof(string))));

            this.customerResourceType.AddProperty(namesResourceProperty);
            var addressesResourceProperty = new ResourceProperty("Addresses", ResourcePropertyKind.Collection, ResourceType.GetCollectionResourceType(addressResourceType));

            this.customerResourceType.AddProperty(addressesResourceProperty);

            var bestFriendResourceProperty = new ResourceProperty("BestFriend", ResourcePropertyKind.ResourceReference, this.customerResourceType);

            this.customerResourceType.AddProperty(bestFriendResourceProperty);
            var otherFriendsResourceProperty = new ResourceProperty("OtherFriends", ResourcePropertyKind.ResourceSetReference, this.customerResourceType);

            this.customerResourceType.AddProperty(otherFriendsResourceProperty);

            this.weaklyBackedResourceProperty = new ResourceProperty("WeaklyBacked", ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(string)))
            {
                CanReflectOnInstanceTypeProperty = false
            };

            var guid1ResourceProperty         = new ResourceProperty("Guid1", ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(Guid)));
            var guid2ResourceProperty         = new ResourceProperty("Guid2", ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(Guid)));
            var nullableGuid1ResourceProperty = new ResourceProperty("NullableGuid1", ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(Guid?)));
            var nullableGuid2ResourceProperty = new ResourceProperty("NullableGuid2", ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(Guid?)));

            this.customerResourceType.AddProperty(guid1ResourceProperty);
            this.customerResourceType.AddProperty(guid2ResourceProperty);
            this.customerResourceType.AddProperty(nullableGuid1ResourceProperty);
            this.customerResourceType.AddProperty(nullableGuid2ResourceProperty);

            var resourceSet = new ResourceSet("Customers", this.customerResourceType);

            resourceSet.SetReadOnly();
            var resourceSetWrapper = ResourceSetWrapper.CreateForTests(resourceSet, EntitySetRights.All);

            this.model = new EdmModel();

            this.customerEdmType = new MetadataProviderEdmEntityType("Fake", this.customerResourceType, null, false, true, false, t => {});
            this.model.AddElement(this.customerEdmType);

            this.derivedCustomerEdmType = new MetadataProviderEdmEntityType("Fake", derivedCustomerResourceType, this.customerEdmType, false, false, false, t => { });
            this.model.AddElement(this.derivedCustomerEdmType);

            this.weaklyBackedCustomerEdmType = new MetadataProviderEdmEntityType("Fake", weaklyBackedDerivedType, this.derivedCustomerEdmType, false, false, false, t => { });
            this.model.AddElement(this.weaklyBackedCustomerEdmType);

            this.nameProperty = new MetadataProviderEdmStructuralProperty(this.customerEdmType, nameResourceProperty, EdmCoreModel.Instance.GetString(true), null, EdmConcurrencyMode.None);
            this.customerEdmType.AddProperty(this.nameProperty);

            var addressEdmType = new MetadataProviderEdmComplexType("Fake", addressResourceType, null, false, false, t => {});

            this.model.AddElement(addressEdmType);

            this.addressProperty = new MetadataProviderEdmStructuralProperty(this.customerEdmType, addressResourceProperty, new EdmComplexTypeReference(addressEdmType, true), null, EdmConcurrencyMode.None);
            this.customerEdmType.AddProperty(this.addressProperty);

            this.namesProperty = new MetadataProviderEdmStructuralProperty(this.customerEdmType, namesResourceProperty, new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetString(false))), null, EdmConcurrencyMode.None);
            this.customerEdmType.AddProperty(this.namesProperty);

            this.addressesProperty = new MetadataProviderEdmStructuralProperty(this.customerEdmType, addressesResourceProperty, new EdmCollectionTypeReference(new EdmCollectionType(new EdmComplexTypeReference(addressEdmType, false))), null, EdmConcurrencyMode.None);
            this.customerEdmType.AddProperty(this.addressesProperty);

            this.bestFriendNavigation = new MetadataProviderEdmNavigationProperty(this.customerEdmType, bestFriendResourceProperty, new EdmEntityTypeReference(this.customerEdmType, true));
            this.customerEdmType.AddProperty(this.bestFriendNavigation);

            this.otherFriendsNavigation = new MetadataProviderEdmNavigationProperty(this.customerEdmType, otherFriendsResourceProperty, new EdmCollectionTypeReference(new EdmCollectionType(new EdmEntityTypeReference(this.customerEdmType, true))));
            this.customerEdmType.AddProperty(this.otherFriendsNavigation);

            this.weaklyBackedProperty = new MetadataProviderEdmStructuralProperty(this.customerEdmType, this.weaklyBackedResourceProperty, EdmCoreModel.Instance.GetString(true), null, EdmConcurrencyMode.None);
            this.customerEdmType.AddProperty(this.weaklyBackedProperty);

            var guid1EdmProperty = new MetadataProviderEdmStructuralProperty(this.customerEdmType, guid1ResourceProperty, EdmCoreModel.Instance.GetGuid(false), null, EdmConcurrencyMode.None);

            this.customerEdmType.AddProperty(guid1EdmProperty);
            var guid2EdmProperty = new MetadataProviderEdmStructuralProperty(this.customerEdmType, guid2ResourceProperty, EdmCoreModel.Instance.GetGuid(false), null, EdmConcurrencyMode.None);

            this.customerEdmType.AddProperty(guid2EdmProperty);
            var nullableGuid1EdmProperty = new MetadataProviderEdmStructuralProperty(this.customerEdmType, nullableGuid1ResourceProperty, EdmCoreModel.Instance.GetGuid(true), null, EdmConcurrencyMode.None);

            this.customerEdmType.AddProperty(nullableGuid1EdmProperty);
            var nullableGuid2EdmProperty = new MetadataProviderEdmStructuralProperty(this.customerEdmType, nullableGuid2ResourceProperty, EdmCoreModel.Instance.GetGuid(true), null, EdmConcurrencyMode.None);

            this.customerEdmType.AddProperty(nullableGuid2EdmProperty);

            this.entitySet = new EdmEntitySetWithResourceSet(new EdmEntityContainer("Fake", "Container"), resourceSetWrapper, this.customerEdmType);
            ((EdmEntitySet)this.entitySet).AddNavigationTarget(this.bestFriendNavigation, this.entitySet);
            ((EdmEntitySet)this.entitySet).AddNavigationTarget(this.otherFriendsNavigation, this.entitySet);

            this.model.SetAnnotationValue(this.customerEdmType, this.customerResourceType);
            this.model.SetAnnotationValue(this.derivedCustomerEdmType, derivedCustomerResourceType);
            this.model.SetAnnotationValue(this.weaklyBackedCustomerEdmType, this.weaklyBackedDerivedType);
            this.model.SetAnnotationValue(this.nameProperty, nameResourceProperty);
            this.model.SetAnnotationValue(addressEdmType, addressResourceType);
            this.model.SetAnnotationValue(this.addressProperty, addressResourceProperty);
            this.model.SetAnnotationValue(this.namesProperty, namesResourceProperty);
            this.model.SetAnnotationValue(this.addressesProperty, addressesResourceProperty);
            this.model.SetAnnotationValue(this.bestFriendNavigation, bestFriendResourceProperty);
            this.model.SetAnnotationValue(this.otherFriendsNavigation, otherFriendsResourceProperty);
            this.model.SetAnnotationValue(this.weaklyBackedProperty, this.weaklyBackedResourceProperty);
            this.model.SetAnnotationValue(this.entitySet, resourceSetWrapper);
            this.model.SetAnnotationValue(guid1EdmProperty, guid1ResourceProperty);
            this.model.SetAnnotationValue(guid2EdmProperty, guid2ResourceProperty);
            this.model.SetAnnotationValue(nullableGuid1EdmProperty, nullableGuid1ResourceProperty);
            this.model.SetAnnotationValue(nullableGuid2EdmProperty, nullableGuid2ResourceProperty);

            this.testSubject = this.CreateTestSubject();
        }
        private void AddResourceTypeProperties(ResourceType rt, ResourceType complexType)
        {
            foreach (PropertyInfo pi in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (typeof(IDictionary <string, object>).IsAssignableFrom(pi.PropertyType) && rt.ResourceTypeKind == ResourceTypeKind.EntityType)
                {
                    this.openTypesPropertyName = pi.Name;
                    continue;
                }

                // This property is only useful for type information.
                if (pi.Name == InstancePropertyName)
                {
                    continue;
                }

                Type elementType = TypeUtils.GetElementType(pi.PropertyType);
                if (elementType != null && pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(List <>))
                {
                    ResourceType itemType = null;
                    if (elementType == typeof(T))
                    {
                        itemType = complexType;
                    }
                    else
                    {
                        itemType = ResourceType.GetPrimitiveResourceType(elementType);
                    }

                    // Ignore properties we can't declare due to unknown types
                    if (itemType == null)
                    {
                        continue;
                    }

                    ResourceProperty rp = new ResourceProperty(
                        pi.Name,
                        ResourcePropertyKind.Collection,
                        ResourceType.GetCollectionResourceType(itemType));
                    rp.CanReflectOnInstanceTypeProperty = true;
                    rt.AddProperty(rp);
                }

                ResourcePropertyKind rpk = ResourcePropertyKind.Primitive;

                if (pi.Name.EndsWith("ID") && rt.ResourceTypeKind == ResourceTypeKind.EntityType)
                {
                    rpk |= ResourcePropertyKind.Key;
                }

                ResourceType primitiveType = ResourceType.GetPrimitiveResourceType(pi.PropertyType);

                if (primitiveType != null)
                {
                    ResourceProperty rp = new ResourceProperty(
                        pi.Name,
                        rpk,
                        ResourceType.GetPrimitiveResourceType(pi.PropertyType));

                    rp.CanReflectOnInstanceTypeProperty = true;
                    rt.AddProperty(rp);
                }
            }
        }