Ejemplo n.º 1
0
    public static ContextUtil getInstance(string serverPath)
    {
        if (serverPath == null)
            return instance;
        if (instance == null)
            instance = new ContextUtil(serverPath);

        return instance;
    }
Ejemplo n.º 2
0
        public void BindSimpleCollection_SubBinderDoesNotExist()
        {
            // Arrange
            CultureInfo         culture        = CultureInfo.GetCultureInfo("fr-FR");
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),
                ModelName     = "someName",
                ValueProvider = new SimpleHttpValueProvider()
            };
            HttpActionContext context = ContextUtil.CreateActionContext();

            context.ControllerContext.Configuration.ServiceResolver.SetService(typeof(ModelBinderProvider), null); // completely remove from resolution?

            // Act
            List <int> boundCollection = CollectionModelBinder <int> .BindSimpleCollection(context, bindingContext, new int[1], culture);

            // Assert
            Assert.Equal(new[] { 0 }, boundCollection.ToArray());
            Assert.Empty(bindingContext.ValidationNode.ChildNodes);
        }
Ejemplo n.º 3
0
        public void MultipleValidationErrorsOnSameMemberReported()
        {
            // Arrange
            ModelMetadataProvider metadataProvider = new CachedDataAnnotationsModelMetadataProvider();
            HttpActionContext     actionContext    = ContextUtil.CreateActionContext();
            object model = new Address()
            {
                Street = "Microsoft Way"
            };

            // Act
            Assert.DoesNotThrow(() =>
                                new DefaultBodyModelValidator().Validate(model, typeof(Address), metadataProvider, actionContext, string.Empty)
                                );

            // Assert
            Assert.Contains("Street", actionContext.ModelState.Keys);
            ModelState streetState = actionContext.ModelState["Street"];

            Assert.Equal(2, streetState.Errors.Count);
        }
Ejemplo n.º 4
0
        public void GetMetadataForProperties_WithBindAttribute()
        {
            // Arrange
            string[] expectedPropertyNames = new[] { "FirstName", "LastName" };

            HttpActionContext   actionContext  = ContextUtil.CreateActionContext();
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = GetMetadataForType(typeof(PersonWithBindExclusion))
            };

            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();

            // Act
            IEnumerable <ModelMetadata> propertyMetadatas = testableBinder.GetMetadataForPropertiesPublic(actionContext, bindingContext);

            string[] returnedPropertyNames = propertyMetadatas.Select(o => o.PropertyName).ToArray();

            // Assert
            Assert.Equal(expectedPropertyNames, returnedPropertyNames);
        }
        public Task ExecuteAuthorizationFilterAsync_IfContinuationTaskWasCanceled_ReturnsCanceledTask()
        {
            // Arrange
            HttpActionContext context = ContextUtil.CreateActionContext();
            Mock <AuthorizationFilterAttribute> filterMock = new Mock <AuthorizationFilterAttribute>()
            {
                CallBase = true,
            };

            var filter = (IAuthorizationFilter)filterMock.Object;

            // Act & Assert
            return(Assert.ThrowsAsync <TaskCanceledException>(
                       () =>
                       filter.ExecuteAuthorizationFilterAsync(
                           context,
                           CancellationToken.None,
                           () => TaskHelpers.Canceled <HttpResponseMessage>()
                           )
                       ));
        }
        public void ExecuteActionFilterAsync_IfOnActionExecutedDoesNotChangeResult_ReturnsSameResult()
        {
            // Arrange
            HttpActionContext            context    = ContextUtil.CreateActionContext();
            Mock <ActionFilterAttribute> filterMock = new Mock <ActionFilterAttribute>();
            var filter = (IActionFilter)filterMock.Object;
            HttpResponseMessage response = new HttpResponseMessage();

            filterMock.Setup(f => f.OnActionExecuted(It.IsAny <HttpActionExecutedContext>())).Callback <HttpActionExecutedContext>(ec =>
            {
                ec.Response = ec.Response;
            });

            // Act
            var result = filter.ExecuteActionFilterAsync(context, CancellationToken.None, () => TaskHelpers.FromResult(response));

            // Assert
            result.WaitUntilCompleted();
            Assert.True(result.IsCompleted);
            Assert.Same(response, result.Result);
        }
Ejemplo n.º 7
0
        public void ValidationErrorsNotAddedOnInvalidFields()
        {
            // Arrange
            ModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();
            HttpActionContext     actionContext    = ContextUtil.CreateActionContext();
            object model = new Address()
            {
                Street = "Microsoft Way"
            };

            actionContext.ModelState.AddModelError("Street", "error");

            // Act
            new DefaultBodyModelValidator().Validate(model, typeof(Address), metadataProvider, actionContext, string.Empty);

            // Assert
            Assert.Contains("Street", actionContext.ModelState.Keys);
            ModelState streetState = actionContext.ModelState["Street"];

            Assert.Equal(1, streetState.Errors.Count);
        }
        public void ExecuteActionFilterAsync_IfOnActionExecutedThrowsException_ReturnsFaultedTask()
        {
            // Arrange
            HttpActionContext            context    = ContextUtil.CreateActionContext();
            Mock <ActionFilterAttribute> filterMock = new Mock <ActionFilterAttribute>();
            var       filter    = (IActionFilter)filterMock.Object;
            Exception exception = new Exception("{AC32AD02-36A7-45E5-8955-76A4E3B461C6}");

            filterMock.Setup(f => f.OnActionExecuted(It.IsAny <HttpActionExecutedContext>())).Callback <HttpActionExecutedContext>(ec =>
            {
                throw exception;
            });

            // Act
            var result = filter.ExecuteActionFilterAsync(context, CancellationToken.None, () => TaskHelpers.FromResult(new HttpResponseMessage()));

            // Assert
            result.WaitUntilCompleted();
            Assert.True(result.IsFaulted);
            Assert.Same(exception, result.Exception.InnerException);
        }
        public void ExecuteActionFilterAsync_IfOnActionExecutedDoesHandleExceptionFromContinuation_ReturnsSuccessfulTask()
        {
            // Arrange
            HttpActionContext            context    = ContextUtil.CreateActionContext();
            Mock <ActionFilterAttribute> filterMock = new Mock <ActionFilterAttribute>();
            var filter = (IActionFilter)filterMock.Object;
            HttpResponseMessage newResponse = new HttpResponseMessage();

            filterMock.Setup(f => f.OnActionExecuted(It.IsAny <HttpActionExecutedContext>())).Callback <HttpActionExecutedContext>(ec =>
            {
                ec.Response = newResponse;
            });

            // Act
            var result = filter.ExecuteActionFilterAsync(context, CancellationToken.None, () => TaskHelpers.FromError <HttpResponseMessage>(new Exception("{ED525C8E-7165-4207-B3F6-4AB095739017}")));

            // Assert
            result.WaitUntilCompleted();
            Assert.True(result.IsCompleted);
            Assert.Same(newResponse, result.Result);
        }
        public void ExecuteActionFilterAsync_IfOnActionExecutedDoesNotHandleExceptionFromContinuation_ReturnsFaultedTask()
        {
            // Arrange
            HttpActionContext            context    = ContextUtil.CreateActionContext();
            Mock <ActionFilterAttribute> filterMock = new Mock <ActionFilterAttribute>();
            var       filter    = (IActionFilter)filterMock.Object;
            Exception exception = new Exception("{1EC330A2-33D0-4892-9335-2D833849D54E}");

            filterMock.Setup(f => f.OnActionExecuted(It.IsAny <HttpActionExecutedContext>())).Callback <HttpActionExecutedContext>(ec =>
            {
                ec.Response = null;
            });

            // Act
            var result = filter.ExecuteActionFilterAsync(context, CancellationToken.None, () => TaskHelpers.FromError <HttpResponseMessage>(exception));

            // Assert
            result.WaitUntilCompleted();
            Assert.True(result.IsFaulted);
            Assert.Same(exception, result.Exception.InnerException);
        }
        public void Validate_SkipsValidationIfHandlerCancels()
        {
            // Arrange
            List <string>            log           = new List <string>();
            LoggingValidatableObject model         = new LoggingValidatableObject(log);
            ModelMetadata            modelMetadata = GetModelMetadata(model);
            ModelValidationNode      node          = new ModelValidationNode(modelMetadata, "theKey");

            node.Validating += (sender, e) =>
            {
                log.Add("In OnValidating()");
                e.Cancel = true;
            };
            node.Validated += (sender, e) => log.Add("In OnValidated()");

            // Act
            node.Validate(ContextUtil.CreateActionContext());

            // Assert
            Assert.Equal(new[] { "In OnValidating()" }, log.ToArray());
        }
        public void SetProperty_SettingNonNullableValueTypeToNull_RequiredValidatorNotPresent_RegistersValidationCallback()
        {
            // Arrange
            HttpActionContext   context        = ContextUtil.CreateActionContext();
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = GetMetadataForObject(new Person()),
            };

            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(
                o => o.PropertyName == "DateOfBirth"
                );
            ModelValidationNode   validationNode = new ModelValidationNode(propertyMetadata, "foo");
            ComplexModelDtoResult dtoResult      = new ComplexModelDtoResult(
                null /* model */
                ,
                validationNode
                );
            ModelValidator requiredValidator = context
                                               .GetValidators(propertyMetadata)
                                               .Where(v => v.IsRequired)
                                               .FirstOrDefault();

            TestableMutableObjectModelBinder testableBinder =
                new TestableMutableObjectModelBinder();

            // Act
            testableBinder.SetPropertyPublic(
                context,
                bindingContext,
                propertyMetadata,
                dtoResult,
                requiredValidator
                );

            // Assert
            Assert.True(context.ModelState.IsValid);
            validationNode.Validate(context, bindingContext.ValidationNode);
            Assert.False(context.ModelState.IsValid);
        }
        public void InvokeActionWithActionFilters_ChainsFiltersInOrderFollowedByInnerActionContinuation()
        {
            // Arrange
            HttpActionContext    actionContextInstance = ContextUtil.CreateActionContext();
            List <string>        log = new List <string>();
            Mock <IActionFilter> globalFilterMock = CreateActionFilterMock((ctx, ct, continuation) =>
            {
                log.Add("globalFilter");
                return(continuation());
            });
            Mock <IActionFilter> actionFilterMock = CreateActionFilterMock((ctx, ct, continuation) =>
            {
                log.Add("actionFilter");
                return(continuation());
            });
            Func <Task <HttpResponseMessage> > innerAction = () => Task <HttpResponseMessage> .Factory.StartNew(() =>
            {
                log.Add("innerAction");
                return(null);
            });

            var filters = new IActionFilter[] {
                globalFilterMock.Object,
                actionFilterMock.Object,
            };

            // Act
            var result = ActionFilterResult.InvokeActionWithActionFilters(actionContextInstance,
                                                                          CancellationToken.None, filters, innerAction);

            // Assert
            Assert.NotNull(result);
            var resultTask = result();

            Assert.NotNull(resultTask);
            resultTask.WaitUntilCompleted();
            Assert.Equal(new[] { "globalFilter", "actionFilter", "innerAction" }, log.ToArray());
            globalFilterMock.Verify();
            actionFilterMock.Verify();
        }
Ejemplo n.º 14
0
        public void Validate_SkipsRemainingValidationIfModelStateIsInvalid()
        {
            // Because a property validator fails, the model validator shouldn't run

            // Arrange
            List <string>            log           = new List <string>();
            LoggingValidatableObject model         = new LoggingValidatableObject(log);
            ModelMetadata            modelMetadata = GetModelMetadata(model);
            ModelMetadata            childMetadata = new EmptyModelMetadataProvider().GetMetadataForProperty(
                () => model,
                model.GetType(),
                "InvalidStringProperty"
                );
            ModelValidationNode node = new ModelValidationNode(modelMetadata, "theKey");

            node.ChildNodes.Add(
                new ModelValidationNode(childMetadata, "theKey.InvalidStringProperty")
                );
            node.Validating += (sender, e) => log.Add("In OnValidating()");
            node.Validated  += (sender, e) => log.Add("In OnValidated()");
            HttpActionContext context = ContextUtil.CreateActionContext();

            // Act
            node.Validate(context);

            // Assert
            Assert.Equal(
                new[]
            {
                "In OnValidating()",
                "In IValidatableObject.Validate()",
                "In OnValidated()"
            },
                log.ToArray()
                );
            Assert.Equal(
                "Sample error message",
                context.ModelState["theKey.InvalidStringProperty"].Errors[0].ErrorMessage
                );
        }
Ejemplo n.º 15
0
        public void Validate_Ordering()
        {
            // Proper order of invocation:
            // 1. OnValidating()
            // 2. Child validators
            // 3. This validator
            // 4. OnValidated()

            // Arrange
            List <string>            log           = new List <string>();
            LoggingValidatableObject model         = new LoggingValidatableObject(log);
            ModelMetadata            modelMetadata = GetModelMetadata(model);
            ModelMetadata            childMetadata = new EmptyModelMetadataProvider().GetMetadataForProperty(
                () => model,
                model.GetType(),
                "ValidStringProperty"
                );
            ModelValidationNode node = new ModelValidationNode(modelMetadata, "theKey");

            node.Validating += (sender, e) => log.Add("In OnValidating()");
            node.Validated  += (sender, e) => log.Add("In OnValidated()");
            node.ChildNodes.Add(
                new ModelValidationNode(childMetadata, "theKey.ValidStringProperty")
                );

            // Act
            node.Validate(ContextUtil.CreateActionContext());

            // Assert
            Assert.Equal(
                new[]
            {
                "In OnValidating()",
                "In LoggingValidatonAttribute.IsValid()",
                "In IValidatableObject.Validate()",
                "In OnValidated()"
            },
                log.ToArray()
                );
        }
        public void ExecuteAsync_Invokes_Inner_And_Traces()
        {
            // Arrange
            HttpResponseMessage  response       = new HttpResponseMessage();
            Mock <ApiController> mockController = new Mock <ApiController>()
            {
                CallBase = true
            };

            mockController.Setup(b => b.ExecuteAsync(It.IsAny <HttpControllerContext>(), It.IsAny <CancellationToken>())).Returns(TaskHelpers.FromResult <HttpResponseMessage>(response));

            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(request: new HttpRequestMessage());

            controllerContext.ControllerDescriptor = _controllerDescriptor;
            controllerContext.Controller           = mockController.Object;

            HttpActionContext actionContext = ContextUtil.CreateActionContext(controllerContext, actionDescriptor: _mockActionDescriptor.Object);

            TestTraceWriter      traceWriter = new TestTraceWriter();
            HttpControllerTracer tracer      = new HttpControllerTracer(mockController.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin
                },
                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.End
                }
            };

            // Act
            HttpResponseMessage actualResponse = ((IHttpController)tracer).ExecuteAsync(controllerContext, CancellationToken.None).Result;

            // Assert
            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(response, actualResponse);
        }
        public void ExpectedValidationErrorsRaised(
            object model,
            Type type,
            Dictionary <string, string> expectedErrors
            )
        {
            // Arrange
            ModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();
            HttpActionContext     actionContext    = ContextUtil.CreateActionContext();

            // Act
            Assert.DoesNotThrow(
                () =>
                new DefaultBodyModelValidator().Validate(
                    model,
                    type,
                    metadataProvider,
                    actionContext,
                    string.Empty
                    )
                );

            // Assert
            Dictionary <string, string> actualErrors = new Dictionary <string, string>();

            foreach (KeyValuePair <string, ModelState> keyStatePair in actionContext.ModelState)
            {
                foreach (ModelError error in keyStatePair.Value.Errors)
                {
                    actualErrors.Add(keyStatePair.Key, error.ErrorMessage);
                }
            }

            Assert.Equal(expectedErrors.Count, actualErrors.Count);
            foreach (KeyValuePair <string, string> keyErrorPair in expectedErrors)
            {
                Assert.Contains(keyErrorPair.Key, actualErrors.Keys);
                Assert.Equal(keyErrorPair.Value, actualErrors[keyErrorPair.Key]);
            }
        }
        public HttpActionBindingTracerTest()
        {
            _mockActionDescriptor = new Mock <HttpActionDescriptor>()
            {
                CallBase = true
            };
            _mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            _mockActionDescriptor
            .Setup(a => a.GetParameters())
            .Returns(new Collection <HttpParameterDescriptor>(new HttpParameterDescriptor[0]));

            _mockParameterDescriptor = new Mock <HttpParameterDescriptor>()
            {
                CallBase = true
            };
            _mockParameterBinding = new Mock <HttpParameterBinding>(_mockParameterDescriptor.Object)
            {
                CallBase = true
            };
            _actionBinding = new HttpActionBinding(
                _mockActionDescriptor.Object,
                new HttpParameterBinding[] { _mockParameterBinding.Object }
                );

            _controllerDescriptor = new HttpControllerDescriptor(
                new HttpConfiguration(),
                "controller",
                typeof(ApiController)
                );

            _controllerContext = ContextUtil.CreateControllerContext(
                request: new HttpRequestMessage()
                );
            _controllerContext.ControllerDescriptor = _controllerDescriptor;

            _actionContext = ContextUtil.CreateActionContext(
                _controllerContext,
                actionDescriptor: _mockActionDescriptor.Object
                );
        }
        public void SetProperty_PropertyIsSettable_CallsSetter()
        {
            // Arrange
            Person              model          = new Person();
            HttpActionContext   context        = ContextUtil.CreateActionContext();
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = GetMetadataForObject(model)
            };

            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(
                o => o.PropertyName == "DateOfBirth"
                );
            ModelValidationNode   validationNode = new ModelValidationNode(propertyMetadata, "foo");
            ComplexModelDtoResult dtoResult      = new ComplexModelDtoResult(
                new DateTime(2001, 1, 1),
                validationNode
                );
            ModelValidator requiredValidator = context
                                               .GetValidators(propertyMetadata)
                                               .Where(v => v.IsRequired)
                                               .FirstOrDefault();

            TestableMutableObjectModelBinder testableBinder =
                new TestableMutableObjectModelBinder();

            // Act
            testableBinder.SetPropertyPublic(
                context,
                bindingContext,
                propertyMetadata,
                dtoResult,
                requiredValidator
                );

            // Assert
            validationNode.Validate(context);
            Assert.True(context.ModelState.IsValid);
            Assert.Equal(new DateTime(2001, 1, 1), model.DateOfBirth);
        }
Ejemplo n.º 20
0
        public void ExecuteAsync_IsCancelled_And_Traces_When_Inner_IsCancelled()
        {
            // Arrange
            Mock <ApiController> mockController = new Mock <ApiController>()
            {
                CallBase = true
            };

            mockController.Setup(b => b.ExecuteAsync(It.IsAny <HttpControllerContext>(), It.IsAny <CancellationToken>())).Returns(TaskHelpers.Canceled <HttpResponseMessage>());

            HttpRequestMessage    request           = new HttpRequestMessage();
            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(request: request);

            controllerContext.ControllerDescriptor = _controllerDescriptor;
            controllerContext.Controller           = mockController.Object;

            HttpActionContext actionContext = ContextUtil.CreateActionContext(controllerContext, actionDescriptor: _mockActionDescriptor.Object);

            TestTraceWriter      traceWriter = new TestTraceWriter();
            HttpControllerTracer tracer      = new HttpControllerTracer(request, mockController.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin
                },
                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Warn)
                {
                    Kind = TraceKind.End
                }
            };

            // Act
            Task      task   = ((IHttpController)tracer).ExecuteAsync(controllerContext, CancellationToken.None);
            Exception thrown = Assert.Throws <TaskCanceledException>(() => task.Wait());

            // Assert
            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
        public void ExecuteExceptionFilterAsync_Traces()
        {
            // Arrange
            HttpRequestMessage              request  = new HttpRequestMessage();
            HttpResponseMessage             response = new HttpResponseMessage();
            Mock <ExceptionFilterAttribute> mockAttr = new Mock <ExceptionFilterAttribute>()
            {
                CallBase = true
            };
            Mock <HttpActionDescriptor> mockActionDescriptor = new Mock <HttpActionDescriptor>()
            {
                CallBase = true
            };

            mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection <HttpParameterDescriptor>(new HttpParameterDescriptor[0]));
            HttpActionExecutedContext      actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response);
            TestTraceWriter                traceWriter           = new TestTraceWriter();
            ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttr.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin, Operation = "OnException"
                },
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.End, Operation = "OnException"
                },
            };

            // Act
            Task task = ((IExceptionFilter)tracer).ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None);

            task.Wait();

            // Assert
            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
Ejemplo n.º 22
0
        public async Task TestConstructor_OnActionExecutingAsync_ResourceIdDoesNotExist()
        {
            var exceptionCaught = false;
            var id              = 1;
            var actionArgument  = "id";
            var permissionModel = new PermissionModel
            {
                Id   = Permission.ViewProgram.Id,
                Name = Permission.ViewProgram.Value
            };
            var user           = GetTestUser();
            var warningMessage = string.Empty;

            userProvider.Setup(x => x.GetCurrentUser()).Returns(user);
            resourceService.Setup(x => x.GetResourceTypeId(It.IsAny <string>())).Returns(1);
            resourceService.Setup(x => x.GetResourceByForeignResourceIdAsync(It.IsAny <int>(), It.IsAny <int>())).ReturnsAsync(default(ForeignResourceCache));
            permissionService.Setup(x => x.HasPermission(It.IsAny <int>(), It.IsAny <int?>(), It.IsAny <int>(), It.IsAny <List <IPermission> >())).Returns(true);
            permissionService.Setup(x => x.GetPermissionByNameAsync(It.IsAny <string>())).ReturnsAsync(permissionModel);
            userProvider.Setup(x => x.IsUserValidAsync(It.IsAny <IWebApiUser>())).ReturnsAsync(true);

            var attribute = new ResourceAuthorizeAttribute(permissionModel.Name, ResourceType.Program.Value, actionArgument);

            try
            {
                var actionContext = ContextUtil.CreateActionContext();
                actionContext.RequestContext.Principal = Thread.CurrentPrincipal;
                actionContext.ActionArguments.Add(actionArgument, id);
                var cts = new CancellationTokenSource();
                await attribute.OnActionExecutingAsync(actionContext, cts.Token);
            }
            catch (HttpResponseException e)
            {
                exceptionCaught = true;
                Assert.AreEqual(HttpStatusCode.Forbidden, e.Response.StatusCode);
            }
            Assert.IsTrue(exceptionCaught);
            Assert.AreEqual(AuthorizationResult.ResourceDoesNotExist, attribute.GetAuthorizationResult());
            //make sure we fall into checking permissions
            userProvider.Verify(x => x.GetPermissionsAsync(It.IsAny <IWebApiUser>()), Times.Once());
        }
Ejemplo n.º 23
0
        public void ExecuteBindingAsync_Traces_And_Invokes_Inner_ReadAsync()
        {
            // Arrange
            Mock <HttpParameterDescriptor> mockParamDescriptor = new Mock <HttpParameterDescriptor>()
            {
                CallBase = true
            };

            mockParamDescriptor.Setup(d => d.ParameterName).Returns("paramName");
            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));
            FormatterParameterBinding       binding       = new FormatterParameterBinding(mockParamDescriptor.Object, new MediaTypeFormatterCollection(), null);
            TestTraceWriter                 traceWriter   = new TestTraceWriter();
            FormatterParameterBindingTracer tracer        = new FormatterParameterBindingTracer(binding, traceWriter);
            HttpActionContext               actionContext = ContextUtil.CreateActionContext();

            actionContext.Request.Content = new StringContent("true");
            actionContext.Request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            ModelMetadataProvider metadataProvider = new EmptyModelMetadataProvider();

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin, Operation = "ExecuteBindingAsync"
                },
                new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.End, Operation = "ExecuteBindingAsync"
                }
            };

            // Act
            Task task = tracer.ExecuteBindingAsync(metadataProvider, actionContext, CancellationToken.None);

            task.Wait();

            // Assert
            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Equal("True", actionContext.ActionArguments["paramName"]);
        }
Ejemplo n.º 24
0
        public async Task TestConstructor_OnActionExecutingAsync_ResourceTypeIsNotKnown()
        {
            var id = 1;
            var foreignResourceCache = new ForeignResourceCache(0, id, 0, null, null, null);
            var actionArgument       = "id";
            var permissionModel      = new PermissionModel
            {
                Id   = Permission.ViewProgram.Id,
                Name = Permission.ViewProgram.Value
            };
            var resourceType = "idontexist";
            var user         = GetTestUser();

            userProvider.Setup(x => x.GetCurrentUser()).Returns(user);
            resourceService.Setup(x => x.GetResourceTypeId(It.IsAny <string>())).Returns(default(int?));
            resourceService.Setup(x => x.GetResourceByForeignResourceIdAsync(It.IsAny <int>(), It.IsAny <int>())).ReturnsAsync(foreignResourceCache);
            permissionService.Setup(x => x.HasPermission(It.IsAny <int>(), It.IsAny <int?>(), It.IsAny <int>(), It.IsAny <List <IPermission> >())).Returns(true);
            permissionService.Setup(x => x.GetPermissionByNameAsync(It.IsAny <string>())).ReturnsAsync(permissionModel);
            userProvider.Setup(x => x.IsUserValidAsync(It.IsAny <IWebApiUser>())).ReturnsAsync(true);

            var attribute     = new ResourceAuthorizeAttribute(permissionModel.Name, resourceType, actionArgument);
            var actionContext = ContextUtil.CreateActionContext();

            actionContext.RequestContext.Principal = Thread.CurrentPrincipal;
            actionContext.ActionArguments.Add(actionArgument, id);

            var cts             = new CancellationTokenSource();
            var exceptionCaught = false;

            try
            {
                await attribute.OnActionExecutingAsync(actionContext, cts.Token);
            }
            catch (NotSupportedException e)
            {
                exceptionCaught = true;
                Assert.AreEqual(String.Format("The resource type name [{0}] does not have a matching resource id in CAM.", resourceType), e.Message);
            }
            Assert.IsTrue(exceptionCaught);
        }
Ejemplo n.º 25
0
        public async Task ExecuteExceptionFilterAsync_Faults_And_Traces_When_Inner_Faults()
        {
            // Arrange
            HttpRequestMessage      request    = new HttpRequestMessage();
            HttpResponseMessage     response   = new HttpResponseMessage();
            Mock <IExceptionFilter> mockFilter = new Mock <IExceptionFilter>()
            {
                CallBase = true
            };
            InvalidOperationException     exception = new InvalidOperationException("test");
            TaskCompletionSource <object> tcs       = new TaskCompletionSource <object>(null);

            tcs.TrySetException(exception);
            mockFilter.Setup(a => a.ExecuteExceptionFilterAsync(It.IsAny <HttpActionExecutedContext>(), It.IsAny <CancellationToken>())).Returns(tcs.Task);
            HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response);
            TestTraceWriter           traceWriter           = new TestTraceWriter();
            ExceptionFilterTracer     tracer = new ExceptionFilterTracer(mockFilter.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin, Operation = "ExecuteExceptionFilterAsync"
                },
                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Error)
                {
                    Kind = TraceKind.End, Operation = "ExecuteExceptionFilterAsync"
                }
            };

            // Act
            Task task = ((IExceptionFilter)tracer).ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None);

            // Assert
            Exception thrown = await Assert.ThrowsAsync <InvalidOperationException>(() => task);

            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
Ejemplo n.º 26
0
        public void ExecuteAsync_ChainsFiltersInOrderFollowedByInnerActionContinuation()
        {
            // Arrange
            HttpActionContext           actionContextInstance = ContextUtil.CreateActionContext();
            List <string>               log = new List <string>();
            Mock <IAuthorizationFilter> globalFilterMock = CreateAuthorizationFilterMock((ctx, ct, continuation) =>
            {
                log.Add("globalFilter");
                return(continuation());
            });
            Mock <IAuthorizationFilter> actionFilterMock = CreateAuthorizationFilterMock((ctx, ct, continuation) =>
            {
                log.Add("actionFilter");
                return(continuation());
            });
            Mock <IHttpActionResult> innerResultMock = new Mock <IHttpActionResult>();

            innerResultMock.Setup(r => r.ExecuteAsync(It.IsAny <CancellationToken>())).Returns(() =>
            {
                log.Add("innerAction");
                return(Task.FromResult <HttpResponseMessage>(null));
            });
            IHttpActionResult innerResult = innerResultMock.Object;
            var filters = new IAuthorizationFilter[] {
                globalFilterMock.Object,
                actionFilterMock.Object,
            };
            IHttpActionResult authorizationFilter = new AuthorizationFilterResult(actionContextInstance, filters,
                                                                                  innerResult);

            // Act
            Task <HttpResponseMessage> result = authorizationFilter.ExecuteAsync(CancellationToken.None);

            // Assert
            Assert.NotNull(result);
            result.WaitUntilCompleted();
            Assert.Equal(new[] { "globalFilter", "actionFilter", "innerAction" }, log.ToArray());
            globalFilterMock.Verify();
            actionFilterMock.Verify();
        }
        public void BindModel_MissingKey_ReturnsFalse()
        {
            // Arrange
            KeyValuePairModelBinder <int, string> binder = new KeyValuePairModelBinder <int, string>();
            ModelBindingContext bindingContext           = new ModelBindingContext
            {
                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(KeyValuePair <int, string>)),
                ModelName     = "someName",
                ValueProvider = new SimpleHttpValueProvider()
            };
            HttpActionContext context = ContextUtil.CreateActionContext();

            context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(KeyValuePair <int, string>), binder));

            // Act
            bool retVal = binder.BindModel(context, bindingContext);

            // Assert
            Assert.False(retVal);
            Assert.Null(bindingContext.Model);
            Assert.Empty(bindingContext.ValidationNode.ChildNodes);
        }
        public async Task ExecuteActionFilterAsync_IfContinuationSucceeded_InvokesOnActionExecutedAsSuccess()
        {
            // Arrange
            HttpActionContext            context    = ContextUtil.CreateActionContext();
            Mock <ActionFilterAttribute> filterMock = new Mock <ActionFilterAttribute>()
            {
                CallBase = true,
            };

            var filter = (IActionFilter)filterMock.Object;
            HttpResponseMessage response = new HttpResponseMessage();

            // Act
            await filter.ExecuteActionFilterAsync(context, CancellationToken.None, () => Task.FromResult(response));

            // Assert
            filterMock.Verify(f => f.OnActionExecuted(It.Is <HttpActionExecutedContext>(ec =>
                                                                                        Object.ReferenceEquals(ec.Response, response) &&
                                                                                        ec.Exception == null &&
                                                                                        Object.ReferenceEquals(ec.ActionContext, context)
                                                                                        )));
        }
Ejemplo n.º 29
0
        public void BindModel()
        {
            // Arrange
            Mock <IModelBinder> mockKvpBinder  = new Mock <IModelBinder>();
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(IDictionary <int, string>)),
                ModelName     = "someName",
                ValueProvider = new SimpleHttpValueProvider
                {
                    { "someName[0]", new KeyValuePair <int, string>(42, "forty-two") },
                    { "someName[1]", new KeyValuePair <int, string>(84, "eighty-four") }
                }
            };
            HttpActionContext context = ContextUtil.CreateActionContext();

            context.ControllerContext.Configuration.ServiceResolver.SetService(typeof(ModelBinderProvider), (new SimpleModelBinderProvider(typeof(KeyValuePair <int, string>), mockKvpBinder.Object)));

            mockKvpBinder
            .Setup(o => o.BindModel(context, It.IsAny <ModelBindingContext>()))
            .Returns((HttpActionContext cc, ModelBindingContext mbc) =>
            {
                mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType);
                return(true);
            });

            // Act
            bool retVal = new DictionaryModelBinder <int, string>().BindModel(context, bindingContext);

            // Assert
            Assert.True(retVal);

            var dictionary = Assert.IsAssignableFrom <IDictionary <int, string> >(bindingContext.Model);

            Assert.NotNull(dictionary);
            Assert.Equal(2, dictionary.Count);
            Assert.Equal("forty-two", dictionary[42]);
            Assert.Equal("eighty-four", dictionary[84]);
        }
        public async Task ExecuteActionFilterAsync_CancellationTokenFlowsThrough()
        {
            // Arrange
            HttpActionContext context = ContextUtil.CreateActionContext();

            using (var cts = new CancellationTokenSource())
            {
                CancellationToken token = cts.Token;

                Mock <ActionFilterAttribute> filterMock = new Mock <ActionFilterAttribute>()
                {
                    CallBase = true,
                };

                var filter = (IActionFilter)filterMock.Object;
                Func <Task <HttpResponseMessage> > continuation = () =>
                                                                  Task.FromResult <HttpResponseMessage>(new HttpResponseMessage());

                // Act
                await filter.ExecuteActionFilterAsync(context, token, continuation);

                // Assert
                filterMock.Verify(
                    f =>
                    f.OnActionExecutingAsync(
                        It.IsAny <HttpActionContext>(),
                        It.Is <CancellationToken>(t => t == token)
                        )
                    );

                filterMock.Verify(
                    f =>
                    f.OnActionExecutedAsync(
                        It.IsAny <HttpActionExecutedContext>(),
                        It.Is <CancellationToken>(t => t == token)
                        )
                    );
            }
        }
        public void ExecuteAuthorizationFilterAsync_Traces()
        {
            // Arrange
            Mock <AuthorizationFilterAttribute> mockAttr = new Mock <AuthorizationFilterAttribute>()
            {
                CallBase = true
            };
            Mock <HttpActionDescriptor> mockActionDescriptor = new Mock <HttpActionDescriptor>()
            {
                CallBase = true
            };

            mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection <HttpParameterDescriptor>(new HttpParameterDescriptor[0]));
            HttpActionContext actionContext = ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object);
            Func <Task <HttpResponseMessage> > continuation = () => TaskHelpers.FromResult <HttpResponseMessage>(new HttpResponseMessage());
            TestTraceWriter traceWriter = new TestTraceWriter();
            AuthorizationFilterAttributeTracer tracer = new AuthorizationFilterAttributeTracer(mockAttr.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin, Operation = "OnAuthorization"
                },
                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.End, Operation = "OnAuthorization"
                },
            };

            // Act
            Task task = ((IAuthorizationFilter)tracer).ExecuteAuthorizationFilterAsync(actionContext, CancellationToken.None, continuation);

            task.Wait();

            // Assert
            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
Ejemplo n.º 32
0
    protected void Page_Load(object sender, EventArgs e)
    {
        byte[] byteData = null;
        try
        {
            if (context == null)
            {
                context = ContextUtil.getInstance(Server.MapPath("."));
                encrypt = context.getOuterEncrypt();
            }

            if (encoder == null)
                encoder = ParamEncoder.getInstance();
            if (decoder == null)
                decoder = ParamDecoder.getInstance();

            encoder.outEncoder = context.getOuterResolve();
            decoder.outDecoder = context.getOuterResolve();

            Stream input = Request.InputStream;

            if (input.CanRead)
            {
                byteData = new byte[input.Length];
                input.Read(byteData, 0, (int)input.Length);
                input.Close();
                input.Dispose();

                // 解密
                if (encrypt != null)
                    byteData = encrypt.decrypt(byteData);

                dataVo = decoder.decoder(byteData);
                Type serviceCls = context.getService(context.getServiceNameSpace() + "." + dataVo.ServiceName);

                MethodInfo method = serviceCls.GetMethod(dataVo.MethodName);

                object result = method.Invoke(System.Activator.CreateInstance(serviceCls), dataVo.Param);

                dataVo.Result = result;
                dataVo.ResultStatus = "success";
                byte[] resultData = encoder.encode(dataVo);

                if (encrypt != null)
                    resultData = encrypt.encrypt(resultData);

                output = Response.OutputStream;
                output.Write(resultData, 0, resultData.Length);
                output.Flush();
                output.Close();
                output.Dispose();
            }
            else
            {

            }
        }
        catch(Exception exc)
        {
            if (dataVo == null && byteData != null)
               dataVo = decoder.decoder(byteData);
            if (dataVo == null)
               dataVo = new DataVO();
            dataVo.ResultStatus = "error";
            dataVo.ErrorMessage = exc.ToString();
            byte[] resultData = encoder.encode(dataVo);

            if (encrypt != null)
                resultData = encrypt.encrypt(resultData);
            output = Response.OutputStream;
            output.Write(resultData, 0, resultData.Length);
            output.Flush();
            output.Close();
            output.Dispose();
        }
    }