internal ReflectedAsyncActionDescriptor(MethodInfo asyncMethodInfo, MethodInfo completedMethodInfo, string actionName, ControllerDescriptor controllerDescriptor, bool validateMethods) {
            if (asyncMethodInfo == null) {
                throw new ArgumentNullException("asyncMethodInfo");
            }
            if (completedMethodInfo == null) {
                throw new ArgumentNullException("completedMethodInfo");
            }
            if (String.IsNullOrEmpty(actionName)) {
                throw Error.ParameterCannotBeNullOrEmpty("actionName");
            }
            if (controllerDescriptor == null) {
                throw new ArgumentNullException("controllerDescriptor");
            }

            if (validateMethods) {
                string asyncFailedMessage = VerifyActionMethodIsCallable(asyncMethodInfo);
                if (asyncFailedMessage != null) {
                    throw new ArgumentException(asyncFailedMessage, "asyncMethodInfo");
                }

                string completedFailedMessage = VerifyActionMethodIsCallable(completedMethodInfo);
                if (completedFailedMessage != null) {
                    throw new ArgumentException(completedFailedMessage, "completedMethodInfo");
                }
            }

            AsyncMethodInfo = asyncMethodInfo;
            CompletedMethodInfo = completedMethodInfo;
            _actionName = actionName;
            _controllerDescriptor = controllerDescriptor;
            _uniqueId = new Lazy<string>(CreateUniqueId);
        }
        internal TaskAsyncActionDescriptor(MethodInfo taskMethodInfo, string actionName, ControllerDescriptor controllerDescriptor, bool validateMethod)
        {
            if (taskMethodInfo == null)
            {
                throw new ArgumentNullException("taskMethodInfo");
            }
            if (String.IsNullOrEmpty(actionName))
            {
                throw Error.ParameterCannotBeNullOrEmpty("actionName");
            }
            if (controllerDescriptor == null)
            {
                throw new ArgumentNullException("controllerDescriptor");
            }

            if (validateMethod)
            {
                string taskFailedMessage = VerifyActionMethodIsCallable(taskMethodInfo);
                if (taskFailedMessage != null)
                {
                    throw new ArgumentException(taskFailedMessage, "taskMethodInfo");
                }
            }

            TaskMethodInfo = taskMethodInfo;
            _actionName = actionName;
            _controllerDescriptor = controllerDescriptor;
            _uniqueId = new Lazy<string>(CreateUniqueId);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ControllerInstanceInfo"/> struct.
 /// </summary>
 /// <param name="controller">The controller.</param>
 /// <param name="parameters">The parameters.</param>
 public ControllerInvocationInfo(
     ControllerDescriptor.BindPointDescriptor controller,
     Dictionary<string, string> parameters)
 {
     BindPoint = controller;
     Parameters = parameters;
 }
 internal ControllerExecutionContext(HttpContextBase httpContext, 
     object controller, RouteData data, 
     ControllerDescriptor controllerDescriptor)
 {
     this.HttpContext = httpContext;
     this.Controller = controller;
     this.RouteData = data;
     this.ControllerDescriptor = controllerDescriptor;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ControllerInstanceInfo"/> struct.
 /// </summary>
 /// <param name="controller">The controller.</param>
 /// <param name="parameters">The parameters.</param>
 /// <param name="matchDepth">The match depth.</param>
 public ControllerInvocationInfo(
     ControllerDescriptor.BindPointDescriptor controller,
     Dictionary<string, string> parameters,
     int matchDepth)
 {
     BindPoint = controller;
     Parameters = parameters;
     MatchDepth = matchDepth;
 }
示例#6
0
        /// <summary>
        /// Gets the route prefix from the provided controller.
        /// </summary>
        /// <param name="controllerDescriptor">The controller descriptor.</param>
        /// <returns>The route prefix or null.</returns>
        protected virtual string GetRoutePrefix(ControllerDescriptor controllerDescriptor)
        {
            IRoutePrefix[] attributes = controllerDescriptor
                                        .GetCustomAttributes(inherit: false)
                                        .OfType <IRoutePrefix>()
                                        .ToArray();

            if (attributes == null)
            {
                return(null);
            }

            if (attributes.Length > 1)
            {
                string errorMessage = Error.Format(
                    MvcResources.RoutePrefix_CannotSupportMultiRoutePrefix,
                    controllerDescriptor.ControllerType.FullName
                    );
                throw new InvalidOperationException(errorMessage);
            }

            if (attributes.Length == 1)
            {
                IRoutePrefix attribute = attributes[0];

                if (attribute != null)
                {
                    string prefix = attribute.Prefix;
                    if (prefix == null)
                    {
                        string errorMessage = Error.Format(
                            MvcResources.RoutePrefix_PrefixCannotBeNull,
                            controllerDescriptor.ControllerType.FullName
                            );
                        throw new InvalidOperationException(errorMessage);
                    }

                    if (
                        prefix.StartsWith("/", StringComparison.Ordinal) ||
                        prefix.EndsWith("/", StringComparison.Ordinal)
                        )
                    {
                        string errorMessage = Error.Format(
                            MvcResources.RoutePrefix_CannotStartOrEnd_WithForwardSlash,
                            prefix,
                            controllerDescriptor.ControllerName
                            );
                        throw new InvalidOperationException(errorMessage);
                    }

                    return(prefix);
                }
            }

            return(null);
        }
示例#7
0
        /// <summary>
        /// Invokes the action return ActionResult
        /// </summary>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="actionName">Name of the action.</param>
        /// <returns></returns>
        public virtual ModuleActionInvokedContext InvokeActionWithoutExecuteResult(ModulePosition modulePosition, ControllerContext controllerContext, string actionName)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }
            if (string.IsNullOrEmpty(actionName))
            {
                throw new ArgumentNullException("actionName");
            }

            ControllerDescriptor controllerDescriptor = this.GetControllerDescriptor(controllerContext);
            ActionDescriptor     actionDescriptor     = this.FindAction(controllerContext, controllerDescriptor, actionName);

            if (actionDescriptor == null)
            {
                return(null);
            }
            FilterInfo filters = this.GetFilters(controllerContext, actionDescriptor);

            try
            {
                //Default AuthorizationFilter
                AuthorizationContext context = this.InvokeAuthorizationFilters(controllerContext, filters.AuthorizationFilters, actionDescriptor);
                if (context.Result != null)
                {
                    return(new ModuleActionInvokedContext(modulePosition, controllerContext, context.Result));
                }

                ActionResult authorizationResult = null;//this.OnAuthorization(controllerContext, GetFilter<FunctionAttribute>((ReflectedActionDescriptor)actionDescriptor));
                if (authorizationResult != null)
                {
                    return(new ModuleActionInvokedContext(modulePosition, controllerContext, authorizationResult));
                }
                else
                {
                    if (controllerContext.Controller.ValidateRequest)
                    {
                        ValidateRequest(controllerContext.HttpContext.Request);
                    }
                    IDictionary <string, object> parameterValues = this.GetParameterValues(controllerContext, actionDescriptor);
                    ActionExecutedContext        context2        = this.InvokeActionMethodWithFilters(controllerContext, filters.ActionFilters, actionDescriptor, parameterValues);
                    //this.InvokeActionResultWithFilters(controllerContext, filters.ResultFilters, context2.Result);
                    return(new ModuleActionInvokedContext(modulePosition, controllerContext, context2.Result));
                }
            }
            catch (Exception exception)
            {
                ExceptionContext context3 = this.InvokeExceptionFilters(controllerContext, filters.ExceptionFilters, exception);
                if (!context3.ExceptionHandled)
                {
                    throw;
                }
                return(new ModuleActionInvokedContext(modulePosition, controllerContext, context3.Result));
            }
        }
        /// <summary>
        /// Gets the area prefix from the provided controller.
        /// </summary>
        /// <param name="controllerDescriptor">The controller descriptor.</param>
        /// <returns>The area prefix or null.</returns>
        protected virtual string GetAreaPrefix(ControllerDescriptor controllerDescriptor)
        {
            RouteAreaAttribute area       = controllerDescriptor.GetAreaFrom();
            string             areaName   = controllerDescriptor.GetAreaName(area);
            string             areaPrefix = area != null ? area.AreaPrefix ?? area.AreaName : null;

            ValidateAreaPrefixTemplate(areaPrefix, areaName, controllerDescriptor);

            return(areaPrefix);
        }
        /// <summary>
        /// Registers the controller.
        /// </summary>
        /// <param name="descriptor">The descriptor.</param>
        private void RegisterController(ControllerDescriptor descriptor)
        {
            if (logger.IsDebugEnabled)
            {
                logger.DebugFormat("Registering controller descriptor for Area: '{0}' Name: '{1}'",
                                   descriptor.Area, descriptor.Name);
            }

            Tree.AddController(descriptor.Area, descriptor.Name, descriptor.ControllerType);
        }
示例#10
0
 public AutofacFilterProviderFixture()
 {
     this._baseControllerContext = new ControllerContext {
         Controller = new TestController()
     };
     this._baseMethodInfo            = TestController.GetAction1MethodInfo <TestController>();
     this._actionName                = this._baseMethodInfo.Name;
     this._controllerDescriptor      = new Mock <ControllerDescriptor>().Object;
     this._reflectedActionDescriptor = new ReflectedActionDescriptor(this._baseMethodInfo, this._actionName, this._controllerDescriptor);
 }
 public ResourceErrorActionDescriptor(
     ControllerDescriptor controllerDescriptor,
     HttpStatusCode statusCode,
     string message
     )
 {
     this.message              = message;
     this.statusCode           = statusCode;
     this.controllerDescriptor = controllerDescriptor;
 }
        private static ActionDescriptor CreateActionDescriptor(ControllerDescriptor controller,
                                                               AsyncActionMethodSelector actionSelector, MethodInfo method)
        {
            string actionName = actionSelector.GetActionName(method);
            ActionDescriptorCreator creator = actionSelector.GetActionDescriptorDelegate(method);

            Debug.Assert(creator != null);

            return(creator(actionName, controller));
        }
示例#13
0
        protected override ControllerDescriptor GetControllerDescriptor(ControllerContext controllerContext)
        {
            ControllerDescriptor controllerDescriptor = base.GetControllerDescriptor(controllerContext);

            if (null != controllerDescriptor)
            {
                return(new MyReflectedControllerDescriptor(controllerDescriptor.ControllerType));
            }
            return(controllerDescriptor);
        }
        public virtual IAsyncResult BeginInvokeAction(ControllerContext controllerContext, string actionName, AsyncCallback callback, object state)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            Contract.Assert(controllerContext.RouteData != null);
            if (String.IsNullOrEmpty(actionName) && !controllerContext.RouteData.HasDirectRouteMatch())
            {
                throw Error.ParameterCannotBeNullOrEmpty("actionName");
            }

            ControllerDescriptor controllerDescriptor = GetControllerDescriptor(controllerContext);
            ActionDescriptor     actionDescriptor     = FindAction(controllerContext, controllerDescriptor, actionName);

            if (actionDescriptor != null)
            {
                BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState)
                {
                    var task = InvokeActionAsync(controllerContext, actionDescriptor);
                    var tcs  = new TaskCompletionSource <bool>(asyncState);
                    task.ContinueWith(t =>
                    {
                        if (t.IsFaulted)
                        {
                            tcs.TrySetException(t.Exception.InnerExceptions);
                        }
                        else if (t.IsCanceled)
                        {
                            tcs.TrySetCanceled();
                        }
                        else
                        {
                            tcs.TrySetResult(t.Result);
                        }
                        if (asyncCallback != null)
                        {
                            asyncCallback(tcs.Task);
                        }
                    }, TaskContinuationOptions.ExecuteSynchronously);
                    return(tcs.Task);
                };
                EndInvokeDelegate <bool> endDelegate = delegate(IAsyncResult asyncResult)
                {
                    return(((Task <bool>)asyncResult).GetAwaiter().GetResult());
                };
                return(AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _invokeActionTag));
            }
            else
            {
                // Notify the controller that no action was found.
                return(BeginInvokeAction_ActionNotFound(callback, state));
            }
        }
示例#15
0
        /// <summary>
        /// Gets direct routes for the given controller descriptor and action descriptors based on
        /// <see cref="IDirectRouteFactory"/> attributes.
        /// </summary>
        /// <param name="controllerDescriptor">The controller descriptor.</param>
        /// <param name="actionDescriptors">The action descriptors for all actions.</param>
        /// <param name="constraintResolver">The constraint resolver.</param>
        /// <returns>A set of route entries.</returns>
        /// <remarks>
        /// The implementation returns route entries for the given controller and actions.
        ///
        /// Any actions that have associated <see cref="IDirectRouteFactory"/> instances will produce route
        /// entries that route direct to those actions.
        ///
        /// Any actions that do not have an associated <see cref="IDirectRouteFactory"/> instances will be
        /// associated with the controller. If the controller has any associated <see cref="IDirectRouteProvider"/>
        /// instances, then route entries will be created for the controller and associated actions.
        /// </remarks>
        public virtual IReadOnlyList <RouteEntry> GetDirectRoutes(
            ControllerDescriptor controllerDescriptor,
            IReadOnlyList <ActionDescriptor> actionDescriptors,
            IInlineConstraintResolver constraintResolver
            )
        {
            List <RouteEntry> entries = new List <RouteEntry>();

            List <ActionDescriptor> actionsWithoutRoutes = new List <ActionDescriptor>();

            foreach (ActionDescriptor action in actionDescriptors)
            {
                IReadOnlyList <IDirectRouteFactory> factories = GetActionRouteFactories(action);

                if (factories != null && factories.Count > 0)
                {
                    IReadOnlyCollection <RouteEntry> actionEntries = GetActionDirectRoutes(
                        action,
                        factories,
                        constraintResolver
                        );
                    if (actionEntries != null)
                    {
                        entries.AddRange(actionEntries);
                    }
                }
                else
                {
                    // IF there are no routes on the specific action, attach it to the controller routes (if any).
                    actionsWithoutRoutes.Add(action);
                }
            }

            if (actionsWithoutRoutes.Count > 0)
            {
                IReadOnlyList <IDirectRouteFactory> controllerFactories =
                    GetControllerRouteFactories(controllerDescriptor);
                if (controllerFactories != null && controllerFactories.Count > 0)
                {
                    IReadOnlyCollection <RouteEntry> controllerEntries = GetControllerDirectRoutes(
                        controllerDescriptor,
                        actionsWithoutRoutes,
                        controllerFactories,
                        constraintResolver
                        );

                    if (controllerEntries != null)
                    {
                        entries.AddRange(controllerEntries);
                    }
                }
            }

            return(entries);
        }
        private static ActionDescriptor CreateStubActionDescriptor(
            ControllerDescriptor controllerDescriptor,
            string actionName
            )
        {
            Mock <ActionDescriptor> mock = new Mock <ActionDescriptor>(MockBehavior.Strict);

            mock.SetupGet(d => d.ControllerDescriptor).Returns(controllerDescriptor);
            mock.SetupGet(d => d.ActionName).Returns(actionName);
            return(mock.Object);
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            return;

            var requestCookies        = filterContext.RequestContext.HttpContext.Request.Cookies;
            ActionDescriptor arg_34_0 = filterContext.ActionDescriptor;
            bool             inherit  = true;
            bool             arg_5B_0;

            if (!arg_34_0.IsDefined(typeof(AllowAnonymousAttribute), inherit))
            {
                ControllerDescriptor arg_53_0 = filterContext.ActionDescriptor.ControllerDescriptor;
                bool inherit2 = true;
                arg_5B_0 = arg_53_0.IsDefined(typeof(AllowAnonymousAttribute), inherit2);
            }
            else
            {
                arg_5B_0 = true;
            }
            bool flag = arg_5B_0;

            if (flag)
            {
                if (requestCookies["UserCookie"] != null)
                {
                    if (userDic.ContainsKey(requestCookies["UserCookie"].Value))
                    {
                        if (requestCookies[userDic[requestCookies["UserCookie"].Value]] != null)
                        {
                            filterContext.HttpContext.Response.Redirect("/admin/adminhome/index");
                            filterContext.HttpContext.ApplicationInstance.CompleteRequest();
                        }
                    }
                }
                return;
            }
            if (requestCookies["UserCookie"] == null)
            {
                filterContext.HttpContext.Response.Redirect("/admin");
                filterContext.HttpContext.ApplicationInstance.CompleteRequest();
                return;
            }
            var guidUName   = requestCookies["UserCookie"].Value;
            var userNameDic = "";

            userDic.TryGetValue(guidUName, out userNameDic);

            if (requestCookies[userNameDic] == null)
            {
                filterContext.HttpContext.Response.Redirect("/admin");
                filterContext.HttpContext.ApplicationInstance.CompleteRequest();
                return;
            }
        }
示例#18
0
        public void GetCustomAttributesReturnsEmptyArrayOfAttributeType()
        {
            // Arrange
            ControllerDescriptor cd = GetControllerDescriptor();

            // Act
            ObsoleteAttribute[] attrs = (ObsoleteAttribute[])cd.GetCustomAttributes(typeof(ObsoleteAttribute), true);

            // Assert
            Assert.Empty(attrs);
        }
示例#19
0
        public void ControllerNamePropertyReturnsControllerTypeName()
        {
            // Arrange
            ControllerDescriptor cd = GetControllerDescriptor(typeof(object));

            // Act
            string name = cd.ControllerName;

            // Assert
            Assert.Equal("Object", name);
        }
示例#20
0
        public void IsDefinedThrowsIfAttributeTypeIsNull()
        {
            // Arrange
            ControllerDescriptor cd = GetControllerDescriptor();

            // Act & assert
            ExceptionHelper.ExpectArgumentNullException(
                delegate {
                cd.IsDefined(null /* attributeType */, true);
            }, "attributeType");
        }
示例#21
0
        /// <summary>
        /// Gets the filters.
        /// </summary>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="actionName">Name of the action.</param>
        /// <returns></returns>
        protected FilterInfo GetFilters(ControllerContext controllerContext, string actionName)
        {
            ControllerDescriptor controllerDescriptor = this.GetControllerDescriptor(controllerContext);
            ActionDescriptor     actionDescriptor     = this.FindAction(controllerContext, controllerDescriptor, actionName);

            if (actionDescriptor == null)
            {
                return(null);
            }
            return(this.GetFilters(controllerContext, actionDescriptor));
        }
示例#22
0
        public void IsDefinedReturnsFalse()
        {
            // Arrange
            ControllerDescriptor cd = GetControllerDescriptor();

            // Act
            bool isDefined = cd.IsDefined(typeof(object), true);

            // Assert
            Assert.False(isDefined);
        }
 private void AddRouteEntries(SubRouteCollection collector, string areaPrefix, string prefix,
                              IEnumerable <IRouteInfoProvider> providers, ControllerDescriptor controller,
                              IList <ActionDescriptor> actions, bool routeIsForAction)
 {
     foreach (IRouteInfoProvider provider in providers)
     {
         RouteEntry entry = CreateRouteEntry(areaPrefix, prefix, provider, controller, actions,
                                             routeIsForAction);
         collector.Add(entry);
     }
 }
示例#24
0
        protected virtual ActionDescriptor GetActionDescriptor(string actionName, ControllerDescriptor controllerDescriptor, ControllerContext controllerContext)
        {
            ActionDescriptor actionDescriptor = null;
            var found = this.TryFindActionDescriptor(actionName, controllerContext, controllerDescriptor, out actionDescriptor);

            if (!found)
            {
                actionDescriptor = controllerDescriptor.GetCanonicalActions().Where(a => a.ActionName == actionName).FirstOrDefault();
            }
            return(actionDescriptor);
        }
示例#25
0
        protected override ControllerDescriptor GetControllerDescriptor(ControllerContext controllerContext)
        {
            // Frequently called, so ensure delegate is static
            Type controllerType = controllerContext.Controller.GetType();
            ControllerDescriptor controllerDescriptor = DescriptorCache.GetDescriptor(
                controllerType: controllerType,
                creator: ReflectedAsyncControllerDescriptor.DefaultDescriptorFactory,
                state: controllerType);

            return(controllerDescriptor);
        }
示例#26
0
        public ActionResult Index()
        {
            AsyncActionInvoker      actionInvoker        = (AsyncActionInvoker)this.ActionInvoker;
            ControllerDescriptor    controllerDescriptor = actionInvoker.GetControllerDescriptor(ControllerContext);
            List <ActionDescriptor> actionDescriptors    = new List <ActionDescriptor>();

            actionDescriptors.Add(controllerDescriptor.FindAction(ControllerContext, "Foo"));
            actionDescriptors.Add(controllerDescriptor.FindAction(ControllerContext, "Bar"));
            actionDescriptors.Add(controllerDescriptor.FindAction(ControllerContext, "Baz"));

            return(View(actionDescriptors));
        }
示例#27
0
        /// <summary>
        /// Si el controlador no se debe aplicar autorizacion. Ejemplo pagina de inicio del sitio web.
        /// </summary>
        /// <param name="controllerDescriptor"></param>
        /// <returns></returns>
        public static bool SkipControllerSecurity(ControllerDescriptor controllerDescriptor)
        {
            var filter = from i in ListSkipController
                         where controllerDescriptor.ControllerName.Equals(i, StringComparison.OrdinalIgnoreCase)
                         select i;

            var list = filter.ToList();

            log.DebugFormat("Resultado de omitir controladores : [{0}]. Cantidad de elementos que coincide con la nombre  de controlador desde el listado de omitidos : [{1}]", controllerDescriptor.ControllerName, list.Count);

            return(list.Count > 0);
        }
        public void FixtureSetUp()
        {
            _baseControllerContext = new ControllerContext {
                Controller = new TestController()
            };

            _baseMethodInfo = TestController.GetAction1MethodInfo <TestController>();
            _actionName     = _baseMethodInfo.Name;

            _controllerDescriptor      = new Mock <ControllerDescriptor>().Object;
            _reflectedActionDescriptor = new ReflectedActionDescriptor(_baseMethodInfo, _actionName, _controllerDescriptor);
        }
        /// <summary>
        /// Finds the action for the controller, if not it is inferred.
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="controllerDescriptor"></param>
        /// <param name="actionName"></param>
        /// <returns></returns>
        protected override ActionDescriptor FindAction(ControllerContext controllerContext,
                                                       ControllerDescriptor controllerDescriptor, string actionName)
        {
            var foundAction = base.FindAction(controllerContext, controllerDescriptor, actionName);

            if (foundAction == null)
            {
                InferredAction inferredAction = GetInferredAction(controllerDescriptor, actionName);
                foundAction = new InferredActionDescriptor(actionName, controllerDescriptor, inferredAction);
            }
            return(foundAction);
        }
        public void Invoke_should_thrown_an_404_if_cannot_find_a_action()
        {
            var data = new RouteData();
            data.Values.Add("action", "Foo");

            var sink = new ActionResolutionSink();
            var descriptor = new ControllerDescriptor(GetType(), "TestController", "Test");
            descriptor.Actions.Add(new TestActionDescriptor());

            var context = new ControllerExecutionContext(null, new ControllerContext(), this, data, descriptor);

            sink.Invoke(context);
        }
        protected virtual ActionDescriptor GetHandleErrorAction(ExceptionContext filterContext)
        {
            string actionName = filterContext.RouteData.GetRequiredString("action");
            ControllerDescriptor       controllerDescriptor = this.GetControllerDescriptor(filterContext);
            ActionDescriptor           actionDescriptor     = controllerDescriptor.FindAction(filterContext, actionName);
            HandleErrorActionAttribute attribute            = actionDescriptor.GetCustomAttributes(true).OfType <HandleErrorActionAttribute>().FirstOrDefault();

            if (null == attribute)
            {
                return(null);
            }
            return(controllerDescriptor.FindAction(filterContext, attribute.HandleErrorAction));
        }
        public void GetDescriptor()
        {
            // Arrange
            Type controllerType             = typeof(object);
            ControllerDescriptorCache cache = new ControllerDescriptorCache();

            // Act
            ControllerDescriptor descriptor1 = cache.GetDescriptor(controllerType, () => new ReflectedControllerDescriptor(controllerType));
            ControllerDescriptor descriptor2 = cache.GetDescriptor(controllerType, () => new ReflectedControllerDescriptor(controllerType));

            // Assert
            Assert.Same(controllerType, descriptor1.ControllerType);
            Assert.Same(descriptor1, descriptor2);
        }
 /// <summary>
 /// Creates <see cref="RouteEntry"/> instances based on the provided factories, controller and actions. The route
 /// entries provided direct routing to the provided controller and can reach the set of provided actions.
 /// </summary>
 /// <param name="controllerDescriptor">The controller descriptor.</param>
 /// <param name="actionDescriptors">The action descriptors.</param>
 /// <param name="factories">The direct route factories.</param>
 /// <param name="constraintResolver">The constraint resolver.</param>
 /// <returns>A set of route entries.</returns>
 protected virtual IReadOnlyList <RouteEntry> GetControllerDirectRoutes(
     ControllerDescriptor controllerDescriptor,
     IReadOnlyList <ActionDescriptor> actionDescriptors,
     IReadOnlyList <IDirectRouteFactory> factories,
     IInlineConstraintResolver constraintResolver)
 {
     return(CreateRouteEntries(
                GetAreaPrefix(controllerDescriptor),
                GetRoutePrefix(controllerDescriptor),
                factories,
                actionDescriptors,
                constraintResolver,
                targetIsAction: false));
 }
示例#34
0
        public void ControllerNamePropertyReturnsControllerTypeNameWithoutControllerSuffix()
        {
            // Arrange
            Mock <Type> mockType = new Mock <Type>();

            mockType.Setup(t => t.Name).Returns("somecontroller");
            ControllerDescriptor cd = GetControllerDescriptor(mockType.Object);

            // Act
            string name = cd.ControllerName;

            // Assert
            Assert.Equal("some", name);
        }
        public void GetDescriptor()
        {
            // Arrange
            Type controllerType             = typeof(object);
            ControllerDescriptorCache cache = new ControllerDescriptorCache();

            // Act
            ControllerDescriptor descriptor1 = cache.GetDescriptor(controllerType, () => new ReflectedControllerDescriptor(controllerType));
            ControllerDescriptor descriptor2 = cache.GetDescriptor(controllerType, () => new ReflectedControllerDescriptor(controllerType));

            // Assert
            Assert.AreSame(controllerType, descriptor1.ControllerType, "ControllerType was incorrect.");
            Assert.AreSame(descriptor1, descriptor2, "Selector was not correctly cached.");
        }
示例#36
0
        protected override string GetRoutePrefix(ControllerDescriptor controllerDescriptor)
        {
            var routePrefix        = base.GetRoutePrefix(controllerDescriptor);
            var controllerBaseType = controllerDescriptor.ControllerType.BaseType;

            //The routes prefix attribute is not working as intended so we instead force the prefix
            switch (controllerBaseType.Name)
            {
            case "HazmatBaseController":
                return("hazmat" + (!string.IsNullOrEmpty(routePrefix) ? "/" + routePrefix : string.Empty));
            }

            return(routePrefix);
        }
示例#37
0
        /// <summary>
        /// Builds an <see cref="Route"/> for a particular controller.
        /// </summary>
        /// <param name="routeTemplate">The tokenized route template for the route.</param>
        /// <param name="controllerDescriptor">The controller the route attribute has been applied on.</param>
        /// <returns>The generated <see cref="Route"/>.</returns>
        public Route BuildDirectRoute(string routeTemplate, ControllerDescriptor controllerDescriptor)
        {
            if (routeTemplate == null)
            {
                throw Error.ArgumentNull("routeTemplate");
            }

            if (controllerDescriptor == null)
            {
                throw Error.ArgumentNull("controllerDescriptor");
            }
                        
            string controllerName = controllerDescriptor.ControllerName;
                        
            RouteAreaAttribute area = controllerDescriptor.GetAreaFrom();
            string areaName = controllerDescriptor.GetAreaName(area);
            string areaPrefix = area != null ? area.AreaPrefix ?? area.AreaName : null;

            RouteValueDictionary defaults = new RouteValueDictionary
            {
                { "controller", controllerName }
            };

            Type controllerType = controllerDescriptor.ControllerType;

            RouteValueDictionary dataTokens = new RouteValueDictionary();
            dataTokens[RouteDataTokenKeys.DirectRouteToController] = controllerDescriptor;
            if (areaName != null)
            {
                dataTokens.Add(RouteDataTokenKeys.Area, areaName);
                dataTokens.Add(RouteDataTokenKeys.UseNamespaceFallback, value: false);
                if (controllerType != null)
                {
                    dataTokens.Add(RouteDataTokenKeys.Namespaces, new[] { controllerType.Namespace });
                }
            }

            RouteValueDictionary constraints = new RouteValueDictionary();
            string detokenizedRouteTemplate = InlineRouteTemplateParser.ParseRouteTemplate(routeTemplate, defaults, constraints, ConstraintResolver);

            Route route = new Route(detokenizedRouteTemplate, new MvcRouteHandler())
            {
                Defaults = defaults,
                Constraints = constraints,
                DataTokens = dataTokens
            };

            return route;
        }
        /// <summary>
        /// Gets direct routes for the given controller descriptor and action descriptors based on 
        /// <see cref="IDirectRouteFactory"/> attributes.
        /// </summary>
        /// <param name="controllerDescriptor">The controller descriptor.</param>
        /// <param name="actionDescriptors">The action descriptors for all actions.</param>
        /// <param name="constraintResolver">The constraint resolver.</param>
        /// <returns>A set of route entries.</returns>
        /// <remarks>
        /// The implementation returns route entries for the given controller and actions. 
        /// 
        /// Any actions that have associated <see cref="IDirectRouteFactory"/> instances will produce route
        /// entries that route direct to those actions.
        /// 
        /// Any actions that do not have an associated <see cref="IDirectRouteFactory"/> instances will be
        /// associated with the controller. If the controller has any associated <see cref="IDirectRouteProvider"/>
        /// instances, then route entries will be created for the controller and associated actions.
        /// </remarks>
        public virtual IReadOnlyList<RouteEntry> GetDirectRoutes(
            ControllerDescriptor controllerDescriptor,
            IReadOnlyList<ActionDescriptor> actionDescriptors,
            IInlineConstraintResolver constraintResolver)
        {
            List<RouteEntry> entries = new List<RouteEntry>();

            List<ActionDescriptor> actionsWithoutRoutes = new List<ActionDescriptor>();

            foreach (ActionDescriptor action in actionDescriptors)
            {
                IReadOnlyList<IDirectRouteFactory> factories = GetActionRouteFactories(action);

                if (factories != null && factories.Count > 0)
                {
                    IReadOnlyCollection<RouteEntry> actionEntries = GetActionDirectRoutes(action, factories, constraintResolver);
                    if (actionEntries != null)
                    {
                        entries.AddRange(actionEntries);
                    }
                }
                else
                {
                    // IF there are no routes on the specific action, attach it to the controller routes (if any).
                    actionsWithoutRoutes.Add(action);
                }
            }

            if (actionsWithoutRoutes.Count > 0)
            {
                IReadOnlyList<IDirectRouteFactory> controllerFactories = GetControllerRouteFactories(controllerDescriptor);
                if (controllerFactories != null && controllerFactories.Count > 0)
                {
                    IReadOnlyCollection<RouteEntry> controllerEntries = GetControllerDirectRoutes(
                        controllerDescriptor,
                        actionsWithoutRoutes,
                        controllerFactories,
                        constraintResolver);

                    if (controllerEntries != null)
                    {
                        entries.AddRange(controllerEntries);
                    }
                }
            }

            return entries;
        }
        public void Invoke_should_find_action_on_controller()
        {
            var data = new RouteData();
            data.Values.Add("action", "TestAction");

            var sink = new ActionResolutionSink();
            var descriptor = new ControllerDescriptor(GetType(), "TestController", "Test");
            descriptor.Actions.Add(new TestActionDescriptor());

            var context = new ControllerExecutionContext(null, new ControllerContext(), this, data, descriptor);

            sink.Invoke(context);

            Assert.IsNotNull(context.SelectedAction);
            Assert.AreEqual("TestAction", context.SelectedAction.Name);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ValidatingControllerHandler"/> class.
 /// </summary>
 /// <param name="descriptor"></param>
 /// <param name="logger"></param>
 protected internal ValidatingControllerHandler(Application application, ControllerDescriptor descriptor, ILogger logger)
     : base(application, descriptor, logger)
 {
     try
     {
         validators.InsertRange(0, ValidationRepository.Instance.RegisterValidatable(descriptor.ControllerType as Type));
     }
     catch (InvalidCastException)
     {
         logger.Report(Exceptions.InvalidCast, descriptor.ControllerTypeName);
     }
     catch (Exception ex)
     {
         logger.Report(Exceptions.RuntimeError, ex, ex.Message, descriptor.ControllerTypeName);
     }
 }
        public void Invoke_should_execute_ActionResult_if_present()
        {
            var controllerCtx = new ControllerContext();
            var descriptor = new ControllerDescriptor(GetType(), "TestController", "Test");
            var sink = new ActionResultExecutionSink();
            var result = new TestActionResult();
            var context = new ControllerExecutionContext(null, controllerCtx, this, new RouteData(), descriptor)
                          	{
                          		InvocationResult = result,
                                SelectedAction = new TestActionDescriptor()
                          	};

            sink.Invoke(context);

            Assert.IsTrue(result.executed);
        }
		internal ReflectedAsyncActionDescriptor(MethodInfo entryMethod, MethodInfo completedMethod, 
			string actionName, ControllerDescriptor controller, bool validateMethods)
		{
			Precondition.Require(entryMethod, () => Error.ArgumentNull("entryMethod"));
			Precondition.Require(completedMethod, () => Error.ArgumentNull("completedMethod"));
			Precondition.Defined(actionName, () => Error.ArgumentNull("actionName"));
			Precondition.Require(controller, () => Error.ArgumentNull("controller"));
			
			if (validateMethods)
			{
				ValidateActionMethod(entryMethod);
				ValidateActionMethod(completedMethod);
			}

			_executeTag = new object();
			_entryMethod = entryMethod;
			_completedMethod = completedMethod;
			_name = actionName;
			_controller = controller;
		}
        // needs caching (per instance)
        public ControllerDescriptor Build(Type controllerType)
        {
            Contract.Requires(controllerType != null);
            Contract.EndContractBlock();

            string name = controllerType.Name;
            name = name.Substring(0, name.Length - "Controller".Length).ToLowerInvariant();

            var controllerDesc = new ControllerDescriptor(controllerType, name, area: string.Empty);

            foreach (var method in controllerType.GetMethods(BindingFlags.Instance | BindingFlags.Public))
            {
                var action = BuildActionDescriptor(method);

                if (action != null)
                    controllerDesc.Actions.Add(action);
            }

            return controllerDesc;
        }
		/// <summary>
		/// Creates a <see cref="ControllerDescriptor"/> based on the conventions
		/// and possible attributes found for the Controller Type specified
		/// </summary>
		/// <param name="controllerType">The controller type</param>
		/// <returns>A controller descriptor</returns>
		public static ControllerDescriptor Inspect(Type controllerType)
		{
			ControllerDescriptor descriptor;

			if (controllerType.IsDefined(typeof(ControllerDetailsAttribute), true))
			{
				object[] attrs = controllerType.GetCustomAttributes(
					typeof(ControllerDetailsAttribute), true);

				ControllerDetailsAttribute details = attrs[0] as ControllerDetailsAttribute;

				descriptor = new ControllerDescriptor(controllerType,
				                                      ObtainControllerName(details.Name, controllerType),
				                                      details.Area);
			}
			else
			{
				descriptor = new ControllerDescriptor(controllerType,
				                                      ObtainControllerName(null, controllerType), String.Empty);
			}

			return descriptor;
		}
        /// <summary>
        /// Gets the area prefix from the provided controller.
        /// </summary>
        /// <param name="controllerDescriptor">The controller descriptor.</param>
        /// <returns>The area prefix or null.</returns>
        protected virtual string GetAreaPrefix(ControllerDescriptor controllerDescriptor)
        {
            RouteAreaAttribute area = controllerDescriptor.GetAreaFrom();
            string areaName = controllerDescriptor.GetAreaName(area);
            string areaPrefix = area != null ? area.AreaPrefix ?? area.AreaName : null;

            ValidateAreaPrefixTemplate(areaPrefix, areaName, controllerDescriptor);

            return areaPrefix;
        }
 public ReflectedAsyncActionDescriptor(MethodInfo asyncMethodInfo, MethodInfo completedMethodInfo, string actionName, ControllerDescriptor controllerDescriptor)
     : this(asyncMethodInfo, completedMethodInfo, actionName, controllerDescriptor, true /* validateMethods */) {
 }
 protected override ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)
 {
     return base.FindAction(controllerContext, controllerDescriptor, "NormalAction");
 }
 protected override ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)
 {
     return PublicFindAction(controllerContext, controllerDescriptor, actionName);
 }
 public virtual ActionDescriptor PublicFindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)
 {
     return base.FindAction(controllerContext, controllerDescriptor, actionName);
 }
        /// <summary>
        /// Creates the controller handler for the given descriptor.
        /// </summary>
        /// <param name="descriptor">The descriptor.</param>
        /// <returns></returns>
        public virtual IControllerHandler CreateControllerHandler(ControllerDescriptor descriptor)
        {
            return new ControllerHandler(application, descriptor, application.LoggerFactory.GetLogger(typeof(ControllerHandler)));
//            return null;
        }
 /// <summary>
 /// Registers the controller.
 /// </summary>
 /// <param name="descriptor">The descriptor.</param>
 public virtual void RegisterController(ControllerDescriptor descriptor)
 {
     handlers.Add(descriptor.ControllerType, handlerFactory.CreateControllerHandler(descriptor));
     dispatcherFactory.GetDispatcherInstance().RegisterController(descriptor);
 }
 private static void ValidateTemplate(string routeTemplate, string actionName, ControllerDescriptor controllerDescriptor)
 {
     if (routeTemplate.StartsWith("/", StringComparison.Ordinal))
     {
         string errorMessage = Error.Format(MvcResources.RouteTemplate_CannotStart_WithForwardSlash,
                                            routeTemplate, actionName, controllerDescriptor.ControllerName);
         throw new InvalidOperationException(errorMessage);
     }
 }
 private static void ValidateAreaPrefixTemplate(string areaPrefix, string areaName, ControllerDescriptor controllerDescriptor)
 {
     if (areaPrefix != null && areaPrefix.EndsWith("/", StringComparison.Ordinal))
     {
         string errorMessage = Error.Format(MvcResources.RouteAreaPrefix_CannotEnd_WithForwardSlash,
                                            areaPrefix, areaName, controllerDescriptor.ControllerName);
         throw new InvalidOperationException(errorMessage);
     }
 }
 private static void ValidatePrefixTemplate(string prefix, ControllerDescriptor controllerDescriptor)
 {
     if (prefix != null && (prefix.StartsWith("/", StringComparison.Ordinal) || prefix.EndsWith("/", StringComparison.Ordinal)))
     {
         string errorMessage = Error.Format(MvcResources.RoutePrefix_CannotStartOrEnd_WithForwardSlash,
                                            prefix, controllerDescriptor.ControllerName);
         throw new InvalidOperationException(errorMessage);
     }
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="ControllerHandler"/> class.
		/// </summary>
		/// <param name="controllerType">Type of the controller.</param>
        protected internal ControllerHandler(Application application, ControllerDescriptor descriptor, ILogger logger)
        {
            this.descriptor = descriptor;
            this.logger = logger;
            this.application = application;

            controllerConstructor = ((Type)descriptor.ControllerType).GetConstructor(Type.EmptyTypes);

            foreach (ControllerDescriptor.BindPointDescriptor bindPoint in descriptor.Targets)
                manipulatedFields.AddRange(bindPoint.ParameterFields.Values);
            manipulatedFields.AddRange(descriptor.FormFields.Values);
            manipulatedFields.AddRange(descriptor.RequestFields.Values);
            manipulatedFields.AddRange(descriptor.SessionFields.Values);
            foreach (ControllerDescriptor.CookieFieldDescriptor cookieField in descriptor.CookieFields.Values)
                manipulatedFields.Add(cookieField.Field);

            manipulatedFields.ForEach(
                (mbr) => 
                {
                    var attributes = mbr.GetCustomAttributes(typeof(FormatAsAttribute), false) as FormatAsAttribute[];
                    // Field can be Request and FormField at the same time. In that case - it will be added twice into the collection.
                    if ((attributes.Length != 1) || (formatters.ContainsKey(mbr)))
                        return;
                    
                    formatters.Add(mbr, application.FormatManagerFactory.GetManagerInstance().GetFormatterByFormat(attributes[0].FormatName));
                }
            );

		    BuildMapper(descriptor);
        }
        /// <summary>
        /// Builds the mapper. MapsWith attribute takes priority over InferMappingFor. Also, multiple mapping attributes are currently unsupported.
        /// </summary>
        /// <param name="descriptor">The descriptor.</param>
        protected virtual void BuildMapper(ControllerDescriptor descriptor)
        {
            var mapperAttribute = descriptor.ControllerType.GetCustomAttributes(typeof (MapsWithAttribute), false) as MapsWithAttribute[];
            if (mapperAttribute != null && mapperAttribute.Length == 1)
            {
                mapper = Activator.CreateInstance(mapperAttribute[0].MapperType) as EntityMapperBase;

                if (mapper != null)
                {
                    MapperRepository.Instance.RegisterMapper(mapper);
                    return;
                }
            }

            var inferredAttribute = descriptor.ControllerType.GetCustomAttributes(typeof(InferMappingForAttribute), false) as InferMappingForAttribute[];
            if (inferredAttribute != null && inferredAttribute.Length == 1)
            {
                var mapperType =
                    typeof (EntityMapper<,>).MakeGenericType(new Type[]
                                                                 {
                                                                     descriptor.ControllerType as Type,
                                                                     inferredAttribute[0].TargetType
                                                                 });
                mapper =
                    Activator.CreateInstance(mapperType) as EntityMapperBase;

                // configure the mapper based on the strict flag.
                if (inferredAttribute[0].Strict)
                    mapper.InferStrictOnly();
                else
                    mapper.InferOnly();

                MapperRepository.Instance.RegisterMapper(mapper);
            }
        }
        /// <summary>
        /// Gets the route prefix from the provided controller.
        /// </summary>
        /// <param name="controllerDescriptor">The controller descriptor.</param>
        /// <returns>The route prefix or null.</returns>
        protected virtual string GetRoutePrefix(ControllerDescriptor controllerDescriptor)
        {
            IRoutePrefix[] attributes = controllerDescriptor.GetCustomAttributes(inherit: false).OfType<IRoutePrefix>().ToArray();

            if (attributes == null)
            {
                return null;
            }

            if (attributes.Length > 1)
            {
                string errorMessage = Error.Format(
                    MvcResources.RoutePrefix_CannotSupportMultiRoutePrefix,
                    controllerDescriptor.ControllerType.FullName);
                throw new InvalidOperationException(errorMessage);
            }

            if (attributes.Length == 1)
            {
                IRoutePrefix attribute = attributes[0];

                if (attribute != null)
                {
                    string prefix = attribute.Prefix;
                    if (prefix == null)
                    {
                        string errorMessage = Error.Format(
                            MvcResources.RoutePrefix_PrefixCannotBeNull,
                            controllerDescriptor.ControllerType.FullName);
                        throw new InvalidOperationException(errorMessage);
                    }

                    if (prefix.StartsWith("/", StringComparison.Ordinal)
                        || prefix.EndsWith("/", StringComparison.Ordinal))
                    {
                        string errorMessage = Error.Format(
                            MvcResources.RoutePrefix_CannotStartOrEnd_WithForwardSlash, prefix,
                            controllerDescriptor.ControllerName);
                        throw new InvalidOperationException(errorMessage);
                    }

                    return prefix;
                }
            }

            return null;
        }
示例#58
0
 public ActionDescriptor GetActionDescripter(ControllerContext context,ControllerDescriptor controllerDescriptor,string actionName)
 {
     ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(context,actionName);
     return actionDescriptor;
 }
        /// <summary>
        /// Gets route factories for the given controller descriptor.
        /// </summary>
        /// <param name="controllerDescriptor">The controller descriptor.</param>
        /// <returns>A set of route factories.</returns>
        /// <remarks>
        /// The implementation returns <see cref="IDirectRouteFactory"/> instances based on attributes on the controller.
        /// </remarks>
        protected virtual IReadOnlyList<IDirectRouteFactory> GetControllerRouteFactories(ControllerDescriptor controllerDescriptor)
        {
            object[] attributes = controllerDescriptor.GetCustomAttributes(inherit: false);
            IEnumerable<IDirectRouteFactory> newFactories = attributes.OfType<IDirectRouteFactory>();
            IEnumerable<IRouteInfoProvider> oldProviders = attributes.OfType<IRouteInfoProvider>();

            List<IDirectRouteFactory> combined = new List<IDirectRouteFactory>();
            combined.AddRange(newFactories);

            foreach (IRouteInfoProvider oldProvider in oldProviders)
            {
                if (oldProvider is IDirectRouteFactory)
                {
                    continue;
                }

                combined.Add(new RouteInfoDirectRouteFactory(oldProvider));
            }

            return combined;
        }
 public TaskAsyncActionDescriptor(MethodInfo taskMethodInfo, string actionName, ControllerDescriptor controllerDescriptor)
     : this(taskMethodInfo, actionName, controllerDescriptor, validateMethod: true)
 {
 }