public void SelectAction_Returns_DollarCount(string method, string[] methodsInController,
                                                     string expectedSelectedAction)
        {
            // Arrange
            var keys = new[] { new KeyValuePair <string, object>("ID", 42) };
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            var       ordersProperty            = model.Customer.FindProperty("Orders") as IEdmNavigationProperty;
            ODataPath odataPath = new ODataPath(new EntitySetSegment(model.Customers), new KeySegment(keys, model.Customer, model.Customers),
                                                new NavigationPropertySegment(ordersProperty, model.Orders), CountSegment.Instance);

            var request   = RequestFactory.Create(new HttpMethod(method), "http://localhost/");
            var actionMap = SelectActionHelper.CreateActionMap(methodsInController);

            // Act
            string selectedAction = SelectActionHelper.SelectAction(new NavigationRoutingConvention(), odataPath, request, actionMap);

            // Assert
            Assert.Equal(expectedSelectedAction, selectedAction);
            Assert.Single(SelectActionHelper.GetRouteData(request).Values);
            Assert.Equal(42, SelectActionHelper.GetRouteData(request).Values["key"]);
        }
Example #2
0
        public void SelectAction_ReturnsNull_NotSupportedMethodForDollarCount(string method, string[] methodsInController)
        {
            // Arrange
            var keys = new[] { new KeyValuePair <string, object>("ID", 42) };
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            var specialOrdersProperty           = model.SpecialCustomer.FindProperty("SpecialOrders") as IEdmNavigationProperty;

            ODataPath odataPath = new ODataPath(new EntitySetSegment(model.Customers), new KeySegment(keys, model.Customer, model.Customers),
                                                new TypeSegment(model.SpecialCustomer, model.Customers),
                                                new NavigationPropertySegment(specialOrdersProperty, model.Orders),
                                                CountSegment.Instance);

            var request   = RequestFactory.Create(new HttpMethod(method), "http://localhost/");
            var actionMap = SelectActionHelper.CreateActionMap(methodsInController);

            // Act
            string selectedAction = SelectActionHelper.SelectAction(new NavigationRoutingConvention(), odataPath, request, actionMap);

            // Assert
            Assert.Null(selectedAction);
        }
Example #3
0
        public void SelectAction_ReturnsNull_IfPostToNavigationPropertyBindingToNonCollectionValuedNavigationProperty(string path)
        {
            // Arrange
            ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create();

            builder.EntitySet <Company>("Companies");
            builder.Singleton <Company>("MyCompany");
            builder.EntitySet <Employee>("Employees");
            builder.Singleton <Employee>("Tony");
            IEdmModel model = builder.GetEdmModel();

            ODataPath odataPath      = new DefaultODataPathHandler().Parse(model, "http://any/", path);
            var       request        = RequestFactory.Create(HttpMethod.Post, "http://localhost/");
            var       emptyActionMap = SelectActionHelper.CreateActionMap();

            // Act
            string selectedAction = SelectActionHelper.SelectAction(new NavigationRoutingConvention(), odataPath, request, emptyActionMap);

            // Assert
            Assert.Null(selectedAction);
        }
Example #4
0
        private ODataMessageReader GetODataMessageReader(string content)
        {
            HttpRequest request = RequestFactory.Create("Post", "http://localhost/odata/CEO", opt => opt.AddModel("odata", _edmModel));

            //request.Content = new StringContent(content);
            //request.Headers.Add("OData-Version", "4.0");

            //MediaTypeWithQualityHeaderValue mediaType = new MediaTypeWithQualityHeaderValue("application/json");
            //mediaType.Parameters.Add(new NameValueHeaderValue("odata.metadata", "full"));
            //request.Headers.Accept.Add(mediaType);
            //request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            byte[] contentBytes = Encoding.UTF8.GetBytes(content);
            request.Body          = new MemoryStream(contentBytes);
            request.ContentType   = "application/json";
            request.ContentLength = contentBytes.Length;
            request.Headers.Add("OData-Version", "4.0");
            request.Headers.Add("Accept", "application/json;odata.metadata=full");

            return(new ODataMessageReader(new HttpRequestODataMessage(request), new ODataMessageReaderSettings(), _edmModel));
        }
Example #5
0
        public void SelectAction_OnSingltonPath_OpenEntityType_ReturnsTheActionName(string url)
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            ODataPath odataPath = new DefaultODataPathHandler().Parse(model.Model, "http://localhost/", url);
            var       request   = RequestFactory.Create(HttpMethod.Get, "http://localhost/");
            var       actionMap = SelectActionHelper.CreateActionMap("GetDynamicProperty");

            // Act
            string selectedAction = SelectActionHelper.SelectAction(_routingConvention, odataPath, request, actionMap);

            // Assert
            Assert.NotNull(selectedAction);
            Assert.Equal("GetDynamicProperty", selectedAction);

            var routeData = SelectActionHelper.GetRouteData(request);

            Assert.Equal(2, routeData.Values.Count);
            Assert.Equal("DynamicPropertyA", routeData.Values["dynamicProperty"]);
            Assert.Equal("DynamicPropertyA", (routeData.Values[ODataParameterValue.ParameterValuePrefix + "dynamicProperty"] as ODataParameterValue).Value);
        }
Example #6
0
        /// <summary> Updates information for a user. </summary>
        /// <param name="id"> The user's ID. </param>
        /// <param name="email"> The user's email address. </param>
        /// <param name="password"> The user's password. </param>
        /// <param name="username"> The user's username. </param>
        /// <param name="name"> The user's full name. </param>
        /// <param name="skype"> The user's Skype profile. </param>
        /// <param name="linkedIn"> The user's LinkedIn profile. </param>
        /// <param name="twitter"> The user's Twitter profile. </param>
        /// <param name="websiteUrl"> The user's website URL. </param>
        /// <param name="projectsLimit"> The maximum projects the user is allowed to create. </param>
        /// <param name="externUid"> The UID for the external authentication provider. </param>
        /// <param name="provider"> The external provider. </param>
        /// <param name="bio"> The user's bio. </param>
        /// <param name="location"> The user's location. </param>
        /// <param name="admin"> Whether or not the user should receive administrator privileges. </param>
        /// <param name="canCreateGroup"> Whether or not the user can create groups. </param>
        /// <param name="external"> Whether or not the user's account should be flagged as external. </param>
        /// <returns> A <see cref="RequestResult{User}" /> representing the results of the request. </returns>
        public async Task <RequestResult <User> > Update(uint id,
                                                         string email        = null,
                                                         string password     = null,
                                                         string username     = null,
                                                         string name         = null,
                                                         string skype        = null,
                                                         string linkedIn     = null,
                                                         string twitter      = null,
                                                         string websiteUrl   = null,
                                                         uint?projectsLimit  = null,
                                                         string externUid    = null,
                                                         string provider     = null,
                                                         string bio          = null,
                                                         string location     = null,
                                                         bool?admin          = null,
                                                         bool?canCreateGroup = null,
                                                         bool?external       = null)
        {
            var request = RequestFactory.Create("users/{id}", Method.Put);

            request.AddUrlSegment("id", id);
            request.AddParameterIfNotNull("email", email);
            request.AddParameterIfNotNull("password", password);
            request.AddParameterIfNotNull("username", username);
            request.AddParameterIfNotNull("name", name);
            request.AddParameterIfNotNull("skype", skype);
            request.AddParameterIfNotNull("linkedin", linkedIn);
            request.AddParameterIfNotNull("twitter", twitter);
            request.AddParameterIfNotNull("website_url", websiteUrl);
            request.AddParameterIfNotNull("projects_limit", projectsLimit);
            request.AddParameterIfNotNull("extern_uid", externUid);
            request.AddParameterIfNotNull("provider", provider);
            request.AddParameterIfNotNull("bio", bio);
            request.AddParameterIfNotNull("location", location);
            request.AddParameterIfNotNull("admin", admin);
            request.AddParameterIfNotNull("can_create_group", canCreateGroup);
            request.AddParameterIfNotNull("external", external);

            return(await request.Execute <User>());
        }
        public void Ctor_ThatBuildsNestedContext_CopiesProperties()
        {
            // Arrange
            var config  = RoutingConfigurationFactory.CreateWithRootContainer("OData");
            var request = RequestFactory.Create(config, "OData");
            CustomersModelWithInheritance model   = new CustomersModelWithInheritance();
            ODataSerializerContext        context = new ODataSerializerContext
            {
                NavigationSource   = model.Customers,
                MetadataLevel      = ODataMetadataLevel.FullMetadata,
                Model              = model.Model,
                Path               = new ODataPath(),
                Request            = request,
                RootElementName    = "somename",
                SelectExpandClause = new SelectExpandClause(new SelectItem[0], allSelected: true),
                SkipExpensiveAvailabilityChecks = true,
#if NETFX // Url is only in AspNet
                Url = new UrlHelper()
#endif
            };
            ResourceContext resource = new ResourceContext {
                SerializerContext = context
            };
            SelectExpandClause     selectExpand = new SelectExpandClause(new SelectItem[0], allSelected: true);
            IEdmNavigationProperty navProp      = model.Customer.NavigationProperties().First();

            // Act
            ODataSerializerContext nestedContext = new ODataSerializerContext(resource, selectExpand, navProp);

            // Assert
            Assert.Equal(context.MetadataLevel, nestedContext.MetadataLevel);
            Assert.Same(context.Model, nestedContext.Model);
            Assert.Same(context.Path, nestedContext.Path);
            Assert.Same(context.Request, nestedContext.Request);
            Assert.Equal(context.RootElementName, nestedContext.RootElementName);
            Assert.Equal(context.SkipExpensiveAvailabilityChecks, nestedContext.SkipExpensiveAvailabilityChecks);
#if NETFX // Url is only in AspNet
            Assert.Same(context.Url, nestedContext.Url);
#endif
        }
Example #8
0
        public void ConvertResourceOrResourceSetCanConvert_ResourceSet()
        {
            // Arrange
            string            odataValue       = "[{\"Id\": 9, \"Name\": \"Sam\"}, {\"Id\": 18, \"Name\": \"Peter\"}]";
            IEdmModel         model            = GetEdmModel();
            IEdmEntityType    customerType     = model.SchemaElements.OfType <IEdmEntityType>().First(c => c.Name == "Customer");
            IEdmTypeReference edmTypeReference = new EdmEntityTypeReference(customerType, false);
            HttpRequest       request          = RequestFactory.Create("Get", "http://localhost/", opt => opt.AddModel("odata", model));

            request.ODataFeature().PrefixName = "odata";
            ODataDeserializerContext context  = new ODataDeserializerContext
            {
                Model           = model,
                Request         = request,
                ResourceType    = typeof(Customer),
                ResourceEdmType = edmTypeReference,
            };

            IEdmTypeReference setType = new EdmCollectionTypeReference(new EdmCollectionType(edmTypeReference));

            // Act
            object value = ODataModelBinderConverter.ConvertResourceOrResourceSet(odataValue, setType, context);

            // Assert
            Assert.NotNull(value);

            IEnumerable <Customer> customers = Assert.IsAssignableFrom <IEnumerable <Customer> >(value);

            Assert.Collection(customers,
                              e =>
            {
                Assert.Equal(9, e.Id);
                Assert.Equal("Sam", e.Name);
            },
                              e =>
            {
                Assert.Equal(18, e.Id);
                Assert.Equal("Peter", e.Name);
            });
        }
        /// <summary> Creates a new label. </summary>
        /// <param name="projectId"> The ID of the project to attach this label to. </param>
        /// <param name="name"> The name for the new label. </param>
        /// <param name="color"> The color for the new label. </param>
        /// <param name="description"> The description for the new label. </param>
        /// <returns> A <see cref="RequestResult{Label}" /> representing the results of the request. </returns>
        public async Task <RequestResult <Label> > Create(uint projectId, string name, string color,
                                                          string description = null)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (color == null)
            {
                throw new ArgumentNullException(nameof(color));
            }

            var request = RequestFactory.Create("projects/{projectId}/labels", Method.Post);

            request.AddUrlSegment("projectId", projectId);
            request.AddParameter("name", name);
            request.AddParameter("color", color);
            request.AddParameterIfNotNull("description", description);

            return(await request.Execute <Label>());
        }
Example #10
0
        public async Task ReadFromStreamAsync_RawValue()
        {
            // Arrange
            string content = "{\"value\":\"Blue\"}";

            ODataEnumDeserializer    deserializer = new ODataEnumDeserializer();
            ODataDeserializerContext readContext  = new ODataDeserializerContext
            {
                Model        = _edmModel,
                ResourceType = typeof(Color)
            };
            HttpRequest request = RequestFactory.Create("Post", "http://localhost/", _edmModel);

            // Act
            object value = await deserializer.ReadAsync(ODataTestUtil.GetODataMessageReader(request.GetODataMessage(content), _edmModel),
                                                        typeof(Color), readContext);

            // Assert
            Color color = Assert.IsType <Color>(value);

            Assert.Equal(Color.Blue, color);
        }
Example #11
0
        public void GetVirtualPath_CanGenerateDirectLinkIsTrue_IfRoutePrefixIsNull()
        {
            // Arrange
            var        config     = RoutingConfigurationFactory.CreateWithRoute("http://localhost/vpath");
            var        request    = RequestFactory.Create(HttpMethod.Get, "http://localhost/vpath/prefix/Customers", config);
            ODataRoute odataRoute = CreateRoute(config, routePrefix: null);

            // Act
            var virtualPathData = GetVirtualPath(odataRoute, request,
                                                 new Dictionary <string, object> {
                { "odataPath", "odataPath" }, { "httproute", true }
            });

            // Assert
            Assert.True(odataRoute.CanGenerateDirectLink);
            Assert.NotNull(virtualPathData);
#if NETCORE
            Assert.Equal("/odataPath", virtualPathData.VirtualPath);
#else
            Assert.Equal("odataPath", virtualPathData.VirtualPath);
#endif
        }
        public void Read_RoundTrips()
        {
            // Arrange
            IEdmModel model        = CreateModel();
            var       deserializer = new ODataEntityReferenceLinkDeserializer();
            MockODataRequestMessage    requestMessage = new MockODataRequestMessage();
            ODataMessageWriterSettings settings       = new ODataMessageWriterSettings()
            {
                ODataUri = new ODataUri {
                    ServiceRoot = new Uri("http://any/")
                }
            };

            settings.SetContentType(ODataFormat.Json);

            ODataMessageWriter messageWriter = new ODataMessageWriter(requestMessage, settings);

            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink {
                Url = new Uri("http://localhost/samplelink")
            });

            var request = RequestFactory.Create("Get", "http://localhost", opt => opt.AddModel("odata", model));

            request.ODataFeature().PrefixName        = "odata";
            ODataMessageReaderSettings readSettings  = new ODataMessageReaderSettings();
            ODataMessageReader         messageReader = new ODataMessageReader(new MockODataRequestMessage(requestMessage), readSettings, model);
            ODataDeserializerContext   context       = new ODataDeserializerContext
            {
                Request = request,
                Path    = new ODataPath(new NavigationPropertySegment(GetNavigationProperty(model), navigationSource: null))
            };

            // Act
            Uri uri = deserializer.Read(messageReader, typeof(Uri), context) as Uri;

            // Assert
            Assert.NotNull(uri);
            Assert.Equal("http://localhost/samplelink", uri.AbsoluteUri);
        }
Example #13
0
        /// <summary>
        /// The main entry point for the example.
        /// </summary>
        /// <param name="pArgs">The arguments from the command line.</param>
        private static void Main(string[] pArgs)
        {
            WriteGreeting();

            CliOptions options = CliOptions.WindowsStyle;

            List <Description> descs = DescriptionFactory.Create(
                options, new HelpResource(Help.ResourceManager),
                "/echo [/mode:string#] /address:string /database:string /username:string [/password:string] filename [output:string]"
                );

            ConsoleFactory consoleFactory = new ConsoleFactory();

            if (pArgs.Length == 0)
            {
                OutputHelp outputHelp = new OutputHelp(options, consoleFactory.Create());
                outputHelp.Show(descs);
                return;
            }

            Request request = RequestFactory.Create(options, pArgs, descs, consoleFactory);
        }
Example #14
0
        public void GetODataPayloadSerializer_ReturnsRawValueSerializer_ForDollarCountRequests(string uri, Type elementType)
        {
            // Arrange
            IEdmModel model = _edmDollarCountModel;

            Type           type   = typeof(ICollection <>).MakeGenericType(elementType);
            ODataUriParser parser = new ODataUriParser(model, new Uri(uri, UriKind.Relative));
            var            path   = parser.ParsePath();

            var request = RequestFactory.Create(model);

            request.ODataFeature().Path = path;

            // Act
            var serializer = _serializerProvider.GetODataPayloadSerializer(type, request);

            // Assert
            Assert.NotNull(serializer);
            var rawValueSerializer = Assert.IsType <ODataRawValueSerializer>(serializer);

            Assert.Equal(ODataPayloadKind.Value, rawValueSerializer.ODataPayloadKind);
        }
Example #15
0
        public void ApplyToOfTSkipTokenQueryOption_Applies_ToQuaryable_WithOrderby()
        {
            // Arrange
            IEdmModel          model    = GetEdmModel();
            ODataQuerySettings settings = new ODataQuerySettings
            {
                HandleNullPropagation = HandleNullPropagationOption.False
            };
            ODataQueryContext context = new ODataQueryContext(model, typeof(SkipTokenCustomer));

            HttpRequest request = RequestFactory.Create(HttpMethods.Get, "http://server/Customers/?$orderby=Name&$skiptoken=Name-'Alex',Id-3");

            ODataQueryOptions    queryOptions   = new ODataQueryOptions(context, request);
            SkipTokenQueryOption skipTokenQuery = queryOptions.SkipToken;

            IQueryable <SkipTokenCustomer> customers = new List <SkipTokenCustomer>
            {
                new SkipTokenCustomer {
                    Id = 2, Name = "Caron"
                },
                new SkipTokenCustomer {
                    Id = 1, Name = "Bndy"
                },
                new SkipTokenCustomer {
                    Id = 3, Name = "Alex"
                },
                new SkipTokenCustomer {
                    Id = 4, Name = "Aab"
                }
            }.AsQueryable();

            // Act
            SkipTokenCustomer[] results = skipTokenQuery.ApplyTo(customers, settings, queryOptions).ToArray();

            // Assert
            Assert.Equal(2, results.Length);
            Assert.Equal(2, results[0].Id);
            Assert.Equal(1, results[1].Id);
        }
        public void Apply_Doesnot_Override_UserConfiguration()
        {
            // Arrange
            ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create();
            var customers   = builder.EntitySet <Customer>("Customers");
            var paintAction = customers.EntityType.Action("Paint");

            paintAction.HasActionLink(ctxt => new Uri("http://localhost/ActionTestWorks"), followsConventions: false);
            ActionLinkGenerationConvention convention = new ActionLinkGenerationConvention();

            // Act
            convention.Apply(paintAction, builder);

            IEdmModel model        = builder.GetEdmModel();
            var       edmCustomers = model.EntityContainer.FindEntitySet("Customers");
            var       edmCustomer  = model.SchemaElements.OfType <IEdmEntityType>().First(c => c.Name == "Customer");
            var       edmAction    = model.SchemaElements.OfType <IEdmAction>().First(a => a.Name == "Paint");

            Assert.NotNull(edmAction);

            string routeName     = "OData";
            var    configuration = RoutingConfigurationFactory.CreateWithRootContainer(routeName);

            configuration.MapODataServiceRoute(routeName, null, model);

            var request = RequestFactory.Create(HttpMethod.Get, "http://localhost", configuration, routeName);

            OperationLinkBuilder actionLinkBuilder = model.GetOperationLinkBuilder(edmAction);

            var serializerContext = ODataSerializerContextFactory.Create(model, edmCustomers, request);
            var entityContext     = new ResourceContext(serializerContext, edmCustomer.AsReference(), new Customer {
                Id = 2009
            });

            // Assert
            Uri link = actionLinkBuilder.BuildLink(entityContext);

            Assert.Equal("http://localhost/ActionTestWorks", link.AbsoluteUri);
        }
Example #17
0
        public async Task ListOfStringsSerializesAsOData()
        {
            // Arrange
            List <string> listOfStrings = new List <string>();

            listOfStrings.Add("Frank");
            listOfStrings.Add("Steve");
            listOfStrings.Add("Tom");
            listOfStrings.Add("Chandler");

            var routeName = "OData";
            var model     = GetSampleModel();
            var config    = RoutingConfigurationFactory.CreateWithRootContainer(routeName, b => b.AddService(ServiceLifetime.Singleton, s => model));
            var request   = RequestFactory.Create(HttpMethod.Get, "http://localhost/property", config, routeName);
            var payload   = new ODataPayloadKind[] { ODataPayloadKind.Collection };
            var formatter = FormatterTestHelper.GetFormatter(payload, request);
            var content   = FormatterTestHelper.GetContent(listOfStrings, formatter,
                                                           ODataMediaTypes.ApplicationJsonODataMinimalMetadata);

            // Act & Assert
            JsonAssert.Equal(Resources.ListOfString, await FormatterTestHelper.GetContentResult(content, request));
        }
Example #18
0
        /// <summary> Creates a new merge request. </summary>
        /// <param name="projectId"> The ID of the project. </param>
        /// <param name="sourceBranch"> The source branch for this merge request. </param>
        /// <param name="targetBranch"> The target branch for this merge request. </param>
        /// <param name="title"> The title for this merge request. </param>
        /// <param name="description"> The description for this merge request. </param>
        /// <param name="assigneeId"> The ID of the user to assign to this merge request. </param>
        /// <param name="targetProjectId"> The ID of the project to merge into. </param>
        /// <param name="labels"> The labels to assign to this merge request. </param>
        /// <param name="milestoneId"> The ID of the milestone to assign to this merge request. </param>
        /// <returns> A <see cref="RequestResult{MergeRequest}" /> representing the results of this request. </returns>
        public async Task <RequestResult <MergeRequest> > Create(uint projectId,
                                                                 string sourceBranch,
                                                                 string targetBranch,
                                                                 string title,
                                                                 string description   = null,
                                                                 uint?assigneeId      = null,
                                                                 uint?targetProjectId = null,
                                                                 string[] labels      = null,
                                                                 uint?milestoneId     = null)
        {
            if (sourceBranch == null)
            {
                throw new ArgumentNullException(nameof(sourceBranch));
            }

            if (targetBranch == null)
            {
                throw new ArgumentNullException(nameof(targetBranch));
            }

            if (title == null)
            {
                throw new ArgumentNullException(nameof(title));
            }

            var request = RequestFactory.Create("projects/{projectId}/merge_requests", Method.Post);

            request.AddUrlSegment("projectId", projectId);
            request.AddParameter("source_branch", sourceBranch);
            request.AddParameter("target_branch", targetBranch);
            request.AddParameter("title", title);
            request.AddParameterIfNotNull("description", description);
            request.AddParameterIfNotNull("assignee_id", assigneeId);
            request.AddParameterIfNotNull("target_project_id", targetProjectId);
            request.AddParameterIfNotNull("labels", labels.ToCommaSeparated());
            request.AddParameterIfNotNull("milestone_id", milestoneId);

            return(await request.Execute <MergeRequest>());
        }
Example #19
0
        public void NavigationLinksGenerationConvention_GeneratesLinksWithoutCast_ForBaseProperties()
        {
            ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create();

            builder.EntitySet <SportBike>("vehicles");
            builder.EntitySet <Manufacturer>("manufacturers");

            IEdmModel              model = builder.GetEdmModel();
            IEdmEntitySet          vehiclesEdmEntitySet           = model.EntityContainer.FindEntitySet("vehicles");
            IEdmEntityType         sportbikeType                  = model.AssertHasEntityType(typeof(SportBike));
            IEdmNavigationProperty motorcycleManufacturerProperty = sportbikeType.AssertHasNavigationProperty(model, "Manufacturer", typeof(MotorcycleManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne);

            var    configuration = RoutingConfigurationFactory.Create();
            string routeName     = "Route";

            configuration.MapODataServiceRoute(routeName, null, model);

            var request = RequestFactory.Create(HttpMethod.Get, "http://localhost", configuration, routeName);

            NavigationSourceLinkBuilderAnnotation linkBuilder = model.GetNavigationSourceLinkBuilder(vehiclesEdmEntitySet);

            linkBuilder.AddNavigationPropertyLinkBuilder(motorcycleManufacturerProperty, new NavigationLinkBuilder((context, property) => context.GenerateNavigationPropertyLink(property, includeCast: false), false));
            var serializerContext = ODataSerializerContextFactory.Create(model, vehiclesEdmEntitySet, request);
            var entityContext     = new ResourceContext(serializerContext, sportbikeType.AsReference(), new SportBike {
                Model = 2009, Name = "Ninja"
            });

            // We might get one of these:
            // http://localhost/vehicles(Model=2009,Name='Ninja')/Manufacturer
            // http://localhost/vehicles(Name='Ninja',Model=2009)/Manufacturer
            Uri    uri        = linkBuilder.BuildNavigationLink(entityContext, motorcycleManufacturerProperty, ODataMetadataLevel.MinimalMetadata);
            string aboluteUri = uri.AbsoluteUri;

            Assert.Contains("http://localhost/vehicles(", aboluteUri);
            Assert.Contains("Model=2009", aboluteUri);
            Assert.Contains("Name='Ninja'", aboluteUri);
            Assert.Contains(")/Manufacturer", aboluteUri);
        }
Example #20
0
        public void AttributeMappingsIsInitialized_WithRightActionAndTemplate(
            Type controllerType,
            string method,
            string expectedPathTemplate,
            string expectedActionName)
        {
            // Arrange
            var configuration   = RoutingConfigurationFactory.CreateWithRootContainer(RouteName);
            var serviceProvider = GetServiceProvider(configuration, RouteName);
            var request         = RequestFactory.Create(configuration, RouteName);

#if NETCORE
            request.ODataFeature().Path = new ODataPath();
            request.Method = method;
#else
            request.Method = new HttpMethod(method);
#endif

            var descriptors = ControllerDescriptorFactory.Create(configuration, "TestController",
                                                                 controllerType);

            ODataPathTemplate pathTemplate = new ODataPathTemplate();
            Mock <IODataPathTemplateHandler> pathTemplateHandler = new Mock <IODataPathTemplateHandler>();
            pathTemplateHandler
            .Setup(p => p.ParseTemplate(expectedPathTemplate, serviceProvider))
            .Returns(pathTemplate)
            .Verifiable();

            AttributeRoutingConvention convention = new AttributeRoutingConvention(RouteName, descriptors, pathTemplateHandler.Object);

            // Act
            Select(convention, request);

            // Assert
            pathTemplateHandler.VerifyAll();
            Assert.NotNull(convention.AttributeMappings);
            Assert.Equal(expectedActionName, convention.AttributeMappings[pathTemplate].ActionName);
        }
Example #21
0
        public void GenerateNavigationLink_WorksToGenerateExpectedNavigationLink_ForNonContainedNavigation()
        {
            // Arrange
            IEdmEntityType         myOrder               = (IEdmEntityType)_myOrderModel.FindDeclaredType("NS.MyOrder");
            IEdmEntityType         orderLine             = (IEdmEntityType)_myOrderModel.FindDeclaredType("NS.OrderLine");
            IEdmNavigationProperty nonOrderLinesProperty = myOrder.NavigationProperties().Single(x => x.Name.Equals("NonContainedOrderLines"));

            IEdmEntitySet entitySet = _myOrderModel.FindDeclaredEntitySet("MyOrders");
            IDictionary <string, object> parameters = new Dictionary <string, object>
            {
                { "ID", 42 }
            };

            IDictionary <string, object> parameters2 = new Dictionary <string, object>
            {
                { "ID", 21 }
            };

            IEdmNavigationSource nonContainedOrderLines = entitySet.FindNavigationTarget(nonOrderLinesProperty);
            ODataPath            path = new ODataPath(
                new EntitySetSegment(entitySet),
                new KeySegment(parameters.ToArray(), myOrder, entitySet),
                new NavigationPropertySegment(nonOrderLinesProperty, nonContainedOrderLines),
                new KeySegment(parameters2.ToArray(), orderLine, nonContainedOrderLines));

            IEdmNavigationProperty orderLinesProperty = myOrder.NavigationProperties().Single(x => x.ContainsTarget);
            IEdmContainedEntitySet orderLines         = (IEdmContainedEntitySet)entitySet.FindNavigationTarget(orderLinesProperty);

            var request           = RequestFactory.Create(_myOrderModel);
            var serializerContext = ODataSerializerContextFactory.Create(_myOrderModel, orderLines, path, request);
            var entityContext     = new ResourceContext(serializerContext, orderLine.AsReference(), new { ID = 21 });

            // Act
            Uri uri = entityContext.GenerateSelfLink(false);

            // Assert
            Assert.Equal("http://localhost/OrderLines(21)", uri.AbsoluteUri);
        }
Example #22
0
        private static ODataQueryOptions GetQueryOptions(string queryOption)
        {
            string uri = "Http://localhost/RoutingCustomers?" + queryOption;

            ODataUriResolver resolver = new ODataUriResolver
            {
                EnableCaseInsensitive = true
            };

            var configuration = RoutingConfigurationFactory.CreateWithRootContainer("OData", b => b.AddService(ServiceLifetime.Singleton, sp => resolver));
            var request       = RequestFactory.Create(HttpMethod.Get, uri, configuration, "OData");

            IEdmModel model = ODataRoutingModel.GetModel();

            IEdmEntitySet  entityset  = model.EntityContainer.FindEntitySet("RoutingCustomers");
            IEdmEntityType entityType =
                model.SchemaElements.OfType <IEdmEntityType>().Single(e => e.Name == "RoutingCustomer");

            ODataPath         path    = new ODataPath(new[] { new EntitySetSegment(entityset) });
            ODataQueryContext context = new ODataQueryContext(model, entityType, path);

            return(new ODataQueryOptions(context, request));
        }
Example #23
0
        public async Task ReadFromStreamAsync_RawGuid()
        {
            // Arrange
            string content  = "{\"value\":\"f4b787c7-920d-4993-a584-ceb68968058c\"}";
            Type   type     = typeof(Guid);
            object expected = new Guid("f4b787c7-920d-4993-a584-ceb68968058c");

            IEdmModel   model   = CreateModel();
            HttpRequest request = RequestFactory.Create("Patch", "http://localhost/OData/Suppliers(1)/Address", opt => opt.AddModel("odata", model));

            ODataPrimitiveDeserializer deserializer = new ODataPrimitiveDeserializer();
            ODataDeserializerContext   readContext  = new ODataDeserializerContext
            {
                Model        = model,
                ResourceType = type
            };

            // Act
            object value = await deserializer.ReadAsync(ODataTestUtil.GetODataMessageReader(request.GetODataMessage(content), model), type, readContext);

            // Assert
            Assert.Equal(expected, value);
        }
Example #24
0
        /// <summary> Creates a new tag. </summary>
        /// <param name="projectId"> The ID of the project. </param>
        /// <param name="tagName"> The name for the new tag. </param>
        /// <param name="refName"> The commit sha, branch name, or tag name to associate this tag with. </param>
        /// <param name="message"> The message for this tag. </param>
        /// <param name="releaseDescription"> The release description for this tag. </param>
        /// <returns> A <see cref="RequestResult{Tag}" /> representing the results of the request. </returns>
        public async Task <RequestResult <Tag> > Create(uint projectId, string tagName, string refName,
                                                        string message = null, string releaseDescription = null)
        {
            if (tagName == null)
            {
                throw new ArgumentNullException(nameof(tagName));
            }

            if (refName == null)
            {
                throw new ArgumentNullException(nameof(refName));
            }

            var request = RequestFactory.Create("projects/{projectId}/repository/tags", Method.Post);

            request.AddUrlSegment("projectId", projectId);
            request.AddParameter("tag_name", tagName);
            request.AddParameter("ref", refName);
            request.AddParameterIfNotNull("message", message);
            request.AddParameterIfNotNull("release_description", releaseDescription);

            return(await request.Execute <Tag>());
        }
Example #25
0
        public void SelectAction_SetsRouteData_ForGetOrCreateRefRequests(string method, string actionName)
        {
            // Arrange
            var keys = new[] { new KeyValuePair <string, object>("ID", 42) };
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            var specialOrdersProperty           = model.SpecialCustomer.FindProperty("SpecialOrders") as IEdmNavigationProperty;

            ODataPath odataPath = new ODataPath(
                new EntitySetSegment(model.Customers),
                new KeySegment(keys, model.Customer, model.Customers),
                new TypeSegment(model.SpecialCustomer, model.Customers),
                new NavigationPropertyLinkSegment(specialOrdersProperty, model.Orders));

            var request   = RequestFactory.Create(new HttpMethod(method), "http://localhost/");
            var actionMap = SelectActionHelper.CreateActionMap(actionName);

            // Act
            string selectedAction = SelectActionHelper.SelectAction(new RefRoutingConvention(), odataPath, request, actionMap);

            // Assert
            Assert.Equal(42, SelectActionHelper.GetRouteData(request).Values["key"]);
            Assert.Equal("SpecialOrders", SelectActionHelper.GetRouteData(request).Values["navigationProperty"]);
        }
        public void ReadFromStreamAsync()
        {
            // Arrange
            string content = "{\"@odata.type\":\"#NS.Color\",\"value\":\"Blue\"}";

            ODataEnumDeserializer    deserializer = new ODataEnumDeserializer();
            ODataDeserializerContext readContext  = new ODataDeserializerContext
            {
                Model        = _edmModel,
                ResourceType = typeof(Color)
            };

            HttpRequest request = RequestFactory.Create("Post", "http://localhost/TestUri", opt => opt.AddModel("odata", _edmModel));

            // Act
            object value = deserializer.Read(ODataTestUtil.GetODataMessageReader(request.GetODataMessage(content), _edmModel),
                                             typeof(Color), readContext);

            // Assert
            Color color = Assert.IsType <Color>(value);

            Assert.Equal(Color.Blue, color);
        }
Example #27
0
        private MediaTypeHeaderValue GetContentTypeFromQueryString(IEdmModel model, Type type, string dollarFormat)
        {
            Action <ODataOptions> setupAction = opt => opt.AddModel("odata", model);
            ODataPath             path        = new ODataPath();
            HttpRequest           request     = string.IsNullOrEmpty(dollarFormat)
                ? RequestFactory.Create("Get", "http://any", setupAction)
                : RequestFactory.Create("Get", "http://any/?$format=" + dollarFormat, setupAction);

            request.Configure("odata", model, path);

            var context = new OutputFormatterWriteContext(
                request.HttpContext,
                CreateWriter,
                type,
                new MemoryStream());

            foreach (var formatter in _formatters)
            {
                context.ContentType = new StringSegment();
                context.ContentTypeIsServerDefined = false;

                if (formatter.CanWriteResult(context))
                {
                    MediaTypeHeaderValue mediaType = MediaTypeHeaderValue.Parse(context.ContentType.ToString());

                    // We don't care what the charset is for these tests.
                    if (mediaType.Parameters.Where(p => p.Name == "charset").Any())
                    {
                        mediaType.Parameters.Remove(mediaType.Parameters.Single(p => p.Name == "charset"));
                    }

                    return(mediaType);
                }
            }

            return(null);
        }
Example #28
0
        public void ODataBatchPathMappingWorksForComplexTemplate(string version, string spec)
        {
            // Arrange
            string routeName     = "odata";
            string routeTemplate = "/v{api-version:apiVersion}/odata{spec}/$batch";
            string uri           = "http://localhost/v" + version + "/odata" + spec + "/$batch";
            var    request       = RequestFactory.Create(HttpMethod.Get, uri);
            var    mapping       = new ODataBatchPathMapping();

            // Act
            mapping.AddRoute(routeName, routeTemplate);

            bool result = mapping.TryGetRouteName(request.HttpContext, out string outputName);

            // Assert
            Assert.True(result);
            Assert.Equal(outputName, routeName);
            var routeData = request.ODataFeature().BatchRouteData;

            Assert.NotNull(routeData);
            Assert.Equal(new[] { "api-version", "spec" }, routeData.Keys);
            Assert.Equal(version, routeData["api-version"]);
            Assert.Equal(spec, routeData["spec"]);
        }
Example #29
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             = ODataConventionModelBuilderFactory.Create();
            EntityTypeConfiguration <Movie> movie = builder.EntitySet <Movie>("Movies").EntityType;
            FunctionConfiguration           watch = movie.Function("Watch").Returns <int>();

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

            var    configuration = RoutingConfigurationFactory.Create();
            string routeName     = "Route";

            configuration.MapODataServiceRoute(routeName, null, model);

            var request = RequestFactory.Create(HttpMethod.Get, "http://server/Movies", configuration, routeName);

            // 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 = ODataSerializerContextFactory.Create(model, entitySet, request);

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

            //Assert
            Assert.Equal(expectedUri, watch.GetFunctionLink()(context));
            Assert.NotNull(functionLinkBuilder);
            Assert.Equal(expectedUri, functionLinkBuilder.BuildLink(context));
        }
Example #30
0
        public async Task EntityTypeSerializesAsODataEntry()
        {
            // Arrange
            const string  routeName = "OData";
            IEdmEntitySet entitySet = _model.EntityContainer.FindEntitySet("employees");
            ODataPath     path      = new ODataPath(new EntitySetSegment(entitySet));

            var request = RequestFactory.Create("Get", "http://localhost/property", opt => opt.AddModel(routeName, _model));

            request.ODataFeature().Model      = _model;
            request.ODataFeature().Path       = path;
            request.ODataFeature().PrefixName = routeName;

            var      payload   = new ODataPayloadKind[] { ODataPayloadKind.Resource };
            var      formatter = ODataFormatterHelpers.GetOutputFormatter(payload);
            Employee employee  = new Employee
            {
                EmployeeID   = 8,
                Birthday     = new System.DateTimeOffset(2020, 9, 10, 1, 2, 3, System.TimeSpan.Zero),
                EmployeeName = "Ssa",
                HomeAddress  = null
            };
            var content = ODataFormatterHelpers.GetContent(employee, formatter, ODataMediaTypes.ApplicationJsonODataMinimalMetadata);

            // Act & Assert
            string actual = await ODataFormatterHelpers.GetContentResult(content, request);

            Assert.Equal("{\"@odata.context\":\"http://localhost/OData/$metadata#employees/$entity\"," +
                         "\"EmployeeID\":8," +
                         "\"EmployeeName\":\"Ssa\"," +
                         "\"BaseSalary\":0," +
                         "\"Birthday\":\"2020-09-10T01:02:03Z\"," +
                         "\"WorkCompanyId\":0," +
                         "\"HomeAddress\":null" +
                         "}", actual);
        }