コード例 #1
0
        public OperationSerializerTests()
        {
            ResourceType intType = ResourceType.GetPrimitiveResourceType(typeof(int));

            var customerType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "FQ.NS", "Customer", false);
            customerType.CanReflectOnInstanceType = false;
            customerType.AddProperty(new ResourceProperty("Id", ResourcePropertyKind.Primitive | ResourcePropertyKind.Key, intType) { CanReflectOnInstanceTypeProperty = false });
            customerType.SetReadOnly();

            var operation = new ServiceAction("Action", intType, OperationParameterBindingKind.Sometimes, new[] { new ServiceActionParameter("P1", customerType), new ServiceActionParameter("P2", intType) }, null);
            operation.SetReadOnly();
            this.baseTypeOperation = new OperationWrapper(operation);

            var bestCustomerType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, customerType, "FQ.NS", "BestCustomer", false);
            bestCustomerType.SetReadOnly();

            operation = new ServiceAction("Action", intType, OperationParameterBindingKind.Sometimes, new[] { new ServiceActionParameter("P1", bestCustomerType) }, null);
            operation.SetReadOnly();
            this.derivedTypeOperation = new OperationWrapper(operation);

            operation = new ServiceAction("Unambiguous", intType, OperationParameterBindingKind.Sometimes, new[] { new ServiceActionParameter("P1", customerType) }, null);
            operation.SetReadOnly();
            this.unambiguousOperation = new OperationWrapper(operation);

            this.entityToSerialize = EntityToSerialize.CreateFromExplicitValues(new object(), bestCustomerType, new TestSerializedEntityKey("http://odata.org/Service.svc/Customers(0)/", bestCustomerType.FullName));

            this.testSubject = CreateOperationSerializer(AlwaysAdvertiseActions);
        }
コード例 #2
0
 /// <summary>
 /// Initializes a new instance of the TestDataServiceInvokable class
 /// </summary>
 /// <param name="dataServiceInstance">Data Service Instance</param>
 /// <param name="dataServiceOperationContext">Data Service Operation Context</param>
 /// <param name="serviceAction">Service Action</param>
 /// <param name="parameters">Parameters to use</param>
 public TestDataServiceInvokable(object dataServiceInstance, DataServiceOperationContext dataServiceOperationContext, ServiceAction serviceAction, object[] parameters)
 {
     this.dataServiceOperationContext = dataServiceOperationContext;
     this.dataServiceInstance = dataServiceInstance;
     this.serviceAction = serviceAction;
     this.parameters = parameters;
 }
コード例 #3
0
        public void DataServiceProviderWrapperShouldFailOnMultipleActionsWithSameNameAndBindingType()
        {
            var entityType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "Fake.NS", "Type", false) { CanReflectOnInstanceType = false };
            entityType.AddProperty(new ResourceProperty("Id", ResourcePropertyKind.Key | ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(int))) {CanReflectOnInstanceTypeProperty = false});
            entityType.SetReadOnly();

            var resourceSet = new ResourceSet("MyEntitySet", entityType);
            resourceSet.SetReadOnly();

            ResourceType stringType = ResourceType.GetPrimitiveResourceType(typeof(string));
            var duplicateAction1 = new ServiceAction("Duplicate", stringType, OperationParameterBindingKind.Always, new[] { new ServiceActionParameter("p1", entityType), new ServiceActionParameter("p2", stringType) }, null);
            duplicateAction1.SetReadOnly();
            var duplicateAction2 = new ServiceAction("Duplicate", ResourceType.GetPrimitiveResourceType(typeof(int)), OperationParameterBindingKind.Sometimes, new[] { new ServiceActionParameter("p1", entityType) }, null);
            duplicateAction2.SetReadOnly();

            var actionProvider = new TestActionProvider
            {
                GetServiceActionsCallback = ctx => new[] { duplicateAction1, duplicateAction2 }
            };

            var providerWrapper = CreateProviderWrapper(actionProvider, p => p.AddResourceSet(resourceSet));

            Action getVisibleOperations = () => providerWrapper.GetVisibleOperations().ToList();
            getVisibleOperations.ShouldThrow<DataServiceException>()
                .WithMessage(ErrorStrings.DataServiceActionProviderWrapper_DuplicateAction("Duplicate"))
                .And.StatusCode.Should().Be(500);
        }
コード例 #4
0
        public OperationLinkBuilderTests()
        {
            ResourceType intType = ResourceType.GetPrimitiveResourceType(typeof(int));

            var customerType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "FQ.NS", "Customer", false);
            customerType.CanReflectOnInstanceType = false;
            customerType.AddProperty(new ResourceProperty("Id", ResourcePropertyKind.Primitive | ResourcePropertyKind.Key, intType) { CanReflectOnInstanceTypeProperty = false });
            customerType.SetReadOnly();

            var operation = new ServiceAction("Action", intType, OperationParameterBindingKind.Sometimes, new[] { new ServiceActionParameter("P1", customerType), new ServiceActionParameter("P2", intType) }, null);
            operation.SetReadOnly();
            this.operationWithParameters = new OperationWrapper(operation);

            var typeWithEscapedName = new ResourceType(typeof(object), ResourceTypeKind.ComplexType, null, "FQ NS", "+ /", false);
            typeWithEscapedName.CanReflectOnInstanceType = false;
            typeWithEscapedName.AddProperty(new ResourceProperty("Number", ResourcePropertyKind.Primitive, intType) { CanReflectOnInstanceTypeProperty = false });
            typeWithEscapedName.SetReadOnly();

            operation = new ServiceAction("Action", intType, OperationParameterBindingKind.Sometimes, new[] { new ServiceActionParameter("P1", customerType), new ServiceActionParameter("P2", typeWithEscapedName) }, null);
            operation.SetReadOnly();
            this.operationWithEscapedParameter = new OperationWrapper(operation);

            var bestCustomerType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, customerType, "FQ.NS", "BestCustomer", false);
            bestCustomerType.SetReadOnly();

            operation = new ServiceAction("Action", intType, OperationParameterBindingKind.Sometimes, new[] { new ServiceActionParameter("P1", customerType) }, null);
            operation.SetReadOnly();
            this.operationBoundToBaseType = new OperationWrapper(operation);

            this.entityToSerialize = EntityToSerialize.CreateFromExplicitValues(new object(), bestCustomerType, new TestSerializedEntityKey("http://odata.org/Service.svc/Customers/", bestCustomerType.FullName));

            var metadataUri = new Uri("http://odata.org/Service.svc/$metadata");
            this.testSubject = new OperationLinkBuilder("MyContainer", metadataUri);
        }
コード例 #5
0
        public void Init()
        {
            this.baseType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "Fake.NS", "BaseType", false) {CanReflectOnInstanceType = false};
            this.baseType.AddProperty(new ResourceProperty("Id", ResourcePropertyKind.Key | ResourcePropertyKind.Primitive, ResourceType.GetPrimitiveResourceType(typeof(int))) { CanReflectOnInstanceTypeProperty = false });
            this.baseType.SetReadOnly();
            
            this.entityType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, this.baseType, "Fake.NS", "Type", false) {CanReflectOnInstanceType = false};
            this.entityType.SetReadOnly();

            this.derivedType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, this.entityType, "Fake.NS", "DerivedType", false) { CanReflectOnInstanceType = false };
            this.derivedType.SetReadOnly();

            var resourceSet = new ResourceSet("Set", this.entityType);
            resourceSet.SetReadOnly();
            this.resourceSetWrapper = ResourceSetWrapper.CreateForTests(resourceSet);

            this.action = new ServiceAction("Fake", ResourceType.GetPrimitiveResourceType(typeof(int)), OperationParameterBindingKind.Sometimes, new[] {new ServiceActionParameter("p1", this.entityType)}, null);
            this.action.SetReadOnly();
            this.actionWrapper = new OperationWrapper(action);

            this.derivedAction = new ServiceAction("Fake", ResourceType.GetPrimitiveResourceType(typeof(int)), OperationParameterBindingKind.Sometimes, new[] { new ServiceActionParameter("p1", this.derivedType) }, null);
            this.derivedAction.SetReadOnly();
            this.derivedActionWrapper = new OperationWrapper(derivedAction);

            this.testSubject = new SelectedOperationsCache();
        }
コード例 #6
0
        /// <summary>
        /// Builds up an instance oz <see cref="IDataServiceInvokable"/> for the given <paramref name="serviceAction"/> with the provided <paramref name="parameterTokens"/>.
        /// </summary>
        /// <param name="operationContext">The data service operation context instance.</param>
        /// <param name="serviceAction">The service action to invoke.</param>
        /// <param name="parameterTokens">The parameter tokens required to invoke the service action.</param>
        /// <returns>An instance of <see cref="IDataServiceInvokable"/> to invoke the action with.</returns>
        public IDataServiceInvokable CreateInvokable(DataServiceOperationContext operationContext, ServiceAction serviceAction, object[] parameterTokens)
        {
            if (DataServiceOverrides.ActionProvider.CreateInvokableFunc != null)
            {
                return DataServiceOverrides.ActionProvider.CreateInvokableFunc(operationContext, serviceAction, parameterTokens);
            }

            return new TestDataServiceInvokable(this.dataServiceInstance, operationContext, serviceAction, parameterTokens);
        }
コード例 #7
0
        public bool TryResolveServiceAction(DataServiceOperationContext operationContext, string serviceActionName, out ServiceAction serviceAction)
        {
            if (this.TryResolveServiceActionCallback != null)
            {
                return this.TryResolveServiceActionCallback(operationContext, serviceActionName, out serviceAction);
            }

            throw new NotImplementedException();
        }
コード例 #8
0
        public void MetadataProviderModelShouldGoDirectlyToProviderWhenLookingUpOperationsInSelect()
        {
            var entityType = CreateResourceTypeWithKeyProperties("Id");
            var derivedType = CreateDerivedType("Derived", entityType);
            var veryDerivedType = CreateDerivedType("VeryDerived", derivedType);
            var unrelatedDerivedType = CreateDerivedType("UnrelatedDerived", entityType);
            var action1 = new ServiceAction("Action", null, null, OperationParameterBindingKind.Always, new[] { new ServiceActionParameter("p1", entityType) });
            var action2 = new ServiceAction("Action", null, null, OperationParameterBindingKind.Always, new[] { new ServiceActionParameter("p1", derivedType) });
            var actionWithDifferentName = new ServiceAction("Action2", null, null, OperationParameterBindingKind.Always, new[] { new ServiceActionParameter("p1", derivedType) });
            var action3 = new ServiceAction("Action", null, null, OperationParameterBindingKind.Always, new[] { new ServiceActionParameter("p1", veryDerivedType) });
            action1.SetReadOnly();
            action2.SetReadOnly();
            actionWithDifferentName.SetReadOnly();
            action3.SetReadOnly();
            int calls = 0;
            var actionProvider = new TestActionProvider
                                 {
                                     GetByBindingTypeCallback = (o, t) =>
                                     {
                                         calls++;

                                         if (t == entityType)
                                         {
                                             return new[] { action1 };
                                         }

                                         if (t == derivedType)
                                         {
                                             return new[] { action2, actionWithDifferentName };
                                         }

                                         if (t == veryDerivedType)
                                         {
                                             return new[] { action3 };
                                         }

                                         t.Should().NotBeSameAs(unrelatedDerivedType);
                                         return null;
                                     }};

            var metadataProvider = new DataServiceProviderSimulator();
            metadataProvider.AddResourceType(entityType);
            metadataProvider.AddResourceType(derivedType);
            metadataProvider.AddResourceType(veryDerivedType);
            metadataProvider.AddResourceType(unrelatedDerivedType);
            var model = CreateMetadataProviderEdmModel(metadataProvider, actionProvider);
            var schemaType = (IEdmEntityType)model.EnsureSchemaType(derivedType);
            var result = model.FindDeclaredBoundOperations(schemaType).FilterByName(false, "Action");
            result.Should().NotBeNull();
            result.Should().HaveCount(3);
            result.Should().OnlyContain(f => f.Name == "Action");
            calls.Should().Be(3);
        }
コード例 #9
0
        /// <summary>
        /// Tries to find the <see cref="ServiceAction"/> for the given <paramref name="sericeActionName"/>.
        /// </summary>
        /// <param name="operationContext">operation Context</param>
        /// <param name="serviceActionName">The name of the service action to resolve.</param>
        /// <param name="serviceAction">Returns the service action instance if the resolution is successful; null otherwise.</param>
        /// <returns>true if the resolution is successful; false otherwise.</returns>
        public bool TryResolveServiceAction(DataServiceOperationContext operationContext, string serviceActionName, out ServiceAction serviceAction)
        {
            if (DataServiceOverrides.ActionProvider.TryResolveServiceActionFunc != null)
            {
                DataServiceOverrides.ActionProvider.TryResolveServiceActionFunc(operationContext, serviceActionName);
                serviceAction = DataServiceOverrides.ActionProvider.OutServiceActionTryResolveServiceActionFunc();

                return DataServiceOverrides.ActionProvider.OutReturnTryResolveServiceActionFunc();
            }

            serviceAction = this.GetServiceActionsInternal(operationContext).SingleOrDefault(sa => sa.Name == serviceActionName);

            return serviceAction != null;
        }
コード例 #10
0
        public OperationCacheTests()
        {
            this.entityType1 = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "My.Namespace", "Entity1", false);
            this.entityType2 = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "My.Namespace", "Entity2", false);

            var intType = ResourceType.GetPrimitiveResourceType(typeof(int));
            this.actionWithBindingParameter1 = CreateAction("SameName", intType, this.entityType1);
            this.actionWithBindingParameter2 = CreateAction("SameName", intType, this.entityType2);
            this.serviceOperation = CreateServiceOperation("SameName", intType);

            this.actionWithBindingParameter1.SetReadOnly();
            this.actionWithBindingParameter2.SetReadOnly();
            this.serviceOperation.SetReadOnly();

            this.actionWithBindingParameterWrapper1 = new OperationWrapper(this.actionWithBindingParameter1);
            this.actionWithBindingParameterWrapper2 = new OperationWrapper(this.actionWithBindingParameter2);
            this.serviceOperationWrapper = new OperationWrapper(this.serviceOperation);
        }
コード例 #11
0
        public bool TryResolveServiceAction(DataServiceOperationContext context, ServiceActionResolverArgs resolverArgs, out ServiceAction serviceAction)
        {
            string actionName = resolverArgs.ServiceActionName;
            IEnumerable<ServiceAction> possibleMatches = this.GetServiceActions(context).Where(a => a.Name == actionName);
            if (possibleMatches.Count() == 1)
            {
                serviceAction = possibleMatches.Single();
            }
            else if (resolverArgs.BindingType == null)
            {
                // unbound action
                serviceAction = possibleMatches.SingleOrDefault(a => a.BindingParameter == null);
            }
            else
            {
                serviceAction = possibleMatches.SingleOrDefault(a => a.BindingParameter != null && a.BindingParameter.ParameterType.FullName == resolverArgs.BindingType.FullName);
            }

            return serviceAction != null;
        }
コード例 #12
0
        public void DataServiceProviderWrapperShouldFailOnMultipleActionsWithSameNameAndNoBindingType()
        {
            ResourceType stringType = ResourceType.GetPrimitiveResourceType(typeof(string));
            var duplicateAction1 = new ServiceAction("Duplicate", stringType, OperationParameterBindingKind.Never, new[] { new ServiceActionParameter("p1", stringType) }, null);
            duplicateAction1.SetReadOnly();
            var duplicateAction2 = new ServiceAction("Duplicate", ResourceType.GetPrimitiveResourceType(typeof(int)), OperationParameterBindingKind.Never, new ServiceActionParameter[0], null);
            duplicateAction2.SetReadOnly();

            var actionProvider = new TestActionProvider
            {
                GetServiceActionsCallback = ctx => new[] { duplicateAction1, duplicateAction2 }
            };

            var providerWrapper = CreateProviderWrapper(actionProvider);

            Action getVisibleOperations = () => providerWrapper.GetVisibleOperations().ToList();
            getVisibleOperations.ShouldThrow<DataServiceException>()
                .WithMessage(ErrorStrings.DataServiceActionProviderWrapper_DuplicateAction("Duplicate"))
                .And.StatusCode.Should().Be(500);
        }
コード例 #13
0
 public IDataServiceInvokable CreateInvokable(DataServiceOperationContext operationContext, ServiceAction serviceAction, object[] parameterTokens)
 {
     throw new NotImplementedException();
 }
コード例 #14
0
 public bool AdvertiseServiceAction(DataServiceOperationContext operationContext, ServiceAction serviceAction, object resourceInstance, bool resourceInstanceInFeed, ref ODataAction actionToSerialize)
 {
     throw new NotImplementedException();
 }
コード例 #15
0
        protected override IEnumerable<ServiceAction> LoadServiceActions(IDataServiceMetadataProvider dataServiceMetadataProvider)
        {
            ResourceType productType;
            dataServiceMetadataProvider.TryResolveResourceType("Microsoft.Test.OData.Services.AstoriaDefaultService.Product", out productType);

            ResourceType orderLineType;
            dataServiceMetadataProvider.TryResolveResourceType("Microsoft.Test.OData.Services.AstoriaDefaultService.OrderLine", out orderLineType);

            ResourceType personType;
            dataServiceMetadataProvider.TryResolveResourceType("Microsoft.Test.OData.Services.AstoriaDefaultService.Person", out personType);

            ResourceType employeeType;
            dataServiceMetadataProvider.TryResolveResourceType("Microsoft.Test.OData.Services.AstoriaDefaultService.Employee", out employeeType);

            ResourceType specialEmployeeType;
            dataServiceMetadataProvider.TryResolveResourceType("Microsoft.Test.OData.Services.AstoriaDefaultService.SpecialEmployee", out specialEmployeeType);

            ResourceType contractorType;
            dataServiceMetadataProvider.TryResolveResourceType("Microsoft.Test.OData.Services.AstoriaDefaultService.Contractor", out contractorType);

            //
            // actions with the same name and non-related binding types
            //
            var RetrieveProductActionProduct = new ServiceAction(
                "RetrieveProduct",
                ResourceType.GetPrimitiveResourceType(typeof(int)),
                null,
                OperationParameterBindingKind.Sometimes,
                new[]
                {
                    new ServiceActionParameter("product", productType), 
                });
            RetrieveProductActionProduct.SetReadOnly();
            yield return RetrieveProductActionProduct;

            var RetrieveProductActionOrderLine = new ServiceAction(
                "RetrieveProduct",
                ResourceType.GetPrimitiveResourceType(typeof(int)),
                null,
                OperationParameterBindingKind.Sometimes,
                new[]
                {
                    new ServiceActionParameter("orderLine", orderLineType), 
                });
            RetrieveProductActionOrderLine.SetReadOnly();
            yield return RetrieveProductActionOrderLine;

            //
            // Collection bound actions with the same name
            //
            var increaseSalariesActionEmployee = new ServiceAction(
                "IncreaseSalaries",
                null,
                null,
                OperationParameterBindingKind.Sometimes,
                new[]
                {
                    new ServiceActionParameter("employees", ResourceType.GetEntityCollectionResourceType(employeeType)),
                    new ServiceActionParameter("n", ResourceType.GetPrimitiveResourceType(typeof(int))),
                });
            increaseSalariesActionEmployee.SetReadOnly();
            yield return increaseSalariesActionEmployee;

            var increaseSalariesActionSpecialEmployee = new ServiceAction(
                "IncreaseSalaries",
                null,
                null,
                OperationParameterBindingKind.Sometimes,
                new[]
                {
                    new ServiceActionParameter("specialEmployees", ResourceType.GetEntityCollectionResourceType(specialEmployeeType)),
                    new ServiceActionParameter("n", ResourceType.GetPrimitiveResourceType(typeof(int))),
                });
            increaseSalariesActionSpecialEmployee.SetReadOnly();
            yield return increaseSalariesActionSpecialEmployee;

            //
            // Actions with the same name and base/derived type binding parameters
            //
            var updatePersonInfoAction = new ServiceAction(
                "UpdatePersonInfo",
                null,
                null,
                OperationParameterBindingKind.Never,
                null);
            updatePersonInfoAction.SetReadOnly();
            yield return updatePersonInfoAction;

            var updatePersonInfoActionPerson = new ServiceAction(
                "UpdatePersonInfo",
                null,
                null,
                OperationParameterBindingKind.Sometimes,
                new[]
                {
                    new ServiceActionParameter("person", personType), 
                });
            updatePersonInfoActionPerson.SetReadOnly();
            yield return updatePersonInfoActionPerson;

            var updatePersonInfoActionEmployee = new ServiceAction(
                "UpdatePersonInfo",
                null,
                null,
                OperationParameterBindingKind.Sometimes,
                new[]
                {
                    new ServiceActionParameter("employee", employeeType), 
                });
            updatePersonInfoActionEmployee.SetReadOnly();
            yield return updatePersonInfoActionEmployee;

            var updatePersonInfoActionSpecialEmployee = new ServiceAction(
                "UpdatePersonInfo",
                null,
                null,
                OperationParameterBindingKind.Sometimes,
                new[]
                {
                    new ServiceActionParameter("specialEmployee", specialEmployeeType), 
                });
            updatePersonInfoActionSpecialEmployee.SetReadOnly();
            yield return updatePersonInfoActionSpecialEmployee;

            var updatePersonInfoActionContractor = new ServiceAction(
                "UpdatePersonInfo",
                null,
                null,
                OperationParameterBindingKind.Always,
                new[]
                {
                    new ServiceActionParameter("contractor", contractorType), 
                });
            updatePersonInfoActionContractor.SetReadOnly();
            yield return updatePersonInfoActionContractor;

            //
            // Actions with the same name, base/derived type binding parameters, different non-binding parameters
            //
            var increaseEmployeeSalaryActionEmployee = new ServiceAction(
                "IncreaseEmployeeSalary",
                ResourceType.GetPrimitiveResourceType(typeof(bool)),
                null,
                OperationParameterBindingKind.Sometimes,
                new[]
                {
                    new ServiceActionParameter("employee", employeeType),
                    new ServiceActionParameter("n", ResourceType.GetPrimitiveResourceType(typeof(int))),
                });
            increaseEmployeeSalaryActionEmployee.SetReadOnly();
            yield return increaseEmployeeSalaryActionEmployee;

            var increaseEmployeeSalaryActionSpecialEmployee = new ServiceAction(
                "IncreaseEmployeeSalary",
                ResourceType.GetPrimitiveResourceType(typeof(int)),
                null,
                OperationParameterBindingKind.Sometimes,
                new[]
                {
                    new ServiceActionParameter("specialEmployee", specialEmployeeType),
                });
            increaseEmployeeSalaryActionSpecialEmployee.SetReadOnly();
            yield return increaseEmployeeSalaryActionSpecialEmployee;
        }
コード例 #16
0
        public bool AdvertiseServiceAction(DataServiceOperationContext operationContext, ServiceAction serviceAction, object resourceInstance, bool resourceInstanceInFeed, ref ODataAction actionToSerialize)
        {
            if (DataServiceOverrides.ActionProvider.AdvertiseServiceActionFunc != null)
            {
                DataServiceOverrides.ActionProvider.AdvertiseServiceActionFunc(operationContext, serviceAction, resourceInstance, resourceInstanceInFeed, actionToSerialize);

                if (DataServiceOverrides.ActionProvider.OutODataActionAdvertiseServiceFunc != null)
                {
                    actionToSerialize = DataServiceOverrides.ActionProvider.OutODataActionAdvertiseServiceFunc();
                }

                return DataServiceOverrides.ActionProvider.OutReturnAdvertiseServiceFunc();
            }

            return true;
        }
コード例 #17
0
 public MyDSPInvokableAction(DataServiceOperationContext operationContext, Provider.ServiceAction action, object[] parameters)
 {
     this.action = action;
     this.parameters = parameters;
 }
コード例 #18
0
            /// <summary>
            /// Determines whether a given <paramref name="serviceAction"/> should be advertised as bindable to the given <paramref name="resourceInstance"/>.
            /// </summary>
            /// <param name="operationContext">The data service operation context instance.</param>
            /// <param name="serviceAction">Service action to be advertised.</param>
            /// <param name="resourceInstance">Instance of the resource to which the service action is bound.</param>
            /// <param name="resourceInstanceInFeed">true if the resource instance to be serialized is inside a feed; false otherwise. The value true
            /// suggests that this method might be called many times during serialization since it will get called once for every resource instance inside
            /// the feed. If it is an expensive operation to determine whether to advertise the service action for the <paramref name="resourceInstance"/>,
            /// the provider may choose to always advertise in order to optimize for performance.</param>
            /// <param name="actionToSerialize">The <see cref="ODataAction"/> to be serialized. The server constructs 
            /// the version passed into this call, which may be replaced by an implementation of this interface.
            /// This should never be set to null unless returning false.</param>
            /// <returns>true if the service action should be advertised; false otherwise.</returns>
            public override bool AdvertiseServiceAction(DataServiceOperationContext operationContext, ServiceAction serviceAction, object resourceInstance, bool resourceInstanceInFeed, ref ODataAction actionToSerialize)
            {
                if (SubstituteAdvertiseServiceAction != null)
                {
                    return SubstituteAdvertiseServiceAction(operationContext, serviceAction, resourceInstance, resourceInstanceInFeed, ref actionToSerialize);
                }

                return base.AdvertiseServiceAction(operationContext, serviceAction, resourceInstance, resourceInstanceInFeed, ref actionToSerialize);
            }
コード例 #19
0
        public void ServiceActionConstructorTests()
        {
            ResourceProperty id = new ResourceProperty("ID", ResourcePropertyKind.Primitive | ResourcePropertyKind.Key, ResourceType.GetPrimitiveResourceType(typeof(int)));
            ResourceType customerType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "Foo", "Customer", false);
            customerType.AddProperty(id);
            customerType.SetReadOnly();
            ResourceSet customerSet = new ResourceSet("Customers", customerType);
            ResourceType orderType = new ResourceType(typeof(object), ResourceTypeKind.EntityType, null, "Foo", "Order", false);
            orderType.AddProperty(id);
            orderType.SetReadOnly();

            ResourceType complexType = new ResourceType(typeof(object), ResourceTypeKind.ComplexType, null, "foo", "Address", false);
            ResourceType collectionOfPrimitive = ResourceType.GetCollectionResourceType(ResourceType.GetPrimitiveResourceType(typeof(int)));
            ResourceType collectionOfComplex = ResourceType.GetCollectionResourceType(complexType);
            ResourceType collectionOfCustomer = ResourceType.GetEntityCollectionResourceType(customerType);
            ResourceType collectionOfOrder = ResourceType.GetEntityCollectionResourceType(orderType);

            var types = ResourceTypeUtils.GetPrimitiveResourceTypes().Concat(new ResourceType[] { null, customerType, orderType, complexType, collectionOfPrimitive, collectionOfComplex, collectionOfCustomer, collectionOfOrder });
            var resultSetsOrPathExpressions = new object[] { null, customerSet, new ResourceSetPathExpression("p1/Foo") };
            var parameters = types.Except(new[] { ResourceType.GetPrimitiveResourceType(typeof(System.IO.Stream)) }).Select(t => t != null ? new ServiceActionParameter[] { new ServiceActionParameter("p1", t) } : new ServiceActionParameter[0]);
            parameters = parameters.Concat(types.Except(new[] { ResourceType.GetPrimitiveResourceType(typeof(System.IO.Stream)), null }).ToList().Combinations(2).Select(tt => new ServiceActionParameter[] { new ServiceActionParameter("p1", tt[0]), new ServiceActionParameter("p2", tt[1]) }));
            var operationParameterBindings = new OperationParameterBindingKind[] { OperationParameterBindingKind.Never, OperationParameterBindingKind.Sometimes, OperationParameterBindingKind.Always };

            AstoriaTestNS.TestUtil.RunCombinations(
                types, resultSetsOrPathExpressions, parameters, operationParameterBindings,
                (returnType, resultSetOrPathExpression, paramList, operationParameterBindingKind) =>
            {
                ServiceAction action = null;
                ResourceSet resourceSet = resultSetOrPathExpression as ResourceSet;
                ResourceSetPathExpression pathExpression = resultSetOrPathExpression as ResourceSetPathExpression;
                bool bindable = (operationParameterBindingKind == OperationParameterBindingKind.Always || operationParameterBindingKind == OperationParameterBindingKind.Sometimes);
                Exception e = null;

                try
                {
                    if (pathExpression != null)
                    {
                        bindable = true;
                        action = new ServiceAction("foo", returnType, OperationParameterBindingKind.Sometimes, paramList, pathExpression);
                    }
                    else
                    {
                        action = new ServiceAction("foo", returnType, resourceSet, operationParameterBindingKind, paramList);
                    }
                }
                catch (Exception ex)
                {
                    e = ex;
                }
                if (resourceSet != null && operationParameterBindingKind != OperationParameterBindingKind.Never)
                {
                    ExceptionUtils.IsExpectedException<ArgumentException>(e, "When 'returnType' is an entity type or an entity collection type, 'resultSetPathExpression' and 'resultSet' cannot be both null and the resource type of the result set must be assignable from 'returnType'.");
                }
                else if (returnType != null && (returnType.ResourceTypeKind == ResourceTypeKind.EntityType || returnType.ResourceTypeKind == ResourceTypeKind.EntityCollection) &&
                    (resourceSet == null && pathExpression == null ||
                    resourceSet != null && returnType.ResourceTypeKind == ResourceTypeKind.EntityType && resourceSet.ResourceType != returnType ||
                    resourceSet != null && returnType.ResourceTypeKind == ResourceTypeKind.EntityCollection && resourceSet.ResourceType != ((EntityCollectionResourceType)returnType).ItemType))
                {
                    ExceptionUtils.IsExpectedException<ArgumentException>(e, "When 'returnType' is an entity type or an entity collection type, 'resultSetPathExpression' and 'resultSet' cannot be both null and the resource type of the result set must be assignable from 'returnType'.");
                }
                else if ((returnType == null || returnType.ResourceTypeKind != ResourceTypeKind.EntityCollection && returnType.ResourceTypeKind != ResourceTypeKind.EntityType) && resourceSet != null)
                {
                    ExceptionUtils.IsExpectedException<ArgumentException>(e, "'resultSet' must be null when 'returnType' is null, not an entity type or not an entity collection type.");
                }
                else if ((returnType == null || returnType.ResourceTypeKind != ResourceTypeKind.EntityCollection && returnType.ResourceTypeKind != ResourceTypeKind.EntityType) && pathExpression != null)
                {
                    ExceptionUtils.IsExpectedException<ArgumentException>(e, "'resultSetPathExpression' must be null when 'returnType' is null, not an entity type or not an entity collection type.");
                }
                else if (returnType == ResourceType.GetPrimitiveResourceType(typeof(System.IO.Stream)))
                {
                    ExceptionUtils.IsExpectedException<ArgumentException>(e, "The resource type 'Edm.Stream' is not a type that can be returned by a function or action. A function or action can only return values of an entity type, an entity collection type, a complex type, a collection type or any primitive type, other than the stream type.\r\nParameter name: returnType");
                }
                else if (paramList.Length > 0 && paramList.Skip(bindable ? 1 : 0).Any(p => p.ParameterType.ResourceTypeKind == ResourceTypeKind.EntityType || p.ParameterType.ResourceTypeKind == ResourceTypeKind.EntityCollection))
                {
                    var param = paramList.Skip(bindable ? 1 : 0).First(p => p.ParameterType.ResourceTypeKind == ResourceTypeKind.EntityType || p.ParameterType.ResourceTypeKind == ResourceTypeKind.EntityCollection);
                    var parameterTypeKind = param.ParameterType.ResourceTypeKind;
                    ExceptionUtils.IsExpectedException<ArgumentException>(e, string.Format("The '{0}' parameter is of resource type kind '{1}' and it is not the binding parameter. Parameter of type kind '{1}' is only supported for the binding parameter.", param.Name, parameterTypeKind));
                }
                else if (pathExpression != null && !bindable)
                {
                    ExceptionUtils.IsExpectedException<ArgumentException>(e, "The binding parameter type must be an entity type or an entity collection type when 'resultSetPathExpression' is not null.");
                }
                else if (bindable && paramList.Length == 0)
                {
                    ExceptionUtils.IsExpectedException<ArgumentException>(e, "Bindable actions or functions must have at least one parameter, where the first parameter is the binding parameter.\r\nParameter name: operationParameterBindingKind");
                }
                else if (pathExpression != null && bindable && paramList.First().ParameterType.ResourceTypeKind != ResourceTypeKind.EntityType && paramList.First().ParameterType.ResourceTypeKind != ResourceTypeKind.EntityCollection)
                {
                    ExceptionUtils.IsExpectedException<ArgumentException>(e, "The binding parameter type must be an entity type or an entity collection type when 'resultSetPathExpression' is not null.");
                }
                else if (paramList.Length > 0 && bindable && paramList[0].ParameterType.ResourceTypeKind != ResourceTypeKind.EntityType && paramList[0].ParameterType.ResourceTypeKind != ResourceTypeKind.EntityCollection)
                {
                    ExceptionUtils.IsExpectedException<ArgumentException>(e, "An action's binding parameter must be of type Entity or EntityCollection.\r\nParameter name: parameters");
                }
                else
                {
                    Assert.IsNull(e, "Received exception but expected none. Exception message: {0}", e == null ? string.Empty : e.Message);
                    Assert.IsNotNull(action, "Action should be constructed.");

                    Assert.AreEqual("foo", action.Name, "unexpected name");
                    Assert.AreEqual(returnType, action.ReturnType, "unexpected return type");
                    Assert.AreEqual(resourceSet, action.ResourceSet, "unexpected result set");
                    Assert.AreEqual(pathExpression, action.ResultSetPathExpression, "unexpected path expression");
                    Assert.IsTrue(!bindable || action.BindingParameter == action.Parameters.First(), "unexpected binding parameter");
                    Assert.IsTrue(action.Method == "POST", "HttpMethod must be POST for ServiceActions.");
                    Assert.IsTrue(action.ResourceSet == null || action.ResultSetPathExpression == null, "'resultSet' and 'resultSetPathExpression' cannot be both set by the constructor.");
                }
            });
        }
コード例 #20
0
        /// <summary>Gets the effective rights on the specified action.</summary>
        /// <param name="serviceAction">Action to get rights for.</param>
        /// <returns>The effective rights as per this configuration.</returns>
        internal ServiceActionRights GetServiceActionRights(ServiceAction serviceAction)
        {
            Debug.Assert(serviceAction != null, "serviceAction != null");
            Debug.Assert(this.serviceActionRights != null, "this.serviceActionRights != null");

            ServiceActionRights result;
            if (!this.serviceActionRights.TryGetValue(serviceAction.Name, out result))
            {
                result = this.rightsForUnspecifiedServiceAction;
            }

            return result;
        }
コード例 #21
0
 public MyDSPInvokableAction(DataServiceOperationContext operationContext, Provider.ServiceAction action, object[] parameters)
 {
     this.action     = action;
     this.parameters = parameters;
 }
コード例 #22
0
        protected override IEnumerable<ServiceAction> LoadServiceActions(IDataServiceMetadataProvider dataServiceMetadataProvider)
        {
            ResourceType employeeType;
            dataServiceMetadataProvider.TryResolveResourceType("Microsoft.Test.OData.Services.AstoriaDefaultService.Employee", out employeeType);
            ResourceType computerDetailType;
            dataServiceMetadataProvider.TryResolveResourceType("Microsoft.Test.OData.Services.AstoriaDefaultService.ComputerDetail", out computerDetailType);
            ResourceType computerType;          
            dataServiceMetadataProvider.TryResolveResourceType("Microsoft.Test.OData.Services.AstoriaDefaultService.Computer", out computerType);
            ResourceType customerType;
            dataServiceMetadataProvider.TryResolveResourceType("Microsoft.Test.OData.Services.AstoriaDefaultService.Customer", out customerType);
            ResourceType auditInfoType;
            dataServiceMetadataProvider.TryResolveResourceType("Microsoft.Test.OData.Services.AstoriaDefaultService.AuditInfo", out auditInfoType);            
            ResourceSet computerSet;
            dataServiceMetadataProvider.TryResolveResourceSet("Computer", out computerSet);
            var increaseSalaryAction = new ServiceAction(
                 "IncreaseSalaries",
                 null,
                 null,
                 OperationParameterBindingKind.Always,
                 new[]
                {
                    new ServiceActionParameter("employees", ResourceType.GetEntityCollectionResourceType(employeeType)),
                    new ServiceActionParameter("n", ResourceType.GetPrimitiveResourceType(typeof(int))),
                });

            increaseSalaryAction.SetReadOnly();

            yield return increaseSalaryAction;

            var sackEmployeeAction = new ServiceAction(
                "Sack",
                null,
                null,
                OperationParameterBindingKind.Always,
                new[]
                {
                    new ServiceActionParameter("employee", employeeType), 
                });

            sackEmployeeAction.SetReadOnly();

            yield return sackEmployeeAction;

            var getComputerAction = new ServiceAction(
                "GetComputer",
                computerType,
                OperationParameterBindingKind.Always,
                new[]
                {
                    new ServiceActionParameter("computer", computerType)
                },
                new ResourceSetPathExpression("computer"));

            getComputerAction.SetReadOnly();

            yield return getComputerAction;
             
            var changeCustomerAuditInfoAction = new ServiceAction(
               "ChangeCustomerAuditInfo",
               null,
               null,
               OperationParameterBindingKind.Always,
               new[]
                {
                
                    new ServiceActionParameter("customer", customerType), 
                    new ServiceActionParameter("auditInfo", auditInfoType),
                });

            changeCustomerAuditInfoAction.SetReadOnly();

            yield return changeCustomerAuditInfoAction;

             var resetComputerDetailsSpecificationsAction = new ServiceAction(
                "ResetComputerDetailsSpecifications",
                null,
                null,
                OperationParameterBindingKind.Always,
                new[]
                {
                    new ServiceActionParameter("computerDetail", computerDetailType), 
                    new ServiceActionParameter("specifications", ResourceType.GetCollectionResourceType(ResourceType.GetPrimitiveResourceType(typeof(string)))),
                    new ServiceActionParameter("purchaseTime", ResourceType.GetPrimitiveResourceType(typeof(DateTimeOffset)))
                });

            resetComputerDetailsSpecificationsAction.SetReadOnly();

            yield return resetComputerDetailsSpecificationsAction;
        }
コード例 #23
0
 public override Provider.IDataServiceInvokable CreateInvokable(DataServiceOperationContext operationContext, Provider.ServiceAction serviceAction, object[] parameterTokens)
 {
     return(new MyDSPInvokableAction(operationContext, serviceAction, parameterTokens));
 }