public void GenerateScript_with_target_migration()
        {
            var toolMock = new Mock <MyMigrationTool> {
                CallBase = true
            };
            var migratorMock  = new Mock <Migrator>();
            var tool          = toolMock.Object;
            var configuration = new Configuration();

            migratorMock.Setup(m => m.GenerateUpdateDatabaseSql(It.IsAny <string>())).Returns(
                new[]
            {
                new SqlStatement("Script")
            });

            toolMock.Protected()
            .Setup <Migrator>("GetMigrator", ItExpr.IsAny <DbContextConfiguration>())
            .Returns(migratorMock.Object);

            configuration.AddCommandLine(
                new[]
            {
                "--TargetMigration=MyMigrationName",
                "--ContextAssembly=EntityFramework.Design.Tests.dll",
                "--ContextType=Microsoft.Data.Entity.Design.Tests.MigrationToolTest+MyContext"
            });

            var statements = tool.GenerateScript(configuration);

            migratorMock.Verify(m => m.GenerateUpdateDatabaseSql("MyMigrationName"), Times.Once);
            Assert.Equal(1, statements.Count);
            Assert.Equal("Script", statements[0].Sql);
        }
        public void GetMigrations_with_source_pending()
        {
            var toolMock = new Mock <MyMigrationTool> {
                CallBase = true
            };
            var migratorMock  = new Mock <Migrator>();
            var tool          = toolMock.Object;
            var configuration = new Configuration();

            migratorMock.Setup(m => m.GetPendingMigrations()).Returns(
                new[]
            {
                new MigrationMetadata("000000000000002_M2")
            });

            toolMock.Protected()
            .Setup <Migrator>("GetMigrator", ItExpr.IsAny <DbContextConfiguration>())
            .Returns(migratorMock.Object);

            configuration.AddCommandLine(
                new[]
            {
                "--ContextAssembly=EntityFramework.Design.Tests.dll",
                "--ContextType=Microsoft.Data.Entity.Design.Tests.MigrationToolTest+MyContext",
                "--MigrationSource=Pending"
            });

            var migrations = tool.GetMigrations(configuration);

            Assert.Equal(1, migrations.Count);
            Assert.Equal("000000000000002_M2", migrations[0].MigrationId);
        }
        public void CreateMigration_with_default_migration_directory()
        {
            var tool          = new MyMigrationTool();
            var configuration = new Configuration();

            configuration.AddCommandLine(
                new[]
            {
                "--MigrationName=MyMigration",
                "--ContextAssembly=EntityFramework.Design.Tests.dll",
                "--ContextType=Microsoft.Data.Entity.Design.Tests.MigrationToolTest+MyContext",
                "--MigrationAssembly=EntityFramework.Design.Tests.dll",
                "--MigrationNamespace=MyNamespace"
            });

            var scaffoldedMigration = tool.CreateMigration(configuration);

            Assert.Equal("MyNamespace", scaffoldedMigration.MigrationNamespace);
            Assert.Equal("MyMigration", scaffoldedMigration.MigrationClass);
            Assert.Equal("MyContextModelSnapshot", scaffoldedMigration.SnapshotModelClass);
            Assert.True(scaffoldedMigration.MigrationFile.EndsWith("MyMigration.cs"));
            Assert.True(scaffoldedMigration.MigrationMetadataFile.EndsWith("MyMigration.Designer.cs"));
            Assert.True(scaffoldedMigration.SnapshotModelFile.EndsWith("MyContextModelSnapshot.cs"));
            Assert.True(Path.IsPathRooted(scaffoldedMigration.MigrationFile));
            Assert.True(Path.IsPathRooted(scaffoldedMigration.MigrationMetadataFile));
            Assert.True(Path.IsPathRooted(scaffoldedMigration.SnapshotModelFile));
        }
示例#4
0
        public void CommitConfiguration_with_default_config_file()
        {
            var toolMock = new Mock <MyMigrationTool>()
            {
                CallBase = true
            };
            var args
                = new[]
                {
                "--ContextAssembly=EntityFramework.Design.Tests.dll",
                };
            var configSourceMock = new Mock <IniFileConfigurationSource>("Foo")
            {
                CallBase = true
            };
            var tool          = toolMock.Object;
            var configuration = new Configuration();

            configSourceMock.Setup(m => m.Load());
            configSourceMock.Setup(m => m.Commit());

            toolMock.Protected()
            .Setup <IniFileConfigurationSource>("CreateIniFileConfigurationSource", ItExpr.IsAny <string>())
            .Callback <string>(AssertConfigFileCallback2)
            .Returns(configSourceMock.Object);

            configuration.AddCommandLine(args);

            tool.CommitConfiguration(configuration);

            toolMock.Protected().Verify <IniFileConfigurationSource>("CreateIniFileConfigurationSource", Times.Once(), ItExpr.IsAny <string>());
        }
        public void CreateMigration()
        {
            var tool          = new MyMigrationTool();
            var configuration = new Configuration();

            configuration.AddCommandLine(
                new[]
            {
                "--MigrationName=MyMigration",
                "--ContextAssembly=EntityFramework.Design.Tests.dll",
                "--ContextType=Microsoft.Data.Entity.Design.Tests.MigrationToolTest+MyContext",
                "--MigrationAssembly=EntityFramework.Design.Tests.dll",
                "--MigrationNamespace=MyNamespace",
                "--MigrationDirectory=C:\\MyDirectory"
            });

            var scaffoldedMigration = tool.CreateMigration(configuration);

            Assert.Equal("MyNamespace", scaffoldedMigration.MigrationNamespace);
            Assert.Equal("MyMigration", scaffoldedMigration.MigrationClass);
            Assert.Equal("MyContextModelSnapshot", scaffoldedMigration.SnapshotModelClass);
            Assert.Equal("C:\\MyDirectory\\MyMigration.cs", scaffoldedMigration.MigrationFile);
            Assert.Equal("C:\\MyDirectory\\MyMigration.Designer.cs", scaffoldedMigration.MigrationMetadataFile);
            Assert.Equal("C:\\MyDirectory\\MyContextModelSnapshot.cs", scaffoldedMigration.SnapshotModelFile);
        }
示例#6
0
        public void Main(string[] args)
        {
            var config = new Configuration();

            if (File.Exists(HostingIniFile))
            {
                config.AddIniFile(HostingIniFile);
            }
            config.AddEnvironmentVariables();
            config.AddCommandLine(args);

            var serviceCollection = new ServiceCollection();

            serviceCollection.Add(HostingServices.GetDefaultServices(config));
            var services = serviceCollection.BuildServiceProvider(_serviceProvider);

            var appEnvironment = _serviceProvider.GetService <IApplicationEnvironment>();

            var context = new HostingContext()
            {
                Services        = services,
                Configuration   = config,
                ServerName      = config.Get("server"), // TODO: Key names
                ApplicationName = config.Get("app")     // TODO: Key names
                                  ?? appEnvironment.ApplicationName,
                EnvironmentName = config.Get("env") ?? "Development"
            };

            var engine = services.GetService <IHostingEngine>();

            if (engine == null)
            {
                throw new Exception("TODO: IHostingEngine service not available exception");
            }

            var appShutdownService = _serviceProvider.GetService <IApplicationShutdown>();

            if (appShutdownService == null)
            {
                throw new Exception("TODO: IApplicationShutdown service not available");
            }
            var shutdownHandle = new ManualResetEvent(false);

            var serverShutdown = engine.Start(context);

            appShutdownService.ShutdownRequested.Register(() =>
            {
                serverShutdown.Dispose();
                shutdownHandle.Set();
            });

            var ignored = Task.Run(() =>
            {
                Console.WriteLine("Started");
                Console.ReadLine();
                appShutdownService.RequestShutdown();
            });

            shutdownHandle.WaitOne();
        }
        public void UpdateDatabase_with_target_migration()
        {
            var toolMock = new Mock <MyMigrationTool> {
                CallBase = true
            };
            var migratorMock  = new Mock <Migrator>();
            var tool          = toolMock.Object;
            var configuration = new Configuration();

            toolMock.Protected()
            .Setup <Migrator>("GetMigrator", ItExpr.IsAny <DbContextConfiguration>())
            .Returns(migratorMock.Object);

            configuration.AddCommandLine(
                new[]
            {
                "--TargetMigration=MyMigrationName",
                "--ContextAssembly=EntityFramework.Design.Tests.dll",
                "--ContextType=Microsoft.Data.Entity.Design.Tests.MigrationToolTest+MyContext"
            });

            tool.UpdateDatabase(configuration);

            migratorMock.Verify(m => m.UpdateDatabase("MyMigrationName"), Times.Once);
        }
示例#8
0
        public Task <int> Main(string[] args)
        {
            //Add command line configuration source to read command line parameters.
            var config = new Configuration();

            config.AddCommandLine(args);

            var serviceCollection = HostingServices.Create(_hostServiceProvider);
            var services          = serviceCollection.BuildServiceProvider();

            var context = new HostingContext()
            {
                Services        = services,
                Configuration   = config,
                ServerName      = "Microsoft.AspNet.Server.WebListener",
                ApplicationName = "MusicStore"
            };

            var engine = services.GetService <IHostingEngine>();

            if (engine == null)
            {
                throw new Exception("TODO: IHostingEngine service not available exception");
            }

            using (engine.Start(context))
            {
                Console.WriteLine("Started the server..");
                Console.WriteLine("Press any key to stop the server");
                Console.ReadLine();
            }
            return(Task.FromResult(0));
        }
        public void CommitConfiguration()
        {
            var toolMock = new Mock <MyMigrationTool>()
            {
                CallBase = true
            };
            var args
                = new[]
                {
                "--ConfigFile=MyConfig.ini",
                "--ContextAssembly=EntityFramework.Design.Tests.dll",
                "--ContextType=Microsoft.Data.Entity.Design.Tests.MigrationToolTest+MyContext",
                "--MigrationAssembly=EntityFramework.Design.Tests.dll",
                "--MigrationNamespace=MyNamespace",
                "--MigrationDirectory=MyDirectory",
                "--References=Ref1;Ref2;Ref3"
                };
            var configSourceMock = new Mock <IniFileConfigurationSource>("Foo")
            {
                CallBase = true
            };
            var tool          = toolMock.Object;
            var configuration = new Configuration();

            configSourceMock
            .Setup(m => m.Load());

            configSourceMock
            .Setup(m => m.Commit())
            .Callback(
                () =>
            {
                Assert.Equal(configSourceMock.Object.Data["ContextAssembly"], "EntityFramework.Design.Tests.dll");
                Assert.Equal(configSourceMock.Object.Data["ContextType"], "Microsoft.Data.Entity.Design.Tests.MigrationToolTest+MyContext");
                Assert.Equal(configSourceMock.Object.Data["MigrationAssembly"], "EntityFramework.Design.Tests.dll");
                Assert.Equal(configSourceMock.Object.Data["MigrationNamespace"], "MyNamespace");
                Assert.Equal(configSourceMock.Object.Data["MigrationDirectory"], "MyDirectory");
                Assert.Equal(configSourceMock.Object.Data["References"], "Ref1;Ref2;Ref3");
            });

            toolMock.Protected()
            .Setup <IniFileConfigurationSource>("CreateIniFileConfigurationSource", ItExpr.IsAny <string>())
            .Callback <string>(
                configFile =>
            {
                Assert.True(configFile.EndsWith("MyConfig.ini"));
                Assert.True(Path.IsPathRooted(configFile));
            })
            .Returns(configSourceMock.Object);

            configuration.AddCommandLine(args);

            tool.CommitConfiguration(configuration);

            configSourceMock.Verify(m => m.Commit(), Times.Once);
            toolMock.Protected().Verify <IniFileConfigurationSource>("CreateIniFileConfigurationSource", Times.Once(), ItExpr.IsAny <string>());
        }
        public void LoadContext_throws_if_context_type_not_specified_and_multiple_DbContext_found_in_assembly()
        {
            var tool          = new MyMigrationTool();
            var configuration = new Configuration();

            configuration.AddCommandLine(
                new[]
            {
                "--ContextAssembly=EntityFramework.Design.Tests.dll"
            });

            Assert.Equal(
                Strings.FormatAssemblyContainsMultipleDbContext(Assembly.GetExecutingAssembly().FullName),
                Assert.Throws <InvalidOperationException>(() => tool.LoadContext(configuration)).Message);
        }
示例#11
0
        public void Main(string[] args)
        {
            var config = new Configuration();

            if (File.Exists(HostingIniFile))
            {
                config.AddIniFile(HostingIniFile);
            }
            config.AddEnvironmentVariables();
            config.AddCommandLine(args);

            var services = HostingServices.Create(_serviceProvider, config)
                           .BuildServiceProvider();

            var appEnv     = services.GetRequiredService <IApplicationEnvironment>();
            var hostingEnv = services.GetRequiredService <IHostingEnvironment>();

            var context = new HostingContext()
            {
                Services        = services,
                Configuration   = config,
                ServerName      = config.Get("server"), // TODO: Key names
                ApplicationName = config.Get("app")     // TODO: Key names
                                  ?? appEnv.ApplicationName,
                EnvironmentName = hostingEnv.EnvironmentName,
            };

            var engine             = services.GetRequiredService <IHostingEngine>();
            var appShutdownService = _serviceProvider.GetRequiredService <IApplicationShutdown>();
            var shutdownHandle     = new ManualResetEvent(false);

            var serverShutdown = engine.Start(context);

            appShutdownService.ShutdownRequested.Register(() =>
            {
                serverShutdown.Dispose();
                shutdownHandle.Set();
            });

            var ignored = Task.Run(() =>
            {
                Console.WriteLine("Started");
                Console.ReadLine();
                appShutdownService.RequestShutdown();
            });

            shutdownHandle.WaitOne();
        }
        public void LoadContext_throws_if_context_type_is_not_DbContext()
        {
            var tool          = new MyMigrationTool();
            var configuration = new Configuration();

            configuration.AddCommandLine(
                new[]
            {
                "--ContextAssembly=EntityFramework.Design.Tests.dll",
                "--ContextType=Microsoft.Data.Entity.Design.Tests.MigrationToolTest+NotAContext"
            });

            Assert.Equal(
                Strings.FormatTypeIsNotDbContext("Microsoft.Data.Entity.Design.Tests.MigrationToolTest+NotAContext"),
                Assert.Throws <InvalidOperationException>(() => tool.LoadContext(configuration)).Message);
        }
        public void GetMigrations_throws_if_invalid_source()
        {
            var tool          = new MyMigrationTool();
            var configuration = new Configuration();

            configuration.AddCommandLine(
                new[]
            {
                "--ContextAssembly=EntityFramework.Design.Tests.dll",
                "--ContextType=Microsoft.Data.Entity.Design.Tests.MigrationToolTest+MyContext",
                "--MigrationSource=Foo"
            });

            Assert.Equal(
                Strings.InvalidMigrationSource,
                Assert.Throws <InvalidOperationException>(() => tool.GetMigrations(configuration)).Message);
        }
        public void LoadContext_throws_if_context_type_not_found()
        {
            var tool          = new MyMigrationTool();
            var configuration = new Configuration();

            configuration.AddCommandLine(
                new[]
            {
                "--ContextAssembly=EntityFramework.Design.Tests.dll",
                "--ContextType=Microsoft.Data.Entity.Design.Tests.Vuvuzelas"
            });

            Assert.Equal(
                Strings.FormatAssemblyDoesNotContainType(
                    Assembly.GetExecutingAssembly().FullName,
                    "Microsoft.Data.Entity.Design.Tests.Vuvuzelas"),
                Assert.Throws <InvalidOperationException>(() => tool.LoadContext(configuration)).Message);
        }
示例#15
0
        public void Main(string[] args)
        {
            var configuration = new Configuration();

            Console.WriteLine("Initial Config Sources: " + configuration.Sources.Count());

            var defaultSettings = new MemoryConfigurationSource();

            defaultSettings.Set("username", "Guest");
            configuration.Add(defaultSettings);
            Console.WriteLine("Added Memory Source. Sources: " + configuration.Sources.Count());

            configuration.AddCommandLine(args);
            Console.WriteLine("Added Command Line Source. Sources: " + configuration.Sources.Count());

            string username = configuration.Get("username");

            Console.WriteLine($"Hello, {username}!");
        }
        public void LoadContext_throws_if_context_type_not_specified_and_no_DbContext_found_in_assembly()
        {
            var toolMock = new Mock <MyMigrationTool> {
                CallBase = true
            };
            var tool          = toolMock.Object;
            var configuration = new Configuration();

            toolMock.Setup(t => t.GetContextTypes(It.IsAny <Assembly>())).Returns(new Type[0]);

            configuration.AddCommandLine(
                new[]
            {
                "--ContextAssembly=EntityFramework.Design.Tests.dll"
            });

            Assert.Equal(
                Strings.FormatAssemblyDoesNotContainDbContext(Assembly.GetExecutingAssembly().FullName),
                Assert.Throws <InvalidOperationException>(() => tool.LoadContext(configuration)).Message);
        }
示例#17
0
        public Task <int> Main(string[] args)
        {
            //Add command line configuration source to read command line parameters.
            var config = new Configuration();

            config.AddCommandLine(args);

            var context = new HostingContext()
            {
                Configuration         = config,
                ServerFactoryLocation = "Microsoft.AspNet.Server.WebListener",
                ApplicationName       = "MusicStore"
            };

            using (new HostingEngine().Start(context))
            {
                Console.WriteLine("Started the server..");
                Console.WriteLine("Press any key to stop the server");
                Console.ReadLine();
            }
            return(Task.FromResult(0));
        }
        public void LoadContext_loads_references_before_instantiating_context_type()
        {
            var toolMock = new Mock <MyMigrationTool> {
                CallBase = true
            };
            var tool          = toolMock.Object;
            var configuration = new Configuration();

            toolMock.Protected()
            .Setup <DbContext>("CreateContext", ItExpr.IsAny <Type>())
            .Callback(() => toolMock.Protected()
                      .Verify <Assembly>("LoadAssembly", Times.Exactly(4), ItExpr.IsAny <string>()));

            configuration.AddCommandLine(
                new[]
            {
                "--ContextAssembly=EntityFramework.Design.Tests.dll",
                "--ContextType=Microsoft.Data.Entity.Design.Tests.MigrationToolTest+MyContext",
                "--References=Ref1;Ref2;Ref3"
            });

            tool.LoadContext(configuration);
        }
示例#19
0
        static async Task Main(string[] args)
        {
            IHost host = new HostBuilder()
                         .ConfigureAppConfiguration((context, Configuration) =>
            {
                Configuration.SetBasePath(Directory.GetCurrentDirectory());
                Configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
                Configuration.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);
                //configApp.AddEnvironmentVariables(prefix: "PREFIX_");
                Configuration.AddCommandLine(args);
            })
                         .ConfigureLogging(configureLogging =>
            {
                // configureLogging.AddConsole();
            })
                         .ConfigureServices(services =>
            {
                // services.AddAuth("Data Source=app.db");
                services.AddNLogFactory();

                services.AddHostedService <HttpServerHost>();
                services.AddHostedService <MqttServerHost>();
            })
                         .Build();

            using (var service = host.Services.GetService <ILoggerFactory>())
            {
                logger = service.CreateLogger("host");
            }

            logger?.LogInformation("host is starting...");

            // await host.WaitForShutdownAsync();
            await host.RunAsync();

            // await CreateMultiHostBuilder(args).Build().RunAsync();
        }
示例#20
0
        public void Main(string[] args)
        {
            var config = new Configuration();

            if (File.Exists(HostingIniFile))
            {
                config.AddIniFile(HostingIniFile);
            }
            config.AddEnvironmentVariables();
            config.AddCommandLine(args);

            var appEnv = _serviceProvider.GetRequiredService <IApplicationEnvironment>();

            var hostingEnv = new HostingEnvironment()
            {
                EnvironmentName = config.Get(EnvironmentKey) ?? DefaultEnvironmentName,
                WebRoot         = HostingUtilities.GetWebRoot(appEnv.ApplicationBasePath),
            };

            var serviceCollection = new ServiceCollection();

            serviceCollection.Add(HostingServices.GetDefaultServices(config));
            serviceCollection.AddInstance <IHostingEnvironment>(hostingEnv);
            // The application name is a "good enough" mechanism to identify this application
            // on the machine and to prevent subkeys from being shared across multiple applications
            // by default.
            serviceCollection.Configure <DataProtectionOptions>(options =>
            {
                options.ApplicationDiscriminator = appEnv.ApplicationName;
            });

            var services = serviceCollection.BuildServiceProvider(_serviceProvider);

            var context = new HostingContext()
            {
                Services        = services,
                Configuration   = config,
                ServerName      = config.Get("server"), // TODO: Key names
                ApplicationName = config.Get("app")     // TODO: Key names
                                  ?? appEnv.ApplicationName,
                EnvironmentName = hostingEnv.EnvironmentName,
            };

            var engine             = services.GetRequiredService <IHostingEngine>();
            var appShutdownService = _serviceProvider.GetRequiredService <IApplicationShutdown>();
            var shutdownHandle     = new ManualResetEvent(false);

            var serverShutdown = engine.Start(context);

            appShutdownService.ShutdownRequested.Register(() =>
            {
                serverShutdown.Dispose();
                shutdownHandle.Set();
            });

            var ignored = Task.Run(() =>
            {
                Console.WriteLine("Started");
                Console.ReadLine();
                appShutdownService.RequestShutdown();
            });

            shutdownHandle.WaitOne();
        }