示例#1
0
        /// <summary>
        /// Selects the controller for OData requests.
        /// </summary>
        /// <param name="odataPath">The OData path.</param>
        /// <returns>
        ///   <c>null</c> if the request isn't handled by this convention; otherwise, the name of the selected controller
        /// </returns>
        internal static SelectControllerResult SelectControllerImpl(ODataPath odataPath)
        {
            ODataPathSegment firstSegment = odataPath.Segments.FirstOrDefault();

            // entity set
            EntitySetSegment entitySetSegment = firstSegment as EntitySetSegment;

            if (entitySetSegment != null)
            {
                return(new SelectControllerResult(entitySetSegment.EntitySet.Name, null));
            }

            // singleton
            SingletonSegment singletonSegment = firstSegment as SingletonSegment;

            if (singletonSegment != null)
            {
                return(new SelectControllerResult(singletonSegment.Singleton.Name, null));
            }

            // operation import
            OperationImportSegment importSegment = firstSegment as OperationImportSegment;

            if (importSegment != null)
            {
                // There's two options: Each one has advantages/disadvantanges. Here picks #1.
                // 1) map all operation import to a certain controller, for example: ODataOperationImportController
                return(new SelectControllerResult("ODataOperationImport", null));

                // 2) map operation import to controller named using operation improt name, for example:  ResetDataController
                // return new SelectControllerResult(importSegment.OperationImports.FirstOrDefault().Name, null);
            }

            return(null);
        }
示例#2
0
        /// <summary>
        /// Handle a SingletonSegment
        /// </summary>
        /// <param name="segment">the segment to handle</param>
        public override void Handle(SingletonSegment segment)
        {
            Contract.Assert(segment != null);
            _navigationSource = segment.Singleton;

            _pathUriLiteral.Add(segment.Singleton.Name);
        }
示例#3
0
        private static IEdmEntityType GetTargetEntityType(ODataPathSegment segment)
        {
            Contract.Assert(segment != null);

            EntitySetSegment entitySetSegment = segment as EntitySetSegment;

            if (entitySetSegment != null)
            {
                return(entitySetSegment.EntitySet.EntityType());
            }

            SingletonSegment singletonSegment = segment as SingletonSegment;

            if (singletonSegment != null)
            {
                return(singletonSegment.Singleton.EntityType());
            }

            NavigationPropertySegment navigationPropertySegment = segment as NavigationPropertySegment;

            if (navigationPropertySegment != null)
            {
                return(navigationPropertySegment.NavigationSource.EntityType());
            }

            return(null);
        }
示例#4
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()
         });
示例#5
0
        /// <inheritdoc/>
        internal static string SelectActionImpl(ODataPath odataPath, IWebApiControllerContext controllerContext,
                                                IWebApiActionMap actionMap)
        {
            if (odataPath.PathTemplate == "~/singleton")
            {
                SingletonSegment singletonSegment = (SingletonSegment)odataPath.Segments[0];
                string           httpMethodName   = GetActionNamePrefix(controllerContext.Request.GetRequestMethodOrPreflightMethod());

                if (httpMethodName != null)
                {
                    // e.g. Try Get{SingletonName} first, then fallback on Get action name
                    return(actionMap.FindMatchingAction(
                               httpMethodName + singletonSegment.Singleton.Name,
                               httpMethodName));
                }
            }
            else if (odataPath.PathTemplate == "~/singleton/cast")
            {
                SingletonSegment singletonSegment = (SingletonSegment)odataPath.Segments[0];
                IEdmEntityType   entityType       = (IEdmEntityType)odataPath.EdmType;
                string           httpMethodName   = GetActionNamePrefix(controllerContext.Request.GetRequestMethodOrPreflightMethod());

                if (httpMethodName != null)
                {
                    // e.g. Try Get{SingletonName}From{EntityTypeName} first, then fallback on Get action name
                    return(actionMap.FindMatchingAction(
                               httpMethodName + singletonSegment.Singleton.Name + "From" + entityType.Name,
                               httpMethodName + "From" + entityType.Name));
                }
            }

            return(null);
        }
        /// <summary>
        /// Selects the controller for OData requests.
        /// </summary>
        /// <param name="odataPath">The OData path.</param>
        /// <param name="request">The request.</param>
        /// <returns>
        ///   <c>null</c> if the request isn't handled by this convention; otherwise, the name of the selected controller
        /// </returns>
        public virtual string SelectController(ODataPath odataPath, HttpRequestMessage request)
        {
            if (odataPath == null)
            {
                throw Error.ArgumentNull("odataPath");
            }

            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            // entity set
            EntitySetSegment entitySetSegment = odataPath.Segments.FirstOrDefault() as EntitySetSegment;

            if (entitySetSegment != null)
            {
                return(entitySetSegment.EntitySet.Name);
            }

            // singleton
            SingletonSegment singletonSegment = odataPath.Segments.FirstOrDefault() as SingletonSegment;

            if (singletonSegment != null)
            {
                return(singletonSegment.Singleton.Name);
            }

            return(null);
        }
        public static SingletonSegment ShouldBeSingletonSegment(this ODataPathSegment segment, IEdmSingleton singleton)
        {
            Assert.NotNull(segment);
            SingletonSegment singletonSegment = Assert.IsType <SingletonSegment>(segment);

            Assert.Same(singleton, singletonSegment.Singleton);
            return(singletonSegment);
        }
示例#8
0
        /// <summary>
        /// Handle a SingletonSegment
        /// </summary>
        /// <param name="segment">the segment to handle</param>
        public override void Handle(SingletonSegment segment)
        {
            _navigationSource = segment.Singleton;

            _pathTemplate.Add(ODataSegmentKinds.Singleton); // singleton

            _pathUriLiteral.Add(segment.Singleton.Name);
        }
示例#9
0
        public static AndConstraint <SingletonSegment> ShouldBeSingletonSegment(this ODataPathSegment segment, IEdmSingleton singleton)
        {
            segment.Should().BeOfType <SingletonSegment>();
            SingletonSegment singletonSegment = segment.As <SingletonSegment>();

            singletonSegment.Singleton.Should().BeSameAs(singleton);
            return(new AndConstraint <SingletonSegment>(singletonSegment));
        }
示例#10
0
        public static string ToUriLiteral(this SingletonSegment segment)
        {
            if (segment == null)
            {
                throw Error.ArgumentNull("segment");
            }

            return(segment.Singleton.Name);
        }
示例#11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SingletonSegmentTemplate"/> class.
        /// </summary>
        /// <param name="segment">The singleton segment</param>
        public SingletonSegmentTemplate(SingletonSegment segment)
        {
            if (segment == null)
            {
                throw Error.ArgumentNull("segment");
            }

            Segment = segment;
        }
示例#12
0
        /// <summary>
        /// Translate SingletonSegment to linq expression.
        /// </summary>
        /// <param name="segment">The SingletonSegment</param>
        /// <returns>The linq expression</returns>
        public override Expression Translate(SingletonSegment segment)
        {
            if (this.LastProcessedSegment != null)
            {
                throw new InvalidOperationException("Unsupported URI segment before SingletonSegment");
            }

            var singleton = Utility.GetRootQuery(this.dataSource, segment.Singleton);

            this.ResultExpression     = Expression.Constant(singleton);
            this.LastProcessedSegment = segment;
            return(this.ResultExpression);
        }
示例#13
0
        private Uri CreateUriFromPath(ODataPath path)
        {
            var segments    = path.Segments;
            var computedUri = _serviceRoot;

            // Append each segment to base uri
            foreach (ODataPathSegment segment in segments)
            {
                KeySegment keySegment = segment as KeySegment;
                if (keySegment != null)
                {
                    computedUri = AppendKeyExpression(computedUri, keySegment.Keys);
                    continue;
                }

                EntitySetSegment entitySetSegment = segment as EntitySetSegment;
                if (entitySetSegment != null)
                {
                    computedUri = AppendSegment(computedUri, entitySetSegment.EntitySet.Name);
                    continue;
                }

                SingletonSegment singletonSegment = segment as SingletonSegment;
                if (singletonSegment != null)
                {
                    computedUri = AppendSegment(computedUri, singletonSegment.Singleton.Name);
                    continue;
                }

                var typeSegment = segment as TypeSegment;
                if (typeSegment != null)
                {
                    var edmType = typeSegment.EdmType;
                    if (edmType.TypeKind == EdmTypeKind.Collection)
                    {
                        var collectionType = (IEdmCollectionType)edmType;
                        edmType = collectionType.ElementType.Definition;
                    }

                    computedUri = AppendSegment(computedUri, edmType.FullTypeName());
                }
                else
                {
                    computedUri = AppendSegment(
                        computedUri,
                        ((NavigationPropertySegment)segment).NavigationProperty.Name);
                }
            }

            return(computedUri);
        }
示例#14
0
        private void RemoveRedundantContainingPathSegments()
        {
            // Find the last non-contained navigation property segment:
            //   Collection valued: entity set
            //   -or-
            //   Single valued: singleton
            // Copy over other path segments such as: not a navigation path segment, contained navigation property,
            // single valued navigation property with navigation source targetting an entity set (we won't have key
            // information for that navigation property.)
            _segments.Reverse();
            NavigationPropertySegment navigationPropertySegment = null;
            List <ODataPathSegment>   newSegments = new List <ODataPathSegment>();

            foreach (ODataPathSegment segment in _segments)
            {
                navigationPropertySegment = segment as NavigationPropertySegment;
                if (navigationPropertySegment != null)
                {
                    EdmNavigationSourceKind navigationSourceKind =
                        navigationPropertySegment.NavigationSource.NavigationSourceKind();
                    if ((navigationPropertySegment.NavigationProperty.TargetMultiplicity() == EdmMultiplicity.Many &&
                         navigationSourceKind == EdmNavigationSourceKind.EntitySet) ||
                        (navigationSourceKind == EdmNavigationSourceKind.Singleton))
                    {
                        break;
                    }
                }

                newSegments.Insert(0, segment);
            }

            // Start the path with the navigation source of the navigation property found above.
            if (navigationPropertySegment != null)
            {
                IEdmNavigationSource navigationSource = navigationPropertySegment.NavigationSource;
                Contract.Assert(navigationSource != null);
                if (navigationSource.NavigationSourceKind() == EdmNavigationSourceKind.Singleton)
                {
                    SingletonSegment singletonSegment = new SingletonSegment((IEdmSingleton)navigationSource);
                    newSegments.Insert(0, singletonSegment);
                }
                else
                {
                    Contract.Assert(navigationSource.NavigationSourceKind() == EdmNavigationSourceKind.EntitySet);
                    EntitySetSegment entitySetSegment = new EntitySetSegment((IEdmEntitySet)navigationSource);
                    newSegments.Insert(0, entitySetSegment);
                }
            }

            _segments = newSegments;
        }
        public void Translate_SingletonSegment_To_SingletonPathSegment_Works()
        {
            // Arrange
            IEdmSingleton singleton = _model.FindDeclaredSingleton("VipCustomer");
            SingletonSegment segment = new SingletonSegment(singleton);

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

            // Assert
            ODataPathSegment pathSegment = Assert.Single(segments);
            SingletonPathSegment singletonPathSegment = Assert.IsType<SingletonPathSegment>(pathSegment);
            Assert.Same(singleton, singletonPathSegment.Singleton);
        }
        public virtual string SelectController(ODataPath odataPath, HttpRequestMessage request)
        {
            SingletonSegment singletonSegment = odataPath.Segments.FirstOrDefault() as SingletonSegment;

            if (singletonSegment != null)
            {
                var edmType = odataPath.EdmType as EdmEntityType;
                if (edmType != null && edmType.Name == "Manufacturer")
                {
                    return("Manufacturers");
                }
            }

            return(null);
        }
示例#17
0
        public override void Handle(SingletonSegment segment)
        {
            this.ThrowIfResolved();

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

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

            this.canonicalSegments.Clear();
            this.canonicalSegments.Add(segment);
        }
示例#18
0
        public void Translate_SingletonSegment_To_SingletonPathSegment_Works()
        {
            // Arrange
            IEdmSingleton    singleton = _model.FindDeclaredSingleton("VipCustomer");
            SingletonSegment segment   = new SingletonSegment(singleton);

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

            // Assert
            ODataPathSegment     pathSegment          = Assert.Single(segments);
            SingletonPathSegment singletonPathSegment = Assert.IsType <SingletonPathSegment>(pathSegment);

            Assert.Same(singleton, singletonPathSegment.Singleton);
        }
示例#19
0
        /// <inheritdoc/>
        public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext,
                                            ILookup <string, HttpActionDescriptor> actionMap)
        {
            if (odataPath == null)
            {
                throw Error.ArgumentNull("odataPath");
            }

            if (controllerContext == null)
            {
                throw Error.ArgumentNull("controllerContext");
            }

            if (actionMap == null)
            {
                throw Error.ArgumentNull("actionMap");
            }

            if (odataPath.PathTemplate == "~/singleton")
            {
                SingletonSegment singletonSegment = (SingletonSegment)odataPath.Segments[0];
                string           httpMethodName   = GetActionNamePrefix(controllerContext.Request.Method);

                if (httpMethodName != null)
                {
                    // e.g. Try Get{SingletonName} first, then fallback on Get action name
                    return(actionMap.FindMatchingAction(
                               httpMethodName + singletonSegment.Singleton.Name,
                               httpMethodName));
                }
            }
            else if (odataPath.PathTemplate == "~/singleton/cast")
            {
                SingletonSegment singletonSegment = (SingletonSegment)odataPath.Segments[0];
                IEdmEntityType   entityType       = (IEdmEntityType)odataPath.EdmType;
                string           httpMethodName   = GetActionNamePrefix(controllerContext.Request.Method);

                if (httpMethodName != null)
                {
                    // e.g. Try Get{SingletonName}From{EntityTypeName} first, then fallback on Get action name
                    return(actionMap.FindMatchingAction(
                               httpMethodName + singletonSegment.Singleton.Name + "From" + entityType.Name,
                               httpMethodName + "From" + entityType.Name));
                }
            }

            return(null);
        }
示例#20
0
        private static void WriteODataEntry(IEdmModel model, Stream stream, SingletonSegment singletonSegment,
                                            ODataPath queryPath)
        {
            var entry = new ODataEntry()
            {
                Properties = new List <ODataProperty>()
                {
                    new ODataProperty()
                    {
                        Name  = "CompanyID",
                        Value = 1
                    },
                    new ODataProperty()
                    {
                        Name  = "Name",
                        Value = "Wonderland"
                    },
                    new ODataProperty()
                    {
                        Name  = "Revenue",
                        Value = 1000
                    }
                }
            };

            ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings();

            writerSettings.Version  = ODataVersion.V4;
            writerSettings.ODataUri = new ODataUri()
            {
                ServiceRoot = ServiceRootUri, Path = queryPath
            };
            writerSettings.PayloadBaseUri = ServiceRootUri;
            writerSettings.SetContentType("application/json;odata.metadata=full", Encoding.UTF8.WebName);
            writerSettings.AutoComputePayloadMetadataInJson = true;

            var message = new ODataResponseMessage(stream);

            using (var messageWriter = new ODataMessageWriter(message, writerSettings, model))
            {
                var entryWriter = messageWriter.CreateODataEntryWriter(singletonSegment.Singleton,
                                                                       singletonSegment.EdmType as EdmEntityType);

                entryWriter.WriteStart(entry);
                entryWriter.WriteEnd();
                entryWriter.Flush();
            }
        }
示例#21
0
        private static void Main(string[] args)
        {
            Stream stream = new NonClosingStream();

            //Create a model with singleton
            //CSDL:
            //<Schema Namespace="ODataSamples.Features.Singleton" xmlns="http://docs.oasis-open.org/odata/ns/edm">
            //  <EntityType Name="Company">
            //      <Key>
            //          <PropertyRef Name="CompanyID" />
            //      </Key>
            //      <Property Name="CompanyID" Type="Edm.Int32" Nullable="false" />
            //      <Property Name="Name" Type="Edm.String" />
            //      <Property Name="EmployeesCount" Type="Edm.Int32" />
            //  </EntityType>
            // <EntityContainer Name="DefaultContainer">
            //      <Singleton Name="Company" Type="ODataSamples.Features.Singleton.Company" />
            // </EntityContainer>
            //</Schema>
            EdmModel model = BuildEdmModel();

            // Parse the URI of singleton
            Uri              queryUri         = new Uri(ServiceRootUri, "Company");
            ODataPath        queryPath        = ParsePath(model, queryUri);
            SingletonSegment singletonSegment = queryPath.LastSegment as SingletonSegment;

            //Write singleton payload to stream
            //Json Light payload:
            //{
            //      "@odata.context":"http://samples.odata.org/sample/$metadata#Company",
            //      "@odata.id":"Company",
            //      "@odata.editLink":"Company",
            //      "CompanyID":1,
            //      "Name":"Wonderland",
            //      "EmployeesCount":1000
            //}
            WriteODataEntry(model, stream, singletonSegment, queryPath);

            stream.Seek(0, SeekOrigin.Begin);

            // Read singleton from stream
            var entry = ReadODataEntry(model, stream);

            Console.WriteLine(entry.Properties.Single(p => p.Name == "Name").Value);

            Console.ReadLine();
        }
示例#22
0
        public void ODataPathSegmentHandler_Handles_SingletonSegment()
        {
            // Arrange
            ODataPathSegmentHandler handler = new ODataPathSegmentHandler();

            EdmEntityContainer entityContainer = new EdmEntityContainer("NS", "Default");
            EdmEntityType      customer        = new EdmEntityType("NS", "Customer");
            EdmSingleton       me      = entityContainer.AddSingleton("me", customer);
            SingletonSegment   segment = new SingletonSegment(me);

            // Act
            handler.Handle(segment);

            // Assert
            Assert.Equal("me", handler.PathLiteral);
            Assert.Same(me, handler.NavigationSource);
        }
示例#23
0
        public void ODataPathSegmentToTemplateHandler_Handles_Singleton()
        {
            // Arrange
            ODataPathSegmentToTemplateHandler handler = new ODataPathSegmentToTemplateHandler(null);

            EdmEntityContainer entityContainer = new EdmEntityContainer("NS", "Default");
            EdmEntityType      customer        = new EdmEntityType("NS", "Customer");
            EdmSingleton       me      = entityContainer.AddSingleton("me", customer);
            SingletonSegment   segment = new SingletonSegment(me);

            // Act
            handler.Handle(segment);

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

            Assert.IsType <SingletonSegmentTemplate>(segmentTemplate);
        }
        public void TryMatch_ReturnsFalse()
        {
            // Arrange
            EdmEntityType       entityType = new EdmEntityType("NS", "entity");
            IEdmEntityContainer container  = new EdmEntityContainer("NS", "default");
            IEdmSingleton       singleton1 = new EdmSingleton(container, "singleton1", entityType);
            IEdmSingleton       singleton2 = new EdmSingleton(container, "singleton2", entityType);

            SingletonSegmentTemplate template = new SingletonSegmentTemplate(new SingletonSegment(singleton1));
            SingletonSegment         segment  = new SingletonSegment(singleton2);

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

            // Assert
            Assert.False(result);
        }
        public void TryTranslateSingletonSegmentTemplate_ReturnsSingletonSegment()
        {
            // Arrange
            EdmEntityType       entityType = new EdmEntityType("NS", "entity");
            IEdmEntityContainer container  = new EdmEntityContainer("NS", "default");
            IEdmSingleton       singleton  = new EdmSingleton(container, "singleton", entityType);

            ODataTemplateTranslateContext context  = new ODataTemplateTranslateContext();
            SingletonSegmentTemplate      template = new SingletonSegmentTemplate(new SingletonSegment(singleton));

            // Act
            Assert.True(template.TryTranslate(context));

            // Assert
            ODataPathSegment segment           = Assert.Single(context.Segments);
            SingletonSegment singletonTemplate = Assert.IsType <SingletonSegment>(segment);

            Assert.Same(singleton, singletonTemplate.Singleton);
        }
        /// <inheritdoc/>
        public virtual ActionDescriptor SelectAction(RouteContext routeContext)
        {
            if (routeContext == null)
            {
                throw Error.ArgumentNull("routeContext");
            }

            ODataPath odataPath = routeContext.HttpContext.Request.ODataFeature().Path;

            string controllerName = null;

            // entity set
            EntitySetSegment entitySetSegment = odataPath.Segments.FirstOrDefault() as EntitySetSegment;

            if (entitySetSegment != null)
            {
                controllerName = entitySetSegment.EntitySet.Name;
            }

            // singleton
            SingletonSegment singletonSegment = odataPath.Segments.FirstOrDefault() as SingletonSegment;

            if (singletonSegment != null)
            {
                controllerName = singletonSegment.Singleton.Name;
            }

            if (String.IsNullOrEmpty(controllerName))
            {
                return(null);
            }

            IActionDescriptorCollectionProvider actionCollectionProvider =
                routeContext.HttpContext.RequestServices.GetRequiredService <IActionDescriptorCollectionProvider>();

            Contract.Assert(actionCollectionProvider != null);

            IEnumerable <ControllerActionDescriptor> actionDescriptors = actionCollectionProvider
                                                                         .ActionDescriptors.Items.OfType <ControllerActionDescriptor>()
                                                                         .Where(c => c.ControllerName == controllerName);

            return(SelectAction(routeContext, actionDescriptors));
        }
示例#27
0
        public void TranslateValueTemplateReturnsAsExpected()
        {
            // Arrange
            EdmEntityType       entityType = new EdmEntityType("NS", "entity");
            IEdmEntityContainer container  = new EdmEntityContainer("NS", "default");
            IEdmSingleton       singleton  = new EdmSingleton(container, "singleton", entityType);

            ODataTemplateTranslateContext context  = new ODataTemplateTranslateContext();
            SingletonSegmentTemplate      template = new SingletonSegmentTemplate(new SingletonSegment(singleton));

            // Act
            ODataPathSegment segment = template.Translate(context);

            // Assert
            Assert.NotNull(segment);
            SingletonSegment singletonTemplate = Assert.IsType <SingletonSegment>(segment);

            Assert.Same(singleton, singletonTemplate.Singleton);
        }
示例#28
0
        /// <summary>
        /// Selects the controller for OData requests.
        /// </summary>
        /// <param name="odataPath">The OData path.</param>
        /// <returns>
        ///   <c>null</c> if the request isn't handled by this convention; otherwise, the name of the selected controller
        /// </returns>
        internal static SelectControllerResult SelectControllerImpl(ODataPath odataPath)
        {
            // entity set
            EntitySetSegment entitySetSegment = odataPath.Segments.FirstOrDefault() as EntitySetSegment;

            if (entitySetSegment != null)
            {
                return(new SelectControllerResult(entitySetSegment.EntitySet.Name, null));
            }

            // singleton
            SingletonSegment singletonSegment = odataPath.Segments.FirstOrDefault() as SingletonSegment;

            if (singletonSegment != null)
            {
                return(new SelectControllerResult(singletonSegment.Singleton.Name, null));
            }

            return(null);
        }
        /// <inheritdoc/>
        public override ActionDescriptor SelectAction(RouteContext routeContext, IEnumerable <ControllerActionDescriptor> actionDescriptors)
        {
            if (routeContext == null)
            {
                throw Error.ArgumentNull("routeContext");
            }

            ODataPath   odataPath = routeContext.HttpContext.Request.ODataFeature().Path;
            HttpRequest request   = routeContext.HttpContext.Request;

            if (odataPath.PathTemplate == "~/singleton")
            {
                SingletonSegment singletonSegment = (SingletonSegment)odataPath.Segments[0];
                string           httpMethodName   = GetActionNamePrefix(request.Method);

                if (httpMethodName != null)
                {
                    // e.g. Try Get{SingletonName} first, then fallback on Get action name
                    return(actionDescriptors.FindMatchingAction(
                               httpMethodName + singletonSegment.Singleton.Name,
                               httpMethodName));
                }
            }
            else if (odataPath.PathTemplate == "~/singleton/cast")
            {
                SingletonSegment singletonSegment = (SingletonSegment)odataPath.Segments[0];
                IEdmEntityType   entityType       = (IEdmEntityType)odataPath.EdmType;
                string           httpMethodName   = GetActionNamePrefix(request.Method);

                if (httpMethodName != null)
                {
                    // e.g. Try Get{SingletonName}From{EntityTypeName} first, then fallback on Get action name
                    return(actionDescriptors.FindMatchingAction(
                               httpMethodName + singletonSegment.Singleton.Name + "From" + entityType.Name,
                               httpMethodName + "From" + entityType.Name));
                }
            }

            return(null);
        }
        public Task ReadRequestBodyAsyncReadsDataButDoesNotCloseStreamWhenContentLengthl()
        {
            // Arrange
            byte[] expectedSampleTypeByte = Encoding.UTF8.GetBytes(
                "{" +
                "\"@odata.context\":\"http://localhost/$metadata#Customers/$entity\"," +
                "\"Number\":42" +
                "}");

            IEdmSingleton    singleton    = _edmModel.EntityContainer.FindSingleton("Me");
            SingletonSegment singletonSeg = new SingletonSegment(singleton);

            ODataInputFormatter formatter = GetInputFormatter();

            formatter.BaseAddressFactory = (request) => new Uri("http://localhost");

            HttpContext httpContext = GetHttpContext(expectedSampleTypeByte, opt => opt.AddModel("odata", _edmModel));

            httpContext.Request.ContentType   = "application/json;odata.metadata=minimal";
            httpContext.Request.ContentLength = expectedSampleTypeByte.Length;
            httpContext.ODataFeature().Model      = _edmModel;
            httpContext.ODataFeature().PrefixName = "odata";
            httpContext.ODataFeature().Path       = new ODataPath(singletonSeg);
            Stream memStream = httpContext.Request.Body;

            InputFormatterContext formatterContext = CreateInputFormatterContext(typeof(Customer), httpContext);

            // Act
            return(formatter.ReadRequestBodyAsync(formatterContext, Encoding.UTF8).ContinueWith(
                       readTask =>
            {
                // Assert
                Assert.Equal(TaskStatus.RanToCompletion, readTask.Status);
                Assert.True(memStream.CanRead);

                var value = Assert.IsType <Customer>(readTask.Result.Model);
                Assert.Equal(42, value.Number);
            }));
        }
示例#31
0
 /// <summary>
 /// Translate an SingletonSegment
 /// </summary>
 /// <param name="segment">the segment to Translate</param>
 /// <returns>Translated odata path segment.</returns>
 public override ODataPathSegment Translate(SingletonSegment segment)
 {
     return(segment);
 }
示例#32
0
        public override void Handle(SingletonSegment segment)
        {
            this.ThrowIfResolved();

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

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

            this.canonicalSegments.Clear();
            this.canonicalSegments.Add(segment);
        }
示例#33
0
 /// <summary>
 /// Handle an SingletonSegment
 /// </summary>
 /// <param name="segment">the segment to Handle</param>
 public virtual void Handle(SingletonSegment segment)
 {
     throw new NotImplementedException();
 }
示例#34
0
        /// <summary>
        /// Tries to parse a segment as an entity set or singleton.
        /// </summary>
        /// <param name="identifier">The name of the segment</param>
        /// <param name="parenthesisExpression">The parenthesis expression</param>
        /// <returns>Whether or not the identifier referred to an entity set or singleton.</returns>
        private bool TryCreateSegmentForNavigationSource(string identifier, string parenthesisExpression)
        {
            ODataPathSegment segment = null;
            IEdmEntitySet targetEdmEntitySet;
            IEdmSingleton targetEdmSingleton;

            IEdmNavigationSource source = this.configuration.Resolver.ResolveNavigationSource(this.configuration.Model, identifier);

            if ((targetEdmEntitySet = source as IEdmEntitySet) != null)
            {
                segment = new EntitySetSegment(targetEdmEntitySet) { Identifier = identifier };
            }
            else if ((targetEdmSingleton = source as IEdmSingleton) != null)
            {
                segment = new SingletonSegment(targetEdmSingleton) { Identifier = identifier };
            }

            if (segment != null)
            {
                this.parsedSegments.Add(segment);
                this.TryBindKeyFromParentheses(parenthesisExpression);
                return true;
            }

            return false;
        }
示例#35
0
        private void RemoveRedundantContainingPathSegments()
        {
            // Find the last non-contained navigation property segment:
            //   Collection valued: entity set
            //   -or-
            //   Single valued: singleton
            // Copy over other path segments such as: not a navigation path segment, contained navigation property,
            // single valued navigation property with navigation source targetting an entity set (we won't have key
            // information for that navigation property.)
            _segments.Reverse();
            NavigationPropertySegment navigationPropertySegment = null;
            List<ODataPathSegment> newSegments = new List<ODataPathSegment>();
            foreach (ODataPathSegment segment in _segments)
            {
                navigationPropertySegment = segment as NavigationPropertySegment;
                if (navigationPropertySegment != null)
                {
                    EdmNavigationSourceKind navigationSourceKind =
                        navigationPropertySegment.NavigationSource.NavigationSourceKind();
                    if ((navigationPropertySegment.NavigationProperty.TargetMultiplicity() == EdmMultiplicity.Many &&
                         navigationSourceKind == EdmNavigationSourceKind.EntitySet) ||
                        (navigationSourceKind == EdmNavigationSourceKind.Singleton))
                    {
                        break;
                    }
                }

                newSegments.Insert(0, segment);
            }

            // Start the path with the navigation source of the navigation property found above.
            if (navigationPropertySegment != null)
            {
                IEdmNavigationSource navigationSource = navigationPropertySegment.NavigationSource;
                Contract.Assert(navigationSource != null);
                if (navigationSource.NavigationSourceKind() == EdmNavigationSourceKind.Singleton)
                {
                    SingletonSegment singletonSegment = new SingletonSegment((IEdmSingleton)navigationSource);
                    newSegments.Insert(0, singletonSegment);
                }
                else
                {
                    Contract.Assert(navigationSource.NavigationSourceKind() == EdmNavigationSourceKind.EntitySet);
                    EntitySetSegment entitySetSegment = new EntitySetSegment((IEdmEntitySet)navigationSource);
                    newSegments.Insert(0, entitySetSegment);
                }
            }

            _segments = newSegments;
        }