public void Validate_ContextUsesDefinedSpecifications()
        {
            //Scan all
            ValidationCatalog.Scan(x => x.TheCallingAssembly());

            //Setup entity
            var customer = new Customer()
            {
                Active    = true,
                Employees = new List <Contact>()
                {
                    new Contact()
                    {
                        Active = true
                    }
                }
            };

            //Validate
            var results = ValidationCatalog <DeleteValidationContext> .Validate(customer);

            Assert.That(results.Errors.First().Message, Is.EqualTo("Active must be false."));
            Assert.That(results.Errors[1].NestedValidationResults.First().Message, Is.EqualTo("Contact 1 in Employees is invalid."));
            Assert.That(results.Errors[1].NestedValidationResults.First().NestedValidationResults.First().Message, Is.EqualTo("Active must be false."));
        }
示例#2
0
        public void Setup()
        {
            ValidationCatalog.Reset();

            //Load specifications
            Assembly assembly = Assembly.LoadFrom("SpecExpress.Test.Domain.dll");

            ValidationCatalog.Scan(x => x.AddAssembly(assembly));
        }
        public void Scan_AppDomainForSpecification_SpecsFound()
        {
            //In Resharper Unit Test, generates:
            //NotSupportedException: The invoked member is not supported in a dynamic assembly

            //Set Assemblies to scan for Specifications
            ValidationCatalog.Scan(x => x.AddAssemblies(AppDomain.CurrentDomain.GetAssemblies().ToList()));
            Assert.That(ValidationCatalog.SpecificationContainer.GetAllSpecifications().Any(), Is.True);
        }
        public void TheCallingAssembly_FindsSpecifications()
        {
            Assembly assembly = Assembly.LoadFrom("SpecExpress.Test.Domain.dll");

            //Set Assemblies to scan for Specifications
            ValidationCatalog.Scan(x => x.AddAssembly(assembly));

            //Assert.That(ValidationCatalog.Registry, Is.Not.Empty);
            Assert.That(ValidationCatalog.SpecificationContainer.GetSpecification <Address>(), Is.Not.Null);
        }
        public void Scan_PathForSpecification_SpecsFound()
        {
            //Set Assemblies to scan for Specifications
            Assembly assembly = Assembly.LoadFrom("SpecExpress.Test.Domain.dll");

            ValidationCatalog.Scan(x => x.AddAssembly(assembly));

            //ValidationCatalog.Scan(x => x.AddAssembliesFromPath(@"C:\Dev\SpecExpress\trunk\SpecExpress\src\SpecExpressTest\bin\Debug"));

            Assert.That(ValidationCatalog.SpecificationContainer.GetAllSpecifications().Any(), Is.True);
        }
        public void ResetRegistries_RegisterAndReset_RegistryIsClean()
        {
            Assembly assembly = Assembly.LoadFrom("SpecExpress.Test.Domain.dll");

            //Set Assemblies to scan for Specifications
            ValidationCatalog.Scan(x => x.AddAssembly(assembly));
            Assert.That(ValidationCatalog.SpecificationContainer.GetAllSpecifications(), Is.Not.Empty);

            ValidationCatalog.Reset();
            Assert.That(ValidationCatalog.SpecificationContainer.GetAllSpecifications(), Is.Empty);
        }
示例#7
0
        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            // Initialize the Validaiton Container
            ValidationCatalog.Scan(x => x.AddAssembly(typeof(Project).Assembly));

            _model = new MainPageModel(new Project()
            {
                ProjectName = ""
            });

            LayoutRoot.DataContext = _model;
        }
示例#8
0
        protected void Application_Start()
        {
            // Initialize the Validation Catalog.  This must be done before adding SpecExpress' Model Validator
            // Provider to the ModelValidatorProviders collection.
            ValidationCatalog.Scan(a => a.TheCallingAssembly());

            // Don't imply that value types are required
            DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

            // Add the SpecExpressModelProvider to the collection of ModelValidators
            ModelValidatorProviders.Providers.Add(new SpecExpressModelProvider());

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
        public void ScanConcurrently()
        {
            var childThread = new Thread(() =>
            {
                Assembly assembly1 = Assembly.LoadFrom("SpecExpress.Test.Domain.dll");
                ValidationCatalog.Scan(x => x.AddAssembly(assembly1));
            });

            childThread.Start();

            Assembly assembly2 = Assembly.LoadFrom("SpecExpress.Test.dll");

            ValidationCatalog.Scan(x => x.AddAssembly(assembly2));

            childThread.Join();

            int specCount = ValidationCatalog.SpecificationContainer.GetAllSpecifications().Count;

            Assert.AreEqual(22, specCount);
        }
示例#10
0
        public void ScanAndEnumerateSpecificationsConcurrently()
        {
            var childThread = new Thread(() =>
            {
                Assembly assembly1 = Assembly.LoadFrom("SpecExpress.Test.Domain.dll");
                ValidationCatalog.Scan(x => x.AddAssembly(assembly1));
            });

            childThread.Start();

            Assembly assembly2 = Assembly.LoadFrom("SpecExpress.Test.dll");

            ValidationCatalog.Scan(x => x.AddAssembly(assembly2));

            foreach (var specification in ValidationCatalog.SpecificationContainer.GetAllSpecifications())
            {
                Assert.IsNotNull(specification);
            }

            childThread.Join();
        }
        public void Scan_Specification_Inhertitance()
        {
            //Set Assemblies to scan for Specifications
            Assembly assembly = Assembly.LoadFrom("SpecExpress.Test.Domain.dll");

            ValidationCatalog.Scan(x => x.AddAssembly(assembly));

            //ValidationCatalog.Scan(x => x.AddAssembliesFromPath(@"C:\Dev\SpecExpress\trunk\SpecExpress\src\SpecExpressTest\bin\Debug"));

            Assert.That(ValidationCatalog.SpecificationContainer.GetAllSpecifications().Any(), Is.True);

            var USWidget = new Widget()
            {
                Name = "ABC"
            };
            var invalidLengthUSWidget = new Widget()
            {
                Name = "ABCDFEFGA"
            };
            var IntWidget = new Widget()
            {
                Name = "123"
            };

            var results = ValidationCatalog.Validate(USWidget);

            Assert.That(results.IsValid, Is.True);

            var results2 = ValidationCatalog.Validate <InternationalWidgetSpecification>(IntWidget);

            Assert.That(results2.IsValid, Is.True);

            var results3 = ValidationCatalog.Validate(IntWidget);

            Assert.That(results3.IsValid, Is.False);

            var results4 = ValidationCatalog.Validate(invalidLengthUSWidget);

            Assert.That(results4.IsValid, Is.False);
        }
示例#12
0
        public void When_multiple_specifications_defined_with_default_spec_defined_return_default()
        {
            Assembly assembly = Assembly.LoadFrom("SpecExpress.Test.Domain.dll");

            ValidationCatalog.Scan(x => x.AddAssembly(assembly));

            //Add Default specification with optional last name
            ValidationCatalog.AddSpecification <SpecExpress.Test.Domain.Entities.Contact>(spec =>
            {
                spec.IsDefaultForType();
                spec.Check(c => c.LastName).Optional();
            });

            //Add Secondary specification with required last name
            ValidationCatalog.AddSpecification <SpecExpress.Test.Domain.Entities.Contact>(spec => spec.Check(c => c.LastName).Required());

            //Create valid object, with null Last Name
            var contact = new SpecExpress.Test.Domain.Entities.Contact();

            var vn = ValidationCatalog.Validate(contact);

            Assert.That(vn.IsValid, Is.True);
        }
示例#13
0
        /// <summary>
        ///     This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore()
            .AddJsonFormatters()
            .AddVersionedApiExplorer(
                options =>
            {
                //The format of the version added to the route URL
                options.GroupNameFormat = "'v'VVV";

                //Tells swagger to replace the version in the controller route
                options.SubstituteApiVersionInUrl = true;
            });
            services.AddApiVersioning(o =>
            {
                o.DefaultApiVersion = new ApiVersion(1, 0);
                o.ReportApiVersions = true;
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.ApiVersionReader = new UrlSegmentApiVersionReader();
            });
            services.AddSwaggerGen(
                options =>
            {
                // Resolve the temporary IApiVersionDescriptionProvider service
                var provider = services.BuildServiceProvider().GetRequiredService <IApiVersionDescriptionProvider>();

                // Add a swagger document for each discovered API version
                foreach (var description in provider.ApiVersionDescriptions)
                {
                    options.SwaggerDoc(description.GroupName, new Info
                    {
                        Title       = $"{GetType().Assembly.GetCustomAttribute<AssemblyProductAttribute>().Product} {description.ApiVersion}",
                        Version     = description.ApiVersion.ToString(),
                        Description = description.IsDeprecated
                                ? $"{GetType().Assembly.GetCustomAttribute<AssemblyDescriptionAttribute>().Description} - DEPRECATED"
                                : GetType().Assembly.GetCustomAttribute <AssemblyDescriptionAttribute>().Description
                    });
                }

                // Add a custom filter for setting the default values
                options.OperationFilter <SwaggerDefaultValues>();

                // Tells swagger to pick up the output XML document file
                options.IncludeXmlComments(Path.Combine(
                                               Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                               $"{GetType().Assembly.GetName().Name}.xml"
                                               ));

                // JWT Filter
                options.AddSecurityDefinition("Bearer", new ApiKeyScheme {
                    In = "header", Description = "Please enter JWT with Bearer into field", Name = "Authorization", Type = "apiKey"
                });
                options.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", Enumerable.Empty <string>() },
                });

                //options.OperationFilter<SecurityRequirementsOperationFilter>();
            });
            // Token
            var tokenDetail = Configuration.GetSection("TokenDetail");
            var signingKey  = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(tokenDetail["Secret"]));
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,
                ValidateIssuer           = true,
                ValidIssuer           = tokenDetail["Issuer"],
                ValidateAudience      = true,
                ValidAudience         = tokenDetail["Audience"],
                ValidateLifetime      = true,
                ClockSkew             = TimeSpan.Zero,
                RequireExpirationTime = true,
            };

            services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = "DefaultAuthKey";
            })
            .AddJwtBearer("DefaultAuthKey", x =>
            {
                x.RequireHttpsMetadata      = true;
                x.TokenValidationParameters = tokenValidationParameters;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.Configure <ConnectionStringSettings>(Configuration.GetSection("ConnectionStringSettings"));

            // Set the default connection string
            DataConnection.DefaultSettings = new Linq2DbSettings(services.BuildServiceProvider().GetService <IOptions <ConnectionStringSettings> >());

            // Can also use multiple assembly names:
            Mapper.Initialize(cfg => cfg.AddProfiles("Classlibrary.Domain", "Middleware.Core.WebApi"));

            // Add spec express
            ValidationCatalog.Scan(x => x.AddAssembly(Assembly.GetExecutingAssembly()));

            // DI setup
            // Transient services are created every time they are injected or requested. Register your services as transient wherever possible. Because it’s simple to design transient services. You generally don’t care about multi-threading and memory leaks and you know the service has a short life.
            // Scoped services are created per scope. In a web application, every web request creates a new separated service scope. That means scoped services are generally created per web request. Use scoped service lifetime carefully since it can be tricky if you create child service scopes or use these services from a non-web application.
            // Singleton services are created per DI container. That generally means that they are created only one time per application and then used for whole the application life time. Use singleton lifetime carefully since then you need to deal with multi-threading and potential memory leak problems.
            // DI container keeps track of all resolved services. Services are released and disposed when their lifetime ends:
            // If the service has dependencies, they are also automatically released and disposed.
            // If the service implements the IDisposable interface, Dispose method is automatically called on service release.
            // Do not depend on a transient or scoped service from a singleton service.Because the transient service becomes a singleton instance when a singleton service injects it and that may cause problems if the transient service is not designed to support such a scenario.ASP.NET Core’s default DI container already throws exceptions in such cases.
            services.AddSingleton <IUtilityManager>(new UtilityManager());
            services.AddSingleton <IAdministrationManager>(new AdministrationManager());
            services.AddSingleton <Microsoft.AspNetCore.Identity.IPasswordHasher <User> >(new PasswordStorage <User>());
            // MediatR
            services.AddTransient(typeof(IRequestPreProcessor <>), typeof(CqrsPreProcessor <>));
            services.AddTransient(typeof(IRequestPostProcessor <,>), typeof(CqrsPostProcessor <,>));
            services.AddMediatR(typeof(GetUserQuery).GetTypeInfo().Assembly);

            // Add the dependencies that the validation engine needs.
            ValidationEngine.AdministrationManager =
                services.BuildServiceProvider().GetService <IAdministrationManager>();

            // Logging
            services.AddLogging(configure => {
                configure.AddConfiguration(Configuration.GetSection("Logging"));
                configure.AddSerilog(dispose: true);
            });
        }