public void CanCreateFunctionWithNoArguments()
        {
            // Arrange
            // Act
            ODataModelBuilder builder = new ODataModelBuilder();

            builder.Namespace     = "MyNamespace";
            builder.ContainerName = "MyContainer";
            FunctionConfiguration function = builder.Function("Format");

            // Assert
            Assert.Equal("Format", function.Name);
            Assert.Equal(ProcedureKind.Function, function.Kind);
            Assert.NotNull(function.Parameters);
            Assert.Empty(function.Parameters);
            Assert.Null(function.ReturnType);
            Assert.False(function.IsSideEffecting);
            Assert.False(function.IsComposable);
            Assert.False(function.IsBindable);
            Assert.False(function.SupportedInFilter);
            Assert.False(function.SupportedInOrderBy);
            Assert.Equal("MyNamespace.Format", function.FullyQualifiedName);
            Assert.NotNull(builder.Procedures);
            Assert.Equal(1, builder.Procedures.Count());
        }
        public virtual FunctionConfiguration Function(string name)
        {
            FunctionConfiguration function = new FunctionConfiguration(this, name);

            _procedures.Add(function);
            return(function);
        }
        public void Can_SetFunctionTitle_OnBindable_Functions()
        {
            // Arrange
            ODataModelBuilder builder             = new ODataModelBuilder();
            EntitySetConfiguration <Movie> movies = builder.EntitySet <Movie>("Movies");

            movies.EntityType.HasKey(m => m.ID);
            FunctionConfiguration entityAction = movies.EntityType.Function("Checkout");

            entityAction.Returns <int>();
            entityAction.Title = "Check out";
            FunctionConfiguration collectionAction = movies.EntityType.Collection.Function("RemoveOld");

            collectionAction.Returns <int>();
            collectionAction.Title = "Remove Old Movies";

            // Act
            IEdmModel                model          = builder.GetEdmModel();
            IEdmOperation            checkout       = model.FindOperations("Default.Checkout").Single();
            IEdmOperation            removeOld      = model.FindOperations("Default.RemoveOld").Single();
            OperationTitleAnnotation checkoutTitle  = model.GetOperationTitleAnnotation(checkout);
            OperationTitleAnnotation removeOldTitle = model.GetOperationTitleAnnotation(removeOld);

            // Assert
            Assert.NotNull(checkoutTitle);
            Assert.Equal("Check out", checkoutTitle.Title);
            Assert.NotNull(removeOldTitle);
            Assert.Equal("Remove Old Movies", removeOldTitle.Title);
        }
        public void CanCreateEdmModel_WithBindableFunction()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration <Customer> customer = builder.EntityType <Customer>();

            customer.HasKey(c => c.CustomerId);
            customer.Property(c => c.Name);
            // Act
            FunctionConfiguration sendEmail = customer.Function("FunctionName");

            sendEmail.Returns <bool>();
            IEdmModel model = builder.GetEdmModel();

            // Assert
            Assert.Equal(1, model.SchemaElements.OfType <IEdmFunction>().Count());
            IEdmFunction function = Assert.Single(model.SchemaElements.OfType <IEdmFunction>());

            Assert.False(function.IsComposable);
            Assert.True(function.IsBound);
            Assert.Equal("FunctionName", function.Name);
            Assert.NotNull(function.ReturnType);
            Assert.Equal(1, function.Parameters.Count());
            Assert.Equal(BindingParameterConfiguration.DefaultBindingParameterName, function.Parameters.Single().Name);
            Assert.Equal(typeof(Customer).FullName, function.Parameters.Single().Type.FullName());
        }
        public void CanManuallyConfigureFunctionLinkFactory()
        {
            // Arrange
            string            uriTemplate = "http://server/service/Customers({0})/Reward";
            Uri               expectedUri = new Uri(string.Format(uriTemplate, 1));
            ODataModelBuilder builder     = new ODataModelBuilder();
            EntityTypeConfiguration <Customer> customer = builder.EntitySet <Customer>("Customers").EntityType;

            customer.HasKey(c => c.CustomerId);
            customer.Property(c => c.Name);

            // Act
            FunctionConfiguration reward = customer.Function("Reward");

            reward.HasFunctionLink(ctx => new Uri(string.Format(uriTemplate, ctx.GetPropertyValue("CustomerId"))),
                                   followsConventions: false);
            reward.Returns <bool>();
            IEdmModel              model             = builder.GetEdmModel();
            IEdmEntityType         customerType      = model.SchemaElements.OfType <IEdmEntityType>().SingleOrDefault();
            ODataSerializerContext serializerContext = new ODataSerializerContext {
                Model = model
            };

            EntityInstanceContext context = new EntityInstanceContext(serializerContext, customerType.AsReference(), new Customer {
                CustomerId = 1
            });
            IEdmFunction        rewardFunction      = Assert.Single(model.SchemaElements.OfType <IEdmFunction>()); // Guard
            FunctionLinkBuilder functionLinkBuilder = model.GetAnnotationValue <FunctionLinkBuilder>(rewardFunction);

            //Assert
            Assert.Equal(expectedUri, reward.GetFunctionLink()(context));
            Assert.NotNull(functionLinkBuilder);
            Assert.Equal(expectedUri, functionLinkBuilder.BuildFunctionLink(context));
        }
        public void CanCreateEdmModel_WithNonBindableFunction()
        {
            // Arrange
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock <ODataModelBuilder>();

            // Act
            FunctionConfiguration functionConfiguration = builder.Function("FunctionName");

            functionConfiguration.ReturnsFromEntitySet <Customer>("Customers");

            IEdmModel model = builder.GetEdmModel();

            // Assert
            IEdmEntityContainer container = model.EntityContainer;

            Assert.NotNull(container);
            Assert.Equal(1, container.Elements.OfType <IEdmFunctionImport>().Count());
            Assert.Equal(1, container.Elements.OfType <IEdmEntitySet>().Count());
            IEdmFunctionImport functionImport = Assert.Single(container.Elements.OfType <IEdmFunctionImport>());
            IEdmFunction       function       = functionImport.Function;

            Assert.False(function.IsComposable);
            Assert.False(function.IsBound);
            Assert.Equal("FunctionName", function.Name);
            Assert.NotNull(function.ReturnType);
            Assert.NotNull(functionImport.EntitySet);
            Assert.Equal("Customers", (functionImport.EntitySet as IEdmEntitySetReferenceExpression).ReferencedEntitySet.Name);
            Assert.Equal(
                typeof(Customer).FullName,
                (functionImport.EntitySet as IEdmEntitySetReferenceExpression).ReferencedEntitySet.EntityType().FullName());
            Assert.Empty(function.Parameters);
        }
        public void CanCreateFunctionWithEntityReturnType()
        {
            // Arrange
            // Act
            ODataModelBuilder builder = new ODataModelBuilder();

            FunctionConfiguration createGoodCustomer = builder.Function("CreateGoodCustomer").ReturnsFromEntitySet <Customer>("GoodCustomers");
            FunctionConfiguration createBadCustomers = builder.Function("CreateBadCustomers").ReturnsCollectionFromEntitySet <Customer>("BadCustomers");

            // Assert
            EntityTypeConfiguration customer = createGoodCustomer.ReturnType as EntityTypeConfiguration;

            Assert.NotNull(customer);
            Assert.Equal(typeof(Customer).FullName, customer.FullName);
            EntitySetConfiguration goodCustomers = builder.EntitySets.SingleOrDefault(s => s.Name == "GoodCustomers");

            Assert.NotNull(goodCustomers);
            Assert.Same(createGoodCustomer.NavigationSource, goodCustomers);

            CollectionTypeConfiguration customers = createBadCustomers.ReturnType as CollectionTypeConfiguration;

            Assert.NotNull(customers);
            customer = customers.ElementType as EntityTypeConfiguration;
            Assert.NotNull(customer);
            EntitySetConfiguration badCustomers = builder.EntitySets.SingleOrDefault(s => s.Name == "BadCustomers");

            Assert.NotNull(badCustomers);
            Assert.Same(createBadCustomers.NavigationSource, badCustomers);
        }
        public void CanCreateFunctionWithNonbindingParameters()
        {
            // Arrange
            // Act
            ODataModelBuilder     builder  = new ODataModelBuilder();
            FunctionConfiguration function = builder.Function("MyFunction");

            function.Parameter <string>("p0");
            function.Parameter <int>("p1");
            function.Parameter <Address>("p2");
            function.CollectionParameter <string>("p3");
            function.CollectionParameter <int>("p4");
            function.CollectionParameter <ZipCode>("p5");
            ParameterConfiguration[]   parameters   = function.Parameters.ToArray();
            ComplexTypeConfiguration[] complexTypes = builder.StructuralTypes.OfType <ComplexTypeConfiguration>().ToArray();

            // Assert
            Assert.Equal(2, complexTypes.Length);
            Assert.Equal(typeof(Address).FullName, complexTypes[0].FullName);
            Assert.Equal(typeof(ZipCode).FullName, complexTypes[1].FullName);
            Assert.Equal(6, parameters.Length);
            Assert.Equal("p0", parameters[0].Name);
            Assert.Equal("Edm.String", parameters[0].TypeConfiguration.FullName);
            Assert.Equal("p1", parameters[1].Name);
            Assert.Equal("Edm.Int32", parameters[1].TypeConfiguration.FullName);
            Assert.Equal("p2", parameters[2].Name);
            Assert.Equal(typeof(Address).FullName, parameters[2].TypeConfiguration.FullName);
            Assert.Equal("p3", parameters[3].Name);
            Assert.Equal("Collection(Edm.String)", parameters[3].TypeConfiguration.FullName);
            Assert.Equal("p4", parameters[4].Name);
            Assert.Equal("Collection(Edm.Int32)", parameters[4].TypeConfiguration.FullName);
            Assert.Equal("p5", parameters[5].Name);
            Assert.Equal(string.Format("Collection({0})", typeof(ZipCode).FullName), parameters[5].TypeConfiguration.FullName);
        }
        public void CanCreateFunctionWithComplexReturnType()
        {
            // Arrange
            // Act
            ODataModelBuilder builder = new ODataModelBuilder();

            FunctionConfiguration createAddress   = builder.Function("CreateAddress").Returns <Address>();
            FunctionConfiguration createAddresses = builder.Function("CreateAddresses").ReturnsCollection <Address>();

            // Assert
            ComplexTypeConfiguration address = createAddress.ReturnType as ComplexTypeConfiguration;

            Assert.NotNull(address);
            Assert.Equal(typeof(Address).FullName, address.FullName);
            Assert.Null(createAddress.NavigationSource);

            CollectionTypeConfiguration addresses = createAddresses.ReturnType as CollectionTypeConfiguration;

            Assert.NotNull(addresses);
            Assert.Equal(string.Format("Collection({0})", typeof(Address).FullName), addresses.FullName);
            address = addresses.ElementType as ComplexTypeConfiguration;
            Assert.NotNull(address);
            Assert.Equal(typeof(Address).FullName, address.FullName);
            Assert.Null(createAddresses.NavigationSource);
        }
Exemple #10
0
        public void CanCreateFunctionWithNonbindingParametersAsNullable()
        {
            // Arrange & Act
            ODataModelBuilder     builder  = new ODataModelBuilder();
            FunctionConfiguration function = builder.Function("MyFunction");

            function.Parameter <string>("p0");
            function.Parameter <string>("p1").OptionalParameter = false;
            function.Parameter <int>("p2").OptionalParameter    = true;
            function.Parameter <int>("p3");
            function.Parameter <Address>("p4");
            function.Parameter <Address>("p5").OptionalParameter = false;

            function.CollectionParameter <ZipCode>("p6");
            function.CollectionParameter <ZipCode>("p7").OptionalParameter = false;

            Dictionary <string, ParameterConfiguration> parameters = function.Parameters.ToDictionary(e => e.Name, e => e);

            // Assert
            Assert.True(parameters["p0"].OptionalParameter);
            Assert.False(parameters["p1"].OptionalParameter);

            Assert.True(parameters["p2"].OptionalParameter);
            Assert.False(parameters["p3"].OptionalParameter);

            Assert.True(parameters["p4"].OptionalParameter);
            Assert.False(parameters["p5"].OptionalParameter);

            Assert.True(parameters["p6"].OptionalParameter);
            Assert.False(parameters["p7"].OptionalParameter);
        }
        /// <summary>
        /// Creates a new Function that binds to Collection(EntityType).
        /// </summary>
        /// <param name="name">The name of the Function</param>
        /// <returns>A <see cref="FunctionConfiguration"/> to allow further configuration of the Function.</returns>
        public FunctionConfiguration Function(string name)
        {
            Contract.Assert(ModelBuilder != null);
            FunctionConfiguration configuration = ModelBuilder.Function(name);

            configuration.SetBindingParameter(BindingParameterConfiguration.DefaultBindingParameterName, this);
            return(configuration);
        }
Exemple #12
0
        /// <summary>
        /// Creates a new Function that sometimes binds to Collection(EntityType).
        /// </summary>
        /// <param name="name">The name of the Function</param>
        /// <returns>A <see cref="FunctionConfiguration"/> to allow further configuration of the Function.</returns>
        public FunctionConfiguration TransientFunction(string name)
        {
            Contract.Assert(ModelBuilder != null);
            FunctionConfiguration configuration = ModelBuilder.Function(name);

            configuration.SetBindingParameter(BindingParameterConfiguration.DefaultBindingParameterName, this, alwaysBindable: false);
            return(configuration);
        }
Exemple #13
0
        public void CanCreateFunctionWithReturnTypeAsNullableByDefault()
        {
            // Arrange & Act
            ODataModelBuilder     builder  = new ODataModelBuilder();
            FunctionConfiguration function = builder.Function("MyFunction").Returns <Address>();

            // Assert
            Assert.True(function.OptionalReturn);
        }
        /// <summary>
        /// Create a Function that binds to this EntityType.
        /// </summary>
        /// <param name="name">The name of the function.</param>
        /// <returns>The FunctionConfiguration to allow further configuration of the new Function.</returns>
        public FunctionConfiguration Function(string name)
        {
            Contract.Assert(_configuration != null && _configuration.ModelBuilder != null);

            FunctionConfiguration function = _configuration.ModelBuilder.Function(name);

            function.SetBindingParameter(BindingParameterConfiguration.DefaultBindingParameterName, _configuration);
            return(function);
        }
Exemple #15
0
        public void HasFeedFunctionLink_ThrowsException_OnNonBindableFunctions()
        {
            // Arrange
            ODataModelBuilder     builder  = new ODataModelBuilder();
            FunctionConfiguration function = builder.Function("NoBindableFunction");

            // Act & Assert
            Assert.Throws <InvalidOperationException>(
                () => function.HasFeedFunctionLink(ctx => new Uri("http://any"), followsConventions: false),
                "To register a function link factory, functions must be bindable to the collection of entity. " +
                "Function 'NoBindableFunction' does not meet this requirement.");
        }
Exemple #16
0
        public void HasFunctionLink_ThrowsException_OnNoBoundToEntityFunctions()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration <Customer> customer = builder.EntityType <Customer>();
            FunctionConfiguration function = customer.Collection.Function("CollectionFunction");

            // Act & Assert
            Assert.Throws <InvalidOperationException>(
                () => function.HasFunctionLink(ctx => new Uri("http://any"), followsConventions: false),
                "To register a function link factory, functions must be bindable to a single entity. " +
                "Function 'CollectionFunction' does not meet this requirement.");
        }
Exemple #17
0
        public void CanCreateFunctionWithPrimitiveCollectionReturnType()
        {
            // Arrange
            // Act
            ODataModelBuilder     builder  = new ODataModelBuilder();
            FunctionConfiguration function = builder.Function("CreateMessages");

            function.ReturnsCollection <string>();

            // Assert
            Assert.NotNull(function.ReturnType);
            Assert.Equal("Collection(Edm.String)", function.ReturnType.FullName);
        }
        public void Parameter_ThrowsInvalidOperationIfGenericArgumentIsDateTime(Type type)
        {
            // Arrange
            ODataModelBuilder     builder  = new ODataModelBuilder();
            FunctionConfiguration function = builder.Function("Format");
            MethodInfo            method   = typeof(FunctionConfiguration)
                                             .GetMethod("Parameter", new[] { typeof(string) })
                                             .MakeGenericMethod(type);

            // Act & Assert
            Assert.Throws <InvalidOperationException>(
                () => method.Invoke(function, new[] { "test" }),
                string.Format("The type '{0}' is not a supported parameter type for the parameter test.", type.FullName));
        }
        public void Returns_ThrowsInvalidOperationIfGenericArgumentIsDateTime(Type type)
        {
            // Arrange
            ODataModelBuilder     builder  = new ODataModelBuilder();
            FunctionConfiguration function = builder.Function("Format");
            MethodInfo            method   = typeof(FunctionConfiguration)
                                             .GetMethod("Returns")
                                             .MakeGenericMethod(type);

            // Act & Assert
            Assert.Throws <InvalidOperationException>(
                () => method.Invoke(function, new object[] { }),
                string.Format("The type '{0}' is not a supported return type.", type.FullName));
        }
Exemple #20
0
        public void CanCreateFunctionThatBindsToEntityCollection()
        {
            // Arrange
            // Act
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration <Customer> customer = builder.EntityType <Customer>();
            FunctionConfiguration sendEmail             = customer.Collection.Function("SendEmail");

            // Assert
            Assert.True(sendEmail.IsBindable);
            Assert.NotNull(sendEmail.Parameters);
            Assert.Equal(1, sendEmail.Parameters.Count());
            Assert.Equal(BindingParameterConfiguration.DefaultBindingParameterName, sendEmail.Parameters.Single().Name);
            Assert.Equal(string.Format("Collection({0})", typeof(Customer).FullName), sendEmail.Parameters.Single().TypeConfiguration.FullName);
        }
Exemple #21
0
        private static EdmOperationImport CreateFunctionImport(
            FunctionConfiguration function,
            EdmEntityContainer container,
            IEdmTypeReference returnReference,
            IEdmExpression expression,
            IEdmPathExpression pathExpression)
        {
            EdmFunction operation = new EdmFunction(
                function.Namespace,
                function.Name,
                returnReference,
                function.IsBindable,
                pathExpression,
                function.IsComposable);

            return(new EdmFunctionImport(container, function.Name, operation, expression, includeInServiceDocument: function.IncludeInServiceDocument));
        }
Exemple #22
0
        public void DollarMetadata_Works_WithFunctionParameterNullable_ReturnTypeNullable()
        {
            // Arrange
            const string expectMetadata =
                @"<Schema Namespace='Default' xmlns='http://docs.oasis-open.org/odata/ns/edm'>
      <Function Name='NullableFunction' IsBound='true'>
        <Parameter Name='bindingParameter' Type='System.Web.OData.Formatter.FormatterPerson' />
        <Parameter Name='param' Type='Edm.String' Unicode='false' />
        <ReturnType Type='System.Web.OData.Formatter.FormatterAddress' />
      </Function>
      <Function Name='NonNullableFunction' IsBound='true'>
        <Parameter Name='bindingParameter' Type='System.Web.OData.Formatter.FormatterPerson' />
        <Parameter Name='param' Type='Edm.String' Nullable='false' Unicode='false' />
        <ReturnType Type='System.Web.OData.Formatter.FormatterAddress' Nullable='false' />
      </Function>
      <EntityContainer Name='Container' />
    </Schema>
  </edmx:DataServices>
</edmx:Edmx>";

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            EntityTypeConfiguration <FormatterPerson> person = builder.EntityType <FormatterPerson>();

            FunctionConfiguration function = person.Function("NullableFunction").Returns <FormatterAddress>();

            function.Parameter <string>("param");

            function = person.Function("NonNullableFunction").Returns <FormatterAddress>();
            function.OptionalReturn = false;
            function.Parameter <string>("param").OptionalParameter = false;
            IEdmModel model = builder.GetEdmModel();

            var config = new[] { typeof(MetadataController) }.GetHttpConfiguration();

            config.MapODataServiceRoute(model);
            HttpServer server = new HttpServer(config);
            HttpClient client = new HttpClient(server);

            // Act
            var response = client.GetAsync("http://localhost/$metadata").Result;

            // Assert
            Assert.True(response.IsSuccessStatusCode);
            Assert.Equal("application/xml", response.Content.Headers.ContentType.MediaType);
            Assert.Contains(expectMetadata.Replace("'", "\""), response.Content.ReadAsStringAsync().Result);
        }
Exemple #23
0
        public void HasFunctionLink_SetsFollowsConventions(bool value)
        {
            // Arrange
            ODataModelBuilder            builder  = new ODataModelBuilder();
            FunctionConfiguration        function = new FunctionConfiguration(builder, "IgnoreFunction");
            Mock <IEdmTypeConfiguration> bindingParameterTypeMock = new Mock <IEdmTypeConfiguration>();

            bindingParameterTypeMock.Setup(o => o.Kind).Returns(EdmTypeKind.Entity);
            IEdmTypeConfiguration bindingParameterType = bindingParameterTypeMock.Object;

            function.SetBindingParameter("IgnoreParameter", bindingParameterType);

            // Act
            function.HasFunctionLink((a) => { throw new NotImplementedException(); }, followsConventions: value);

            // Assert
            Assert.Equal(value, function.FollowsConventions);
        }
Exemple #24
0
        private static void AddProcedureLinkBuilder(IEdmModel model, IEdmOperation operation, ProcedureConfiguration procedure)
        {
            ActionConfiguration   actionConfiguration = procedure as ActionConfiguration;
            IEdmAction            action = operation as IEdmAction;
            FunctionConfiguration functionConfiguration = procedure as FunctionConfiguration;
            IEdmFunction          function = operation as IEdmFunction;

            if (procedure.BindingParameter.TypeConfiguration.Kind == EdmTypeKind.Entity)
            {
                if (actionConfiguration != null && actionConfiguration.GetActionLink() != null && action != null)
                {
                    model.SetActionLinkBuilder(
                        action,
                        new ActionLinkBuilder(actionConfiguration.GetActionLink(), actionConfiguration.FollowsConventions));
                }
                else if (functionConfiguration != null && functionConfiguration.GetFunctionLink() != null && function != null)
                {
                    model.SetFunctionLinkBuilder(
                        function,
                        new FunctionLinkBuilder(functionConfiguration.GetFunctionLink(), functionConfiguration.FollowsConventions));
                }
            }
            else if (procedure.BindingParameter.TypeConfiguration.Kind == EdmTypeKind.Collection)
            {
                CollectionTypeConfiguration collectionTypeConfiguration =
                    (CollectionTypeConfiguration)procedure.BindingParameter.TypeConfiguration;

                if (collectionTypeConfiguration.ElementType.Kind == EdmTypeKind.Entity)
                {
                    if (actionConfiguration != null && actionConfiguration.GetFeedActionLink() != null && action != null)
                    {
                        model.SetActionLinkBuilder(
                            action,
                            new ActionLinkBuilder(actionConfiguration.GetFeedActionLink(), actionConfiguration.FollowsConventions));
                    }
                    else if (functionConfiguration != null && functionConfiguration.GetFeedFunctionLink() != null && function != null)
                    {
                        model.SetFunctionLinkBuilder(
                            function,
                            new FunctionLinkBuilder(functionConfiguration.GetFeedFunctionLink(), functionConfiguration.FollowsConventions));
                    }
                }
            }
        }
Exemple #25
0
        public void Cant_SetFunctionTitle_OnNonBindableFunctions()
        {
            // Arrange
            ODataModelBuilder     builder  = new ODataModelBuilder();
            FunctionConfiguration function = builder.Function("MyFunction");

            function.Returns <int>();
            function.Title = "My Function";

            // Act
            IEdmModel           model          = builder.GetEdmModel();
            IEdmOperationImport functionImport = model.EntityContainer.OperationImports().OfType <IEdmFunctionImport>().Single();

            Assert.NotNull(functionImport);
            OperationTitleAnnotation functionTitleAnnotation = model.GetOperationTitleAnnotation(functionImport.Operation);

            // Assert
            Assert.Null(functionTitleAnnotation);
        }
Exemple #26
0
        public void CanCreateFunctionWithCollectionReturnTypeViaEntitySetPath()
        {
            // Arrange
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock <ODataModelBuilder>();
            EntityTypeConfiguration <Customer> customer = builder.EntityType <Customer>();
            EntityTypeConfiguration <Order>    order    = builder.EntityType <Order>();

            customer.HasMany <Order>(c => c.Orders);
            FunctionConfiguration getOrders = customer.Function("GetOrders").ReturnsCollectionViaEntitySetPath <Order>("bindingParameter/Orders");

            // Act
            IEdmModel model = builder.GetEdmModel();

            // Assert
            IEdmFunction function = Assert.Single(model.SchemaElements.OfType <IEdmFunction>());

            Assert.Equal(EdmExpressionKind.Path, function.EntitySetPath.ExpressionKind);
            Assert.Equal("bindingParameter/Orders", string.Join("/", ((IEdmPathExpression)(function.EntitySetPath)).Path));
        }
Exemple #27
0
        public void CanCreateFunctionWithNonbindingParameters_AddParameterNonGenericMethod()
        {
            // Arrange
            // Act
            ODataModelBuilder     builder  = new ODataModelBuilder();
            FunctionConfiguration function = builder.Function("MyFunction");

            function.Parameter(typeof(string), "p0");
            function.Parameter(typeof(int), "p1");
            function.Parameter(typeof(Address), "p2");
            ParameterConfiguration[] parameters = function.Parameters.ToArray();

            // Assert
            Assert.Equal(3, parameters.Length);
            Assert.Equal("p0", parameters[0].Name);
            Assert.Equal("Edm.String", parameters[0].TypeConfiguration.FullName);
            Assert.Equal("p1", parameters[1].Name);
            Assert.Equal("Edm.Int32", parameters[1].TypeConfiguration.FullName);
            Assert.Equal("p2", parameters[2].Name);
            Assert.Equal(typeof(Address).FullName, parameters[2].TypeConfiguration.FullName);
        }
Exemple #28
0
        public void UnboundFunction_ForEnumTypeInODataConventionModelBuilder()
        {
            // Arrange
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            FunctionConfiguration       functionConfiguration = builder.Function("UnboundFunction");

            functionConfiguration.Parameter <Color>("Color");
            functionConfiguration.ReturnsCollection <Color>();

            // Act & Assert
            IEdmModel          model          = builder.GetEdmModel();
            IEdmFunctionImport functionImport = model.EntityContainer.OperationImports().Single(o => o.Name == "UnboundFunction") as IEdmFunctionImport;

            IEdmTypeReference color      = functionImport.Function.Parameters.Single(p => p.Name == "Color").Type;
            IEdmTypeReference returnType = functionImport.Function.ReturnType;
            IEdmEnumType      colorType  = model.SchemaElements.OfType <IEdmEnumType>().Single(e => e.Name == "Color");

            Assert.Same(colorType, color.Definition);
            Assert.True(returnType.IsCollection());
            Assert.Same(colorType, returnType.AsCollection().ElementType().Definition);
        }
        public void CanCreateEdmModel_WithTransientBindableFunction()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration <Customer> customer = builder.EntityType <Customer>();

            customer.HasKey(c => c.CustomerId);
            customer.Property(c => c.Name);

            // Act
            FunctionConfiguration sendEmail = customer.TransientFunction("FunctionName");

            sendEmail.Returns <bool>();
            IEdmModel model = builder.GetEdmModel();

            // Assert
            Assert.Equal(1, model.SchemaElements.OfType <IEdmFunction>().Count());
            IEdmFunction function = Assert.Single(model.SchemaElements.OfType <IEdmFunction>());

            Assert.True(function.IsBound);
        }
Exemple #30
0
        public void WhenFunctionLinksNotManuallyConfigured_ConventionBasedBuilderUsesConventions()
        {
            // Arrange
            string            uriTemplate         = "http://server/Movies({0})/Default.Watch(param=@param)";
            Uri               expectedUri         = new Uri(string.Format(uriTemplate, 1));
            ODataModelBuilder builder             = new ODataConventionModelBuilder();
            EntityTypeConfiguration <Movie> movie = builder.EntitySet <Movie>("Movies").EntityType;
            FunctionConfiguration           watch = movie.Function("Watch").Returns <int>();

            watch.Parameter <string>("param");
            IEdmModel model = builder.GetEdmModel();

            HttpRequestMessage request       = new HttpRequestMessage(HttpMethod.Get, "http://server/Movies");
            HttpConfiguration  configuration = new HttpConfiguration();
            string             routeName     = "Route";

            configuration.MapODataServiceRoute(routeName, null, model);
            request.SetConfiguration(configuration);
            request.ODataProperties().RouteName = routeName;
            UrlHelper urlHelper = new UrlHelper(request);

            // Act
            IEdmEntityType         movieType         = model.SchemaElements.OfType <IEdmEntityType>().SingleOrDefault();
            IEdmEntityContainer    container         = model.SchemaElements.OfType <IEdmEntityContainer>().SingleOrDefault();
            IEdmFunction           watchFunction     = Assert.Single(model.SchemaElements.OfType <IEdmFunction>()); // Guard
            IEdmEntitySet          entitySet         = container.EntitySets().SingleOrDefault();
            ODataSerializerContext serializerContext = new ODataSerializerContext {
                Model = model, NavigationSource = entitySet, Url = urlHelper
            };

            EntityInstanceContext context = new EntityInstanceContext(serializerContext, movieType.AsReference(), new Movie {
                ID = 1, Name = "Avatar"
            });
            FunctionLinkBuilder functionLinkBuilder = model.GetAnnotationValue <FunctionLinkBuilder>(watchFunction);

            //Assert
            Assert.Equal(expectedUri, watch.GetFunctionLink()(context));
            Assert.NotNull(functionLinkBuilder);
            Assert.Equal(expectedUri, functionLinkBuilder.BuildFunctionLink(context));
        }