Пример #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // entity app
            var connStr = Configuration["MsSqlConnectionString"];

            BooksEntityApp = CreateBooksEntityApp(connStr);

            // Setup Authentication with jwt token
            var jwtSecret       = Configuration["JwtSecret"];
            var jwtTokenHandler = new VitaJwtTokenHandler(BooksEntityApp, services, jwtSecret);

            services.Add(new ServiceDescriptor(typeof(IAuthenticationTokenHandler), jwtTokenHandler));

            var loginAssembly = typeof(Vita.Modules.Login.Api.LoginController).Assembly;

            services.AddControllers()
            // Note: by default System.Text.Json ns/serializer is used by AspNetCore 3.1; this serializer is broken piece of sh..
            // - does not serialize fields, does not handle dictionaries, etc. So we put back Newtonsoft serializer.
            .AddNewtonsoftJson()
            // make API controllers in Vita.Modules.Login.dll discovered by ASP.NET infrastructure
            .PartManager.ApplicationParts.Add(new AssemblyPart(loginAssembly));

            // clear out default configuration - it installs Console output logger which sends out tons of garbage
            //  https://weblog.west-wind.com/posts/2018/Dec/31/Dont-let-ASPNET-Core-Default-Console-Logging-Slow-your-App-down
            services.AddLogging(config => {
                config.ClearProviders();
            });
        }
Пример #2
0
        public static void InitImpl()
        {
            if (BooksApp != null)
            {
                return;
            }
            LogFilePath = ConfigurationManager.AppSettings["LogFilePath"];
            DeleteLocalLogFile();

            var protectedSection = (NameValueCollection)ConfigurationManager.GetSection("protected");
            var loginCryptoKey   = protectedSection["LoginInfoCryptoKey"];
            var connString       = protectedSection["MsSqlConnectionString"];
            var logConnString    = protectedSection["MsSqlLogConnectionString"];

            BooksApp = new BooksEntityApp(loginCryptoKey);
            //Add mock email/sms service
            NotificationListener = new NotificationListener(BooksApp, blockAll: true);
            //Set magic captcha in login settings, so we can pass captcha in unit tests
            var loginStt = BooksApp.GetConfig <Vita.Modules.Login.LoginModuleSettings>();

            loginStt.MagicCaptcha = "Magic";
            BooksApp.Init();
            //connect to database
            var driver     = MsSqlDbDriver.Create(connString);
            var dbOptions  = MsSqlDbDriver.DefaultMsSqlDbOptions;
            var dbSettings = new DbSettings(driver, dbOptions, connString, upgradeMode: DbUpgradeMode.Always); // schemas);
            var resetDb    = ConfigurationManager.AppSettings["ResetDatabase"] == "true";

            if (resetDb)
            {
                Vita.UnitTests.Common.TestUtil.DropSchemaObjects(dbSettings);
            }
            BooksApp.ConnectTo(dbSettings);
            var logDbSettings = new DbSettings(driver, dbOptions, logConnString);

            BooksApp.LoggingApp.ConnectTo(logDbSettings);
            BooksApp.LoggingApp.LogPath = LogFilePath;
            TestUtil.DeleteAllData(BooksApp, exceptEntities: new [] { typeof(IDbInfo), typeof(IDbModuleInfo) });
            TestUtil.DeleteAllData(BooksApp.LoggingApp);

            SampleDataGenerator.CreateUnitTestData(BooksApp);

            // Start service
            var serviceUrl      = ConfigurationManager.AppSettings["ServiceUrl"];
            var jsonNames       = ConfigurationManager.AppSettings["JsonStyleNames"] == "true";
            var jsonMappingMode = jsonNames ? ApiNameMapping.UnderscoreAllLower : ApiNameMapping.Default;

            StartService(serviceUrl, jsonMappingMode);
            // create client
            var clientContext = new OperationContext(BooksApp);

            // change options to None to disable logging of test client calls
            Client = new WebApiClient(clientContext, serviceUrl, clientName: "TestClient", nameMapping: jsonMappingMode,
                                      options: ClientOptions.EnableLog, badRequestContentType: typeof(List <ClientFault>));
            WebApiClient.SharedHttpClientHandler.AllowAutoRedirect = false; //we need it for Redirect test
        }
Пример #3
0
        //Prepares for full run with a specified server
        internal static void Reset(TestConfig config)
        {
            if (BooksApp != null)
            {
                BooksApp.Flush();
            }
            Thread.Sleep(100); //to allow log dump of buffered messages
            DeleteLogFiles();  //it will happen only once
            WriteLog("\r\n------------------------ " + config.ToString() + "---------------------------------------------\r\n\r\n");

            ServerType   = config.ServerType;
            CacheEnabled = config.EnableCache;
            UseBatchMode = config.UseBatchMode;
            BooksApp     = null;
            _initFailed  = false;

            var protectedSection = (NameValueCollection)ConfigurationManager.GetSection("protected");

            //Load connection string
            ConnectionString = ReplaceBinFolderToken(protectedSection[ServerType + "ConnectionString"]);
            Util.Check(!string.IsNullOrEmpty(ConnectionString), "Connection string not found for server: {0}.", ServerType);
            LogConnectionString = ReplaceBinFolderToken(protectedSection[ServerType + "LogConnectionString"]);
            LogConnectionString = LogConnectionString ?? ConnectionString;

            LoginCryptoKey = protectedSection["LoginInfoCryptoKey"];
            Driver         = ToolHelper.CreateDriver(ServerType, ConnectionString);
            var dbOptions = ToolHelper.GetDefaultOptions(ServerType);

            if (config.UseStoredProcs)
            {
                dbOptions |= DbOptions.UseStoredProcs;
            }
            else
            {
                dbOptions &= ~DbOptions.UseStoredProcs;
            }
            if (config.UseBatchMode)
            {
                dbOptions |= DbOptions.UseBatchMode;
            }
            else
            {
                dbOptions &= ~DbOptions.UseBatchMode;
            }

            // dbOptions |= DbOptions.ForceArraysAsLiterals; -- just to test this flag
            DbSettings = new DbSettings(Driver, dbOptions, ConnectionString, upgradeMode: DbUpgradeMode.Always);
            //Test: remap login schema into login2
            // if (ServerType == DbServerType.MsSql)
            //    DbSettings.ModelConfig.MapSchema("login", "login2");
        }
Пример #4
0
        public static void InitApp()
        {
            Util.Check(!_initFailed, "App initialization failed. Cannot run tests. See other tests output for failure details.");
            if (BooksApp != null)
            {
                return;
            }
            try {
                //force randomization of schema update SQLs, to test that they will put in correct order anyway
                DbModelUpdater.Test_RandomizeInitialSchemaUpdatesOrder = true;
                //Check if Reset was called; if Driver is null, we are running in Test Explorer mode
                if (Driver == null)
                {
                    SetupForTestExplorerMode();
                }
                //Setup model, initialize Books module, create database model, update schema -------------------------------------------------
                BooksApp               = new BooksEntityApp(LoginCryptoKey);
                BooksApp.LogPath       = LogFilePath;
                BooksApp.SystemLogPath = ActivationLogFilePath;
                BooksApp.CacheSettings.CacheEnabled = CacheEnabled;
                NotificationListener = new NotificationListener(BooksApp, blockAll: true); //SmtpMock for testing password reset and other processes
                BooksApp.Init();
                //Reset Db and drop schema objects; first set schema list
                var resetDb = ConfigurationManager.AppSettings["ResetDatabase"] == "true";
                if (resetDb)
                {
                    DbSettings.SetSchemas(BooksApp.Areas.Select(a => a.Name));
                    Vita.UnitTests.Common.TestUtil.DropSchemaObjects(DbSettings);
                }
                //Now connect the main app
                BooksApp.ConnectTo(DbSettings);
                //if we have logging app as a separate app - we need to connect it too.
                // NOTE: good pracice to connect LoggingApp before we connect the main app, so it can log main database update scripts
                // but it should work anyway.
                var logDbSettings = new DbSettings(Driver, DbSettings.ModelConfig.Options, LogConnectionString);
                BooksApp.LoggingApp.ConnectTo(logDbSettings);

                CreateSampleData();
            } catch (ClientFaultException cfx) {
                Debug.WriteLine("Validation errors: \r\n" + cfx.ToString());
                throw;
            } catch (Exception sx) {
                _initFailed = true;
                //Unit test framework shows only ex message, not details; let's write specifics into debug output - it will be shown in test failure report
                Debug.WriteLine("app init encountered errors: ");
                Debug.WriteLine(sx.ToLogString());
                throw;
            }
        }
Пример #5
0
        static void Init()
        {
            // clear log
            if (File.Exists(LogFileName))
            {
                File.Delete(LogFileName);
            }
            // create and connect the app
            _app              = new BooksEntityApp();
            _app.LogPath      = LogFileName;
            _app.ErrorLogPath = "_errors.log";
            var driver     = new MsSqlDbDriver();
            var dbSettings = new DbSettings(driver, MsSqlDbDriver.DefaultMsSqlDbOptions, ConnString);

            _app.ConnectTo(dbSettings);
        }
Пример #6
0
        public static void TearDown()
        {
            //You should do this normally - shutdown the entity store
            // but in this test app it would take too long time for all tests (re-init database for each test class)
            // so by default running without it
#if FULL_SHUTDOWN
            if (BooksApp != null)
            {
                BooksApp.Shutdown();
            }
            BooksApp = null;
#endif
            if (BooksApp != null)
            {
                BooksApp.Flush();
            }
        }
Пример #7
0
        //Prepares for full run with a specified server
        internal static void Reset(TestRunConfig config)
        {
            CurrentConfig = config;
            ServerType    = config.ServerType;
            if (BooksApp != null)
            {
                BooksApp.Flush();
            }
            Thread.Sleep(100); //to allow log dump of buffered messages
            DeleteLogFiles();  //it will happen only once
            WriteLog("\r\n------------------------ " + config.ToString() + "---------------------------------------------\r\n\r\n");

            ServerType   = config.ServerType;
            UseBatchMode = config.UseBatchMode;
            BooksApp     = null;
            _initFailed  = false;

            //Check connection string
            Util.Check(!string.IsNullOrEmpty(config.ConnectionString), "Connection string not found for server: {0}.", ServerType);

            Driver = DataUtility.CreateDriver(ServerType);
            var dbOptions = Driver.GetDefaultOptions();

            if (config.UseBatchMode)
            {
                dbOptions |= DbOptions.UseBatchMode;
            }
            else
            {
                dbOptions &= ~DbOptions.UseBatchMode;
            }

            // Custom naming policy. Uncomment below to see how all-lower case policy works for Postgres
            IDbNamingPolicy customNamingPolicy = null;

            //if(ServerType == DbServerType.Postgres)
            //customNamingPolicy = new AllLowCaseNamingPolicy("books", "login");
            DbSettings = new DbSettings(Driver, dbOptions, config.ConnectionString, upgradeMode: DbUpgradeMode.Always,
                                        namingPolicy: customNamingPolicy);

            //Test: remap login schema into login2
            // Remapping schemas might used in MySql, where schemas are actually databases
            // if (ServerType == DbServerType.MsSql)
            //    DbSettings.ModelConfig.MapSchema("login", "login2");
        }
Пример #8
0
        private BooksEntityApp CreateBooksEntityApp(string connString)
        {
            // If we are running WebTests, the BooksApp is already setup
            if (BooksEntityApp.Instance != null)
            {
                return(BooksEntityApp.Instance);
            }

            var booksApp = new BooksEntityApp();

            booksApp.Init();

            //connect to db
            var driver     = new MsSqlDbDriver();
            var dbOptions  = driver.GetDefaultOptions();
            var dbSettings = new DbSettings(driver, dbOptions, connString, upgradeMode: DbUpgradeMode.Always);

            booksApp.ConnectTo(dbSettings);
            return(booksApp);
        }
Пример #9
0
 public static BooksEntityApp CreateConfigureBooksApp()
 {
     // set up application
       var protectedSection = (NameValueCollection)ConfigurationManager.GetSection("protected");
       var cryptoKey = protectedSection["LoginInfoCryptoKey"];
       var booksApp = new BooksEntityApp(cryptoKey);
       booksApp.Init();
       var connString = protectedSection["MsSqlConnectionString"];
       var logConnString = protectedSection["MsSqlLogConnectionString"];
       var driver = MsSqlDbDriver.Create(connString);
       var dbOptions = MsSqlDbDriver.DefaultMsSqlDbOptions;
       var logDbSettings = new DbSettings(driver, dbOptions, logConnString);
       booksApp.LoggingApp.ConnectTo(logDbSettings);
       var dbSettings = new DbSettings(driver, dbOptions, connString, upgradeMode: DbUpgradeMode.Always);
       booksApp.ConnectTo(dbSettings);
       //Web Api
       WebHelper.ConfigureWebApi(GlobalConfiguration.Configuration, booksApp, logLevel: Entities.Services.LogLevel.Details);
       /*
       var hc = GlobalConfiguration.Configuration;
       var webH = hc.MessageHandlers.First(h => h is WebCallContextHandler);
       hc.MessageHandlers.Remove(webH);
       */
       return booksApp;
 }
Пример #10
0
        public static BooksEntityApp CreateConfigureBooksApp()
        {
            // set up application
            var protectedSection = (NameValueCollection)ConfigurationManager.GetSection("protected");
            var cryptoKey        = protectedSection["LoginInfoCryptoKey"];
            var booksApp         = new BooksEntityApp(cryptoKey);

            booksApp.Init();
            var connString    = protectedSection["MsSqlConnectionString"];
            var logConnString = protectedSection["MsSqlLogConnectionString"];
            var driver        = MsSqlDbDriver.Create(connString);
            var dbOptions     = MsSqlDbDriver.DefaultMsSqlDbOptions;
            var logDbSettings = new DbSettings(driver, dbOptions, logConnString);

            booksApp.LoggingApp.ConnectTo(logDbSettings);
            var dbSettings = new DbSettings(driver, dbOptions, connString, upgradeMode: DbUpgradeMode.Always);

            booksApp.ConnectTo(dbSettings);
            //Web Api
            WebHelper.ConfigureWebApi(GlobalConfiguration.Configuration, booksApp, logLevel: Entities.Services.LogLevel.Details

                                      );
            return(booksApp);
        }
Пример #11
0
        public static void InitImpl()
        {
            if (BooksApp != null)
            {
                return;
            }
            LoadAppConfig();
            LogFilePath = AppConfiguration["LogFilePath"];
            if (File.Exists(LogFilePath))
            {
                File.Delete(LogFilePath);
            }

            BooksApp         = new BooksEntityApp();
            BooksApp.LogPath = LogFilePath;
            //Add mock email/sms service
            // NotificationListener = new NotificationListener(BooksApp, blockAll: true);
            // Setup mock messaging service
            LoginMessagingService = new MockLoginMessagingService();
            var loginConfig = BooksApp.GetConfig <Modules.Login.LoginModuleSettings>();

            loginConfig.MessagingService = LoginMessagingService;
            BooksApp.Init();
            //connect to database
            var driver     = new MsSqlDbDriver();
            var dbOptions  = MsSqlDbDriver.DefaultMsSqlDbOptions;
            var connString = AppConfiguration["MsSqlConnectionString"];
            var dbSettings = new DbSettings(driver, dbOptions, connString, upgradeMode: DbUpgradeMode.Always); // schemas);

            BooksApp.ConnectTo(dbSettings);

            // Logging app
            LoggingApp = new DbLoggingEntityApp();
            LoggingApp.ListenTo(BooksApp);
            var logConnString = AppConfiguration["MsSqlLogConnectionString"];
            var logDbSettings = new DbSettings(driver, dbOptions, logConnString, upgradeMode: DbUpgradeMode.Always); // schemas);

            LoggingApp.ConnectTo(logDbSettings);

            // create sample data
            DataUtility.DeleteAllData(BooksApp,
                                      exceptEntities: new Type[] { typeof(IDbInfo), typeof(IDbModuleInfo) });
            SampleDataGenerator.CreateUnitTestData(BooksApp);

            // Start service
            var serviceUrl = AppConfiguration["ServiceUrl"];

            StartService(serviceUrl);
            // create client
            var useXml = false;

            if (useXml)
            {
                var clientSettings = new RestClientSettings(serviceUrl, serializer: new XmlContentSerializer(), badRequestContentType: typeof(string)); // typeof(List<ClientFault>));
                Client = new RestClient(clientSettings);
            }
            else
            {
                Client = new RestClient(serviceUrl, badRequestContentType: typeof(List <ClientFault>)); //json, very simple setup
            }
            RestClient.SharedHttpClientHandler.AllowAutoRedirect = false;                               //we need it for Redirect test
            // Setup handler converting BadRequestException into ClientFaultException, with list of faults already converted
            Client.Settings.Events.ReceivedError += (s, e) => {
                if (e.CallData.Exception is BadRequestException bre)
                {
                    e.CallData.Exception = new ClientFaultException((IList <ClientFault>)bre.Details);
                }
            };
        }
Пример #12
0
        public static void InitApp()
        {
            Util.Check(!_initFailed, "App initialization failed. Cannot run tests. See other tests output for failure details.");
            if (BooksApp != null)
            {
                return;
            }
            try {
                //force randomization of schema update SQLs, to test that they will be put in correct order anyway
                DbModelUpdater.Test_RandomizeInitialSchemaUpdatesOrder = true;
                //Check if Reset was called; if Driver is null, we are running in Test Explorer mode
                if (Driver == null)
                {
                    SetupForTestExplorerMode();
                }
                if (ServerType == DbServerType.SQLite)
                {
                    DeleteSqliteDbFile("VitaBooksSQLite");
                }
                //Setup model, initialize Books module, create database model, update schema -------------------------------------------------
                BooksApp = new BooksEntityApp();
                BooksApp.EntityClassProvider = Vita.Entities.Emit.EntityClassEmitter.CreateEntityClassProvider();
                BooksApp.LogPath             = LogFilePath;
                BooksApp.ActivationLogPath   = ActivationLogFilePath;
                BooksApp.Init();

                // Oracle - uncomment this to see tablespace use, but you must pre-create the tablespace in SQL-Developer

                /*
                 * if(ServerType == DbServerType.Oracle)
                 * foreach(var area in BooksApp.Areas)
                 *   area.OracleTableSpace = "Books";
                 */

                // Setup mock messaging service
                LoginMessagingService = new MockLoginMessagingService();
                var loginConfig = BooksApp.GetConfig <Modules.Login.LoginModuleSettings>();
                loginConfig.MessagingService = LoginMessagingService;

                // for SQLite- drop and copy database
                //Reset Db and drop schema objects; first set schema list
                var resetDb = AppSettings["ResetDatabase"] == "true";
                if (resetDb)
                {
                    DataUtility.DropSchemaObjects(BooksApp, DbSettings);
                }

                //Now connect the main app
                BooksApp.ConnectTo(DbSettings);


                //if we have logging app as a separate app - we need to connect it too.
                // NOTE: good pracice to connect LoggingApp before we connect the main app, so it can log main database update scripts
                // but it should work anyway.
                //var logDbSettings = new DbSettings(Driver, DbSettings.ModelConfig.Options, LogConnectionString);
                //BooksApp.LoggingApp.ConnectTo(logDbSettings);

                CreateSampleData();
            } catch (ClientFaultException cfx) {
                Debug.WriteLine("Validation errors: \r\n" + cfx.ToString());
                _initFailed = true;
                throw;
            } catch (Exception sx) {
                _initFailed = true;
                //Unit test framework shows only ex message, not details; let's write specifics into debug output - it will be shown in test failure report
                Debug.WriteLine("app init encountered errors: ");
                Debug.WriteLine(sx.ToLogString());
                throw;
            }
        }