Exemplo n.º 1
0
        public static string ToUriLiteral(this OperationImportSegment segment)
        {
            if (segment == null)
            {
                throw Error.ArgumentNull("segment");
            }

            IEdmActionImport action = segment.OperationImports.Single() as IEdmActionImport;

            if (action != null)
            {
                return(action.Name);
            }
            else
            {
                // Translate the nodes in ODL path to string literals as parameter of BoundFunctionPathSegment.
                Dictionary <string, string> parameterValues = segment.Parameters.ToDictionary(
                    parameterValue => parameterValue.Name,
                    parameterValue => TranslateNode(parameterValue.Value));

                // TODO: refactor the function literal for parameter alias
                IEdmFunctionImport function = (IEdmFunctionImport)segment.OperationImports.Single();

                IEnumerable <string> parameters = parameterValues.Select(v => String.Format(CultureInfo.InvariantCulture, "{0}={1}", v.Key, v.Value));
                return(String.Format(CultureInfo.InvariantCulture, "{0}({1})", function.Name, String.Join(",", parameters)));
            }
        }
        /// <summary>
        /// Handle a OperationImportSegment
        /// </summary>
        /// <param name="segment">the segment to Handle</param>
        public override void Handle(OperationImportSegment segment)
        {
            Contract.Assert(segment != null);

            NavigationSource = segment.EntitySet;

            IEdmActionImport actionImport = segment.OperationImports.Single() as IEdmActionImport;

            if (actionImport != null)
            {
                _path.Add(actionImport.Name);
            }
            else
            {
                IEdmFunctionImport function = (IEdmFunctionImport)segment.OperationImports.Single();

                IList <string> parameterValues = new List <string>();
                foreach (var parameter in segment.Parameters)
                {
                    var functionParameter = function.Function.Parameters.FirstOrDefault(p => p.Name == parameter.Name);
                    if (functionParameter == null)
                    {
                        continue;
                    }

                    parameterValues.Add(functionParameter.Type.FullName());
                }

                string literal = string.Format(CultureInfo.InvariantCulture, "{0}({1})", function.Name, string.Join(",", parameterValues));

                _path.Add(literal);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Handle a OperationImportSegment
        /// </summary>
        /// <param name="segment">the segment to Handle</param>
        public override void Handle(OperationImportSegment segment)
        {
            _navigationSource = segment.EntitySet;

            IEdmActionImport actionImport = segment.OperationImports.Single() as IEdmActionImport;

            if (actionImport != null)
            {
                _pathTemplate.Add(ODataSegmentKinds.UnboundAction); // unbound action
                _pathUriLiteral.Add(actionImport.Name);
            }
            else
            {
                _pathTemplate.Add(ODataSegmentKinds.UnboundFunction); // unbound function

                // Translate the nodes in ODL path to string literals as parameter of UnboundFunctionPathSegment.
                Dictionary <string, string> parameterValues = segment.Parameters.ToDictionary(
                    parameterValue => parameterValue.Name,
                    parameterValue => TranslateNode(parameterValue.Value));

                IEdmFunctionImport function = (IEdmFunctionImport)segment.OperationImports.Single();

                IEnumerable <string> parameters = parameterValues.Select(v => String.Format(CultureInfo.InvariantCulture, "{0}={1}", v.Key, v.Value));
                string literal = String.Format(CultureInfo.InvariantCulture, "{0}({1})", function.Name, String.Join(",", parameters));

                _pathUriLiteral.Add(literal);
            }
        }
Exemplo n.º 4
0
        public async Task Posting_NonDerivedType_To_Action_Expecting_BaseType_Throws()
        {
            // Arrange
            StringContent        content      = new StringContent("{ '@odata.type' : '#Microsoft.AspNet.OData.Test.Builder.TestModels.Motorcycle' }");
            var                  headers      = FormatterTestHelper.GetContentHeaders("application/json");
            IODataRequestMessage oDataRequest = ODataMessageWrapperHelper.Create(await content.ReadAsStreamAsync(), headers);
            ODataMessageReader   reader       = new ODataMessageReader(oDataRequest, new ODataMessageReaderSettings(), _model);

            ODataDeserializerProvider deserializerProvider = ODataDeserializerProviderFactory.Create();

            ODataDeserializerContext context = new ODataDeserializerContext {
                Model = _model
            };
            IEdmActionImport action = _model.EntityContainer
                                      .OperationImports()
                                      .Single(f => f.Name == "PostMotorcycle_When_Expecting_Car") as IEdmActionImport;

            Assert.NotNull(action);
            IEdmEntitySetBase actionEntitySet;

            action.TryGetStaticEntitySet(_model, out actionEntitySet);
            context.Path = new ODataPath(new OperationImportSegment(new[] { action }, actionEntitySet, null));

            // Act & Assert
            ExceptionAssert.Throws <ODataException>(
                () => new ODataResourceDeserializer(deserializerProvider).Read(reader, typeof(Car), context),
                "A resource with type 'Microsoft.AspNet.OData.Test.Builder.TestModels.Motorcycle' was found, " +
                "but it is not assignable to the expected type 'Microsoft.AspNet.OData.Test.Builder.TestModels.Car'. " +
                "The type specified in the resource must be equal to either the expected type or a derived type.");
        }
        public static IEdmAction GetUnboundAction(string actionName)
        {
            IEdmActionImport actionImport = _container.OperationImports().SingleOrDefault(a => a.Name == actionName) as IEdmActionImport;

            Assert.NotNull(actionImport); // Guard
            return(actionImport.Action);
        }
Exemplo n.º 6
0
        public void CanCreateEdmModel_WithNonBindableAction()
        {
            // Arrange
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock <ODataModelBuilder>();

            // Act
            ActionConfiguration actionConfiguration = builder.Action("ActionName");

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

            IEdmModel model = builder.GetEdmModel();

            // Assert
            IEdmEntityContainer container = model.EntityContainer;

            Assert.NotNull(container);
            Assert.Equal(1, container.Elements.OfType <IEdmActionImport>().Count());
            Assert.Equal(1, container.Elements.OfType <IEdmEntitySet>().Count());
            IEdmActionImport action = container.Elements.OfType <IEdmActionImport>().Single();

            Assert.False(action.Action.IsBound);
            Assert.Equal("ActionName", action.Name);
            Assert.NotNull(action.Action.ReturnType);
            Assert.NotNull(action.EntitySet);
            Assert.Equal("Customers", (action.EntitySet as IEdmEntitySetReferenceExpression).ReferencedEntitySet.Name);
            Assert.Equal(
                typeof(Customer).FullName,
                (action.EntitySet as IEdmEntitySetReferenceExpression).ReferencedEntitySet.EntityType().FullName());
            Assert.Empty(action.Action.Parameters);
        }
        public OpenApiRequestBodyGeneratorTest()
        {
            EdmModel           model     = new EdmModel();
            EdmEntityContainer container = new EdmEntityContainer("NS", "Default");

            model.AddElement(container);

            EdmEntityType customer = new EdmEntityType("NS", "Customer", null, false, false, true);

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

            var boolType = EdmCoreModel.Instance.GetBoolean(false);

            var actionEntitySetPath = new EdmPathExpression("Param1/Nav");
            var edmAction           = new EdmAction("NS", "Checkout", boolType, true, actionEntitySetPath);

            edmAction.AddParameter(new EdmOperationParameter(edmAction, "bindingParameter", new EdmEntityTypeReference(customer, true)));
            edmAction.AddParameter("param", EdmCoreModel.Instance.GetString(true));
            model.AddElement(edmAction);

            var actionImportEntitySetPath = new EdmPathExpression("Param1/Nav2");
            var edmActionImport           = new EdmActionImport(container, "CheckoutImport", edmAction, actionImportEntitySetPath);

            container.AddElement(edmActionImport);

            _model        = model;
            _entityType   = customer;
            _action       = edmAction;
            _actionImport = edmActionImport;
        }
Exemplo n.º 8
0
        public void Posting_NonDerivedType_To_Action_Expecting_BaseType_Throws()
        {
            // Arrange
            StringContent content = new StringContent("{ '@odata.type' : '#System.Web.OData.Builder.TestModels.Motorcycle' }");

            content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
            IODataRequestMessage oDataRequest = new ODataMessageWrapper(content.ReadAsStreamAsync().Result, content.Headers);
            ODataMessageReader   reader       = new ODataMessageReader(oDataRequest, new ODataMessageReaderSettings(), _model);

            ODataDeserializerProvider deserializerProvider = DependencyInjectionHelper.GetDefaultODataDeserializerProvider();

            ODataDeserializerContext context = new ODataDeserializerContext {
                Model = _model
            };
            IEdmActionImport action = _model.EntityContainer
                                      .OperationImports()
                                      .Single(f => f.Name == "PostMotorcycle_When_Expecting_Car") as IEdmActionImport;

            Assert.NotNull(action);
            IEdmEntitySetBase actionEntitySet;

            action.TryGetStaticEntitySet(_model, out actionEntitySet);
            context.Path = new ODataPath(new OperationImportSegment(new[] { action }, actionEntitySet, null));

            // Act & Assert
            Assert.Throws <ODataException>(
                () => new ODataResourceDeserializer(deserializerProvider).Read(reader, typeof(Car), context),
                "An resource with type 'System.Web.OData.Builder.TestModels.Motorcycle' was found, " +
                "but it is not assignable to the expected type 'System.Web.OData.Builder.TestModels.Car'. " +
                "The type specified in the resource must be equal to either the expected type or a derived type.");
        }
        /// <summary>
        /// Create the <see cref="OpenApiPaths"/>
        /// </summary>
        /// <returns>the paths object.</returns>
        public OpenApiPaths Generate()
        {
            if (_paths == null)
            {
                _paths = new OpenApiPaths();

                if (Model.EntityContainer != null)
                {
                    foreach (var element in Model.EntityContainer.Elements)
                    {
                        switch (element.ContainerElementKind)
                        {
                        case EdmContainerElementKind.EntitySet:
                            IEdmEntitySet entitySet = element as IEdmEntitySet;
                            if (entitySet != null)
                            {
                                foreach (var item in _nsGenerator.CreatePaths(entitySet))
                                {
                                    _paths.Add(item.Key, item.Value);
                                }
                            }
                            break;

                        case EdmContainerElementKind.Singleton:
                            IEdmSingleton singleton = element as IEdmSingleton;
                            if (singleton != null)
                            {
                                foreach (var item in _nsGenerator.CreatePaths(singleton))
                                {
                                    _paths.Add(item.Key, item.Value);
                                }
                            }
                            break;

                        case EdmContainerElementKind.FunctionImport:
                            IEdmFunctionImport functionImport = element as IEdmFunctionImport;
                            if (functionImport != null)
                            {
                                var functionImportPathItem = functionImport.CreatePathItem();

                                _paths.Add(functionImport.CreatePathItemName(), functionImportPathItem);
                            }
                            break;

                        case EdmContainerElementKind.ActionImport:
                            IEdmActionImport actionImport = element as IEdmActionImport;
                            if (actionImport != null)
                            {
                                var functionImportPathItem = actionImport.CreatePathItem();
                                _paths.Add(actionImport.CreatePathItemName(), functionImportPathItem);
                            }
                            break;
                        }
                    }
                }
            }

            return(_paths);
        }
        private static ActionImportSegmentTemplate GetSegmentTemplate(out IEdmActionImport actionImport)
        {
            EdmEntityContainer container = new EdmEntityContainer("NS", "default");
            EdmAction          action    = new EdmAction("NS", "action", null);

            actionImport = new EdmActionImport(container, "actionImport", action);
            return(new ActionImportSegmentTemplate(actionImport, null));
        }
Exemplo n.º 11
0
        private static OperationImportSegment BuildSegment(IEdmActionImport actionImport, IEdmNavigationSource navigationSource)
        {
            if (actionImport == null)
            {
                throw Error.ArgumentNull(nameof(actionImport));
            }

            return(new OperationImportSegment(actionImport, navigationSource as IEdmEntitySetBase));
        }
Exemplo n.º 12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UnboundActionPathSegment" /> class.
        /// </summary>
        /// <param name="action">The action being invoked.</param>
        public UnboundActionPathSegment(IEdmActionImport action)
        {
            if (action == null)
            {
                throw Error.ArgumentNull("action");
            }

            Action     = action;
            ActionName = Action.Name;
        }
        protected override void SetRequestBody(OpenApiOperation operation)
        {
            IEdmActionImport actionImport = EdmOperationImport as IEdmActionImport;

            // The requestBody field contains a Request Body Object describing the structure of the request body.
            // Its schema value follows the rules for Schema Objects for complex types, with one property per action parameter.
            operation.RequestBody = Context.CreateRequestBody(actionImport);

            base.SetRequestBody(operation);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ActionPathSegment" /> class.
        /// </summary>
        /// <param name="action">The action being invoked.</param>
        public ActionPathSegment(IEdmActionImport action)
        {
            if (action == null)
            {
                throw Error.ArgumentNull("action");
            }

            Action = action;
            ActionName = Action.Container.FullName() + "." + Action.Name;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="UnboundActionPathSegment" /> class.
        /// </summary>
        /// <param name="action">The action being invoked.</param>
        public UnboundActionPathSegment(IEdmActionImport action)
        {
            if (action == null)
            {
                throw Error.ArgumentNull("action");
            }

            Action = action;
            ActionName = Action.Name;
        }
Exemplo n.º 16
0
        public void Ctor_TakingAction_InitializesActionNameProperty()
        {
            // Arrange
            IEdmActionImport action = _container.FindOperationImports("CreateCustomer").SingleOrDefault() as IEdmActionImport;

            // Act
            UnboundActionPathSegment actionPathSegment = new UnboundActionPathSegment(action);

            // Assert
            Assert.Equal("CreateCustomer", actionPathSegment.ActionName);
        }
Exemplo n.º 17
0
        public void GetEdmType_ReturnsNull_UnboundAction()
        {
            // Arrange
            IEdmActionImport action = _container.FindOperationImports("ActionWithoutReturn").SingleOrDefault() as IEdmActionImport;

            // Act
            UnboundActionPathSegment segment = new UnboundActionPathSegment(action);
            var result = segment.GetEdmType(previousEdmType: null);

            // Assert
            Assert.Null(result);
        }
Exemplo n.º 18
0
        public ODataSwaggerUtilitiesTest()
        {
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();
            _customer = model.Customer;
            _customers = model.Customers;

            IEdmAction action = new EdmAction("NS", "GetCustomers", null, false, null);
            _getCustomers = new EdmActionImport(model.Container, "GetCustomers", action);

            _isAnyUpgraded = model.Model.SchemaElements.OfType<IEdmFunction>().FirstOrDefault(e => e.Name == "IsAnyUpgraded");
            _isCustomerUpgradedWithParam = model.Model.SchemaElements.OfType<IEdmFunction>().FirstOrDefault(e => e.Name == "IsUpgradedWithParam");
        }
Exemplo n.º 19
0
        public void ToString_ReturnsActionName()
        {
            // Arrange
            IEdmActionImport         action  = _container.FindOperationImports("CreateCustomer").SingleOrDefault() as IEdmActionImport;
            UnboundActionPathSegment segment = new UnboundActionPathSegment(action);

            // Act
            var result = segment.ToString();

            // Assert
            Assert.Equal("CreateCustomer", result);
        }
Exemplo n.º 20
0
        public void GetNavigationSource_ReturnsNull_UnboundActionPrimitveReturnType()
        {
            // Arrange
            IEdmActionImport         action  = _container.FindOperationImports("MyAction").SingleOrDefault() as IEdmActionImport;
            UnboundActionPathSegment segment = new UnboundActionPathSegment(action);

            // Act
            var result = segment.GetNavigationSource(previousNavigationSource: null);

            // Assert
            Assert.Null(result);
        }
Exemplo n.º 21
0
        public void GetEdmType_ReturnsNotNull_UnboundActionEntityType()
        {
            // Arrange
            IEdmActionImport action = _container.FindOperationImports("CreateCustomer").SingleOrDefault() as IEdmActionImport;

            // Act
            UnboundActionPathSegment segment = new UnboundActionPathSegment(action);
            var result = segment.GetEdmType(previousEdmType: null);

            // Assert
            Assert.NotNull(result);
            Assert.Equal("System.Web.OData.Routing.MyCustomer", result.FullTypeName());
        }
Exemplo n.º 22
0
        public void GetEdmType_ReturnsNotNull_UnboundActionPrimitiveType()
        {
            // Arrange
            IEdmActionImport action = _container.FindOperationImports("MyAction").SingleOrDefault() as IEdmActionImport;

            // Act
            UnboundActionPathSegment segment = new UnboundActionPathSegment(action);
            var result = segment.GetEdmType(previousEdmType: null);

            // Assert
            Assert.NotNull(result);
            Assert.Equal("Edm.String", result.FullTypeName());
        }
Exemplo n.º 23
0
        public override void VisitEntityContainerElements(IEnumerable <IEdmEntityContainerElement> elements)
        {
            HashSet <string> functionImportsWritten = new HashSet <string>();
            HashSet <string> actionImportsWritten   = new HashSet <string>();

            foreach (IEdmEntityContainerElement element in elements)
            {
                switch (element.ContainerElementKind)
                {
                case EdmContainerElementKind.EntitySet:
                    this.ProcessEntitySet((IEdmEntitySet)element);
                    break;

                case EdmContainerElementKind.Singleton:
                    this.ProcessSingleton((IEdmSingleton)element);
                    break;

                case EdmContainerElementKind.ActionImport:
                    // Skip actionImports that have the same name for same overloads of a action.
                    IEdmActionImport actionImport     = (IEdmActionImport)element;
                    string           uniqueActionName = actionImport.Name + "_" + actionImport.Action.FullName() + GetEntitySetString(actionImport);
                    if (!actionImportsWritten.Contains(uniqueActionName))
                    {
                        actionImportsWritten.Add(uniqueActionName);
                        this.ProcessActionImport(actionImport);
                    }

                    break;

                case EdmContainerElementKind.FunctionImport:
                    // Skip functionImports that have the same name for same overloads of a function.
                    IEdmFunctionImport functionImport     = (IEdmFunctionImport)element;
                    string             uniqueFunctionName = functionImport.Name + "_" + functionImport.Function.FullName() + GetEntitySetString(functionImport);
                    if (!functionImportsWritten.Contains(uniqueFunctionName))
                    {
                        functionImportsWritten.Add(uniqueFunctionName);
                        this.ProcessFunctionImport(functionImport);
                    }

                    break;

                case EdmContainerElementKind.None:
                    this.ProcessEntityContainerElement(element);
                    break;

                default:
                    throw new InvalidOperationException(Edm.Strings.UnknownEnumVal_ContainerElementKind(element.ContainerElementKind.ToString()));
                }
            }
        }
Exemplo n.º 24
0
        public ODataSwaggerUtilitiesTest()
        {
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();

            _customer  = model.Customer;
            _customers = model.Customers;

            IEdmAction action = new EdmAction("NS", "GetCustomers", null, false, null);

            _getCustomers = new EdmActionImport(model.Container, "GetCustomers", action);

            _isAnyUpgraded = model.Model.SchemaElements.OfType <IEdmFunction>().FirstOrDefault(e => e.Name == "IsAnyUpgraded");
            _isCustomerUpgradedWithParam = model.Model.SchemaElements.OfType <IEdmFunction>().FirstOrDefault(e => e.Name == "IsUpgradedWithParam");
        }
Exemplo n.º 25
0
        /// <summary>
        /// Parses the first OData segment following the service base URI.
        /// </summary>
        /// <param name="model">The model to use for path parsing.</param>
        /// <param name="segment">The value of the segment to parse.</param>
        /// <param name="segments">The queue of pending segments.</param>
        /// <returns>A parsed representation of the segment.</returns>
        protected virtual ODataPathSegment ParseEntrySegment(IEdmModel model, string segment, Queue <string> segments)
        {
            if (segments == null)
            {
                throw Error.ArgumentNull("segments");
            }
            if (String.IsNullOrEmpty(segment))
            {
                throw Error.Argument(SRResources.SegmentNullOrEmpty);
            }

            if (segment == ODataSegmentKinds.Metadata)
            {
                return(new MetadataPathSegment());
            }
            if (segment == ODataSegmentKinds.Batch)
            {
                return(new BatchPathSegment());
            }

            IEdmEntityContainer container = ExtractEntityContainer(model);
            IEdmEntitySet       entitySet = container.FindEntitySet(segment);

            if (entitySet != null)
            {
                return(new EntitySetPathSegment(entitySet));
            }

            // It's not possible to use a bound function (or action) at root.
            // So, try to match an unbound action call
            IEdmActionImport action = container.FindActionImport(segment);

            if (action != null)
            {
                return(new UnboundActionPathSegment(action));
            }

            // Try to match an unbound function call
            UnboundFunctionPathSegment pathSegment = TryMatchUnboundFunctionCall(segment, segments, model);

            if (pathSegment != null)
            {
                return(pathSegment);
            }

            // segment does not match the model
            return(null);
        }
        internal static IEdmAction GetAction(ODataDeserializerContext readContext)
        {
            if (readContext == null)
            {
                throw Error.ArgumentNull("readContext");
            }

            ODataPath path = readContext.Path;

            if (path == null || path.Segments.Count == 0)
            {
                throw new SerializationException(SRResources.ODataPathMissing);
            }

            IEdmAction action = null;

            if (path.PathTemplate == "~/unboundaction")
            {
                // only one segment, it may be an unbound action
                OperationImportSegment unboundActionSegment = path.Segments.Last() as OperationImportSegment;
                if (unboundActionSegment != null)
                {
                    IEdmActionImport actionImport = unboundActionSegment.OperationImports.First() as IEdmActionImport;
                    if (actionImport != null)
                    {
                        action = actionImport.Action;
                    }
                }
            }
            else
            {
                // otherwise, it may be a bound action
                OperationSegment actionSegment = path.Segments.Last() as OperationSegment;
                if (actionSegment != null)
                {
                    action = actionSegment.Operations.First() as IEdmAction;
                }
            }

            if (action == null)
            {
                string message = Error.Format(SRResources.RequestNotActionInvocation, path.ToString());
                throw new SerializationException(message);
            }

            return(action);
        }
        public string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup <string, HttpActionDescriptor> actionMap)
        {
            //var es = odataPath.Segments.FirstOrDefault(s => s.SegmentKind == "entityset") as EntitySetPathSegment;
            var nav = odataPath.Segments.FirstOrDefault(s => s.SegmentKind == "navigation") as NavigationPathSegment;

            if (odataPath.PathTemplate == "~/unboundaction")
            {
                UnboundActionPathSegment actionSegment = odataPath.Segments.First() as UnboundActionPathSegment;
                if (actionSegment != null)
                {
                    IEdmActionImport action = actionSegment.Action;

                    if (actionMap.Contains(action.Name))
                    {
                        return(action.Name);
                    }
                }
            }
            else if (odataPath.PathTemplate == "~/unboundfunction")
            {
                UnboundFunctionPathSegment functionSegment = odataPath.Segments.First() as UnboundFunctionPathSegment;
                if (functionSegment != null)
                {
                    IEdmFunctionImport function = functionSegment.Function;

                    if (actionMap.Contains(function.Name))
                    {
                        return(function.Name);
                    }
                }
            }

            if (odataPath.PathTemplate == "~/entityset/key/navigation" && nav != null)
            {
                controllerContext.RouteData.Values["key"] = (odataPath.Segments[1] as KeyValuePathSegment).Value;
                return("Get" + nav.NavigationPropertyName);
            }
            else if (odataPath.PathTemplate == "~/entityset/key/navigation/key" && nav != null)
            {
                controllerContext.RouteData.Values["key1"] = (odataPath.Segments[1] as KeyValuePathSegment).Value;
                controllerContext.RouteData.Values["key2"] = (odataPath.Segments[3] as KeyValuePathSegment).Value;
                return("Get" + nav.NavigationProperty.ToEntityType().Name);
            }

            return(null);
        }
        // Determine action from readContext
        // This function is copied from default ODataActionPayloadDeserializer because it cannot be inherited
        private static IEdmAction GetAction(ODataDeserializerContext readContext)
        {
            if (readContext == null)
            {
                throw new ArgumentNullException(nameof(readContext));
            }

            ODataPath path = readContext.Path;

            if (path == null || path.Segments.Count == 0)
            {
                throw new SerializationException("OData Path is missing");
            }

            IEdmAction action = null;

            if (path.PathTemplate == "~/unboundaction")
            {
                // only one segment, it may be an unbound action
                OperationImportSegment unboundActionSegment = path.Segments.Last() as OperationImportSegment;
                if (unboundActionSegment != null)
                {
                    IEdmActionImport actionImport = unboundActionSegment.OperationImports.First() as IEdmActionImport;
                    if (actionImport != null)
                    {
                        action = actionImport.Action;
                    }
                }
            }
            else
            {
                // otherwise, it may be a bound action
                OperationSegment actionSegment = path.Segments.Last() as OperationSegment;
                if (actionSegment != null)
                {
                    action = actionSegment.Operations.First() as IEdmAction;
                }
            }

            if (action == null)
            {
                throw new SerializationException("Request is not an action invocation");
            }

            return(action);
        }
Exemplo n.º 29
0
        public static void SetResourcePathCoreAnnotation(this EdmModel model, IEdmActionImport import, string url)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }
            if (import == null)
            {
                throw new ArgumentNullException("import");
            }
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }

            model.SetCoreAnnotation(import, ResourcePathTerm, url);
        }
Exemplo n.º 30
0
        /*
         * private static object TranslateKeyValue(object value)
         * {
         *  UriTemplateExpression uriTemplateExpression = value as UriTemplateExpression;
         *  if (uriTemplateExpression != null)
         *  {
         *      return uriTemplateExpression.LiteralText;
         *  }
         *
         *  return value;
         * }*/

        /// <summary>
        /// Translate a OperationImportSegment
        /// </summary>
        /// <param name="segment">the segment to Translate</param>
        /// <returns>Translated odata path segment.</returns>
        public override ODataPathSegment Translate(OperationImportSegment segment)
        {
            IEdmActionImport actionImport = segment.OperationImports.Single() as IEdmActionImport;

            if (actionImport != null)
            {
                return(segment);
            }

            OperationImportSegment newSegment = segment;

            if (segment.Parameters.Any(p => p.Value is ParameterAliasNode || p.Value is ConvertNode))
            {
                var newParameters =
                    segment.Parameters.Select(e => new OperationSegmentParameter(e.Name, TranslateNode(e.Value)));
                newSegment = new OperationImportSegment(segment.OperationImports, segment.EntitySet, newParameters);
            }

            return(newSegment);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Translate a OperationImportSegment
        /// </summary>
        /// <param name="segment">the segment to Translate</param>
        /// <returns>Translated WebApi path segment.</returns>
        public override IEnumerable <ODataPathSegment> Translate(OperationImportSegment segment)
        {
            IEdmActionImport actionImport = segment.OperationImports.Single() as IEdmActionImport;

            if (actionImport != null)
            {
                yield return(new UnboundActionPathSegment(actionImport));
            }
            else
            {
                // Translate the nodes in ODL path to string literals as parameter of UnboundFunctionPathSegment.
                Dictionary <string, string> parameterValues = segment.Parameters.ToDictionary(
                    parameterValue => parameterValue.Name,
                    parameterValue => TranslateNode(parameterValue.Value));

                yield return(new UnboundFunctionPathSegment(
                                 (IEdmFunctionImport)segment.OperationImports.Single(),
                                 _model,
                                 parameterValues));
            }
        }
Exemplo n.º 32
0
        public void MetadataFunctionImportAnnotationsWriterTest()
        {
            // HttpMethod
            var interestingValues = new []
            {
                new { HttpMethod = "GET" },
                new { HttpMethod = "POST" },
                new { HttpMethod = string.Empty },
                new { HttpMethod = "45" },
            };

            EdmModel model     = (EdmModel)Microsoft.Test.OData.Utils.Metadata.TestModels.BuildODataAnnotationTestModel(false);
            var      container = (EdmEntityContainer)model.EntityContainer;

            foreach (var value in interestingValues)
            {
                var action = new EdmAction("TestModel", "ActionImport_" + value.HttpMethod, null, true, null);
                model.AddElement(action);
                IEdmActionImport actionImport = container.AddActionImport(action);
                this.Assert.IsNotNull(actionImport, "Expected to find the function import.");
            }

            MetadataWriterTestDescriptor[] testDescriptors = new MetadataWriterTestDescriptor[]
            {
                new MetadataWriterTestDescriptor(this.Settings)
                {
                    EdmVersion = EdmVersion.V40,
                    Model      = model,
                }
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.DefaultFormatConfigurationsWithIndent
                .Where(tc => tc.Synchronous && !tc.IsRequest),
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor.RunTest(testConfiguration, this.Logger);
            });
        }
Exemplo n.º 33
0
        public void UnboundAction_ForEnumTypeInODataModelBuilder()
        {
            // Arrange
            ODataModelBuilder   builder             = new ODataModelBuilder().Add_Color_EnumType();
            ActionConfiguration actionConfiguration = builder.Action("UnboundAction");

            actionConfiguration.Parameter <Color>("Color");
            actionConfiguration.Returns <Color>();

            // Act & Assert
            IEdmModel        model        = builder.GetEdmModel();
            IEdmActionImport actionImport = model.EntityContainer.OperationImports().Single(o => o.Name == "UnboundAction") as IEdmActionImport;

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

            Assert.False(color.IsNullable);
            Assert.Same(colorType, color.Definition);
            Assert.False(returnType.IsNullable);
            Assert.Same(colorType, returnType.Definition);
        }
 private void TestWriteActionImportElementHeaderMethod(IEdmActionImport actionImport, string expected)
 {
     this.EdmModelCsdlSchemaWriterTest(writer => writer.WriteActionImportElementHeader(actionImport), expected);
 }