public void Build_WithControllerPropertiesSet_AddsPropertiesWithBinderMetadataSet()
        {
            // Arrange
            var applicationModel = new ApplicationModel();
            var controller = new ControllerModel(typeof(TestController).GetTypeInfo(),
                                                 new List<object>() { });
            controller.ControllerProperties.Add(
                new PropertyModel(
                    controller.ControllerType.GetProperty("BoundProperty"),
                    new List<object>() { })
                {
                    BindingInfo = BindingInfo.GetBindingInfo(new object[] { new FromQueryAttribute() }),
                    PropertyName = "BoundProperty"
                });

            controller.ControllerProperties.Add(
               new PropertyModel(controller.ControllerType.GetProperty("UnboundProperty"), new List<object>() { }));

            controller.Application = applicationModel;
            applicationModel.Controllers.Add(controller);

            var methodInfo = typeof(TestController).GetMethod("SomeAction");
            var actionModel = new ActionModel(methodInfo, new List<object>() { });
            actionModel.Controller = controller;
            controller.Actions.Add(actionModel);

            // Act
            var descriptors = ControllerActionDescriptorBuilder.Build(applicationModel);

            // Assert
            var property = Assert.Single(descriptors.Single().BoundProperties);
            Assert.Equal("BoundProperty", property.Name);
            Assert.Equal(typeof(string), property.ParameterType);
            Assert.Equal(BindingSource.Query, property.BindingInfo.BindingSource);
        }
 public void Apply(ApplicationModel application)
 {
     foreach (var controller in application.Controllers)
     {
         if (Routes.ContainsKey(controller.ControllerType))
         {
             var typedRoutes = Routes[controller.ControllerType];
             foreach (var route in typedRoutes)
             {
                 var action = controller.Actions.FirstOrDefault(x => x.ActionMethod == route.ActionMember);
                 if (action != null)
                 {
                     action.AttributeRouteModel = route;
                     foreach (var method in route.HttpMethods)
                     {
                         action.HttpMethods.Add(method);
                     }
                 }
                 else
                 {
                     controller.AttributeRoutes.Add(route);
                 }
             }
         }
     }
 }
Example #3
0
    public void Apply(ApplicationModel application)
    {
        foreach (var controller in application.Controllers)
        { 
            var newActions = new List<ActionModel>();
            foreach (var action in controller.Actions)
            {
                var localizedRouteAttributes = action.Attributes.OfType<LocalizedRouteAttribute>().ToArray();
                if (localizedRouteAttributes.Any())
                {
                    foreach (var localizedRouteAttribute in localizedRouteAttributes)
                    {
                        var localizedVersions = GetLocalizedVersionsForARoute(localizedRouteAttribute.Name);

                        foreach (var localizedVersion in localizedVersions)
                        {
                            var newAction = new ActionModel(action)
                            {
                                AttributeRouteModel = localizedVersion,
                            };
                            newAction.Properties["culture"] = new CultureInfo(((LocalizedRouteAttribute) localizedVersion.Attribute).Culture ?? "en-US");
                            newAction.Filters.Add(new LocalizedRouteFilter());
                            newActions.Add(newAction);
                        }
                    }
                }
            }

            foreach (var newAction in newActions)
            {
                controller.Actions.Add(newAction);
            }
        }
    }
 public void Apply(ApplicationModel application)
 {
     application.ApiExplorer.IsVisible = true;
     foreach (var controller in application.Controllers)
     {
         controller.ApiExplorer.GroupName = controller.ControllerName;
     }
 }
 public void Apply(ApplicationModel application)
 {
     foreach (var controller in application.Controllers)
     {
         if (controller.ControllerType == _type)
         {
             controller.ApiExplorer.IsVisible = false;
         }
     }
 }
        public void Apply(ApplicationModel application)
        {
            //Remove controllers from the application model that are not in the accepted namespace
            application.Controllers.RemoveAll(controller => !controller.ControllerType.FullName.StartsWith(options.Namespace));

            //Remove any actions found that aren't the accepted single action method name from the application model
            foreach(var controllerModel in application.Controllers) {
                controllerModel.Actions.RemoveAll(x => x.ActionName != options.ActionMethodName);
            }
        }
 public void Apply(ApplicationModel application)
 {
     foreach (var controller in application.Controllers)
         if (controller.AttributeRoutes.Any())
             for (var i = 0; i < controller.AttributeRoutes.Count; i++)
                 controller.AttributeRoutes[i] = AttributeRouteModel.CombineAttributeRouteModel(_centralPrefix,
                     controller.AttributeRoutes[i]);
         else
             controller.AttributeRoutes.Add(_centralPrefix);
 }
        public void Apply(ApplicationModel application)
        {
            foreach (var controller in application.Controllers.Where(x => x.ControllerName == "_"))
            {
                var name = controller.ControllerType.AsType()?.Namespace?.Split('.').Last();

                if (name != null)
                {
                    controller.ControllerName = name;
                }
            }
        }
        public void Apply(ApplicationModel application)
        {
            application.ApiExplorer.IsVisible = true;
            foreach (var controller in application.Controllers)
            {
                controller.ApiExplorer.GroupName = controller.ControllerName;

                foreach (var action in controller.Actions)
                {
                    AddProperties(action, controller.Attributes);
                }
            }
        }
 public void Apply(ApplicationModel model)
 {
     foreach (var c in model.Controllers)
     {
         if (typeof(SurfaceController).IsAssignableFrom(c.ControllerType))
         {
             foreach (var a in c.Actions)
             {
                 a.HttpMethods.Add("POST");
             }
         }
     }
 }
        public void Apply(ApplicationModel application)
        {
            foreach(var controller in application.Controllers)
            {
                var module = controller.ControllerType.Assembly.FullName;
                var splitIndex = module.IndexOf(',');
                if (splitIndex > 0)
                {
                    module = module.Substring(0, splitIndex);
                }

                controller.RouteConstraints.Add(new AreaAttribute(module));
            }
        }
            /// <inheritdoc />
            public void Apply(ApplicationModel application)
            {
                if (application == null)
                {
                    throw new ArgumentNullException(nameof(application));
                }

                foreach (var controller in application.Controllers)
                {
                    foreach (var action in controller.Actions)
                    {
                        _actionModelConvention.Apply(action);
                    }
                }
            }
        public void DefaultControllerModelConvention_AppliesToAllControllers()
        {
            // Arrange
            var options = new MvcOptions();
            var app = new ApplicationModel();
            app.Controllers.Add(new ControllerModel(typeof(HelloController).GetTypeInfo(), new List<object>()));
            app.Controllers.Add(new ControllerModel(typeof(WorldController).GetTypeInfo(), new List<object>()));
            options.Conventions.Add(new SimpleControllerConvention());

            // Act
            options.Conventions[0].Apply(app);

            // Assert
            foreach (var controller in app.Controllers)
            {
                Assert.True(controller.Properties.ContainsKey("TestProperty"));
            }
        }
        internal protected ApplicationModel BuildModel()
        {
            var applicationModel = new ApplicationModel();
            foreach (var filter in _globalFilters)
            {
                applicationModel.Filters.Add(filter);
            }

            foreach (var type in _controllerTypeProvider.ControllerTypes)
            {
                var controllerModel = _applicationModelBuilder.BuildControllerModel(type);
                if (controllerModel != null)
                {
                    controllerModel.Application = applicationModel;
                    applicationModel.Controllers.Add(controllerModel);
                }
            }

            return applicationModel;
        }
 /// <summary>
 /// Called to apply the convention to the <see cref="ApplicationModel"/>.
 /// </summary>
 /// <param name="application"> The<see cref="ApplicationModel"/>.</param>
 public virtual void Apply(ApplicationModel application)
 {
     var centralPrefix = new AttributeRouteModel(new RouteAttribute(template));
     foreach (var controller in application.Controllers)
     {
         if (controller.AttributeRoutes.Count > 0)
         {
             for (var i = 0; i < controller.AttributeRoutes.Count; ++i)
             {
                 controller.AttributeRoutes[i] = AttributeRouteModel.CombineAttributeRouteModel(
                     centralPrefix,
                     controller.AttributeRoutes[i]);
             }
         }
         else
         {
             controller.AttributeRoutes.Add(centralPrefix);
         }
     }
 }
 public void Apply(ApplicationModel application)
 {
     foreach (var controller in application.Controllers)
     {
         foreach (var action in controller.Actions)
         {
             foreach (var parameter in action.Parameters)
             {
                 if (parameter.BinderMetadata is IBinderMetadata || ValueProviderResult.CanConvertFromString(parameter.ParameterInfo.ParameterType))
                 {
                     // behavior configured or simple type so do nothing
                 }
                 else
                 {
                     // Complex types are by-default from the body.
                     parameter.BinderMetadata = new FromBodyAttribute();
                 }
             }
         }
     }
 }
        public void Build_WithPropertiesSet_FromApplicationModel()
        {
            // Arrange
            var applicationModel = new ApplicationModel();
            applicationModel.Properties["test"] = "application";

            var controller = new ControllerModel(typeof(TestController).GetTypeInfo(),
                                                 new List<object>() { });
            controller.Application = applicationModel;
            applicationModel.Controllers.Add(controller);

            var methodInfo = typeof(TestController).GetMethod("SomeAction");
            var actionModel = new ActionModel(methodInfo, new List<object>() { });
            actionModel.Controller = controller;
            controller.Actions.Add(actionModel);

            // Act
            var descriptors = ControllerActionDescriptorBuilder.Build(applicationModel);

            // Assert
            Assert.Equal("application", descriptors.Single().Properties["test"]);
        }
        public void Apply(ApplicationModel application)
        {
            foreach (var controller in application.Controllers)
            {
                if (controller.AttributeRoutes.Count == 0)
                {
                    //Create new attribute Route for the controller
                    var attributeRouteModel = new AttributeRouteModel();

                    //Replace the . in the namespace with a / to create the attribute route 
                    //Ex: MySite.Admin namespace will correspond to MySite/Admin attribute route
                    //Then attach [controller], [action] and optional {id?} token. 
                    //[Controller] and [action] is replaced with the controller and action 
                    //name to generate the final template
                    var template = controller.ControllerType.Namespace.Replace('.', '/') + "/[controller]/[action]/{id?}";
                    attributeRouteModel.Template = template;

                    controller.AttributeRoutes.Add(attributeRouteModel);
                }
            }

            //You can continue to put attribute route templates for the controller actions depending on the way you want them to behave            
        }
 public void Apply(ApplicationModel application)
 {
     foreach (var controller in application.Controllers)
     {
         foreach (var action in controller.Actions)
         {
             foreach (var parameter in action.Parameters)
             {
                 if (parameter.BindingInfo?.BindingSource != null ||
                     parameter.Attributes.OfType<IBindingSourceMetadata>().Any() ||
                     ValueProviderResult.CanConvertFromString(parameter.ParameterInfo.ParameterType))
                 {
                     // behavior configured or simple type so do nothing
                 }
                 else
                 {
                     // Complex types are by-default from the body.
                     parameter.BindingInfo = parameter.BindingInfo ?? new BindingInfo();
                     parameter.BindingInfo.BindingSource = BindingSource.Body;
                 }
             }
         }
     }
 }
        public void Apply(ApplicationModel model)
        {
            foreach (var controller in model.Controllers)
            {
                var ns = controller.ControllerType.Namespace.Split('.');
				if (ns.Length < 4)
					continue;

				var actionName = controller.ControllerName;
				var areas = ns[ns.Length - 4];
				var areaName = ns[ns.Length - 3];
				var app = ns[ns.Length - 2];
				var controllerName = ns[ns.Length - 1];

				if (!string.Equals(areas, "areas", System.StringComparison.OrdinalIgnoreCase) || !string.Equals(app, "app", System.StringComparison.OrdinalIgnoreCase))
					continue;

				controller.RouteConstraints.Add(new AreaAttribute(areaName));
				controller.ControllerName = controllerName;

				foreach (var action in controller.Actions)
					action.ActionName = actionName;
			}
        }
 public void Apply(ApplicationModel application)
 {
     application.Properties["description"] = _description;
 }
        /// <summary>
        /// Applies conventions to a <see cref="ApplicationModel"/>.
        /// </summary>
        /// <param name="applicationModel">The <see cref="ApplicationModel"/>.</param>
        /// <param name="conventions">The set of conventions.</param>
        public static void ApplyConventions(
            ApplicationModel applicationModel,
            IEnumerable<IApplicationModelConvention> conventions)
        {
            if (applicationModel == null)
            {
                throw new ArgumentNullException(nameof(applicationModel));
            }

            if (conventions == null)
            {
                throw new ArgumentNullException(nameof(conventions));
            }

            // Conventions are applied from the outside-in to allow for scenarios where an action overrides
            // a controller, etc.
            foreach (var convention in conventions)
            {
                convention.Apply(applicationModel);
            }

            // First apply the conventions from attributes in decreasing order of scope.
            foreach (var controller in applicationModel.Controllers)
            {
                // ToArray is needed here to prevent issues with modifying the attributes collection
                // while iterating it.
                var controllerConventions =
                    controller.Attributes
                        .OfType<IControllerModelConvention>()
                        .ToArray();

                foreach (var controllerConvention in controllerConventions)
                {
                    controllerConvention.Apply(controller);
                }

                foreach (var action in controller.Actions)
                {
                    // ToArray is needed here to prevent issues with modifying the attributes collection
                    // while iterating it.
                    var actionConventions =
                        action.Attributes
                            .OfType<IActionModelConvention>()
                            .ToArray();

                    foreach (var actionConvention in actionConventions)
                    {
                        actionConvention.Apply(action);
                    }

                    foreach (var parameter in action.Parameters)
                    {
                        // ToArray is needed here to prevent issues with modifying the attributes collection
                        // while iterating it.
                        var parameterConventions =
                            parameter.Attributes
                                .OfType<IParameterModelConvention>()
                                .ToArray();

                        foreach (var parameterConvention in parameterConventions)
                        {
                            parameterConvention.Apply(parameter);
                        }
                    }
                }
            }
        }
        public void ApplyConventions_RunsInOrderOfDecreasingScope()
        {
            // Arrange
            var sequence = 0;

            var applicationConvention = new Mock<IApplicationModelConvention>();
            applicationConvention
                .Setup(c => c.Apply(It.IsAny<ApplicationModel>()))
                .Callback(() => { Assert.Equal(0, sequence++); });

            var controllerConvention = new Mock<IControllerModelConvention>();
            controllerConvention
                .Setup(c => c.Apply(It.IsAny<ControllerModel>()))
                .Callback(() => { Assert.Equal(1, sequence++); });

            var actionConvention = new Mock<IActionModelConvention>();
            actionConvention
                .Setup(c => c.Apply(It.IsAny<ActionModel>()))
                .Callback(() => { Assert.Equal(2, sequence++); });

            var parameterConvention = new Mock<IParameterModelConvention>();
            parameterConvention
                .Setup(c => c.Apply(It.IsAny<ParameterModel>()))
                .Callback(() => { Assert.Equal(3, sequence++); });

            var options = new TestOptionsManager<MvcOptions>();
            options.Value.Conventions.Add(applicationConvention.Object);

            var applicationModel = new ApplicationModel();

            var controller = new ControllerModel(typeof(ConventionsController).GetTypeInfo(),
                                                 new List<object>() { controllerConvention.Object });
            controller.Application = applicationModel;
            applicationModel.Controllers.Add(controller);

            var methodInfo = typeof(ConventionsController).GetMethod("Create");
            var actionModel = new ActionModel(methodInfo, new List<object>() { actionConvention.Object });
            actionModel.Controller = controller;
            controller.Actions.Add(actionModel);

            var parameterInfo = actionModel.ActionMethod.GetParameters().Single();
            var parameterModel = new ParameterModel(parameterInfo,
                                           new List<object>() { parameterConvention.Object });
            parameterModel.Action = actionModel;
            actionModel.Parameters.Add(parameterModel);

            // Act
            ApplicationModelConventions.ApplyConventions(applicationModel, options.Value.Conventions);

            // Assert
            Assert.Equal(4, sequence);
        }
 public void Apply(ApplicationModel application)
 {
     application.ApiExplorer.IsVisible = _isVisible;
 }