public static IEdmModel GetExplicitModel(string singletonName)
        {
            ODataModelBuilder builder = new ODataModelBuilder();

            // Define EntityType of Partner
            var partner = builder.EntityType<Partner>();
            partner.HasKey(p => p.ID);
            partner.Property(p => p.Name);
            var partnerCompany = partner.HasRequired(p => p.Company);

            // Define Enum Type
            var category = builder.EnumType<CompanyCategory>();
            category.Member(CompanyCategory.IT);
            category.Member(CompanyCategory.Communication);
            category.Member(CompanyCategory.Electronics);
            category.Member(CompanyCategory.Others);

            // Define EntityType of Company
            var company = builder.EntityType<Company>();
            company.HasKey(p => p.ID);
            company.Property(p => p.Name);
            company.Property(p => p.Revenue);
            company.EnumProperty(p => p.Category);
            var companyPartners = company.HasMany(p => p.Partners);
            companyPartners.IsNotCountable();

            var companyBranches = company.CollectionProperty(p => p.Branches);

            // Define Complex Type: Office
            var office = builder.ComplexType<Office>();
            office.Property(p => p.City);
            office.Property(p => p.Address);

            // Define Derived Type: SubCompany
            var subCompany = builder.EntityType<SubCompany>();
            subCompany.DerivesFrom<Company>();
            subCompany.Property(p => p.Location);
            subCompany.Property(p => p.Description);
            subCompany.ComplexProperty(p => p.Office);

            builder.Namespace = typeof(Partner).Namespace;

            // Define PartnerSet and Company(singleton)
            EntitySetConfiguration<Partner> partnersConfiguration = builder.EntitySet<Partner>("Partners");
            partnersConfiguration.HasIdLink(c=>c.GenerateSelfLink(false), true);
            partnersConfiguration.HasSingletonBinding(c => c.Company, singletonName);
            Func<EntityInstanceContext<Partner>, IEdmNavigationProperty, Uri> link = (eic, np) => eic.GenerateNavigationPropertyLink(np, false);
            partnersConfiguration.HasNavigationPropertyLink(partnerCompany, link, true);
            partnersConfiguration.EntityType.Collection.Action("ResetDataSource");

            SingletonConfiguration<Company> companyConfiguration = builder.Singleton<Company>(singletonName);
            companyConfiguration.HasIdLink(c => c.GenerateSelfLink(false), true);
            companyConfiguration.HasManyBinding(c => c.Partners, "Partners");
            Func<EntityInstanceContext<Company>, IEdmNavigationProperty, Uri> linkFactory = (eic, np) => eic.GenerateNavigationPropertyLink(np, false);
            companyConfiguration.HasNavigationPropertyLink(companyPartners, linkFactory, true);
            companyConfiguration.EntityType.Action("ResetDataSource");
            companyConfiguration.EntityType.Function("GetPartnersCount").Returns<int>();

            return builder.GetEdmModel();
        }
        public static IEdmModel GetTypedExplicitModel()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            var accountType = builder.EntityType<Account>();
            accountType.HasKey(c => c.Id);
            accountType.Property(c => c.Name);
            accountType.HasDynamicProperties(c => c.DynamicProperties);

            accountType.ComplexProperty<AccountInfo>(c => c.AccountInfo);
            accountType.ComplexProperty<Address>(a => a.Address);
            accountType.ComplexProperty<Tags>(a => a.Tags);

            var premiumAccountType = builder.EntityType<PremiumAccount>();
            premiumAccountType.Property(p => p.Since);
            premiumAccountType.DerivesFrom<Account>();

            var accountInfoType = builder.ComplexType<AccountInfo>();
            accountInfoType.Property(i => i.NickName);
            accountInfoType.HasDynamicProperties(i => i.DynamicProperties);

            var addressType = builder.ComplexType<Address>();
            addressType.Property(a => a.City);
            addressType.Property(a => a.Street);
            addressType.HasDynamicProperties(a => a.DynamicProperties);

            var globalAddressType = builder.ComplexType<GlobalAddress>();
            globalAddressType.Property(a => a.CountryCode);
            globalAddressType.DerivesFrom<Address>();

            var tagsType = builder.ComplexType<Tags>();
            tagsType.HasDynamicProperties(t => t.DynamicProperties);

            var gender = builder.EnumType<Gender>();
            gender.Member(Gender.Female);
            gender.Member(Gender.Male);

            var employeeType = builder.EntityType<Employee>();
            employeeType.HasKey(e => e.Id);
            employeeType.HasOptional(e => e.Account);
            builder.EntitySet<Employee>("Employees");

            var managerType = builder.EntityType<Manager>();
            managerType.Property(m => m.Heads);
            managerType.HasDynamicProperties(m => m.DynamicProperties);
            managerType.DerivesFrom<Employee>();

            AddBoundActionsAndFunctions(accountType);
            AddUnboundActionsAndFunctions(builder);

            EntitySetConfiguration<Account> accounts = builder.EntitySet<Account>("Accounts");
            builder.Namespace = typeof(Account).Namespace;
            return builder.GetEdmModel();
        }
Beispiel #3
0
        public static IEdmModel GetEdmModel()
        {
            var builder = new ODataModelBuilder();

            var employee = builder.EntityType<Employee>();
            employee.HasKey(e => e.EmployeeID);
            employee.HasMany(e => e.Orders);

            var order = builder.EntityType<Order>();
            order.HasKey(c => c.OrderID);
            order.HasMany(c => c.OrderDetails);

            return builder.GetEdmModel();
        }
Beispiel #4
0
        private static void BuildFunctions(ODataModelBuilder builder)
        {
            FunctionConfiguration GetWeapons =
                builder.EntityType<Hero>()
                    .Collection.Function("GetWeapons")
                    .ReturnsCollectionFromEntitySet<Weapon>("Weapons");
            GetWeapons.IsComposable = true;

            FunctionConfiguration GetNames =
                builder.EntityType<Hero>()
                    .Collection.Function("GetNames")
                    .ReturnsCollection<string>();
            GetNames.IsComposable = true;
        }
        public void CanCreateEntityWithCollectionProperties()
        {
            var builder = new ODataModelBuilder();
            var customer = builder.EntityType<Customer>();
            customer.HasKey(c => c.CustomerId);
            customer.CollectionProperty(c => c.Aliases);
            customer.CollectionProperty(c => c.Addresses);


            var aliasesProperty = customer.Properties.OfType<CollectionPropertyConfiguration>().SingleOrDefault(p => p.Name == "Aliases");
            var addressesProperty = customer.Properties.OfType<CollectionPropertyConfiguration>().SingleOrDefault(p => p.Name == "Addresses");

            Assert.Equal(3, customer.Properties.Count());
            Assert.Equal(2, customer.Properties.OfType<CollectionPropertyConfiguration>().Count());
            Assert.NotNull(aliasesProperty);
            Assert.Equal(typeof(string), aliasesProperty.ElementType);
            Assert.NotNull(addressesProperty);
            Assert.Equal(typeof(Address), addressesProperty.ElementType);

            Assert.Equal(2, builder.StructuralTypes.Count());
            var addressType = builder.StructuralTypes.Skip(1).FirstOrDefault();
            Assert.NotNull(addressType);
            Assert.Equal(EdmTypeKind.Complex, addressType.Kind);
            Assert.Equal(typeof(Address).FullName, addressType.FullName);

            var model = builder.GetServiceModel();
            var edmCustomerType = model.FindType(typeof(Customer).FullName) as IEdmEntityType;
            var edmAddressType = model.FindType(typeof(Address).FullName) as IEdmComplexType;
        }
        public static IEdmModel GetExplicitModel()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            var customerType = builder.EntityType<DCustomer>().HasKey(c => c.Id);
            customerType.Property(c => c.DateTime);
            customerType.Property(c => c.Offset);
            customerType.Property(c => c.Date);
            customerType.Property(c => c.TimeOfDay);

            customerType.Property(c => c.NullableDateTime);
            customerType.Property(c => c.NullableOffset);
            customerType.Property(c => c.NullableDate);
            customerType.Property(c => c.NullableTimeOfDay);

            customerType.CollectionProperty(c => c.DateTimes);
            customerType.CollectionProperty(c => c.Offsets);
            customerType.CollectionProperty(c => c.Dates);
            customerType.CollectionProperty(c => c.TimeOfDays);

            customerType.CollectionProperty(c => c.NullableDateTimes);
            customerType.CollectionProperty(c => c.NullableOffsets);
            customerType.CollectionProperty(c => c.NullableDates);
            customerType.CollectionProperty(c => c.NullableTimeOfDays);

            var customers = builder.EntitySet<DCustomer>("DCustomers");
            customers.HasIdLink(link, true);
            customers.HasEditLink(link, true);

            BuildFunctions(builder);
            BuildActions(builder);

            return builder.GetEdmModel();
        }
        public void CreateQueryOptions_SetsContextProperties_WithModelAndPath()
        {
            // Arrange
            ApiController controller = new Mock<ApiController>().Object;
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Customers");
            controller.Configuration = new HttpConfiguration();
            ODataModelBuilder odataModel = new ODataModelBuilder();
            string setName = typeof(Customer).Name;
            odataModel.EntityType<Customer>().HasKey(c => c.Id);
            odataModel.EntitySet<Customer>(setName);
            IEdmModel model = odataModel.GetEdmModel();
            IEdmEntitySet entitySet = model.EntityContainer.FindEntitySet(setName);
            request.ODataProperties().Model = model;
            request.ODataProperties().Path = new ODataPath(new EntitySetPathSegment(entitySet));
            controller.Request = request;

            // Act
            ODataQueryOptions<Customer> queryOptions =
                EntitySetControllerHelpers.CreateQueryOptions<Customer>(controller);

            // Assert
            Assert.Same(model, queryOptions.Context.Model);
            Assert.Same(entitySet, queryOptions.Context.NavigationSource);
            Assert.Same(typeof(Customer), queryOptions.Context.ElementClrType);
        }
        public void NonbindingParameterConfigurationSupportsParameterTypeAs(Type type, bool isNullable)
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            builder.EntityType<Customer>();
            builder.ComplexType<Address>();
            builder.EnumType<Color>();

            // Act
            Type underlyingType = TypeHelper.GetUnderlyingTypeOrSelf(type);
            IEdmTypeConfiguration edmTypeConfiguration = builder.GetTypeConfigurationOrNull(type);
            if (underlyingType.IsEnum)
            {
                edmTypeConfiguration = builder.GetTypeConfigurationOrNull(underlyingType);
                if (edmTypeConfiguration != null && isNullable)
                {
                    edmTypeConfiguration = ((EnumTypeConfiguration)edmTypeConfiguration).GetNullableEnumTypeConfiguration();
                }
            }
            NonbindingParameterConfiguration parameter = new NonbindingParameterConfiguration("name",
                edmTypeConfiguration);

            // Assert
            Assert.Equal(isNullable, parameter.OptionalParameter);
        }
        public void CanBuildBoundProcedureCacheForIEdmModel()
        {
            // Arrange            
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration<Customer> customer = builder.EntitySet<Customer>("Customers").EntityType;
            customer.HasKey(c => c.ID);
            customer.Property(c => c.Name);
            customer.ComplexProperty(c => c.Address);

            EntityTypeConfiguration<Movie> movie = builder.EntitySet<Movie>("Movies").EntityType;
            movie.HasKey(m => m.ID);
            movie.HasKey(m => m.Name);
            EntityTypeConfiguration<Blockbuster> blockBuster = builder.EntityType<Blockbuster>().DerivesFrom<Movie>();
            EntityTypeConfiguration movieConfiguration = builder.StructuralTypes.OfType<EntityTypeConfiguration>().Single(t => t.Name == "Movie");

            // build actions that are bindable to a single entity
            customer.Action("InCache1_CustomerAction");
            customer.Action("InCache2_CustomerAction");
            movie.Action("InCache3_MovieAction");
            ActionConfiguration incache4_MovieAction = builder.Action("InCache4_MovieAction");
            incache4_MovieAction.SetBindingParameter("bindingParameter", movieConfiguration);
            blockBuster.Action("InCache5_BlockbusterAction");

            // build actions that are either: bindable to a collection of entities, have no parameter, have only complex parameter 
            customer.Collection.Action("NotInCache1_CustomersAction");
            movie.Collection.Action("NotInCache2_MoviesAction");
            ActionConfiguration notInCache3_NoParameters = builder.Action("NotInCache3_NoParameters");
            ActionConfiguration notInCache4_AddressParameter = builder.Action("NotInCache4_AddressParameter");
            notInCache4_AddressParameter.Parameter<Address>("address");

            IEdmModel model = builder.GetEdmModel();
            IEdmEntityType customerType = model.SchemaElements.OfType<IEdmEntityType>().Single(e => e.Name == "Customer");
            IEdmEntityType movieType = model.SchemaElements.OfType<IEdmEntityType>().Single(e => e.Name == "Movie");
            IEdmEntityType blockBusterType = model.SchemaElements.OfType<IEdmEntityType>().Single(e => e.Name == "Blockbuster");

            // Act 
            BindableProcedureFinder annotation = new BindableProcedureFinder(model);
            IEdmAction[] movieActions = annotation.FindProcedures(movieType)
                .OfType<IEdmAction>()
                .ToArray();
            IEdmAction[] customerActions = annotation.FindProcedures(customerType)
                .OfType<IEdmAction>()
                .ToArray();
            IEdmAction[] blockBusterActions = annotation.FindProcedures(blockBusterType)
                .OfType<IEdmAction>()
                .ToArray();

            // Assert
            Assert.Equal(2, customerActions.Length);
            Assert.NotNull(customerActions.SingleOrDefault(a => a.Name == "InCache1_CustomerAction"));
            Assert.NotNull(customerActions.SingleOrDefault(a => a.Name == "InCache2_CustomerAction"));
            Assert.Equal(2, movieActions.Length);
            Assert.NotNull(movieActions.SingleOrDefault(a => a.Name == "InCache3_MovieAction"));
            Assert.NotNull(movieActions.SingleOrDefault(a => a.Name == "InCache4_MovieAction"));
            Assert.Equal(3, blockBusterActions.Length);
            Assert.NotNull(blockBusterActions.SingleOrDefault(a => a.Name == "InCache3_MovieAction"));
            Assert.NotNull(blockBusterActions.SingleOrDefault(a => a.Name == "InCache4_MovieAction"));
            Assert.NotNull(blockBusterActions.SingleOrDefault(a => a.Name == "InCache5_BlockbusterAction"));
        }
 private static void BuildFunctions(ODataModelBuilder builder)
 {
     FunctionConfiguration function =
         builder.EntityType<File>()
             .Collection.Function("GetFilesModifiedAt")
             .ReturnsCollectionViaEntitySetPath<File>("bindingParameter");
     function.Parameter<DateTime>("modifiedDate");
 }
 public void CreateComplexTypeProperty()
 {
     var builder = new ODataModelBuilder().Add_Customer_EntityType().Add_Address_ComplexType();
     builder.EntityType<Customer>().ComplexProperty(c => c.Address);
     var model = builder.GetServiceModel();
     var customerType = model.SchemaElements.OfType<IEdmEntityType>().Single();
     var addressProperty = customerType.FindProperty("Address");
     Assert.NotNull(addressProperty);
 }
 public UnboundFunctionPathSegmentTest()
 {
     ODataModelBuilder builder = new ODataModelBuilder();
     builder.EntityType<MyCustomer>().HasKey(c => c.Id).Property(c => c.Name);
     builder.EntitySet<MyCustomer>("Customers");
     FunctionConfiguration function = builder.Function("TopCustomer");
     function.ReturnsFromEntitySet<MyCustomer>("Customers");
     builder.Function("MyFunction").Returns<string>();
     _model = builder.GetEdmModel();
     _container = _model.EntityContainers().Single();
 }
        public static IEdmModel GetExplicitModel()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            var accountType = builder.EntityType<Account>();
            accountType.HasKey(a => a.AccountID);
            accountType.Property(a => a.Name);
            var payoutPI = accountType.ContainsOptional(a => a.PayoutPI);
            var payinPIs = accountType.HasMany(a => a.PayinPIs)
                .Contained();

            var premiumAccountType = builder.EntityType<PremiumAccount>()
                .DerivesFrom<Account>();
            var giftCard = premiumAccountType.ContainsRequired(pa => pa.GiftCard);

            var giftCardType = builder.EntityType<GiftCard>();
            giftCardType.HasKey(g => g.GiftCardID);
            giftCardType.Property(g => g.GiftCardNO);
            giftCardType.Property(g => g.Amount);

            var paymentInstrumentType = builder.EntityType<PaymentInstrument>();
            paymentInstrumentType.HasKey(pi => pi.PaymentInstrumentID);
            paymentInstrumentType.Property(pi => pi.FriendlyName);
            var statement = paymentInstrumentType.ContainsOptional(pi => pi.Statement);

            var statementType = builder.EntityType<Statement>();
            statementType.HasKey(s => s.StatementID);
            statementType.Property(s => s.TransactionDescription);
            statementType.Property(s => s.Amount);

            var accounts = builder.EntitySet<Account>("Accounts"); 
            accounts.HasIdLink(c => c.GenerateSelfLink(false), true);
            accounts.HasEditLink(c => c.GenerateSelfLink(true), true);
            
            builder.Singleton<Account>("AnonymousAccount");

            AddBoundActionsAndFunctions(builder);

            builder.Namespace = typeof(Account).Namespace;

            return builder.GetEdmModel();
        }
 public UnboundActionPathSegmentTest()
 {
     ODataModelBuilder builder = new ODataModelBuilder();
     builder.EntityType<MyCustomer>().HasKey(c => c.Id).Property(c => c.Name);
     builder.EntitySet<MyCustomer>("Customers");
     ActionConfiguration action = builder.Action("CreateCustomer");
     action.ReturnsFromEntitySet<MyCustomer>("Customers");
     builder.Action("MyAction").Returns<string>();
     builder.Action("ActionWithoutReturn");
     _model = builder.GetEdmModel();
     _container = _model.EntityContainer;
 }
Beispiel #15
0
        public void SelectViaOData(
            [IncludeDataSources(TestProvName.AllSqlServer)] string context,
            [ValueSource(nameof(ODataQueriesTestCases))] ODataQueries testCase)
        {
            var modelBuilder = new ODataModelBuilder();
            var person       = modelBuilder.EntityType <PersonClass>();

            person.HasKey(p => p.Name);
            person.Property(p => p.Title);
            person.Property(p => p.YearsExperience);

            var model    = modelBuilder.GetEdmModel();
            var testData = GenerateTestData();

            using (var db = GetDataContext(context))
                using (var table = db.CreateLocalTable(testData))
                {
                    var path = new ODataPath();
                    ODataQueryContext queryContext = new ODataQueryContext(model, typeof(PersonClass), path);

                    var uri = new Uri("http://localhost:15580" + testCase.Query);
#if NETFRAMEWORK
                    var request = new HttpRequestMessage()
                    {
                        Method     = HttpMethod.Get,
                        RequestUri = uri
                    };

                    var config = new HttpConfiguration();
                    config.EnableDependencyInjection();

                    request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, config);
#else
                    // https://github.com/OData/AspNetCoreOData/blob/master/test/Microsoft.AspNetCore.OData.Tests/Extensions/RequestFactory.cs#L78
                    var         httpContext = new DefaultHttpContext();
                    HttpRequest request     = httpContext.Request;

                    IServiceCollection services = new ServiceCollection();
                    httpContext.RequestServices = services.BuildServiceProvider();

                    request.Method      = "GET";
                    request.Scheme      = uri.Scheme;
                    request.Host        = uri.IsDefaultPort ? new HostString(uri.Host) : new HostString(uri.Host, uri.Port);
                    request.QueryString = new QueryString(uri.Query);
                    request.Path        = new PathString(uri.AbsolutePath);
#endif
                    var options = new ODataQueryOptions(queryContext, request);

                    var resultQuery  = options.ApplyTo(table);
                    var materialized = Materialize(resultQuery);
                    Assert.That(materialized.Count, Is.EqualTo(1));
                }
        }
        private IEdmModel BuildEdmModel(ODataModelBuilder builder)
        {
            builder.EntitySet <Case>("cases");
            builder.EntitySet <Editor>("editors");
            builder.EntitySet <Location>("locations");
            builder.EntitySet <Visitor>("visitors");
            var caseTypeBuilder           = builder.EntityType <Case>();
            var caseTypeGetStatusFunction = caseTypeBuilder.Function("status").Returns <ChangeDependentSubjectStateEntry>();

            caseTypeGetStatusFunction.Parameter <int>("subjectId").Required();
            return(builder.GetEdmModel());
        }
Beispiel #17
0
        public static ODataModelBuilder Add_Order_EntityType(this ODataModelBuilder builder)
        {
            var order = builder.EntityType <Order>();

            order.HasKey(o => o.OrderId);
            order.Property(o => o.OrderDate);
            order.Property(o => o.Price);
            order.Property(o => o.OrderDate);
            order.Property(o => o.DeliveryDate);
            order.Ignore(o => o.Cost);
            return(builder);
        }
Beispiel #18
0
        // Adds a Customer EntityType but allows caller to configure Keys()
        public static ODataModelBuilder Add_Customer_With_Keys_EntityType <TKey>(this ODataModelBuilder builder, Expression <Func <Customer, TKey> > keyDefinitionExpression)
        {
            var customer = builder.EntityType <Customer>();

            customer.HasKey(keyDefinitionExpression);
            customer.Property(c => c.CustomerId);
            customer.Property(c => c.Name);
            customer.Property(c => c.Website);
            customer.Property(c => c.SharePrice);
            customer.Property(c => c.ShareSymbol);
            return(builder);
        }
Beispiel #19
0
        public static ODataModelBuilder Add_Customer_EntityType(this ODataModelBuilder builder)
        {
            var customer = builder.EntityType <Customer>();

            customer.HasKey(c => c.CustomerId);
            customer.Property(c => c.CustomerId);
            customer.Property(c => c.Name).IsConcurrencyToken();
            customer.Property(c => c.Website);
            customer.Property(c => c.SharePrice);
            customer.Property(c => c.ShareSymbol);
            return(builder);
        }
Beispiel #20
0
        public void CreateEdmModelWithEntitySetFromAbstractEntityTypeWithoutKey_Throws()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            builder.EntityType <Customer>().Abstract().Property(c => c.CustomerId);
            builder.EntitySet <Customer>("Customers");

            // Act & Assert
            ExceptionAssert.Throws <InvalidOperationException>(() => builder.GetEdmModel(),
                                                               "The entity set 'Customers' is based on type 'Microsoft.OData.ModelBuilder.Tests.TestModels.Customer' that has no keys defined.");
        }
Beispiel #21
0
        public void BuildEdmModel_WorksOnModelBuilder_ForUntypedProperty(bool convention)
        {
            // Arrange & Act
            IEdmModel model = null;

            if (convention)
            {
                ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
                builder.EntityType <UntypedEntity>();
                model = builder.GetEdmModel();
            }
            else
            {
                ODataModelBuilder builder = new ODataModelBuilder();
                var entity = builder.EntityType <UntypedEntity>();
                entity.HasKey(p => p.Id);
                entity.Property(p => p.Value);
                entity.CollectionProperty(p => p.Data);
                entity.CollectionProperty(p => p.Infos);
                model = builder.GetEdmModel();
            }

            // Assert
            Assert.NotNull(model);
            IEdmEntityType edmEntityType = model.SchemaElements.OfType <IEdmEntityType>().First(c => c.Name == "UntypedEntity");

            IEdmProperty[] edmProperties = edmEntityType.Properties().ToArray();
            Assert.Equal(4, edmProperties.Length);

            // Value property
            IEdmProperty valueProperty = edmProperties.First(p => p.Name == "Value");

            Assert.True(valueProperty.Type.IsNullable); // always "true"?
            Assert.True(valueProperty.Type.IsUntyped());
            Assert.Same(EdmCoreModel.Instance.GetUntypedType(), valueProperty.Type.Definition);
            Assert.Equal("Edm.Untyped", valueProperty.Type.FullName());

            // Data collection property
            IEdmProperty dataProperty = edmProperties.First(p => p.Name == "Data");

            Assert.True(dataProperty.Type.IsNullable); // always "true"?
            Assert.True(dataProperty.Type.IsCollection());
            Assert.True(dataProperty.Type.AsCollection().ElementType().IsUntyped());
            Assert.Equal("Collection(Edm.Untyped)", dataProperty.Type.FullName());

            // Infos collection property
            IEdmProperty infosProperty = edmProperties.First(p => p.Name == "Infos");

            Assert.True(infosProperty.Type.IsNullable); // always "true"?
            Assert.True(infosProperty.Type.IsCollection());
            Assert.True(infosProperty.Type.AsCollection().ElementType().IsUntyped());
            Assert.Equal("Collection(Edm.Untyped)", infosProperty.Type.FullName());
        }
Beispiel #22
0
        public void Validate_Throws_If_EntityWithoutKeyDefined_UsedToDefineEntitySet()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            builder.EntityType <Customer>();
            builder.EntitySet <Customer>("Customers");

            // Act & Assert
            ExceptionAssert.Throws <InvalidOperationException>(() => builder.GetEdmModel(),
                                                               "The entity set 'Customers' is based on type 'Microsoft.AspNet.OData.Test.Common.Models.Customer' that has no keys defined.");
        }
        public void HasFeedFunctionLink_SetsFollowsConventions(bool value)
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            var function = builder.EntityType <Customer>().Collection.Function("IgnoreFunction");

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

            // Assert
            Assert.Equal(value, function.FollowsConventions);
        }
        public void ExecuteBindingAsync_Works_WithPath(string methodName, Type entityClrType)
        {
            // Arrange
            HttpRequestMessage request = new HttpRequestMessage(
                HttpMethod.Get,
                "http://localhost/Customer/?$orderby=Name");
            HttpConfiguration config = new HttpConfiguration();

            request.SetConfiguration(config);

            // Get EDM model, and set path to request.
            ODataModelBuilder odataModel = new ODataModelBuilder();
            string            setName    = typeof(Customer).Name;

            odataModel.EntityType <Customer>().HasKey(c => c.Id);
            odataModel.EntitySet <Customer>(setName);
            IEdmModel     model     = odataModel.GetEdmModel();
            IEdmEntitySet entitySet = model.EntityContainer.FindEntitySet(setName);

            request.ODataProperties().Model = model;
            request.ODataProperties().Path  = new ODataPath(new EntitySetPathSegment(entitySet));

            // Setup action context and parameter descriptor.
            HttpControllerContext controllerContext = new HttpControllerContext(
                config,
                new HttpRouteData(new HttpRoute()),
                request);
            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(
                config,
                "CustomerLowLevel",
                typeof(CustomerHighLevelController));
            MethodInfo              methodInfo          = typeof(CustomerLowLevelController).GetMethod(methodName);
            HttpActionDescriptor    actionDescriptor    = new ReflectedHttpActionDescriptor(controllerDescriptor, methodInfo);
            HttpActionContext       actionContext       = new HttpActionContext(controllerContext, actionDescriptor);
            HttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(
                actionDescriptor,
                methodInfo.GetParameters().First());

            // Act
            new ODataQueryParameterBindingAttribute().GetBinding(parameterDescriptor)
            .ExecuteBindingAsync((ModelMetadataProvider)null, actionContext, CancellationToken.None)
            .Wait();

            // Assert
            Assert.Equal(1, actionContext.ActionArguments.Count);
            ODataQueryOptions options =
                actionContext.ActionArguments[parameterDescriptor.ParameterName] as ODataQueryOptions;

            Assert.NotNull(options);
            Assert.Same(model, options.Context.Model);
            Assert.Same(entitySet, options.Context.NavigationSource);
            Assert.Same(entityClrType, options.Context.ElementClrType);
        }
Beispiel #25
0
        private static IEdmModel GetModel(WebRouteConfiguration config)
        {
            ODataModelBuilder builder = config.CreateConventionModelBuilder();

            builder.EntitySet <DerivedTypeA>("SetA");
            builder.EntitySet <DerivedTypeB>("SetB");

            builder.EntityType <BaseType>(); // this line is necessary.
            builder.Function("ReturnAll").ReturnsCollection <BaseType>();

            return(builder.GetEdmModel());
        }
Beispiel #26
0
        public static IEdmModel NewNonConventionalBuildModel()
        {
            var builder = new ODataModelBuilder();
            var color   = builder.EnumType <Color>();

            color.Member(Color.Red);
            color.Member(Color.Blue);
            color.Member(Color.Green);
            var address = builder.ComplexType <Address>();

            address.Property(a => a.Country);
            address.Property(a => a.City);
            address.HasDynamicProperties(a => a.Dynamics);
            var subAddress = builder.ComplexType <SubAddress>().DerivesFrom <Address>();

            subAddress.Property(s => s.Street);
            var customer = builder.EntityType <Customer>();

            customer.HasKey(c => c.CustomerId);
            customer.ComplexProperty(c => c.Location);
            customer.HasMany(c => c.Orders);
            var order = builder.EntityType <Order>();

            order.HasKey(o => o.OrderId);
            order.Property(o => o.Token);
            builder.EntityType <Registration>().HasKey(r => new { r.ParticipantId, r.ThreadId });
            builder.EntityType <Participant>().HasKey(p => p.Login);
            builder.EntityType <Thread>().HasKey(t => t.Id);
            builder.EntityType <Box>().HasKey(b => b.Id);
            builder.EntitySet <Thread>("Threads");
            builder.EntitySet <Box>("Boxes");
            builder.EntitySet <Participant>("Participants");
            return(builder.GetEdmModel());
        }
Beispiel #27
0
        public EnableNestedPathsTest()
        {
            _deserializerProvider    = ODataDeserializerProviderFactory.Create();
            _resourceSetDeserializer = new ODataResourceSetDeserializer(_deserializerProvider);
            _resourceDeserializer    = new ODataResourceDeserializer(_deserializerProvider);
            _primitiveDeserializer   = new ODataPrimitiveDeserializer();

            ODataModelBuilder builder = ODataConventionModelBuilderFactory.Create();

            builder.EntitySet <EnableNestedPathsCustomer>("EnableNestedPathsCustomers");
            builder.EntitySet <EnableNestedPathsProduct>("EnableNestedPathsProducts");
            builder.Singleton <EnableNestedPathsCustomer>("EnableNestedPathsTopCustomer");
            builder.EntityType <EnableNestedPathsVipCustomer>();

            builder.EntityType <EnableNestedPathsVipCustomer>()
            .Function("GetMostPurchasedProduct")
            .ReturnsFromEntitySet <EnableNestedPathsProduct>("EnableNestedPathsProduct");

            builder.EntityType <EnableNestedPathsProduct>()
            .Collection
            .Action("SetDiscountRate");

            _model = builder.GetEdmModel();

            Type[] controllers = new Type[] {
                typeof(EnableNestedPathsCustomersController),
                typeof(EnableNestedPathsProductsController),
                typeof(EnableNestedPathsTopCustomerController)
            };

            _server = TestServerFactory.Create(controllers, (config) =>
            {
                config.MapODataServiceRoute("odata", "odata", _model);
                config.Count().OrderBy().Filter().Expand().MaxTop(null).Select();
            });

            _client = TestServerFactory.CreateClient(_server);

            _db = new EnableNestedPathsDatabase();
        }
Beispiel #28
0
        private static void MapCommonOData(ODataModelBuilder builder)
        {
            builder
            .EntitySet <DocumentModel>("Documents")
            .EntityType.HasKey(p => p.Id);

            builder
            .EntitySet <Core.Models.Workflows.Parameters.MetadataModel>("MetadataModel")
            .EntityType.HasKey(p => new { p.KeyName, p.Value });

            builder
            .EntitySet <CategoryModel>("Categories")
            .EntityType.HasKey(p => p.Id);

            builder
            .EntitySet <ContainerModel>("Containers")
            .EntityType.HasKey(p => p.Id);

            builder
            .EntitySet <GenericDocumentUnitModel>("GenericDocumentUnits")
            .EntityType.HasKey(p => p.Id);

            #region [ Functions ]

            FunctionConfiguration getProtocolDocumentsFunc = builder
                                                             .EntityType <DocumentModel>().Collection
                                                             .Function("GetDocuments");
            getProtocolDocumentsFunc.Namespace = "DocumentUnitService";
            getProtocolDocumentsFunc.ReturnsCollectionFromEntitySet <DocumentModel>("DocumentUnits");
            getProtocolDocumentsFunc.Parameter <Guid>("uniqueId");
            getProtocolDocumentsFunc.Parameter <Guid?>("workflowArchiveChainId");

            FunctionConfiguration getActivityDocuments = builder
                                                         .EntityType <DocumentModel>().Collection
                                                         .Function("GetDocumentsByArchiveChain");
            getActivityDocuments.Namespace = "DocumentUnitService";
            getActivityDocuments.ReturnsCollectionFromEntitySet <DocumentModel>("DocumentUnits");
            getActivityDocuments.Parameter <Guid>("idArchiveChain");
            #endregion
        }
Beispiel #29
0
        private static void RegisterMembershipODataActions(ODataModelBuilder builder)
        {
            var getUsersInRoleAction = builder.EntityType <KoreUser>().Collection.Action("GetUsersInRole");

            getUsersInRoleAction.Parameter <string>("roleId");
            getUsersInRoleAction.ReturnsCollectionFromEntitySet <KoreUser>("Users");

            var assignUserToRolesAction = builder.EntityType <KoreUser>().Collection.Action("AssignUserToRoles");

            assignUserToRolesAction.Parameter <string>("userId");
            assignUserToRolesAction.CollectionParameter <string>("roles");
            assignUserToRolesAction.Returns <IHttpActionResult>();

            var changePasswordAction = builder.EntityType <KoreUser>().Collection.Action("ChangePassword");

            changePasswordAction.Parameter <string>("userId");
            changePasswordAction.Parameter <string>("password");
            changePasswordAction.Returns <IHttpActionResult>();

            var getRolesForUserAction = builder.EntityType <KoreRole>().Collection.Action("GetRolesForUser");

            getRolesForUserAction.Parameter <string>("userId");
            getRolesForUserAction.ReturnsCollection <EdmKoreRole>();

            var assignPermissionsToRoleAction = builder.EntityType <KoreRole>().Collection.Action("AssignPermissionsToRole");

            assignPermissionsToRoleAction.Parameter <string>("roleId");
            assignPermissionsToRoleAction.CollectionParameter <string>("permissions");
            assignPermissionsToRoleAction.Returns <IHttpActionResult>();

            var getPermissionsForRoleAction = builder.EntityType <KorePermission>().Collection.Action("GetPermissionsForRole");

            getPermissionsForRoleAction.Parameter <string>("roleId");
            getPermissionsForRoleAction.ReturnsCollection <EdmKorePermission>();
        }
Beispiel #30
0
        public void GetIfMatchOrNoneMatch_ReturnsETag_SetETagHeaderValue(string header)
        {
            // Arrange
            HttpRequestMessage request      = new HttpRequestMessage();
            HttpConfiguration  cofiguration = new HttpConfiguration();

            request.SetConfiguration(cofiguration);
            Dictionary <string, object> properties = new Dictionary <string, object> {
                { "Name", "Foo" }
            };
            EntityTagHeaderValue etagHeaderValue = new DefaultODataETagHandler().CreateETag(properties);

            if (header.Equals("IfMatch"))
            {
                request.Headers.IfMatch.Add(etagHeaderValue);
            }
            else
            {
                request.Headers.IfNoneMatch.Add(etagHeaderValue);
            }

            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration <Customer> customer = builder.EntityType <Customer>();

            customer.HasKey(c => c.Id);
            customer.Property(c => c.Id);
            customer.Property(c => c.Name).IsConcurrencyToken();
            builder.EntitySet <Customer>("Customers");
            IEdmModel model = builder.GetEdmModel();

            var customers = model.FindDeclaredEntitySet("Customers");
            Mock <ODataPathSegment> mockSegment = new Mock <ODataPathSegment> {
                CallBase = true
            };

            mockSegment.Setup(s => s.GetEdmType(null)).Returns(model.GetEdmType(typeof(Customer)));
            mockSegment.Setup(s => s.GetNavigationSource(null)).Returns((IEdmNavigationSource)customers);
            ODataPath odataPath = new ODataPath(new[] { mockSegment.Object });

            request.ODataProperties().Path  = odataPath;
            request.ODataProperties().Model = model;
            ODataQueryContext context       = new ODataQueryContext(model, typeof(Customer));

            // Act
            ODataQueryOptions <Customer> query = new ODataQueryOptions <Customer>(context, request);
            ETag    result        = header.Equals("IfMatch") ? query.IfMatch : query.IfNoneMatch;
            dynamic dynamicResult = result;

            // Assert
            Assert.Equal("Foo", result["Name"]);
            Assert.Equal("Foo", dynamicResult.Name);
        }
        private EntityTypeConfiguration <FlightPlan> ConfigureCurrent(ODataModelBuilder builder)
        {
            //var flightplan = builder.EntitySet<FlightPlan>("FlightPlans").EntityType;
            builder.EntitySet <FlightPlan>("FlightPlans");
            var flightPlanType = builder.EntityType <FlightPlan>();

            //flightPlanType
            //   .Function("Current")
            //   .Returns<FlightPlan>()
            //   .Parameter<string>("flightNumber");
            flightPlanType
            .Function("Current")
            .ReturnsFromEntitySet <FlightPlan>("FlightPlan");

            var fnGetCurrent = builder.Function("GetCurrentFlightPlan");

            fnGetCurrent.Returns <FlightPlan>();
            fnGetCurrent.Parameter <string>("flightNumber");
            fnGetCurrent.Parameter <string>("iataAirlineCode");

            //var fnCurrent = builder.EntityType<FlightPlan>().Collection.Function("Current");
            //fnCurrent.Parameter<string>("flightNumber");
            //fnCurrent.ReturnsFromEntitySet<FlightPlan>("FlightPlan");
            //var functionFlightPlan = builder.Function("GetFlightPlansP");
            //functionFlightPlan.Returns<FlightPlan>();
            //functionFlightPlan.Parameter<string>("flightNumber");
            //functionFlightPlan.Parameter<string>("iataCode");
            //builder.Function("GetFlightPlans")
            //    .Returns<FlightPlan>()
            //    .Parameter(<string>("flightNumber")


            return(builder.EntityType <FlightPlan>());

            //var conventions = ODataRoutingConventions.CreateDefault();
            //conventions.Insert(0, new CompositeKeyRoutingConvention());

            // return flightplan;
        }
        public static IEdmModel GetExplicitModel()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            var fileType = builder.EntityType <File>().HasKey(f => f.FileId);

            fileType.Property(f => f.Name);
            fileType.Property(f => f.CreatedDate);
            fileType.Property(f => f.DeleteDate);

            var files = builder.EntitySet <File>("Files");

            return(builder.GetEdmModel());
        }
        public void CtorODataQueryContext_TakingClrType_Throws_For_UnknownType(Type elementType)
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            builder.EntityType <Customer>();
            IEdmModel model = builder.GetEdmModel();

            // Act && Assert
            ExceptionAssert.ThrowsArgument(() => new ODataQueryContext(model, elementType),
                                           "elementClrType",
                                           Error.Format("The given model does not contain the type '{0}'.", elementType.FullName));
        }
Beispiel #34
0
        public void HasFeedFunctionLink_ThrowsException_OnNoBoundToCollectionEntityFunctions()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration <Customer> customer = builder.EntityType <Customer>();
            FunctionConfiguration function = customer.Function("NonCollectionFunction");

            // Act & Assert
            ExceptionAssert.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 'NonCollectionFunction' does not meet this requirement.");
        }
Beispiel #35
0
        private static void GetModel(out IEdmModel model, out IEdmEntityTypeReference reference)
        {
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock <ODataConventionModelBuilder>();
            EntityTypeConfiguration <TestEntity> entity = builder.EntityType <TestEntity>();

            entity.Namespace = "Test";
            entity.Name      = "Entity";
            NavigationPropertyConfiguration property = entity.HasOptional(p => p.Property);

            property.Name = "Alias";
            model         = builder.GetEdmModel();
            reference     = new EdmEntityTypeReference((IEdmEntityType)model.FindType("Test.Entity"), false);
        }
        public UnboundFunctionPathSegmentTest()
        {
            ODataModelBuilder builder = new ODataModelBuilder();

            builder.EntityType <MyCustomer>().HasKey(c => c.Id).Property(c => c.Name);
            builder.EntitySet <MyCustomer>("Customers");
            FunctionConfiguration function = builder.Function("TopCustomer");

            function.ReturnsFromEntitySet <MyCustomer>("Customers");
            builder.Function("MyFunction").Returns <string>();
            _model     = builder.GetEdmModel();
            _container = _model.EntityContainer;
        }
Beispiel #37
0
        private static System.Web.Http.HttpServer CreateServer(string customersEntitySet)
#endif
        {
            // We need to do this to avoid controllers with incorrect attribute
            // routing configuration in this assembly that cause an exception to
            // be thrown at runtime. With this, we restrict the test to the following
            // set of controllers.
            Type[] controllers = new Type[]
            {
                typeof(OnlyFilterAllowedCustomersController),
                typeof(OnlyFilterAndEqualsAllowedCustomersController),
                typeof(FilterDisabledCustomersController),
                typeof(EverythingAllowedCustomersController),
                typeof(OtherLimitationsCustomersController),
            };

            ODataModelBuilder builder = ODataConventionModelBuilderFactory.Create();

            builder.EntitySet <EnableQueryCustomer>(customersEntitySet);
            builder.EntityType <PremiumEnableQueryCustomer>();

            builder.EntitySet <EnableQueryCategory>("EnableQueryCategories");
            builder.EntityType <PremiumEnableQueryCategory>();

            builder.EntitySet <EnableQueryOrder>("EnableQueryOrders");
            builder.EntityType <DiscountedEnableQueryOrder>();

            builder.EntitySet <EnableQueryOrderLine>("EnableQueryOrderLines");

            builder.ComplexType <EnableQueryAddress>();

            IEdmModel model = builder.GetEdmModel();

            return(TestServerFactory.Create(controllers, (config) =>
            {
                config.MapODataServiceRoute("odata", "odata", model);
                config.Count().OrderBy().Filter().Expand().MaxTop(null).Select().SkipToken();
            }));
        }
Beispiel #38
0
        protected override ODataModelBuilder OnCreateEdmModel(ODataModelBuilder oDataModelBuilder)
        {
            oDataModelBuilder.Namespace = "Example";

            oDataModelBuilder.EntitySet <Product>("Products");
            oDataModelBuilder.AddPluralizedEntitySet <Book>();
            oDataModelBuilder.AddPluralizedEntitySet <Author>();
            oDataModelBuilder.AddPluralizedEntitySet <Publisher>();

            oDataModelBuilder.EntityType <Publisher>().HasKey(c => new { c.PublisherId1, c.PublisherId2 });

            return(oDataModelBuilder);
        }
        public void HasActionLink_ThrowsException_OnNoBoundToEntityActions()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration <Customer> customer = builder.EntityType <Customer>();
            ActionConfiguration action = customer.Collection.Action("CollectionAction");

            // Act & Assert
            ExceptionAssert.Throws <InvalidOperationException>(
                () => action.HasActionLink(ctx => new Uri("http://any"), followsConventions: false),
                "To register an action link factory, actions must be bindable to a single entity. " +
                "Action 'CollectionAction' does not meet this requirement.");
        }
        public void ReturnsCollection_ThrowsInvalidOperationException_IfReturnTypeIsEntity()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            builder.EntityType <Movie>();
            var action = builder.Action("action");

            // Act & Assert
            ExceptionAssert.Throws <InvalidOperationException>(() => action.ReturnsCollection <Movie>(),
                                                               "The EDM type 'Microsoft.AspNet.OData.Test.Builder.Movie' is already declared as an entity type. Use the " +
                                                               "method 'ReturnsCollectionFromEntitySet' if the return type is an entity collection.");
        }
        public void HasManyPath_AddBindindPath_Derived(bool contained)
        {
            // Assert
            ODataModelBuilder builder = new ODataModelBuilder();
            var customerType          = builder.EntityType <BindingCustomer>();
            var navigationSource      = builder.EntitySet <BindingCustomer>("Customers");

            StructuralTypeConfiguration addressType = builder.StructuralTypes.FirstOrDefault(c => c.Name == "BindingAddress");

            Assert.Null(addressType);              // Guard
            Assert.Empty(customerType.Properties); // Guard

            // Act
            var binding    = new BindingPathConfiguration <BindingCustomer>(builder, customerType, navigationSource.Configuration);
            var newBinding = binding.HasManyPath((BindingVipCustomer v) => v.VipAddresses, contained);

            // Assert
            addressType = builder.StructuralTypes.FirstOrDefault(c => c.Name == "BindingAddress");
            Assert.NotNull(addressType);
            Assert.Empty(customerType.Properties);

            StructuralTypeConfiguration vipCustomerType = builder.StructuralTypes.FirstOrDefault(c => c.Name == "BindingVipCustomer");

            Assert.NotNull(vipCustomerType);
            var vipAddressesProperty = Assert.Single(vipCustomerType.Properties);

            Assert.Equal("VipAddresses", vipAddressesProperty.Name);

            if (contained)
            {
                Assert.Equal(EdmTypeKind.Entity, addressType.Kind);
                Assert.Equal(PropertyKind.Navigation, vipAddressesProperty.Kind);
                NavigationPropertyConfiguration navigationProperty = Assert.IsType <NavigationPropertyConfiguration>(vipAddressesProperty);
                Assert.Equal(EdmMultiplicity.Many, navigationProperty.Multiplicity);
                Assert.True(navigationProperty.ContainsTarget);
            }
            else
            {
                Assert.Equal(EdmTypeKind.Complex, addressType.Kind);
                Assert.Equal(PropertyKind.Collection, vipAddressesProperty.Kind);
                CollectionPropertyConfiguration collection = Assert.IsType <CollectionPropertyConfiguration>(vipAddressesProperty);
                Assert.Equal(typeof(BindingAddress), collection.ElementType);
            }

            // different bindings
            Assert.NotSame(binding, newBinding);
            Assert.Equal("", binding.BindingPath);

            Assert.IsType <BindingPathConfiguration <BindingAddress> >(newBinding);
            Assert.Equal("Microsoft.AspNet.OData.Test.Formatter.BindingVipCustomer/VipAddresses", newBinding.BindingPath);
        }
Beispiel #42
0
        private static IEdmModel CreateModel()
        {
            var builder = new ODataModelBuilder();

            builder.Namespace = "HS";

            var personType = builder.EntityType <Person>()
                             .HasKey(p => p.Id);

            personType.Property(p => p.Name);
            personType.Property(p => p.Age);
            personType.OrderBy().Select().Filter().Expand().Count();

            personType.Action("Mark").Parameter <string>("comment");

            // Entity Function
            var function = personType
                           .Function("ToLongString");

            function.Parameter <string>("prefix");
            function.Returns <string>();

            // Collection Functions
            var allAdultsFunction = personType
                                    .Collection
                                    .Function("AllAdults");

            allAdultsFunction.ReturnsCollectionFromEntitySet <Person>("Persons");

            var allChildrenFunction = personType
                                      .Collection
                                      .Function("AllChildren");

            allChildrenFunction.ReturnsCollectionFromEntitySet <Person>("Persons");

            // Unbound Function
            var addFunction = builder.Function("Add");

            addFunction.Parameter <int>("z1");
            addFunction.Parameter <int>("z2");
            addFunction.Returns <int>();

            // Unbound Action
            var clearAction = builder.Action("ClearLoggingTable");

            clearAction.Parameter <int>("days");

            builder.EntitySet <Person>("Persons");

            return(builder.GetEdmModel());
        }
        private static IEdmModel GetExplicitEdmModel()
        {
            var builder = new ODataModelBuilder();

            // enum type "Color"
            var color = builder.EnumType<Color>();
            color.Member(Color.Red);
            color.Member(Color.Green);
            color.Member(Color.Blue);
            color.Member(Color.Yellow);
            color.Member(Color.Pink);
            color.Member(Color.Purple);

            // complex type "Address"
            var address = builder.ComplexType<Address>();
            address.Property(a => a.City);
            address.Property(a => a.Street);

            // entity type "Customer"
            var customer = builder.EntityType<Customer>().HasKey(c => c.CustomerId);
            customer.Property(c => c.Name);
            customer.Property(c => c.Token);
            // customer.Property(c => c.Email).IsNotNavigable(); // you can call Fluent API
            customer.Property(c => c.Email);
            customer.CollectionProperty(c => c.Addresses);
            customer.CollectionProperty(c => c.FavoriateColors);
            customer.HasMany(c => c.Orders);

            // entity type "Order"
            var order = builder.EntityType<Order>().HasKey(o => o.OrderId);
            order.Property(o => o.Price);

            // entity sets
            builder.EntitySet<Customer>("Customers").HasManyBinding(c => c.Orders, "Orders");
            builder.EntitySet<Order>("Orders");

            return builder.GetEdmModel();
        }
        public void NonbindingParameterConfigurationThrowsWhenParameterTypeIsEntity()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            builder.EntityType<Customer>();

            // Act & Assert
            ArgumentException exception = Assert.Throws<ArgumentException>(() =>
            {
                NonbindingParameterConfiguration configuration = new NonbindingParameterConfiguration("name", builder.GetTypeConfigurationOrNull(typeof(Customer)));
            });
            Assert.True(exception.Message.Contains(string.Format("'{0}'", typeof(Customer).FullName)));
            Assert.Equal("parameterType", exception.ParamName);
        }
Beispiel #45
0
        public static IEdmModel GetExplicitModel(WebRouteConfiguration configuration)
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            var employee = builder.EntityType <Employee>();

            employee.HasKey(c => c.ID);
            employee.Property(c => c.Name);
            employee.CollectionProperty <Skill>(c => c.SkillSet);
            employee.EnumProperty <Gender>(c => c.Gender);
            employee.EnumProperty <AccessLevel>(c => c.AccessLevel);
            employee.ComplexProperty <FavoriteSports>(c => c.FavoriteSports);
            employee.HasInstanceAnnotations(c => c.InstanceAnnotations);

            var skill = builder.EnumType <Skill>();

            skill.Member(Skill.CSharp);
            skill.Member(Skill.Sql);
            skill.Member(Skill.Web);

            var gender = builder.EnumType <Gender>();

            gender.Member(Gender.Female);
            gender.Member(Gender.Male);

            var accessLevel = builder.EnumType <AccessLevel>();

            accessLevel.Member(AccessLevel.Execute);
            accessLevel.Member(AccessLevel.Read);
            accessLevel.Member(AccessLevel.Write);

            var favoriteSports = builder.ComplexType <FavoriteSports>();

            favoriteSports.EnumProperty <Sport>(f => f.LikeMost);
            favoriteSports.CollectionProperty <Sport>(f => f.Like);

            var sport = builder.EnumType <Sport>();

            sport.Member(Sport.Basketball);
            sport.Member(Sport.Pingpong);

            AddBoundActionsAndFunctions(employee);
            AddUnboundActionsAndFunctions(builder);

            EntitySetConfiguration <Employee> employees = builder.EntitySet <Employee>("Employees");

            employees.HasEditLink(link, true);
            employees.HasIdLink(link, true);
            builder.Namespace = "NS";
            return(builder.GetEdmModel());
        }
Beispiel #46
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.Single(sendEmail.Parameters);
            Assert.Equal(BindingParameterConfiguration.DefaultBindingParameterName, sendEmail.Parameters.Single().Name);
            Assert.Equal(string.Format("Collection({0})", typeof(Customer).FullName), sendEmail.Parameters.Single().TypeConfiguration.FullName);
        }
        public void CreateStreamPrimitiveProperty()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            var file = builder.EntityType<File>();
            var data = file.Property(f => f.StreamData);

            var model = builder.GetServiceModel();
            var fileType = model.SchemaElements.OfType<IEdmEntityType>().Single();
            var streamProperty = fileType.DeclaredProperties.SingleOrDefault(p => p.Name == "StreamData");

            Assert.Equal(PropertyKind.Primitive, data.Kind);

            Assert.NotNull(streamProperty);
            Assert.Equal("Edm.Stream", streamProperty.Type.FullName());
        }
        private static void BuildFunctions(ODataModelBuilder builder)
        {
            FunctionConfiguration function = builder.EntityType<DCustomer>().Function("BoundFunction")
                    .ReturnsCollectionViaEntitySetPath<DCustomer>("bindingParameter");
            function.Parameter<Date>("modifiedDate");
            function.Parameter<TimeOfDay>("modifiedTime");
            function.Parameter<Date?>("nullableModifiedDate");
            function.Parameter<TimeOfDay?>("nullableModifiedTime");

            function = builder.Function("UnboundFunction").ReturnsCollectionFromEntitySet<DCustomer>("DCustomers");
            function.Parameter<Date>("modifiedDate");
            function.Parameter<TimeOfDay>("modifiedTime");
            function.Parameter<Date?>("nullableModifiedDate");
            function.Parameter<TimeOfDay?>("nullableModifiedTime");
        }
        public void CanCreateEntityWithCompoundKey()
        {
            var builder = new ODataModelBuilder();
            var customer = builder.EntityType<Customer>();
            customer.HasKey(c => new { c.CustomerId, c.Name });
            customer.Property(c => c.SharePrice);
            customer.Property(c => c.ShareSymbol);
            customer.Property(c => c.Website);

            var model = builder.GetServiceModel();
            var customerType = model.FindType(typeof(Customer).FullName) as IEdmEntityType;
            Assert.Equal(5, customerType.Properties().Count());
            Assert.Equal(2, customerType.DeclaredKey.Count());
            Assert.NotNull(customerType.DeclaredKey.SingleOrDefault(k => k.Name == "CustomerId"));
            Assert.NotNull(customerType.DeclaredKey.SingleOrDefault(k => k.Name == "Name"));
        }
        public void GetEntry_UsesRouteModel_ForMultipleModels()
        {
            // Model 1 only has Name, Model 2 only has Age
            ODataModelBuilder builder1 = new ODataModelBuilder();
            var personType1 = builder1.EntityType<FormatterPerson>();
            personType1.HasKey(p => p.PerId);
            personType1.Property(p => p.Name);
            builder1.EntitySet<FormatterPerson>("People").HasIdLink(p => new Uri("http://link/"), false);
            var model1 = builder1.GetEdmModel();

            ODataModelBuilder builder2 = new ODataModelBuilder();
            var personType2 = builder2.EntityType<FormatterPerson>();
            personType2.HasKey(p => p.PerId);
            personType2.Property(p => p.Age);
            builder2.EntitySet<FormatterPerson>("People").HasIdLink(p => new Uri("http://link/"), false);
            var model2 = builder2.GetEdmModel();

            var config = new[] { typeof(PeopleController) }.GetHttpConfiguration();
            config.MapODataServiceRoute("OData1", "v1", model1);
            config.MapODataServiceRoute("OData2", "v2", model2);

            using (HttpServer host = new HttpServer(config))
            using (HttpClient client = new HttpClient(host))
            {
                using (HttpResponseMessage response = client.GetAsync("http://localhost/v1/People(10)").Result)
                {
                    Assert.True(response.IsSuccessStatusCode);
                    JToken json = JToken.Parse(response.Content.ReadAsStringAsync().Result);

                    // Model 1 has the Name property but not the Age property
                    Assert.NotNull(json["Name"]);
                    Assert.Null(json["Age"]);
                }

                using (HttpResponseMessage response = client.GetAsync("http://localhost/v2/People(10)").Result)
                {
                    Assert.True(response.IsSuccessStatusCode);
                    JToken json = JToken.Parse(response.Content.ReadAsStringAsync().Result);

                    // Model 2 has the Age property but not the Name property
                    Assert.Null(json["Name"]);
                    Assert.NotNull(json["Age"]);
                }
            }
        }
        public static IEdmModel GetExplicitModel()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            var fileType = builder.EntityType<File>().HasKey(f => f.FileId);
            fileType.Property(f => f.Name);
            fileType.Property(f => f.CreatedDate);
            fileType.Property(f => f.DeleteDate);
            fileType.CollectionProperty(f => f.ModifiedDates);

            var files = builder.EntitySet<File>("Files");
            files.HasIdLink(link, true);
            files.HasEditLink(link, true);

            BuildFunctions(builder);
            BuildActions(builder);

            return builder.GetEdmModel();
        }
Beispiel #52
0
        public void CanCreateEntityWithCompoundKey_ForDateAndTimeOfDay()
        {
            // Arrange
            var builder = new ODataModelBuilder();
            var entity = builder.EntityType<EntityTypeWithDateAndTimeOfDay>();
            entity.HasKey(e => new { e.Date, e.TimeOfDay });

            // Act
            var model = builder.GetServiceModel();

            // Assert
            var entityType =
                model.SchemaElements.OfType<IEdmEntityType>().Single(e => e.Name == "EntityTypeWithDateAndTimeOfDay");
            Assert.Equal(2, entityType.Properties().Count());
            Assert.Equal(2, entityType.DeclaredKey.Count());
            Assert.NotNull(entityType.DeclaredKey.SingleOrDefault(k => k.Name == "Date"));
            Assert.NotNull(entityType.DeclaredKey.SingleOrDefault(k => k.Name == "TimeOfDay"));
        }
        public void CreateDatePrimitiveProperty()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration<File> file = builder.EntityType<File>();
            PrimitivePropertyConfiguration date = file.Property(f => f.DateProperty);

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

            // Assert
            Assert.Equal(PropertyKind.Primitive, date.Kind);

            IEdmEntityType fileType = Assert.Single(model.SchemaElements.OfType<IEdmEntityType>());

            IEdmProperty dateProperty = Assert.Single(fileType.DeclaredProperties.Where(p => p.Name == "DateProperty"));
            Assert.NotNull(dateProperty);
            Assert.Equal("Edm.Date", dateProperty.Type.FullName());
        }
        private static void BuildActions(ODataModelBuilder builder)
        {
            ActionConfiguration action = builder.EntityType<DCustomer>().Action("BoundAction");
            action.Parameter<Date>("modifiedDate");
            action.Parameter<TimeOfDay>("modifiedTime");
            action.Parameter<Date?>("nullableModifiedDate");
            action.Parameter<TimeOfDay?>("nullableModifiedTime");
            action.CollectionParameter<Date>("dates");

            action = builder.Action("UnboundAction");
            action.Parameter<Date>("modifiedDate");
            action.Parameter<TimeOfDay>("modifiedTime");
            action.Parameter<Date?>("nullableModifiedDate");
            action.Parameter<TimeOfDay?>("nullableModifiedTime");
            action.CollectionParameter<Date>("dates");

            // just for reset the data source
            builder.Action("ResetDataSource");
        }
        private static void AddBoundActionsAndFunctions(ODataModelBuilder builder)
        {
            var paymentInstrumentType = builder.EntityType<PaymentInstrument>();

            var actionConfiguration = paymentInstrumentType.Collection.Action("Clear");
            actionConfiguration.Parameter<string>("nameContains");
            actionConfiguration.Returns<int>();// deleted count

            // Bug 2021-Should support Action/Function returns contained entities.
            //paymentInstrumentType.Action("Duplicate").Returns<PaymentInstrument>();

            paymentInstrumentType.Action("Delete");

            var functionConfiguration = paymentInstrumentType.Collection.Function("GetCount");
            functionConfiguration.Parameter<string>("nameContains");
            functionConfiguration.Returns<int>();

            builder.Action("ResetDataSource");
        }
        public void GetIfMatchOrNoneMatch_ReturnsETag_SetETagHeaderValue(string header)
        {
            // Arrange
            HttpRequestMessage request = new HttpRequestMessage();
            HttpConfiguration cofiguration = new HttpConfiguration();
            request.SetConfiguration(cofiguration);
            Dictionary<string, object> properties = new Dictionary<string, object> { { "Name", "Foo" } };
            EntityTagHeaderValue etagHeaderValue = new DefaultODataETagHandler().CreateETag(properties);
            if (header.Equals("IfMatch"))
            {
                request.Headers.IfMatch.Add(etagHeaderValue);
            }
            else
            {
                request.Headers.IfNoneMatch.Add(etagHeaderValue);
            }

            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration<Customer> customer = builder.EntityType<Customer>();
            customer.HasKey(c => c.Id);
            customer.Property(c => c.Id);
            customer.Property(c => c.Name).IsConcurrencyToken();
            builder.EntitySet<Customer>("Customers");
            IEdmModel model = builder.GetEdmModel();

            var customers = model.FindDeclaredEntitySet("Customers");
            Mock<ODataPathSegment> mockSegment = new Mock<ODataPathSegment> { CallBase = true };
            mockSegment.Setup(s => s.GetEdmType(null)).Returns(model.GetEdmType(typeof(Customer)));
            mockSegment.Setup(s => s.GetNavigationSource(null)).Returns((IEdmNavigationSource)customers);
            ODataPath odataPath = new ODataPath(new[] { mockSegment.Object });
            request.ODataProperties().Path = odataPath;
            request.ODataProperties().Model = model;
            ODataQueryContext context = new ODataQueryContext(model, typeof(Customer));

            // Act
            ODataQueryOptions<Customer> query = new ODataQueryOptions<Customer>(context, request);
            ETag result = header.Equals("IfMatch") ? query.IfMatch : query.IfNoneMatch;
            dynamic dynamicResult = result;

            // Assert
            Assert.Equal("Foo", result["Name"]);
            Assert.Equal("Foo", dynamicResult.Name);
        }
        public static IEdmModel GetExplicitModel()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration<Window> windowType = builder.EntityType<Window>();
            windowType.HasKey(a => a.Id);
            windowType.Property(a => a.Name).IsRequired();
            windowType.ComplexProperty(w => w.CurrentShape);
            windowType.CollectionProperty(w => w.OptionalShapes);
            windowType.HasOptional<Window>(w => w.Parent);

            ComplexTypeConfiguration<Shape> shapeType = builder.ComplexType<Shape>();
            shapeType.Property(s => s.HasBorder);
            shapeType.Abstract();

            ComplexTypeConfiguration<Circle> circleType = builder.ComplexType<Circle>();
            circleType.ComplexProperty(c => c.Center);
            circleType.Property(c => c.Radius);
            circleType.DerivesFrom<Shape>();

            ComplexTypeConfiguration<Polygon> polygonType = builder.ComplexType<Polygon>();
            polygonType.CollectionProperty(p => p.Vertexes);
            polygonType.DerivesFrom<Shape>();

            ComplexTypeConfiguration<Rectangle> rectangleType = builder.ComplexType<Rectangle>();
            rectangleType.ComplexProperty(r => r.TopLeft);
            rectangleType.Property(r => r.Width);
            rectangleType.Property(r => r.Height);
            rectangleType.DerivesFrom<Polygon>();

            ComplexTypeConfiguration<Point> pointType = builder.ComplexType<Point>();
            pointType.Property(p => p.X);
            pointType.Property(p => p.Y);

            EntitySetConfiguration<Window> windows = builder.EntitySet<Window>("Windows");
            windows.HasEditLink(link, true);
            windows.HasIdLink(link, true);

            builder.Namespace = typeof(Window).Namespace;

            return builder.GetEdmModel();
        }
Beispiel #58
0
        public static IEdmModel GetExplicitModel()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            var employee = builder.EntityType<Employee>();
            employee.HasKey(c => c.ID);
            employee.Property(c => c.Name);
            employee.CollectionProperty<Skill>(c => c.SkillSet);
            employee.EnumProperty<Gender>(c => c.Gender);
            employee.EnumProperty<AccessLevel>(c => c.AccessLevel);
            employee.ComplexProperty<FavoriteSports>(c => c.FavoriteSports);

            var skill = builder.EnumType<Skill>();
            skill.Member(Skill.CSharp);
            skill.Member(Skill.Sql);
            skill.Member(Skill.Web);

            var gender = builder.EnumType<Gender>();
            gender.Member(Gender.Female);
            gender.Member(Gender.Male);

            var accessLevel = builder.EnumType<AccessLevel>();
            accessLevel.Member(AccessLevel.Execute);
            accessLevel.Member(AccessLevel.Read);
            accessLevel.Member(AccessLevel.Write);

            var favoriteSports = builder.ComplexType<FavoriteSports>();
            favoriteSports.EnumProperty<Sport>(f => f.LikeMost);
            favoriteSports.CollectionProperty<Sport>(f => f.Like);

            var sport = builder.EnumType<Sport>();
            sport.Member(Sport.Basketball);
            sport.Member(Sport.Pingpong);

            AddBoundActionsAndFunctions(employee);
            AddUnboundActionsAndFunctions(builder);

            EntitySetConfiguration<Employee> employees = builder.EntitySet<Employee>("Employees");
            builder.Namespace = typeof(Employee).Namespace;
            return builder.GetEdmModel();
        }
        public void NonbindingParameterConfigurationSupportsParameterCollectionTypeAs(Type type, bool isNullable)
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            builder.EntityType<Customer>();
            builder.ComplexType<Address>();
            builder.EnumType<Color>();

            Type elementType;
            Assert.True(type.IsCollection(out elementType));

            // Act
            Type underlyingType = TypeHelper.GetUnderlyingTypeOrSelf(elementType);
            IEdmTypeConfiguration elementTypeConfiguration = builder.GetTypeConfigurationOrNull(underlyingType);
            CollectionTypeConfiguration collectionType = new CollectionTypeConfiguration(elementTypeConfiguration,
                typeof(IEnumerable<>).MakeGenericType(elementType));

            NonbindingParameterConfiguration parameter = new NonbindingParameterConfiguration("name", collectionType);

            // Assert
            Assert.Equal(isNullable, parameter.OptionalParameter);
        }
        public void CreateDatePrimitiveProperty_FromDateTime()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration<File> file = builder.EntityType<File>();
            file.Property(f => f.Birthday).AsDate();
            file.Property(f => f.PublishDay).AsDate();

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

            // Assert
            IEdmEntityType fileType = Assert.Single(model.SchemaElements.OfType<IEdmEntityType>());

            IEdmProperty birthdayProperty = Assert.Single(fileType.DeclaredProperties.Where(p => p.Name == "Birthday"));
            Assert.NotNull(birthdayProperty);
            Assert.False(birthdayProperty.Type.IsNullable);
            Assert.Equal("Edm.Date", birthdayProperty.Type.FullName());

            IEdmProperty publishDayProperty = Assert.Single(fileType.DeclaredProperties.Where(p => p.Name == "PublishDay"));
            Assert.NotNull(publishDayProperty);
            Assert.True(publishDayProperty.Type.IsNullable);
            Assert.Equal("Edm.Date", publishDayProperty.Type.FullName());
        }