public virtual IEnumerable <string> WriteMigration(
            [NotNull] string projectDir,
            [NotNull] ScaffoldedMigration migration)
        {
            Check.NotEmpty(projectDir, "projectDir");
            Check.NotNull(migration, "migration");

            var migrationDir = Path.Combine(projectDir, migration.Directory);

            Directory.CreateDirectory(migrationDir);

            // TODO: Get from migration (set in MigrationScaffolder)
            var extension = ".cs";

            var userCodeFile = Path.Combine(migrationDir, migration.MigrationId + extension);

            File.WriteAllText(userCodeFile, migration.MigrationCode);
            yield return(userCodeFile);

            var designerCodeFile = Path.Combine(migrationDir, migration.MigrationId + ".Designer" + extension);

            File.WriteAllText(designerCodeFile, migration.MigrationMetadataCode);
            yield return(designerCodeFile);

            var modelSnapshotFile = Path.Combine(migrationDir, migration.SnapshotModelClass + extension);

            File.WriteAllText(modelSnapshotFile, migration.SnapshotModelCode);
            yield return(modelSnapshotFile);
        }
        public string Write(ScaffoldedMigration scaffoldedMigration, bool rescaffolding = false, bool force = false, string name = null)
        {
            DebugCheck.NotNull(scaffoldedMigration);

            var userCodeFileName     = scaffoldedMigration.MigrationId + "." + scaffoldedMigration.Language;
            var userCodePath         = Path.Combine(scaffoldedMigration.Directory, userCodeFileName);
            var designerCodeFileName = scaffoldedMigration.MigrationId + ".Designer."
                                       + scaffoldedMigration.Language;
            var designerCodePath  = Path.Combine(scaffoldedMigration.Directory, designerCodeFileName);
            var resourcesFileName = scaffoldedMigration.MigrationId + ".resx";
            var resourcesPath     = Path.Combine(scaffoldedMigration.Directory, resourcesFileName);

            if (rescaffolding && !force)
            {
                var absoluteUserCodePath = Path.Combine(_command.Project.GetProjectDir(), userCodePath);

                if (!string.Equals(scaffoldedMigration.UserCode, File.ReadAllText(absoluteUserCodePath)))
                {
                    Debug.Assert(!string.IsNullOrWhiteSpace(name));

                    _command.WriteWarning(Strings.RescaffoldNoForce(name));
                }
            }
            else
            {
                _command.Project.AddFile(userCodePath, scaffoldedMigration.UserCode);
            }

            WriteResources(userCodePath, resourcesPath, scaffoldedMigration.Resources);
            _command.Project.AddFile(designerCodePath, scaffoldedMigration.DesignerCode);

            return(userCodePath);
        }
Example #3
0
        public virtual IEnumerable <string> WriteMigration(
            [NotNull] string projectDir,
            [NotNull] ScaffoldedMigration migration,
            [NotNull] string rootNamespace)
        {
            Check.NotEmpty(projectDir, "projectDir");
            Check.NotNull(migration, "migration");
            Check.NotEmpty(rootNamespace, "rootNamespace");

            var migrationDir = GetMigrationDirectory(projectDir, migration, rootNamespace);

            Directory.CreateDirectory(migrationDir);

            var userCodeFile = Path.Combine(migrationDir, migration.MigrationId + migration.Language);

            File.WriteAllText(userCodeFile, migration.MigrationCode);
            yield return(userCodeFile);

            var designerCodeFile = Path.Combine(migrationDir, migration.MigrationId + ".Designer" + migration.Language);

            File.WriteAllText(designerCodeFile, migration.MigrationMetadataCode);
            yield return(designerCodeFile);

            var modelShapshotDir  = GetSnapshotDirectory(projectDir, migration, rootNamespace);
            var modelSnapshotFile = Path.Combine(
                modelShapshotDir,
                migration.SnapshotModelClass + migration.Language);

            File.WriteAllText(modelSnapshotFile, migration.SnapshotModelCode);
            yield return(modelSnapshotFile);
        }
    /// <summary>
    ///     Saves a scaffolded migration to files.
    /// </summary>
    /// <param name="projectDir">The project's root directory.</param>
    /// <param name="migration">The scaffolded migration.</param>
    /// <param name="outputDir">The directory to put files in. Paths are relative to the project directory.</param>
    /// <returns>The saved migrations files.</returns>
    public virtual MigrationFiles Save(string projectDir, ScaffoldedMigration migration, string?outputDir)
    {
        var lastMigrationFileName  = migration.PreviousMigrationId + migration.FileExtension;
        var migrationDirectory     = outputDir ?? GetDirectory(projectDir, lastMigrationFileName, migration.MigrationSubNamespace);
        var migrationFile          = Path.Combine(migrationDirectory, migration.MigrationId + migration.FileExtension);
        var migrationMetadataFile  = Path.Combine(migrationDirectory, migration.MigrationId + ".Designer" + migration.FileExtension);
        var modelSnapshotFileName  = migration.SnapshotName + migration.FileExtension;
        var modelSnapshotDirectory = GetDirectory(projectDir, modelSnapshotFileName, migration.SnapshotSubnamespace);
        var modelSnapshotFile      = Path.Combine(modelSnapshotDirectory, modelSnapshotFileName);

        Dependencies.OperationReporter.WriteVerbose(DesignStrings.WritingMigration(migrationFile));
        Directory.CreateDirectory(migrationDirectory);
        File.WriteAllText(migrationFile, migration.MigrationCode, Encoding.UTF8);
        File.WriteAllText(migrationMetadataFile, migration.MetadataCode, Encoding.UTF8);

        Dependencies.OperationReporter.WriteVerbose(DesignStrings.WritingSnapshot(modelSnapshotFile));
        Directory.CreateDirectory(modelSnapshotDirectory);
        File.WriteAllText(modelSnapshotFile, migration.SnapshotCode, Encoding.UTF8);

        return(new MigrationFiles
        {
            MigrationFile = migrationFile,
            MetadataFile = migrationMetadataFile,
            SnapshotFile = modelSnapshotFile
        });
    }
Example #5
0
        /*
         * public static string GetAllMigration()
         * {
         *
         *
         *  var config = new DbMigrationsConfiguration<SampleDBContext> { AutomaticMigrationsEnabled = true };
         *
         *  var migrator = new DbMigrator(config);
         *
         *  //Get code migration//
         *  var scaffolder = new MigrationScaffolder(migrator.Configuration);
         *
         *  ScaffoldedMigration migration = scaffolder.Scaffold("codeMigration");
         *
         *  var migrationFile = System.IO.Path.Combine(rootPath, migration.Directory, migration.MigrationId);
         *
         *  var userCodeFile = migrationFile + ".cs";
         *
         *  File.WriteAllText(userCodeFile, migration.UserCode);
         *
         *  //Get Db script//
         *  var scriptor = new MigratorScriptingDecorator(migrator);
         *
         *  string script = scriptor.ScriptUpdate(sourceMigration: null, targetMigration: null);
         *
         *  var SqlScriptFile = migrationFile + ".sql";
         *
         *  File.WriteAllText(SqlScriptFile, script);
         *
         *  //Get Edmx Document//
         *
         *  var _currenModelProp = migrator.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Single(m => m.Name == "_currentModel");
         *
         *  var _currenModelValueXDOC = (XDocument)_currenModelProp.GetValue(migrator);
         *
         *  var edmxFile = migrationFile + ".xml";
         *
         *
         *  File.WriteAllText(edmxFile, _currenModelValueXDOC.ToString());
         *
         *  return script;
         * }
         */

        static void gettypfromassebmly()
        {
            var assemblyPath = @"C:\Users\rajneesh.kumar\source\repos\EF6-Code-First-Demo-master\EF6CodeFirstDemo\bin\Debug";

            var assemblyName = string.Format(@"{0}\{1}.{2}", assemblyPath, "EF6ClassLibraryCodeFirst", "dll");

            var assembly = Assembly.LoadFrom(assemblyName);

            var type = assembly.GetType("EF6ClassLibraryCodeFirst.SampleDBContext");

            Type genericClass = typeof(DbMigrationsConfiguration <>);

            //MakeGenericType is badly named
            Type constructedClass = genericClass.MakeGenericType(type);

            object created = Activator.CreateInstance(constructedClass);

            ////////////////////////////////////////////////////////////////////
            ///////////////////////////////////////////////////////////////////


            var config = (DbMigrationsConfiguration)created;

            config.AutomaticMigrationsEnabled = true;

            var migrator = new DbMigrator(config);

            //Get code migration//
            var scaffolder = new MigrationScaffolder(migrator.Configuration);

            ScaffoldedMigration migration = scaffolder.Scaffold("codeMigration");

            var migrationFile = System.IO.Path.Combine(rootPath, migration.Directory, migration.MigrationId);

            var userCodeFile = migrationFile + ".cs";

            File.WriteAllText(userCodeFile, migration.UserCode);

            //Get Db script//
            var scriptor = new MigratorScriptingDecorator(migrator);

            string script = scriptor.ScriptUpdate(sourceMigration: null, targetMigration: null);

            var SqlScriptFile = migrationFile + ".sql";

            File.WriteAllText(SqlScriptFile, script);

            //Get Edmx Document//
            var _currenModelProp = migrator.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Single(m => m.Name == "_currentModel");

            var _currenModelValueXDOC = (XDocument)_currenModelProp.GetValue(migrator);

            var edmxFile = migrationFile + ".xml";

            File.WriteAllText(edmxFile, _currenModelValueXDOC.ToString());
        }
Example #6
0
        private void ResetDatabaseToV1()
        {
            ResetDatabase();

            var migrator = CreateMigrator <TContextV1>();

            _generatedMigration_v1 = new MigrationScaffolder(migrator.Configuration).Scaffold("V1");

            CreateMigrator <TContextV1>(scaffoldedMigrations: _generatedMigration_v1).Update();
        }
        public static void RefreshDb()
        {
            using (var dbContext = new AppDbContext())
            {
                DbConnectionInfo connectionStringInfo = new DbConnectionInfo(
                    ConnectionString, "System.Data.SqlClient"); // We shoud retrieve this from App.config

                ToolingFacade toolingFacade = new ToolingFacade(
                    "DotNetFrameworkDataLayer",            // MigrationAssemblyName. In this case dll should be located in "C:\\Temp\\MigrationTest" dir
                    "DotNetFrameworkDataLayer",            // 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)
                {
                    LogInfoDelegate    = s => { Console.WriteLine(s); },
                    LogWarningDelegate = s => { Console.WriteLine("WARNING: " + s); },
                    LogVerboseDelegate = s => { Console.WriteLine("VERBOSE: " + s); }
                };

                var scriptUpdate = toolingFacade.ScriptUpdate(null, null, true);

                if (!string.IsNullOrEmpty(scriptUpdate))
                {
                    ScaffoldedMigration scaffoldedMigration =
                        toolingFacade.Scaffold("AutoMigrationCode", "C#", "DotNetFrameworkDataLayer", 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);

                    File.WriteAllText(
                        AppDomain.CurrentDomain.BaseDirectory + "\\Migrations\\" + fileName + "\\" + fileName + ".sql",
                        scriptUpdate);

                    //if (!Database.CreateIfNotExists())
                    //{
                    dbContext.Database.ExecuteSqlCommand(scriptUpdate);
                    //}
                }
                else
                {
                    //If there is no changes only make sure we have created database
                    dbContext.Database.CreateIfNotExists();
                }
            }
        }
Example #8
0
 private static IDictionary ToHashtable(ScaffoldedMigration result)
 => result == null
         ? null
         : new Hashtable
 {
     ["MigrationId"]  = result.MigrationId,
     ["UserCode"]     = result.UserCode,
     ["DesignerCode"] = result.DesignerCode,
     ["Language"]     = result.Language,
     ["Directory"]    = result.Directory,
     ["Resources"]    = result.Resources,
     ["IsRescaffold"] = result.IsRescaffold
 };
Example #9
0
        private void SaveMigration(ScaffoldedMigration scaffold)
        {
            var itemGroupName = XName.Get("ItemGroup", PROJECT_NAMESPACE);
            var newItemGroup  = new XElement(itemGroupName);

            var migrationUserFileName = String.Format("{0}.{1}", scaffold.MigrationId, scaffold.Language);
            var migrationUserPath     = Path.Combine(scaffold.Directory, migrationUserFileName);

            File.WriteAllText(Path.Combine(_baseFolder, migrationUserPath), scaffold.UserCode);
            var migrationUserItem = new XElement(XName.Get("Compile", PROJECT_NAMESPACE));

            migrationUserItem.SetAttributeValue(XName.Get("Include"), migrationUserPath);
            newItemGroup.Add(migrationUserItem);

            var migrationDesignerPath = Path.Combine(scaffold.Directory, String.Format("{0}.Designer.{1}", scaffold.MigrationId, scaffold.Language));

            File.WriteAllText(Path.Combine(_baseFolder, migrationDesignerPath), scaffold.DesignerCode);
            var migrationDesignerItem = new XElement(XName.Get("Compile", PROJECT_NAMESPACE));

            migrationDesignerItem.SetAttributeValue(XName.Get("Include"), migrationDesignerPath);
            var migrationDesignerDependentUponItem = new XElement(XName.Get("DependentUpon", PROJECT_NAMESPACE))
            {
                Value = migrationUserFileName
            };

            migrationDesignerItem.Add(migrationDesignerDependentUponItem);
            newItemGroup.Add(migrationDesignerItem);

#if (EF5 || EF6)
            var migrationResourcePath = Path.Combine(scaffold.Directory, String.Format("{0}.resx", scaffold.MigrationId));
            var writer = new ResXResourceWriter(Path.Combine(_baseFolder, migrationResourcePath));
            foreach (var resource in scaffold.Resources)
            {
                writer.AddResource(resource.Key, resource.Value);
            }
            writer.Close();
            var migrationResourceItem = new XElement(XName.Get("EmbeddedResource", PROJECT_NAMESPACE));
            migrationResourceItem.SetAttributeValue(XName.Get("Include"), migrationResourcePath);
            var migrationResourceDependentUponItem = new XElement(XName.Get("DependentUpon", PROJECT_NAMESPACE));
            migrationResourceDependentUponItem.Value = migrationUserFileName;
            migrationResourceItem.Add(migrationResourceDependentUponItem);
            newItemGroup.Add(migrationResourceItem);
#endif

            var projectXml    = XElement.Load(_projectPath);
            var lastItemGroup = projectXml.Elements(itemGroupName).Last();
            lastItemGroup.AddAfterSelf(newItemGroup);
            projectXml.Save(_projectPath, SaveOptions.OmitDuplicateNamespaces);
        }
Example #10
0
        protected string WriteMigration(
            ScaffoldedMigration scaffoldedMigration,
            bool rescaffolding = false,
            bool force         = false,
            string name        = null)
        {
            DebugCheck.NotNull(scaffoldedMigration);

            var userCodeFileName         = scaffoldedMigration.MigrationId + "." + scaffoldedMigration.Language;
            var userCodePath             = Path.Combine(scaffoldedMigration.Directory, userCodeFileName);
            var absoluteUserCodePath     = Path.Combine(ProjectDir.Value(), userCodePath);
            var designerCodeFileName     = scaffoldedMigration.MigrationId + ".Designer." + scaffoldedMigration.Language;
            var designerCodePath         = Path.Combine(scaffoldedMigration.Directory, designerCodeFileName);
            var absoluteDesignerCodePath = Path.Combine(ProjectDir.Value(), designerCodePath);
            var resourcesFileName        = scaffoldedMigration.MigrationId + ".resx";
            var resourcesPath            = Path.Combine(scaffoldedMigration.Directory, resourcesFileName);

            if (rescaffolding && !force)
            {
                if (!string.Equals(scaffoldedMigration.UserCode, File.ReadAllText(absoluteUserCodePath)))
                {
                    Debug.Assert(!string.IsNullOrWhiteSpace(name));

                    Reporter.WriteWarning(string.Format(MyResources.RescaffoldNoForce, name));
                }
            }
            else
            {
                Directory.CreateDirectory(Path.GetDirectoryName(absoluteUserCodePath));
                File.WriteAllText(absoluteUserCodePath, scaffoldedMigration.UserCode, Encoding.UTF8);
            }

            var absoluteResourcesPath = Path.Combine(ProjectDir.Value(), resourcesPath);

            using (var writer = new ResXResourceWriter(absoluteResourcesPath))
            {
                foreach (var i in scaffoldedMigration.Resources)
                {
                    writer.AddResource(i.Key, i.Value);
                }
            }

            Directory.CreateDirectory(Path.GetDirectoryName(absoluteDesignerCodePath));
            File.WriteAllText(absoluteDesignerCodePath, scaffoldedMigration.DesignerCode, Encoding.UTF8);

            return(userCodePath);
        }
Example #11
0
        private static string GetSnapshotDirectory(string projectDir, ScaffoldedMigration migration, string rootNamespace)
        {
            if (migration.LastModelSnapshot != null)
            {
                var lastSnapshotFile = FindProjectFile(
                    projectDir,
                    migration.LastModelSnapshot.GetType().Name + migration.Language);
                if (lastSnapshotFile != null)
                {
                    return(Path.GetDirectoryName(lastSnapshotFile));
                }
            }

            var snapshotDirectory = GetDirectoryFromNamespace(migration.ModelSnapshotNamespace, rootNamespace);

            return(Path.Combine(projectDir, snapshotDirectory));
        }
Example #12
0
        private static string GetMigrationDirectory(string projectDir, ScaffoldedMigration migration, string rootNamespace)
        {
            if (migration.LastMigration != null)
            {
                var lastMigrationFile = FindProjectFile(
                    projectDir,
                    migration.LastMigration.GetMigrationId() + migration.Language);
                if (lastMigrationFile != null)
                {
                    return(Path.GetDirectoryName(lastMigrationFile));
                }
            }

            var migrationDirectory = GetDirectoryFromNamespace(migration.MigrationNamespace, rootNamespace);

            return(Path.Combine(projectDir, migrationDirectory));
        }
Example #13
0
        internal ScaffoldedMigration ScaffoldInitialCreate(string @namespace)
        {
            string    migrationId;
            string    productVersion;
            XDocument lastModel = this._historyRepository.GetLastModel(out migrationId, out productVersion, this._legacyContextKey);

            if (lastModel == null || !migrationId.MigrationName().Equals(Strings.InitialCreate))
            {
                return((ScaffoldedMigration)null);
            }
            List <MigrationOperation> list = this._modelDiffer.Diff(this._emptyModel.Value, lastModel, this._modificationCommandTreeGenerator, this.SqlGenerator, (string)null, (string)null).ToList <MigrationOperation>();
            ScaffoldedMigration       scaffoldedMigration = this._configuration.CodeGenerator.Generate(migrationId, (IEnumerable <MigrationOperation>)list, (string)null, Convert.ToBase64String(new ModelCompressor().Compress(this._currentModel)), @namespace, Strings.InitialCreate);

            scaffoldedMigration.MigrationId = migrationId;
            scaffoldedMigration.Directory   = this._configuration.MigrationsDirectory;
            scaffoldedMigration.Resources.Add("DefaultSchema", (object)this._defaultSchema);
            return(scaffoldedMigration);
        }
        private void TestWrite(
            Func <System.Data.Entity.Migrations.Utilities.MigrationWriter, ScaffoldedMigration, string> action,
            bool skipUserCodeVerification = false)
        {
            var command             = CreateCommand(_projectDir);
            var writer              = new System.Data.Entity.Migrations.Utilities.MigrationWriter(command);
            var scaffoldedMigration = new ScaffoldedMigration
            {
                MigrationId  = MigrationId,
                Language     = Language,
                Directory    = MigrationsDirectory,
                UserCode     = "The user code.",
                DesignerCode = "The designer code.",
                Resources    =
                {
                    { ResourceName, "The resource." }
                }
            };

            var relativeUserCodePath = action(writer, scaffoldedMigration);

            Assert.Equal(UserCodePath, relativeUserCodePath);

            if (!skipUserCodeVerification)
            {
                var userCodePath = Path.Combine(_projectDir, UserCodePath);
                Assert.Equal("The user code.", File.ReadAllText(userCodePath));
            }

            var designerCodePath = Path.Combine(_projectDir, DesignerCodePath);

            Assert.Equal("The designer code.", File.ReadAllText(designerCodePath));

            var resourcesPath = Path.Combine(_projectDir, ResourcesPath);

            using (var reader = new ResXResourceReader(resourcesPath))
            {
                var resources = reader.Cast <DictionaryEntry>();

                Assert.Equal(1, resources.Count());
                Assert.Contains(new DictionaryEntry(ResourceName, "The resource."), resources);
            }
        }
Example #15
0
        internal ScaffoldedMigration Scaffold(
            string migrationName,
            string @namespace,
            bool ignoreChanges)
        {
            string        migrationId1 = (string)null;
            bool          flag         = false;
            List <string> list         = this.GetPendingMigrations().ToList <string>();

            if (list.Any <string>())
            {
                string str = list.Last <string>();
                if (!str.EqualsIgnoreCase(migrationName) && !str.MigrationName().EqualsIgnoreCase(migrationName))
                {
                    throw Error.MigrationsPendingException((object)list.Join <string>((Func <string, string>)null, ", "));
                }
                flag          = true;
                migrationId1  = str;
                migrationName = str.MigrationName();
            }
            XDocument sourceModel = (XDocument)null;

            this.CheckLegacyCompatibility((Action)(() => sourceModel = this._currentModel));
            string migrationId2   = (string)null;
            string productVersion = (string)null;

            sourceModel = sourceModel ?? this._historyRepository.GetLastModel(out migrationId2, out productVersion, (string)null) ?? this._emptyModel.Value;
            IEnumerable <MigrationOperation> operations = ignoreChanges ? Enumerable.Empty <MigrationOperation>() : (IEnumerable <MigrationOperation>) this._modelDiffer.Diff(sourceModel, this._currentModel, this._modificationCommandTreeGenerator, this.SqlGenerator, productVersion, (string)null).ToList <MigrationOperation>();

            if (!flag)
            {
                migrationName = this._migrationAssembly.UniquifyName(migrationName);
                migrationId1  = MigrationAssembly.CreateMigrationId(migrationName);
            }
            ModelCompressor     modelCompressor     = new ModelCompressor();
            ScaffoldedMigration scaffoldedMigration = this._configuration.CodeGenerator.Generate(migrationId1, operations, sourceModel == this._emptyModel.Value || sourceModel == this._currentModel || !migrationId2.IsAutomaticMigration() ? (string)null : Convert.ToBase64String(modelCompressor.Compress(sourceModel)), Convert.ToBase64String(modelCompressor.Compress(this._currentModel)), @namespace, migrationName);

            scaffoldedMigration.MigrationId  = migrationId1;
            scaffoldedMigration.Directory    = this._configuration.MigrationsDirectory;
            scaffoldedMigration.IsRescaffold = flag;
            scaffoldedMigration.Resources.Add("DefaultSchema", (object)this._defaultSchema);
            return(scaffoldedMigration);
        }
Example #16
0
        private static string GetMigrationDirectory(string projectDir, ScaffoldedMigration migration, string rootNamespace)
        {
            if (migration.LastMigration != null)
            {
                var lastMigrationFiles = Directory.EnumerateFiles(
                    projectDir,
                    migration.LastMigration.GetMigrationId() + migration.Language,
                    SearchOption.AllDirectories);

                foreach (var lastMigrationFile in lastMigrationFiles)
                {
                    return(Path.GetDirectoryName(lastMigrationFile));
                }
            }

            var migrationDirectory = GetDirectoryFromNamespace(migration.MigrationNamespace, rootNamespace);

            return(Path.Combine(projectDir, migrationDirectory));
        }
Example #17
0
        private static string GetSnapshotDirectory(string projectDir, ScaffoldedMigration migration, string rootNamespace)
        {
            if (migration.LastModelSnapshot != null)
            {
                var lastSnapshotFiles = Directory.EnumerateFiles(
                    projectDir,
                    migration.LastModelSnapshot.GetType().Name + migration.Language,
                    SearchOption.AllDirectories);

                foreach (var lastSnapshotFile in lastSnapshotFiles)
                {
                    return(Path.GetDirectoryName(lastSnapshotFile));
                }
            }

            var snapshotDirectory = GetDirectoryFromNamespace(migration.ModelSnapshotNamespace, rootNamespace);

            return(Path.Combine(projectDir, snapshotDirectory));
        }
Example #18
0
        private MigrationData ApplyMigration(Type type, Version version, ScaffoldedMigration scaffoldedMigration)
        {
            var migration = new MigrationData
            {
                Context   = type.Name,
                Version   = version.ToString(),
                Migration = scaffoldedMigration.MigrationCode,
                Metadata  = scaffoldedMigration.MetadataCode
            };

            var migrationAssemblyName = this.GenerateMigrationAssemblyName(type, version);

            this.LoadAssembly(migrationAssemblyName, scaffoldedMigration.SnapshotCode, migration);
            using (var context = (DbContextBase)this.contextService.Get(type))
            {
                context.Initialize(new DefaultInitializeDbContext(this.app, migrationAssemblyName, this.GenerateMigrationsHistoryTableName(type)));
                context.Database.Migrate();
            }

            return(migration);
        }
Example #19
0
        private static ScaffoldedMigration ToScaffoldedMigration(IDictionary result)
        {
            if (result == null)
            {
                return(null);
            }

            var scaffoldedMigration = new ScaffoldedMigration
            {
                MigrationId  = (string)result["MigrationId"],
                UserCode     = (string)result["UserCode"],
                DesignerCode = (string)result["DesignerCode"],
                Language     = (string)result["Language"],
                Directory    = (string)result["Directory"],
                IsRescaffold = (bool)result["IsRescaffold"]
            };

            foreach (DictionaryEntry entry in (IDictionary)result["Resources"])
            {
                scaffoldedMigration.Resources.Add((string)entry.Key, entry.Value);
            }

            return(scaffoldedMigration);
        }
Example #20
0
 protected virtual string WriteMigration(string name, bool force, ScaffoldedMigration scaffoldedMigration, bool rescaffolding)
 {
     return(new MigrationWriter(this).Write(scaffoldedMigration, rescaffolding, force, name));
 }
Example #21
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();
            }
        }
 protected override string WriteMigration(string name, bool force, ScaffoldedMigration scaffoldedMigration, bool rescaffolding)
 {
     return(name);
 }