Beispiel #1
0
        public void TranslateWithNavigationPropertyLinkSegmentReturnsFalse()
        {
            IsCollectionTranslator translator = new IsCollectionTranslator();
            var segment = new NavigationPropertyLinkSegment(HardCodedTestModel.GetPersonMyDogNavProp(), null);

            Assert.False(translator.Translate(segment));
        }
        public void TryTranslateNavigationSegmentTemplate_ReturnsODataNavigationSegment()
        {
            // Arrange
            EdmEntityType          employee   = new EdmEntityType("NS", "Employee");
            IEdmNavigationProperty navigation = employee.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Name               = "DirectReports",
                Target             = employee,
                TargetMultiplicity = EdmMultiplicity.Many
            });

            NavigationLinkSegmentTemplate linkSegment = new NavigationLinkSegmentTemplate(navigation, null);
            ODataTemplateTranslateContext context     = new ODataTemplateTranslateContext();

            // Act
            bool ok = linkSegment.TryTranslate(context);

            // Assert
            Assert.True(ok);
            ODataPathSegment actual = Assert.Single(context.Segments);
            NavigationPropertyLinkSegment navLinkSegment = Assert.IsType <NavigationPropertyLinkSegment>(actual);

            Assert.Same(navigation, navLinkSegment.NavigationProperty);
            Assert.Null(navLinkSegment.NavigationSource);
        }
Beispiel #3
0
        public void EqualityCorrect()
        {
            NavigationPropertyLinkSegment navigationPropertyLinkSegment1 = new NavigationPropertyLinkSegment(HardCodedTestModel.GetPersonMyDogNavProp(), null);
            NavigationPropertyLinkSegment navigationPropertyLinkSegment2 = new NavigationPropertyLinkSegment(HardCodedTestModel.GetPersonMyDogNavProp(), null);

            navigationPropertyLinkSegment1.Equals(navigationPropertyLinkSegment2).Should().BeTrue();
        }
        /// <summary>
        /// This function is meant to simulate the function located at the link below to provide consistent generation with the SDK
        /// https://github.com/microsoftgraph/MSGraph-SDK-Code-Generator/blob/aa09c93658b984377a646ba046c9f63fd8a6a6e6/src/GraphODataTemplateWriter/Extensions/OdcmModelExtensions.cs#L227
        /// It returns true if any of the conditions below are met
        /// 1. If a navigation property specifies "ContainsTarget='true'", it is self-contained.
        ///    Generate a direct path to the item (ie "parent/child").
        /// 2. If a navigation property does not specify ContainsTarget but there is a defined EntitySet
        ///    of the given type, it is a reference relationship. Generate a reference path to the item (ie "item/$ref").
        /// 3. If a navigation property does not have a defined EntitySet but there is a Singleton which has
        ///    a self-contained reference to the given type, we can make a relationship to the implied EntitySet of
        ///    the singleton(i.e. the entity collection contained by the singleton). Generate a reference path to the item (ie "singleton/item/$ref").
        /// 4. Otherwise return false so that the generator can find another way to generate snippets
        /// </summary>
        /// <param name="navigationPropertyLinkSegment">The navigation property link to test</param>
        /// <returns></returns>
        public bool CanGetServiceCollectionNavigationPropertyForProperty(NavigationPropertyLinkSegment navigationPropertyLinkSegment)
        {
            if (navigationPropertyLinkSegment == null)
            {
                throw new ArgumentNullException(nameof(navigationPropertyLinkSegment));
            }

            if (navigationPropertyLinkSegment.NavigationProperty.ContainsTarget)
            {
                return(true);
            }

            // Check if its defined directly in an the entitySet
            var isDirectlyInEntitySet = Model.EntityContainer.EntitySets()
                                        .Any(entitySet => entitySet.EntityType().FullName().Equals(navigationPropertyLinkSegment.NavigationProperty.ToEntityType().FullName(), StringComparison.OrdinalIgnoreCase));

            if (isDirectlyInEntitySet)
            {
                return(true);
            }

            // check the navBindings/nav Properties on singletons
            var isImplicitFromSingleton = Model.EntityContainer.Singletons()
                                          .SelectMany(singleton => singleton.NavigationPropertyBindings.Select(navPropertyBindings => navPropertyBindings.NavigationProperty) // get the nav propertyBinding from the singleton
                                                      .Concat(singleton.EntityType().NavigationProperties()))                                                                 // Append the nav properties from the singleton type
                                          .Any(property => property.ContainsTarget && property.ToEntityType().FullName().Equals(navigationPropertyLinkSegment.NavigationProperty.ToEntityType().FullName(), StringComparison.OrdinalIgnoreCase));

            return(isImplicitFromSingleton);
        }
 public void SingleResultIsSetCorrectly()
 {
     NavigationPropertyLinkSegment navigationPropertyLinkSegment1 = new NavigationPropertyLinkSegment(HardCodedTestModel.GetPersonMyDogNavProp(), null);
     navigationPropertyLinkSegment1.SingleResult.Should().BeTrue();
     NavigationPropertyLinkSegment navigationPropertyLinkSegment2 = new NavigationPropertyLinkSegment(HardCodedTestModel.GetDogMyPeopleNavProp(), null);
     navigationPropertyLinkSegment2.SingleResult.Should().BeFalse();
 }
Beispiel #6
0
 public async Task VisitAsync(ODataPath path)
 {
     NotFound       = false;
     BadRequest     = false;
     Result         = null;
     ResultType     = null;
     PropertySetter = null;
     Index          = 0;
     foreach (var segment in path)
     {
         await(segment switch
         {
             TypeSegment typeSegment => VisitAsync(typeSegment),
             NavigationPropertySegment navigationPropertySegment => VisitAsync(navigationPropertySegment),
             EntitySetSegment entitySetSegment => VisitAsync(entitySetSegment),
             SingletonSegment singletonSegment => VisitAsync(singletonSegment),
             KeySegment keySegment => VisitAsync(keySegment),
             PropertySegment propertySegment => VisitAsync(propertySegment),
             AnnotationSegment annotationSegment => VisitAsync(annotationSegment),
             OperationImportSegment operationImportSegment => VisitAsync(operationImportSegment),
             OperationSegment operationSegment => VisitAsync(operationSegment),
             DynamicPathSegment dynamicPathSegment => VisitAsync(dynamicPathSegment),
             CountSegment countSegment => VisitAsync(countSegment),
             FilterSegment filterSegment => VisitAsync(filterSegment),
             ReferenceSegment referenceSegment => VisitAsync(referenceSegment),
             EachSegment eachSegment => VisitAsync(eachSegment),
             NavigationPropertyLinkSegment navigationPropertyLinkSegment => VisitAsync(navigationPropertyLinkSegment),
             ValueSegment valueSegment => VisitAsync(valueSegment),
             BatchSegment batchSegment => VisitAsync(batchSegment),
             BatchReferenceSegment batchReferenceSegment => VisitAsync(batchReferenceSegment),
             MetadataSegment metadataSegment => VisitAsync(metadataSegment),
             PathTemplateSegment pathTemplateSegment => VisitAsync(pathTemplateSegment),
             _ => throw new NotSupportedException()
         });
Beispiel #7
0
        public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup <string, HttpActionDescriptor> actionMap)
        {
            if (odataPath == null)
            {
                throw new ArgumentNullException("odataPath");
            }

            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            if (actionMap == null)
            {
                throw new ArgumentNullException("actionMap");
            }

            HttpMethod requestMethod = controllerContext.Request.Method;

            if (odataPath.PathTemplate == "~/entityset/key/navigation/$ref" && requestMethod == HttpMethod.Get)
            {
                KeySegment keyValueSegment = odataPath.Segments[1] as KeySegment;
                controllerContext.AddKeyValueToRouteData(keyValueSegment);
                NavigationPropertyLinkSegment navigationLinkSegment = odataPath.Segments[2] as NavigationPropertyLinkSegment;
                IEdmNavigationProperty        navigationProperty    = navigationLinkSegment.NavigationProperty;
                IEdmEntityType declaredType = navigationProperty.DeclaringType as IEdmEntityType;

                string action = requestMethod + "LinksFor" + navigationProperty.Name + "From" + declaredType.Name;
                return(actionMap.Contains(action) ? action : requestMethod + "LinksFor" + navigationProperty.Name);
            }
            return(base.SelectAction(odataPath, controllerContext, actionMap));
        }
Beispiel #8
0
        public static AndConstraint <NavigationPropertyLinkSegment> ShouldBeNavigationPropertyLinkSegment(this ODataPathSegment segment, IEdmNavigationProperty navigationProperty)
        {
            segment.Should().BeOfType <NavigationPropertyLinkSegment>();
            NavigationPropertyLinkSegment navigationPropertyLinkSegment = segment.As <NavigationPropertyLinkSegment>();

            navigationPropertyLinkSegment.NavigationProperty.Should().Be(navigationProperty);
            return(new AndConstraint <NavigationPropertyLinkSegment>(navigationPropertyLinkSegment));
        }
        public static NavigationPropertyLinkSegment ShouldBeNavigationPropertyLinkSegment(this ODataPathSegment segment, IEdmNavigationProperty navigationProperty)
        {
            Assert.NotNull(segment);
            NavigationPropertyLinkSegment navigationPropertyLinkSegment = Assert.IsType <NavigationPropertyLinkSegment>(segment);

            Assert.Same(navigationProperty, navigationPropertyLinkSegment.NavigationProperty);
            return(navigationPropertyLinkSegment);
        }
Beispiel #10
0
        /// <summary>
        /// Handle a NavigationPropertyLinkSegment
        /// </summary>
        /// <param name="segment">the segment to Handle</param>
        public override void Handle(NavigationPropertyLinkSegment segment)
        {
            Contract.Assert(segment != null);
            _navigationSource = segment.NavigationSource;

            _pathUriLiteral.Add(segment.NavigationProperty.Name);
            _pathUriLiteral.Add(ODataSegmentKinds.Ref);
        }
 public void InequalityCorrect()
 {
     NavigationPropertyLinkSegment navigationPropertyLinkSegment1 = new NavigationPropertyLinkSegment(HardCodedTestModel.GetPersonMyDogNavProp(), null);
     NavigationPropertyLinkSegment navigationPropertyLinkSegment3 = new NavigationPropertyLinkSegment(HardCodedTestModel.GetDogMyPeopleNavProp(), null);
     BatchSegment segment3 = BatchSegment.Instance;
     navigationPropertyLinkSegment1.Equals(navigationPropertyLinkSegment3).Should().BeFalse();
     navigationPropertyLinkSegment1.Equals(segment3).Should().BeFalse();
 }
        /// <inheritdoc/>
        internal static string SelectActionImpl(ODataPath odataPath, IWebApiControllerContext controllerContext, IWebApiActionMap actionMap)
        {
            ODataRequestMethod requestMethod = controllerContext.Request.Method;

            if (!IsSupportedRequestMethod(requestMethod))
            {
                return(null);
            }

            if (odataPath.PathTemplate == "~/entityset/key/navigation/$ref" ||
                odataPath.PathTemplate == "~/entityset/key/cast/navigation/$ref" ||
                odataPath.PathTemplate == "~/singleton/navigation/$ref" ||
                odataPath.PathTemplate == "~/singleton/cast/navigation/$ref")
            {
                NavigationPropertyLinkSegment navigationLinkSegment = (NavigationPropertyLinkSegment)odataPath.Segments.Last();
                IEdmNavigationProperty        navigationProperty    = navigationLinkSegment.NavigationProperty;
                IEdmEntityType declaringType = navigationProperty.DeclaringEntityType();

                string refActionName = FindRefActionName(actionMap, navigationProperty, declaringType, requestMethod);
                if (refActionName != null)
                {
                    if (odataPath.PathTemplate.StartsWith("~/entityset/key", StringComparison.Ordinal))
                    {
                        controllerContext.AddKeyValueToRouteData((KeySegment)odataPath.Segments[1]);
                    }

                    controllerContext.RouteData.Add(ODataRouteConstants.NavigationProperty, navigationLinkSegment.NavigationProperty.Name);
                    return(refActionName);
                }
            }
            else if ((ODataRequestMethod.Delete == requestMethod) && (
                         odataPath.PathTemplate == "~/entityset/key/navigation/key/$ref" ||
                         odataPath.PathTemplate == "~/entityset/key/cast/navigation/key/$ref" ||
                         odataPath.PathTemplate == "~/singleton/navigation/key/$ref" ||
                         odataPath.PathTemplate == "~/singleton/cast/navigation/key/$ref"))
            {
                // the second key segment is the last segment in the path.
                // So the previous of last segment is the navigation property link segment.
                NavigationPropertyLinkSegment navigationLinkSegment = (NavigationPropertyLinkSegment)odataPath.Segments[odataPath.Segments.Count - 2];
                IEdmNavigationProperty        navigationProperty    = navigationLinkSegment.NavigationProperty;
                IEdmEntityType declaringType = navigationProperty.DeclaringEntityType();

                string refActionName = FindRefActionName(actionMap, navigationProperty, declaringType, requestMethod);
                if (refActionName != null)
                {
                    if (odataPath.PathTemplate.StartsWith("~/entityset/key", StringComparison.Ordinal))
                    {
                        controllerContext.AddKeyValueToRouteData((KeySegment)odataPath.Segments[1]);
                    }

                    controllerContext.RouteData.Add(ODataRouteConstants.NavigationProperty, navigationLinkSegment.NavigationProperty.Name);
                    controllerContext.AddKeyValueToRouteData((KeySegment)odataPath.Segments.Last(e => e is KeySegment), ODataRouteConstants.RelatedKey);
                    return(refActionName);
                }
            }

            return(null);
        }
 /// <summary>
 /// Handle a NavigationPropertyLinkSegment
 /// </summary>
 /// <param name="segment">the segment to Handle</param>
 public override void Handle(NavigationPropertyLinkSegment segment)
 {
     if (EdmLibHelpers.IsNotNavigable(segment.NavigationProperty, _edmModel))
     {
         throw new ODataException(Error.Format(
                                      SRResources.NotNavigablePropertyUsedInNavigation,
                                      segment.NavigationProperty.Name));
     }
 }
Beispiel #14
0
        public static string ToUriLiteral(this NavigationPropertyLinkSegment segment)
        {
            if (segment == null)
            {
                throw Error.ArgumentNull("segment");
            }

            return(segment.NavigationProperty.Name + "/$ref");
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="NavigationPropertyLinkSegmentTemplate"/> class.
        /// </summary>
        /// <param name="segment">The navigation property link segment</param>
        public NavigationPropertyLinkSegmentTemplate(NavigationPropertyLinkSegment segment)
        {
            if (segment == null)
            {
                throw Error.ArgumentNull("segment");
            }

            Segment = segment;
        }
Beispiel #16
0
        public void InequalityCorrect()
        {
            NavigationPropertyLinkSegment navigationPropertyLinkSegment1 = new NavigationPropertyLinkSegment(HardCodedTestModel.GetPersonMyDogNavProp(), null);
            NavigationPropertyLinkSegment navigationPropertyLinkSegment3 = new NavigationPropertyLinkSegment(HardCodedTestModel.GetDogMyPeopleNavProp(), null);
            BatchSegment segment3 = BatchSegment.Instance;

            navigationPropertyLinkSegment1.Equals(navigationPropertyLinkSegment3).Should().BeFalse();
            navigationPropertyLinkSegment1.Equals(segment3).Should().BeFalse();
        }
Beispiel #17
0
        public void SingleResultIsSetCorrectly()
        {
            NavigationPropertyLinkSegment navigationPropertyLinkSegment1 = new NavigationPropertyLinkSegment(HardCodedTestModel.GetPersonMyDogNavProp(), null);

            navigationPropertyLinkSegment1.SingleResult.Should().BeTrue();
            NavigationPropertyLinkSegment navigationPropertyLinkSegment2 = new NavigationPropertyLinkSegment(HardCodedTestModel.GetDogMyPeopleNavProp(), null);

            navigationPropertyLinkSegment2.SingleResult.Should().BeFalse();
        }
Beispiel #18
0
        /// <summary>
        /// Handle a NavigationPropertyLinkSegment
        /// </summary>
        /// <param name="segment">the segment to Handle</param>
        public override void Handle(NavigationPropertyLinkSegment segment)
        {
            _navigationSource = segment.NavigationSource;

            // TODO: do we really need to add $ref?
            _pathTemplate.Add(ODataSegmentKinds.Navigation); // navigation
            _pathTemplate.Add(ODataSegmentKinds.Ref);        // $ref

            _pathUriLiteral.Add(segment.NavigationProperty.Name);
            _pathUriLiteral.Add(ODataSegmentKinds.Ref);
        }
Beispiel #19
0
        public void TryTranslateNavigationLinkSegmentTemplate_ReturnsODataNavigationSegment()
        {
            // Arrange
            EdmModel model = new EdmModel();

            model.AddElement(_employee);

            NavigationLinkSegmentTemplate linkSegment          = new NavigationLinkSegmentTemplate(_navigation, null);
            RouteValueDictionary          routeValueDictionary = new RouteValueDictionary(new { id = "42" });
            ODataTemplateTranslateContext context = new ODataTemplateTranslateContext
            {
                RouteValues = routeValueDictionary,
                Model       = model
            };

            // Without key segment
            // Act & Assert
            bool ok = linkSegment.TryTranslate(context);

            Assert.True(ok);
            ODataPathSegment actual = Assert.Single(context.Segments);
            NavigationPropertyLinkSegment navLinkSegment = Assert.IsType <NavigationPropertyLinkSegment>(actual);

            Assert.Same(_navigation, navLinkSegment.NavigationProperty);
            Assert.Null(navLinkSegment.NavigationSource);

            // With Key segment
            // Act & Assert
            context = new ODataTemplateTranslateContext
            {
                RouteValues = routeValueDictionary,
                Model       = model
            };

            linkSegment.Key = KeySegmentTemplate.CreateKeySegment(_employee, null, "id");
            ok = linkSegment.TryTranslate(context);

            Assert.True(ok);
            Assert.Collection(context.Segments,
                              e =>
            {
                NavigationPropertyLinkSegment navLinkSegment = Assert.IsType <NavigationPropertyLinkSegment>(e);
                Assert.Same(_navigation, navLinkSegment.NavigationProperty);
                Assert.Null(navLinkSegment.NavigationSource);
            },
                              e =>
            {
                KeySegment keySegment             = Assert.IsType <KeySegment>(e);
                KeyValuePair <string, object> key = Assert.Single(keySegment.Keys);
                Assert.Equal("Id", key.Key);
                Assert.Equal(42, key.Value);
            });
        }
        public void SelectController_RetrunsNull_IfNotNavigationSourceRequest()
        {
            // Arrange
            var request = RequestFactory.Create();
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            var ordersProperty = model.Customer.FindProperty("Orders") as IEdmNavigationProperty;
            NavigationPropertyLinkSegment navigationLinkSegment = new NavigationPropertyLinkSegment(ordersProperty, model.Orders);
            ODataPath odataPath = new ODataPath(navigationLinkSegment);

            // Act
            string controller = SelectController(new MockNavigationSourceRoutingConvention(), odataPath, request);

            // Assert
            Assert.Null(controller);
        }
Beispiel #21
0
        public override void Handle(NavigationPropertyLinkSegment segment)
        {
            this.ThrowIfResolved();

            this.NavigationSource = segment.NavigationSource;;
            this.Property         = null;
            this.Type             = segment.EdmType;
            this.ElementType      = this.GetElementType(this.Type);

            this.IsReference = true;


            this.PushParentSegment();
            this.childSegments.Add(segment);

            this.canonicalSegments.Add(segment);
        }
        public void TryMatch_ReturnsFalse()
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            var ordersProperty       = model.Customer.FindProperty("Orders") as IEdmNavigationProperty;
            var specialOrderProperty = model.SpecialCustomer.FindProperty("SpecialOrders") as IEdmNavigationProperty;

            NavigationPropertyLinkSegmentTemplate template =
                new NavigationPropertyLinkSegmentTemplate(new NavigationPropertyLinkSegment(ordersProperty, model.Orders));
            NavigationPropertyLinkSegment segment = new NavigationPropertyLinkSegment(specialOrderProperty, model.Orders);

            // Act
            Dictionary <string, object> values = new Dictionary <string, object>();
            bool result = template.TryMatch(segment, values);

            // Assert
            Assert.False(result);
        }
Beispiel #23
0
        public void Translate_NavigationPropertyLinkSegment_To_RefPathSegments_Works()
        {
            // Arrange
            IEdmEntitySet                 entityset          = _model.FindDeclaredEntitySet("Products");
            IEdmEntityType                entityType         = _model.FindDeclaredType("System.Web.OData.Routing.RoutingCustomer") as IEdmEntityType;
            IEdmNavigationProperty        navigationProperty = entityType.NavigationProperties().First(e => e.Name == "Products");
            NavigationPropertyLinkSegment segment            = new NavigationPropertyLinkSegment(navigationProperty, entityset);

            // Act
            IEnumerable <ODataPathSegment> segments = _translator.Translate(segment);

            // Assert
            Assert.Equal(2, segments.Count());
            NavigationPathSegment navigationPathSegment = Assert.IsType <NavigationPathSegment>(segments.First());

            Assert.Same(navigationProperty, navigationPathSegment.NavigationProperty);

            Assert.IsType <RefPathSegment>(segments.Last());
        }
Beispiel #24
0
        /// <summary>
        /// Translate NavigationPropertyLinkSegment to linq expression.
        /// </summary>
        /// <param name="segment">The NavigationPropertyLinkSegment</param>
        /// <returns>The linq expression</returns>
        public override Expression Translate(NavigationPropertyLinkSegment segment)
        {
            if (!(this.LastProcessedSegment is KeySegment ||
                  this.LastProcessedSegment is SingletonSegment ||
                  this.LastProcessedSegment is TypeSegment))
            {
                throw new InvalidOperationException("Unsupported URI segment before NavigationPropertyLinkSegment");
            }

            var lastSegmentEntityType = this.LastProcessedSegment.EdmType as EdmEntityType;

            // <context>/PropertyName will be translated to <context>.PropertyName
            this.ResultExpression = Expression.Property(
                this.ResultExpression,
                EdmClrTypeUtils.GetInstanceType(lastSegmentEntityType.FullTypeName()),
                segment.NavigationProperty.Name);

            this.LastProcessedSegment = segment;
            return(this.ResultExpression);
        }
Beispiel #25
0
        public void ODataPathSegmentToTemplateHandler_Handles_Key_AfterNavigationProperty()
        {
            // Arrange
            ODataPathSegmentToTemplateHandler handler = new ODataPathSegmentToTemplateHandler(null);

            EdmEntityType customer = new EdmEntityType("NS", "Customer");

            customer.AddKeys(customer.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));

            EdmEntityType order = new EdmEntityType("NS", "order");

            order.AddKeys(order.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));

            IEdmNavigationProperty ordersNavProperty = customer.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Name               = "Orders",
                Target             = order,
                TargetMultiplicity = EdmMultiplicity.Many
            });
            NavigationPropertyLinkSegment segment1 = new NavigationPropertyLinkSegment(ordersNavProperty, null);

            EdmEntityContainer           entityContainer = new EdmEntityContainer("NS", "Default");
            EdmEntitySet                 orders          = entityContainer.AddEntitySet("Orders", order);
            IDictionary <string, object> keys            = new Dictionary <string, object>
            {
                { "Id", "{relatedKey}" }
            };

            KeySegment segment2 = new KeySegment(keys, order, orders);

            // Act
            handler.Handle(segment1);
            handler.Handle(segment2);

            // Assert
            ODataSegmentTemplate          segmentTemplate = Assert.Single(handler.Templates);
            NavigationLinkSegmentTemplate nlTemplate      = Assert.IsType <NavigationLinkSegmentTemplate>(segmentTemplate);

            Assert.NotNull(nlTemplate.Key);
        }
Beispiel #26
0
        public void ODataPathSegmentHandler_Handles_NavigationPropertyLinkSegment()
        {
            // Arrange
            ODataPathSegmentHandler handler = new ODataPathSegmentHandler();

            EdmEntityType          customer          = new EdmEntityType("NS", "customer");
            EdmEntityType          order             = new EdmEntityType("NS", "order");
            IEdmNavigationProperty ordersNavProperty = customer.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Name               = "Orders",
                Target             = order,
                TargetMultiplicity = EdmMultiplicity.Many
            });
            NavigationPropertyLinkSegment segment = new NavigationPropertyLinkSegment(ordersNavProperty, null);

            // Act
            handler.Handle(segment);

            // Assert
            Assert.Equal("Orders/$ref", handler.PathLiteral);
            Assert.Null(handler.NavigationSource);
        }
Beispiel #27
0
        public void ODataPathSegmentHandler_Handles_KeySegment_AfterNavigationProperty()
        {
            // Arrange
            ODataPathSegmentHandler handler = new ODataPathSegmentHandler();

            EdmEntityType customer = new EdmEntityType("NS", "Customer");

            customer.AddKeys(customer.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));

            EdmEntityType order = new EdmEntityType("NS", "order");

            order.AddKeys(order.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));

            IEdmNavigationProperty ordersNavProperty = customer.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Name               = "Orders",
                Target             = order,
                TargetMultiplicity = EdmMultiplicity.Many
            });
            NavigationPropertyLinkSegment segment1 = new NavigationPropertyLinkSegment(ordersNavProperty, null);

            EdmEntityContainer           entityContainer = new EdmEntityContainer("NS", "Default");
            EdmEntitySet                 orders          = entityContainer.AddEntitySet("Orders", order);
            IDictionary <string, object> keys            = new Dictionary <string, object>
            {
                { "Id", 42 }
            };

            KeySegment segment2 = new KeySegment(keys, order, orders);

            // Act
            handler.Handle(segment1);
            handler.Handle(segment2);

            // Assert
            Assert.Equal("Orders(42)/$ref", handler.PathLiteral);
            Assert.Same(orders, handler.NavigationSource);
        }
Beispiel #28
0
        public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup <string, HttpActionDescriptor> actionMap)
        {
            string requestMethod          = controllerContext.Request.Method.ToString().ToUpperInvariant();
            TestControllerContext context = new TestControllerContext(controllerContext);
#endif
            if (odataPath.PathTemplate == "~/entityset/key/navigation/$ref" && requestMethod == "GET")
            {
                KeySegment keyValueSegment = odataPath.Segments[1] as KeySegment;
                context.AddKeyValueToRouteData(keyValueSegment);
                NavigationPropertyLinkSegment navigationLinkSegment = odataPath.Segments[2] as NavigationPropertyLinkSegment;
                IEdmNavigationProperty        navigationProperty    = navigationLinkSegment.NavigationProperty;
                IEdmEntityType declaredType = navigationProperty.DeclaringType as IEdmEntityType;

                string action = requestMethod + "LinksFor" + navigationProperty.Name + "From" + declaredType.Name;
                return(actionMap.Contains(action) ? action : requestMethod + "LinksFor" + navigationProperty.Name);
            }

#if NETCORE
            return(base.SelectAction(routeContext, controllerResult, actionDescriptors));
#else
            return(base.SelectAction(odataPath, controllerContext, actionMap));
#endif
        }
Beispiel #29
0
        public void TryTranslateNavigationSegmentTemplate_ReturnsODataNavigationLinkSegment()
        {
            // Arrange
            NavigationLinkTemplateSegmentTemplate navigationSegment = new NavigationLinkTemplateSegmentTemplate(_employeeType, _entitySet);

            RouteValueDictionary          routeValueDictionary = new RouteValueDictionary(new { navigationProperty = "DirectReports" });
            ODataTemplateTranslateContext context = new ODataTemplateTranslateContext
            {
                RouteValues = routeValueDictionary,
                Model       = _model
            };

            // Act
            bool ok = navigationSegment.TryTranslate(context);

            // Assert
            Assert.True(ok);
            ODataPathSegment actual = Assert.Single(context.Segments);
            NavigationPropertyLinkSegment navSegment = Assert.IsType <NavigationPropertyLinkSegment>(actual);

            Assert.Same(_directReportsNav, navSegment.NavigationProperty);
            Assert.Same(_entitySet, navSegment.NavigationSource);
        }
Beispiel #30
0
        public void ODataPathSegmentToTemplateHandler_Handles_NavigationPropertyLink()
        {
            // Arrange
            ODataPathSegmentToTemplateHandler handler = new ODataPathSegmentToTemplateHandler(null);

            EdmEntityType          customer          = new EdmEntityType("NS", "customer");
            EdmEntityType          order             = new EdmEntityType("NS", "order");
            IEdmNavigationProperty ordersNavProperty = customer.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
            {
                Name               = "Orders",
                Target             = order,
                TargetMultiplicity = EdmMultiplicity.Many
            });
            NavigationPropertyLinkSegment segment = new NavigationPropertyLinkSegment(ordersNavProperty, null);

            // Act
            handler.Handle(segment);

            // Assert
            ODataSegmentTemplate segmentTemplate = Assert.Single(handler.Templates);

            Assert.IsType <NavigationLinkSegmentTemplate>(segmentTemplate);
        }
 public void EqualityCorrect()
 {
     NavigationPropertyLinkSegment navigationPropertyLinkSegment1 = new NavigationPropertyLinkSegment(HardCodedTestModel.GetPersonMyDogNavProp(), null);
     NavigationPropertyLinkSegment navigationPropertyLinkSegment2 = new NavigationPropertyLinkSegment(HardCodedTestModel.GetPersonMyDogNavProp(), null);
     navigationPropertyLinkSegment1.Equals(navigationPropertyLinkSegment2).Should().BeTrue();
 }
 public void NavigationPropertySetCorrectly()
 {
     NavigationPropertyLinkSegment navigationPropertyLinkSegment = new NavigationPropertyLinkSegment(HardCodedTestModel.GetPersonMyDogNavProp(), null);
     navigationPropertyLinkSegment.NavigationProperty.Should().BeSameAs(HardCodedTestModel.GetPersonMyDogNavProp());
 }
 public void TargetKindIsResource()
 {
     NavigationPropertyLinkSegment navigationPropertyLinkSegment = new NavigationPropertyLinkSegment(HardCodedTestModel.GetPersonMyDogNavProp(), null);
     navigationPropertyLinkSegment.TargetKind.Should().Be(RequestTargetKind.Resource);
 }
Beispiel #34
0
        public override void Handle(NavigationPropertyLinkSegment segment)
        {
            this.ThrowIfResolved();

            this.NavigationSource = segment.NavigationSource; ;
            this.Property = null;
            this.Type = segment.EdmType;
            this.ElementType = this.GetElementType(this.Type);

            this.IsReference = true;


            this.PushParentSegment();
            this.childSegments.Add(segment);

            this.canonicalSegments.Add(segment);
        }
 public void TargetEdmTypeIsNavPropTypeDefinition()
 {
     NavigationPropertyLinkSegment navigationPropertyLinkSegment = new NavigationPropertyLinkSegment(HardCodedTestModel.GetPersonMyDogNavProp(), null);
     navigationPropertyLinkSegment.TargetEdmType.Should().BeSameAs(HardCodedTestModel.GetPersonMyDogNavProp().Type.Definition);
 }
 public void IdentifierIsNavPropName()
 {
     NavigationPropertyLinkSegment navigationPropertyLinkSegment = new NavigationPropertyLinkSegment(HardCodedTestModel.GetPersonMyDogNavProp(), null);
     navigationPropertyLinkSegment.Identifier.Should().Be(HardCodedTestModel.GetPersonMyDogNavProp().Name);
 }
Beispiel #37
0
 /// <summary>
 /// Translate NavigationPropertyLinkSegment to linq expression.
 /// </summary>
 /// <param name="segment">The NavigationPropertyLinkSegment</param>
 /// <returns>The linq expression</returns>
 public override Expression Translate(NavigationPropertyLinkSegment segment)
 {
     throw new NotImplementedException("NavigationPropertyLinkSegment translation is not supported");
 }
Beispiel #38
0
        /// <summary>
        /// Tries to handle the segment as $ref. If it is $ref, then the rest of the path will be parsed/validated in this call.
        /// </summary>
        /// <param name="text">The text of the segment.</param>
        /// <returns>Whether the text was $ref.</returns>
        private bool TryCreateEntityReferenceSegment(string text)
        {
            string identifier;
            string parenthesisExpression;
            ExtractSegmentIdentifierAndParenthesisExpression(text, out identifier, out parenthesisExpression);

            if (!this.IdentifierIs(UriQueryConstants.RefSegment, identifier))
            {
                return false;
            }

            if (parenthesisExpression != null)
            {
                throw ExceptionUtil.CreateSyntaxError();
            }

            // Create a stack to keep track of KeySegments
            Stack<KeySegment> keySegmentsForPreviousPathSegment = new Stack<KeySegment>();

            while (true)
            {
                KeySegment key = this.parsedSegments[this.parsedSegments.Count - 1] as KeySegment;

                if (key == null)
                {
                    break;
                }

                keySegmentsForPreviousPathSegment.Push(key);
                this.parsedSegments.Remove(key);
            }

            // Get the previous Path segment
            ODataPathSegment previous = this.parsedSegments[this.parsedSegments.Count - 1];
            NavigationPropertySegment navPropSegment = previous as NavigationPropertySegment;

            // $ref can not be applied for entity set. It can be applied only on entity and collection of entities
            if ((navPropSegment == null) || navPropSegment.TargetKind != RequestTargetKind.Resource)
            {
                throw ExceptionUtil.CreateBadRequestError(ODataErrorStrings.PathParser_EntityReferenceNotSupported(previous.Identifier));
            }

            // Since this $ref segment, remove the previous segment from parsedSegments as we need to repalce that with new ref segment
            this.parsedSegments.Remove(previous);

            // If this is a navigation property, find target navigation source
            var targetNavigationSource = this.parsedSegments[parsedSegments.Count - 1].TargetEdmNavigationSource.FindNavigationTarget(navPropSegment.NavigationProperty);

            // If we can't compute the target navigation source, then pretend the navigation property does not exist
            if (targetNavigationSource == null)
            {
                throw ExceptionUtil.CreateResourceNotFoundError(navPropSegment.NavigationProperty.Name);
            }

            // Create new NavigationPropertyLinkSegment
            var navPropLinkSegment = new NavigationPropertyLinkSegment(navPropSegment.NavigationProperty, targetNavigationSource);

            // Add this segment to parsedSegments
            this.parsedSegments.Add(navPropLinkSegment);

            // Add key segments back to the parsed segments
            while (keySegmentsForPreviousPathSegment.Count > 0)
            {
                this.parsedSegments.Add(keySegmentsForPreviousPathSegment.Pop());
            }

            string nextSegmentText;

            // Nothing is allowed after $ref.
            if (this.TryGetNextSegmentText(out nextSegmentText))
            {
                throw ExceptionUtil.ResourceNotFoundError(ODataErrorStrings.RequestUriProcessor_MustBeLeafSegment(UriQueryConstants.RefSegment));
            }

            return true;
        }
        public void Translate_NavigationPropertyLinkSegment_To_RefPathSegments_Works()
        {
            // Arrange
            IEdmEntitySet entityset = _model.FindDeclaredEntitySet("Products");
            IEdmEntityType entityType = _model.FindDeclaredType("System.Web.OData.Routing.RoutingCustomer") as IEdmEntityType;
            IEdmNavigationProperty navigationProperty = entityType.NavigationProperties().First(e => e.Name == "Products");
            NavigationPropertyLinkSegment segment = new NavigationPropertyLinkSegment(navigationProperty, entityset);

            // Act
            IEnumerable<ODataPathSegment> segments = _translator.Translate(segment);

            // Assert
            Assert.Equal(2, segments.Count());
            NavigationPathSegment navigationPathSegment = Assert.IsType<NavigationPathSegment>(segments.First());
            Assert.Same(navigationProperty, navigationPathSegment.NavigationProperty);

            Assert.IsType<RefPathSegment>(segments.Last());
        }
Beispiel #40
0
 /// <summary>
 /// Visit a NavigationPropertyLinkSegment
 /// </summary>
 /// <param name="segment">the segment to Translate</param>
 /// <returns>Translated odata path segment.</returns>
 public override ODataPathSegment Translate(NavigationPropertyLinkSegment segment)
 {
     return(segment);
 }
 /// <summary>
 /// Handle a LinksSegment
 /// </summary>
 /// <param name="segment">the segment to Handle</param>
 public virtual void Handle(NavigationPropertyLinkSegment segment)
 {
     throw new NotImplementedException();
 }