Example #1
0
        public void Can_get_context_type_by_name()
        {
            ResetDatabase();

            using (var facade = new ToolingFacade(
                       "ClassLibrary1",
                       configurationTypeName: null,
                       workingDirectory: _projectDir,
                       configurationFilePath: null,
                       dataDirectory: null,
                       connectionStringInfo: null))
            {
                var result = facade.GetContextType("Context");

                Assert.Equal("ClassLibrary1.Context", result);
            }
        }
        public void Wraps_assembly_not_found_exceptions()
        {
            const string unknownAssemblyName = "UnknownAssembly";

            using (var facade = new ToolingFacade(
                       unknownAssemblyName,
                       unknownAssemblyName,
                       "ClassLibrary1.Configuration",
                       _projectDir,
                       Path.Combine(_projectDir, "App.config"),
                       null,
                       null))
            {
                Assert.Throws <ToolingException>(() => facade.GetDatabaseMigrations())
                .ValidateMessage("ToolingFacade_AssemblyNotFound", unknownAssemblyName);
            }
        }
        public void Can_still_scaffold_abstract_context_by_specifying_name_directly()
        {
            ResetDatabase();

            using (var facade = new ToolingFacade(
                       "ClassLibrary1",
                       "ContextLibrary1",
                       configurationTypeName: null,
                       workingDirectory: _contextDir,
                       configurationFilePath: null,
                       dataDirectory: null,
                       connectionStringInfo: null))
            {
                var result = facade.GetContextType("AbstractContext");
                Assert.Equal("ContextLibrary1.AbstractContext", result);
            }
        }
Example #4
0
        public void Can_scaffold_empty()
        {
            using (var facade = new ToolingFacade(
                       "ClassLibrary1",
                       "ClassLibrary1.Configuration",
                       _projectDir,
                       Path.Combine(_projectDir, "App.config"),
                       null,
                       null))
            {
                var scaffoldedMigration = facade.Scaffold("Create", "cs", "ClassLibrary1", ignoreChanges: true);

                Assert.True(scaffoldedMigration.DesignerCode.Length > 500);
                Assert.Equal("cs", scaffoldedMigration.Language);
                Assert.True(scaffoldedMigration.MigrationId.EndsWith("_Create"));
                Assert.True(scaffoldedMigration.UserCode.Length < 300);
            }
        }
        public EntityFrameworkRepositoryBaseTests()
        {
            CodeFirstContext context = new CodeFirstContext();

            if (!context.Database.Exists())
            {
                context.Database.Initialize(true);

                context.SaveChanges();
            }
            ToolingFacade facade = new ToolingFacade(typeof(TimeSheet).Assembly.FullName,
                                                     typeof(TimeSheet).Assembly.FullName,
                                                     typeof(Dot.UtilityTests.Migrations.Configuration).FullName,
                                                     AppDomain.CurrentDomain.BaseDirectory,
                                                     AppDomain.CurrentDomain.BaseDirectory + "\\Dot.UtilityTests.dll.config",
                                                     null,
                                                     new DbConnectionInfo("CodeFirst"));

            facade.Update(null, false);
        }
        private ToolingFacade CreateFacade()
        {
            DbConnectionInfo connectionStringInfo = null;

            if (!string.IsNullOrWhiteSpace(_arguments.ConnectionStringName))
            {
                Debug.Assert(string.IsNullOrWhiteSpace(_arguments.ConnectionString));
                Debug.Assert(string.IsNullOrWhiteSpace(_arguments.ConnectionProviderName));

                connectionStringInfo = new DbConnectionInfo(_arguments.ConnectionStringName);
            }
            else if (!string.IsNullOrWhiteSpace(_arguments.ConnectionString))
            {
                Debug.Assert(string.IsNullOrWhiteSpace(_arguments.ConnectionStringName));
                Debug.Assert(!string.IsNullOrWhiteSpace(_arguments.ConnectionProviderName));

                connectionStringInfo = new DbConnectionInfo(
                    _arguments.ConnectionString, _arguments.ConnectionProviderName);
            }

            var facade
                = new ToolingFacade(
                      _arguments.AssemblyName,
                      string.IsNullOrWhiteSpace(_arguments.ContextAssemblyName) ? _arguments.AssemblyName : _arguments.ContextAssemblyName,
                      _arguments.ConfigurationTypeName,
                      _arguments.WorkingDirectory,
                      _arguments.ConfigurationFile,
                      _arguments.DataDirectory,
                      connectionStringInfo);

            facade.LogInfoDelegate    = WriteLine;
            facade.LogWarningDelegate = WriteWarning;

            if (_arguments.Verbose)
            {
                facade.LogVerboseDelegate = sql => WriteVerbose(Strings.VerboseMessage(sql));
            }

            return(facade);
        }
Example #7
0
        public virtual MigrationCode GenerateMigration(MigrationInfo migrationInfo)
        {
            //var assembly = Assembly.LoadFrom((migrationInfo.ContextAssemblyPath
            //    + "\\KS.Dynamic.Migration_r3.dll").Replace(@"\\", @"\"));
            //var type = assembly.GetType("KS.Dynamic.Migration.EntityFramework.Migration");

            //// Get the constructor and create an instance of MagicClass

            ////Type magicType = Type.GetType("MagicClass");
            //ConstructorInfo magicConstructor = type.GetConstructor(Type.EmptyTypes);
            //object magicClassObject = magicConstructor.Invoke(new object[] { });

            //// Get the ItsMagic method and invoke with a parameter value of 100

            //MethodInfo magicMethod = type.GetMethod("GenerateMigration");
            //object magicValue = magicMethod.Invoke(magicClassObject, new object[] { migrationInfo });


            //return (MigrationCode) magicValue;

            var infos    = new StringBuilder();
            var warnings = new StringBuilder();
            var verbose  = new StringBuilder();

            //connection:connectionString, NameSpaceQualifiedConnectionType:for example :"System.Data.SqlClient"
            var connectionStringInfo = new DbConnectionInfo(migrationInfo.Connection,
                                                            migrationInfo.NameSpaceQualifiedConnectionType);

            var toolingFacade = new ToolingFacade(
                migrationInfo.ContextAssemblyName,   //"MyDll",   // MigrationAssemblyName. In this case dll should be located in "C:\\Temp\\MigrationTest" dir
                migrationInfo.ContextAssemblyName,   //"MyDll",  // ContextAssemblyName. Same as above
                migrationInfo.ConfigurationTypeName, //KS.ObjectiveDataAccess.ContentManagementDbContextMigrations.Configuration
                migrationInfo.ContextAssemblyPath,   //"C:\\Temp\\MigrationTest",   // Where the dlls are located
                migrationInfo.WebConfigPath,         //"C:\\Temp\\MigrationTest\\App.config", // Insert the right directory and change with Web.config if required
                migrationInfo.AppDataPath,           //"C:\\Temp\\App_Data",
                connectionStringInfo)
            {
                LogInfoDelegate    = s => { infos.AppendLine($"Infos : {s} . <br>"); },
                LogWarningDelegate = s => { warnings.AppendLine($"Warning : {s} . <br>"); },
                LogVerboseDelegate = s => { verbose.AppendLine($"Verbose : {s} . <br>"); }
            };



            ScaffoldedMigration scaffoldedMigration = toolingFacade
                                                      .Scaffold(migrationInfo.TargetName,
                                                                migrationInfo.Language == GlobalVarioable.SourceType.Csharp ?
                                                                CSharp : VisualBasic, migrationInfo.ContextAssemblyRootNameSpace, false);


            var designCode = scaffoldedMigration.DesignerCode.Insert(
                scaffoldedMigration.DesignerCode.IndexOf("private readonly ResourceManager Resources", StringComparison.Ordinal), "//");

            return(new MigrationCode()
            {
                DesignerCode = designCode.Replace("Resources.GetString(\"Target\")", "\"" + scaffoldedMigration.Resources["Target"] + "\""),
                UserCode = scaffoldedMigration.UserCode,
                Resources = scaffoldedMigration.Resources,
                MigrationId = scaffoldedMigration.MigrationId,
                Infos = infos.ToString(),
                Warnings = warnings.ToString(),
                Verbose = verbose.ToString()
            });

            //using (var db = new KS.DataAccess.Contexts.SecurityContext())
            //{
            //    var services = ((IInfrastructure<IServiceProvider>)db).Instance;
            //    var codeHelper = new CSharpHelper();
            //    var scaffolder = ActivatorUtilities.CreateInstance<MigrationsScaffolder>(
            //        services,
            //        new CSharpMigrationsGenerator(
            //            codeHelper,
            //            new CSharpMigrationOperationGenerator(codeHelper),
            //            new CSharpSnapshotGenerator(codeHelper)));

            //    var migration = scaffolder.ScaffoldMigration(
            //        "MyMigration",
            //        "MyApp.Data");

            //    File.WriteAllText(
            //        migration.MigrationId + migration.FileExtension,
            //        migration.MigrationCode);
            //    File.WriteAllText(
            //        migration.MigrationId + ".Designer" + migration.FileExtension,
            //        migration.MetadataCode);
            //    File.WriteAllText(
            //        migration.SnapshotName + migration.FileExtension,
            //        migration.SnapshotCode);
            //}
        }
        public void RefreshDb()
        {
            //Create directory if it's not exists
            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\Migrations\\"))
            {
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\Migrations\\");
            }

            //Create database Connection info based on Connection string which is set in app.config
            DbConnectionInfo connectionStringInfo = new DbConnectionInfo(
                ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString, "System.Data.SqlClient");  // We shoud retrieve this from App.config

            //Get Current Assembly name
            //This is important because our dbcontext is in this assembly
            var assemblyName = Assembly.GetExecutingAssembly().GetName().Name;

            //Create tooling face to stimulate Entity framework tools
            ToolingFacade toolingFacade = new ToolingFacade(
                assemblyName,                          // MigrationAssemblyName. In this case dll should be located in "C:\\Temp\\MigrationTest" dir
                assemblyName,                          // ContextAssemblyName. Same as above
                null,
                AppDomain.CurrentDomain.BaseDirectory, // Where the dlls are located
                AppDomain.CurrentDomain.BaseDirectory +
                "\\App.config",                        // Insert the right directory and change with Web.config if required
                AppDomain.CurrentDomain.BaseDirectory + "\\App_Data",
                connectionStringInfo)
            {
                //If we want to log our database changes we can write our logger here
                //LogInfoDelegate = s => { Console.WriteLine(s); },
                //LogWarningDelegate = s => { Console.WriteLine("WARNING: " + s); },
                //LogVerboseDelegate = s => { Console.WriteLine("VERBOSE: " + s); }
            };

            //create sql script of currently changes
            var scriptUpdate = toolingFacade.ScriptUpdate(null, null, true);

            //if any changes exists then Create Change files and also update-database
            if (!string.IsNullOrEmpty(scriptUpdate))
            {
                ScaffoldedMigration scaffoldedMigration =
                    toolingFacade.Scaffold("AutoMigrationCode", "C#", assemblyName, false);

                var fileName = GetFileName(scriptUpdate);

                //Create Directory to insert .cs and .sql file
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\Migrations\\" + fileName);
                File.WriteAllText(
                    AppDomain.CurrentDomain.BaseDirectory + "\\Migrations\\" + fileName + "\\" + fileName + ".cs",
                    scaffoldedMigration.UserCode);

                //Write logs to Migrations folder
                File.WriteAllText(
                    AppDomain.CurrentDomain.BaseDirectory + "\\Migrations\\" + fileName + "\\" + fileName + ".sql",
                    scriptUpdate);

                //Run script to migrate database to latest version
                Database.ExecuteSqlCommand(scriptUpdate);
            }
            else
            {
                //If there is no changes only make sure we have created database
                Database.CreateIfNotExists();
            }
        }
        private static void ScriptUpdate(ToolingFacade facade, Arguments arguments)
        {
            string scriptContents = facade.ScriptUpdate(arguments.SourceMigration, arguments.TargetMigration, arguments.Force);

            File.WriteAllText(arguments.ScriptFile, scriptContents, Encoding.UTF8);
        }
Example #10
0
        public void CanInstantiateEfTooling()
        {
            ToolingFacade facade = CreateToolingFacadeForBaseData();

            Assert.That(facade, Is.Not.Null);
        }