public void GetUserResourceString_ValidResourceObject_ReturnsResourceString()
        {
            Mock <ControllerContext> mockControllerContext = new Mock <ControllerContext>();

            mockControllerContext
            .Setup(
                o =>
                o.HttpContext.GetGlobalResourceObject(
                    "someResourceClassKey",
                    "someResourceName",
                    CultureInfo.CurrentUICulture
                    )
                )
            .Returns("My custom resource string");

            // Act
            string customResourceString = ModelBinderConfig.GetUserResourceString(
                mockControllerContext.Object,
                "someResourceName",
                "someResourceClassKey"
                );

            // Assert
            Assert.Equal("My custom resource string", customResourceString);
        }
Esempio n. 2
0
        /// <summary>
        /// Application Start
        /// </summary>
        protected void Application_Start()
        {
            log4net.Config.XmlConfigurator.Configure();
            LogService.Instance.SetApplicationVariables(DomainApplicationService.Instance.MachineName, DomainApplicationService.Instance.ApplicationCode);

            LogService.Instance.Log.InfoFormat("Global.asax Application_Start() Called.");

            DomainApplicationService.Instance.IOCContainer = new ClientBootstrapper().Run();

            GlobalConfiguration.Configure(WebApiConfig.Register);
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            EntityConfig.Register();
            CacheConfig.PreloadItems();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            ModelBinderConfig.Register();

            //
            //If you want to ignore the certificate check when requesting an https resource, uncomment the following code.
            //This is useful if your app connects uses https/ssl resources which dont have a cert issued by a valid
            //signing authority.
            //This should probably never be uncommented in a production app though. Its here for reference in case its needed.
            //
            //ServicePointManager.ServerCertificateValidationCallback = delegate
            //{
            //    return true;
            //};
        }
 protected void Application_Start()
 {
     Version version = Assembly.GetExecutingAssembly().GetName().Version;
     Application["Version"] = String.Format("{0}.{1}", version.Major, version.Minor);
     Application["Name"] = ConfigurationManager.AppSettings["ApplicationName"];
     //create empty container
     //scan this assembly for any installers to register services/components with Windsor
     Container = new WindsorContainer().Install(FromAssembly.This());
     //API controllers use the dependency resolver and need to be initialized differently than the mvc controllers
     GlobalConfiguration.Configuration.DependencyResolver = new WindsorDependencyResolver(Container.Kernel);
     //tell ASP.NET to get its controllers from Castle
     ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(Container.Kernel));
     //initialize NHibernate
     ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings[Environment.MachineName];
     if (connectionString == null)
         throw new ConfigurationErrorsException(String.Format("Connection string {0} is empty.",
             Environment.MachineName));
     if (String.IsNullOrWhiteSpace(connectionString.ConnectionString))
         throw new ConfigurationErrorsException(String.Format("Connection string {0} is empty.",
             Environment.MachineName));
     string mappingAssemblyName = ConfigurationManager.AppSettings["NHibernate.Mapping.Assembly"];
     if (String.IsNullOrWhiteSpace(mappingAssemblyName))
         throw new ConfigurationErrorsException(
             "NHibernate.Mapping.Assembly key not set in application config file.");
     var nh = new NHInit(connectionString.ConnectionString, mappingAssemblyName);
     nh.Initialize();
      SessionFactory = nh.SessionFactory;
     AutoMapConfig.RegisterMaps();
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     ModelBinderConfig.RegisterModelBinders(ModelBinders.Binders);
     AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
 }
Esempio n. 4
0
        public void GetUserResourceString_NullControllerContext_ReturnsNull()
        {
            // Act
            string customResourceString = ModelBinderConfig.GetUserResourceString(null /* controllerContext */, "someResourceName", "someResourceClassKey");

            // Assert
            Assert.Null(customResourceString);
        }
Esempio n. 5
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     WebApiConfig.Register(GlobalConfiguration.Configuration);
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     ModelBinderConfig.RegisterModelBinders(System.Web.Mvc.ModelBinders.Binders);
 }
Esempio n. 6
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     DIConfig.Initialize();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     ModelBinderConfig.RegisterModelBinders();
 }
Esempio n. 7
0
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            ModelBindingHelper.ValidateBindingContext(bindingContext);

            ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(
                bindingContext.ModelName
                );

            if (valueProviderResult == null)
            {
                return(false); // no entry
            }

            // Provider should have verified this before creating
            Contract.Assert(TypeHelper.HasStringConverter(bindingContext.ModelType));

            object newModel;

            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);
            try
            {
                newModel = valueProviderResult.ConvertTo(bindingContext.ModelType);
            }
            catch (Exception ex)
            {
                if (IsFormatException(ex))
                {
                    // there was a type conversion failure
                    string errorString = ModelBinderConfig.TypeConversionErrorMessageProvider(
                        actionContext,
                        bindingContext.ModelMetadata,
                        valueProviderResult.AttemptedValue
                        );
                    if (errorString != null)
                    {
                        bindingContext.ModelState.AddModelError(
                            bindingContext.ModelName,
                            errorString
                            );
                    }
                }
                else
                {
                    bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex);
                }
                return(false);
            }

            ModelBindingHelper.ReplaceEmptyStringWithNull(
                bindingContext.ModelMetadata,
                ref newModel
                );
            bindingContext.Model = newModel;
            return(true);
        }
Esempio n. 8
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            AutoMapperConfig.RegisterMappings();
            ModelBinderConfig.RegisterModelBinders();
        }
Esempio n. 9
0
        public void TypeConversionErrorMessageProvider_DefaultValue()
        {
            // Arrange
            ModelMetadata metadata = new ModelMetadata(new Mock <ModelMetadataProvider>().Object, null, null, typeof(int), "SomePropertyName");

            // Act
            string errorString = ModelBinderConfig.TypeConversionErrorMessageProvider(null, metadata, "some incoming value");

            // Assert
            Assert.Equal("The value 'some incoming value' is not valid for SomePropertyName.", errorString);
        }
Esempio n. 10
0
        public void GetUserResourceString_NullResourceKey_ReturnsNull()
        {
            Mock <ControllerContext> mockControllerContext = new Mock <ControllerContext>();

            // Act
            string customResourceString = ModelBinderConfig.GetUserResourceString(mockControllerContext.Object, "someResourceName", null /* resourceClassKey */);

            // Assert
            mockControllerContext.Verify(o => o.HttpContext, Times.Never());
            Assert.Null(customResourceString);
        }
Esempio n. 11
0
        public void ValueRequiredErrorMessageProvider_DefaultValue()
        {
            // Arrange
            ModelMetadata metadata = new ModelMetadata(new Mock <ModelMetadataProvider>().Object, null, null, typeof(int), "SomePropertyName");

            // Act
            string errorString = ModelBinderConfig.ValueRequiredErrorMessageProvider(null, metadata, "some incoming value");

            // Assert
            Assert.Equal("A value is required.", errorString);
        }
Esempio n. 12
0
        public void GetUserResourceString_NullHttpContext_ReturnsNull()
        {
            Mock <ControllerContext> mockControllerContext = new Mock <ControllerContext>();

            mockControllerContext.Setup(o => o.HttpContext).Returns((HttpContextBase)null);

            // Act
            string customResourceString = ModelBinderConfig.GetUserResourceString(mockControllerContext.Object, "someResourceName", "someResourceClassKey");

            // Assert
            Assert.Null(customResourceString);
        }
Esempio n. 13
0
        public void Configuration(IAppBuilder app)
        {
            var container = SimpleInjectorConfig.RegisterServices(Assembly.GetExecutingAssembly());

            FilterConfig.RegisterGlobalFilters(
                GlobalFilters.Filters,
                new object[] { new ActionFilterDispatcher(container.GetAllInstances), });

            AuthConfig.ConfigureAuth(app, container);

            ModelBinderConfig.RegisterModelBinders(container);
        }
Esempio n. 14
0
        // Called when the property setter null check failed, allows us to add our own error message to ModelState.
        internal static EventHandler <ModelValidatedEventArgs> CreateNullCheckFailedHandler(ModelMetadata modelMetadata, object incomingValue)
        {
            return((sender, e) =>
            {
                ModelValidationNode validationNode = (ModelValidationNode)sender;
                ModelStateDictionary modelState = e.ActionContext.ModelState;

                if (modelState.IsValidField(validationNode.ModelStateKey))
                {
                    string errorMessage = ModelBinderConfig.ValueRequiredErrorMessageProvider(e.ActionContext, modelMetadata, incomingValue);
                    if (errorMessage != null)
                    {
                        modelState.AddModelError(validationNode.ModelStateKey, errorMessage);
                    }
                }
            });
        }
Esempio n. 15
0
        public void Initialize_ReplacesOriginalCollection()
        {
            // Arrange
            ModelBinderDictionary oldBinders = new ModelBinderDictionary();

            oldBinders[typeof(int)] = new Mock <IModelBinder>().Object;
            ModelBinderProviderCollection newBinderProviders = new ModelBinderProviderCollection();

            // Act
            ModelBinderConfig.Initialize(oldBinders, newBinderProviders);

            // Assert
            Assert.Empty(oldBinders);

            var shimBinder = Assert.IsType <ExtensibleModelBinderAdapter>(oldBinders.DefaultBinder);

            Assert.Same(newBinderProviders, shimBinder.Providers);
        }
Esempio n. 16
0
        public void Initialize_ReplacesOriginalCollection()
        {
            // Arrange
            ModelBinderDictionary oldBinders = new ModelBinderDictionary();

            oldBinders[typeof(int)] = new Mock <IModelBinder>().Object;
            ModelBinderProviderCollection newBinderProviders = new ModelBinderProviderCollection();

            // Act
            ModelBinderConfig.Initialize(oldBinders, newBinderProviders);

            // Assert
            Assert.AreEqual(0, oldBinders.Count, "Old binder dictionary should have been cleared.");

            ExtensibleModelBinderAdapter shimBinder = oldBinders.DefaultBinder as ExtensibleModelBinderAdapter;

            Assert.IsNotNull(shimBinder, "The default binder for the old system should have been replaced with a compatibility shim.");
            Assert.AreSame(newBinderProviders, shimBinder.Providers, "Providers collection was not passed through correctly.");
        }
        protected virtual void ConfigureAspNet(IAppBuilder appBuilder)
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters, Container);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
            ModelBinderConfig.RegisterModelBinder();

            DependencyResolver.SetResolver(new WindsorDependencyResolver(Container));

            var controllerFactory = new CastleWindsorControllerFactory(Container.Kernel);

            ControllerBuilder.Current.SetControllerFactory(controllerFactory);

            var fluentValidationModelValidatorProvider = new FluentValidationModelValidatorProvider(new CastleWindsorFluentValidatorFactory(Container.Kernel));

            ModelValidatorProviders.Providers.Add(fluentValidationModelValidatorProvider);
            DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
        }