Beispiel #1
0
        public void RunMigrationScriptError_Test()
        {
            bool executed = false;

            UnityCache.RegisterInstance <IFaustAccessor>(new Fakes.StubIFaustAccessor
            {
                ExecuteSqlCommandStringUserContext = (command, userContext) =>
                {
                    executed = true;
                    throw new Exception();
                }
            });

            FaustMigrationScript script = new FaustMigrationScript
            {
                ReleaseNumber = 1,
                ScriptName    = "UnitTestScript",
                Commands      = new string[] { "Command 1" }
            };

            FaustMigrationHistory result = new FaustEngine().RunMigrationScript(script, new UserContext());

            Assert.IsTrue(executed);
            Assert.IsFalse(result.Successful.Value);
            Assert.IsNotNull(result);
        }
Beispiel #2
0
        public FaustMigrationHistory RunMigrationScript(FaustMigrationScript script, UserContext userContext)
        {
            Logger.Log(string.Format("FaustEngine.RunMigrationScript: Running commands for script {0}.", script.ScriptName), TraceEventType.Verbose);

            FaustMigrationHistory migrationHistory = new FaustMigrationHistory();

            try
            {
                migrationHistory.ReleaseNumber = script.ReleaseNumber;
                migrationHistory.ScriptName    = script.ScriptName;
                migrationHistory.Committed     = true;
                migrationHistory.Successful    = true;
                migrationHistory.LastRun       = DateTime.Now;

                foreach (string sqlCommand in script.Commands)
                {
                    migrationHistory.Log = sqlCommand;

                    UnityCache.Resolve <IFaustAccessor>().ExecuteSqlCommand(sqlCommand, userContext);
                }

                return(migrationHistory);
            }
            catch (Exception ex)
            {
                migrationHistory.Successful = false;
                migrationHistory.Log        = string.Format("Error: {0}\r\nCommand: {1}", ex.Message, migrationHistory.Log);

                Logger.Log(string.Format("FaustEngine.RunMigrationScript: {0}", migrationHistory.Log), TraceEventType.Error);

                return(migrationHistory);
            }
        }
Beispiel #3
0
        public void SaveMigrationsHistoryUpdate_Test()
        {
            bool created = false;
            bool updated = false;

            UnityCache.RegisterInstance <IFaustMigrationsHistoryAccessor>(new Fakes.StubIFaustMigrationsHistoryAccessor
            {
                FindManyFaustMigrationHistoryUserContext = (history, userContext) =>
                {
                    return(new FaustMigrationHistory[] { new FaustMigrationHistory() });
                },
                CreateFaustMigrationHistoryUserContext = (history, userContext) =>
                {
                    created = true;
                    return(new FaustMigrationHistory());
                },
                UpdateFaustMigrationHistoryUserContext = (history, userContext) =>
                {
                    updated = true;
                    return(new FaustMigrationHistory());
                }
            });

            new FaustEngine().SaveMigrationsHistory(new FaustMigrationHistory[] { new FaustMigrationHistory() }, new UserContext());

            Assert.IsFalse(created);
            Assert.IsTrue(updated);
        }
Beispiel #4
0
        public void SaveMigrationsHistory(FaustMigrationHistory[] migrationHistories, UserContext userContext)
        {
            Logger.Log(string.Format("FaustEngine.SaveMigrationsHistory: Saving History for {0} scripts.", migrationHistories.Length), TraceEventType.Verbose);

            foreach (FaustMigrationHistory migration in migrationHistories)
            {
                FaustMigrationHistory searchCriteria = new FaustMigrationHistory
                {
                    ReleaseNumber = migration.ReleaseNumber,
                    ScriptName    = migration.ScriptName
                };

                using (TransactionScope loggingScope = new TransactionScope(TransactionScopeOption.RequiresNew))
                {
                    FaustMigrationHistory existingHistory = UnityCache.Resolve <IFaustMigrationsHistoryAccessor>()
                                                            .FindMany(searchCriteria, userContext)
                                                            .FirstOrDefault();
                    if (existingHistory == null)
                    {
                        UnityCache.Resolve <IFaustMigrationsHistoryAccessor>().Create(migration, userContext);
                    }
                    else
                    {
                        existingHistory.LastRun    = migration.LastRun;
                        existingHistory.Committed  = migration.Committed;
                        existingHistory.Successful = migration.Successful;
                        existingHistory.Log        = migration.Log;

                        UnityCache.Resolve <IFaustMigrationsHistoryAccessor>().Update(existingHistory, userContext);
                    }

                    loggingScope.Complete();
                }
            }
        }
        // GET: Registration
        public ActionResult Index()
        {
            List <Attendee> attendees = new List <Attendee>();
            UserContext     uc        = new UserContext();

            uc.ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            attendees           = UnityCache.ResolveDefault <IRegistrationManager>().GetAllAttendees(uc).ToList();
            return(View(attendees));
        }
        static void Main(string[] args)
        {
            DalGeneratorConfigSection config = DalGeneratorConfigSection.current;

            UnityCache.Resolve <IDalManager>().CreateDataContracts();
            UnityCache.Resolve <IDalManager>().CreateFluentApiEntries();
            UnityCache.Resolve <IDalManager>().CreateDatabaseAccessors();
            UnityCache.Resolve <IDalManager>().CreateUnitTests();
        }
        public ProgramTestsBase()
        {
            UnityCache.Register(Mock.Create <IDependency>());

            #region JustMock Full Required

            Mock.Arrange(() => Logger.Log(Arg.AnyString)).DoNothing();

            #endregion
        }
        public ActionResult Create(Attendee attendee)
        {
            List <Attendee> attendees = new List <Attendee>();

            attendees.Add(attendee);
            IRegistrationManager regManager = UnityCache.ResolveDefault <IRegistrationManager>();
            UserContext          uc         = new UserContext();

            uc.ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            regManager.ProcessRegistration(uc, attendees);
            return(View());
        }
        public ActionResult Create(List <Attendee> attendees)
        {
            IRegistrationManager regManager = UnityCache.ResolveDefault <IRegistrationManager>();
            UserContext          uc         = new UserContext();

            uc.AuditUserName = "******";

            uc.ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            var reg = regManager.ProcessRegistration(uc, attendees);

            return(View());
        }
Beispiel #10
0
        public void ProcessRegistration(UserContext userContext, ICollection <Attendee> attendees)
        {
            Registration    returnRegistration    = new Registration();
            List <Attendee> registrationAttendees = new List <Attendee>(UnityCache.ResolveDefault <IRegistrationEngine>().ProcessAttendees(userContext, attendees));


            Registration newReg = new Registration();

            newReg.Attendees = registrationAttendees;

            UnityCache.ResolveDefault <IRegistrationAccessor>().AddRegistration(userContext, newReg);
        }
        public void CreateDataContracts()
        {
            DalGeneratorConfigSection config = DalGeneratorConfigSection.current;

            foreach (IncludedTablesElement table in config.IncludedTables)
            {
                InformationSchemaColumn[] columns = UnityCache.Resolve <IDatabaseAccessor>().GetColumnsForTable(table.Name, table.Schema);

                string tableName = columns.First().TABLE_NAME.TrimEnd(new char[] { 's' });

                UnityCache.Resolve <IDalEngine>().GenerateCodeFile(config.TemplatesPath, "DataContract.cshtml", config.DataContractsPath, tableName, columns);
            }
        }
Beispiel #12
0
        public ICollection <Attendee> ProcessAttendees(UserContext userContext, ICollection <Attendee> attendees)
        {
            List <Attendee> registrationAttendees = new List <Attendee>();

            foreach (Attendee attendee in attendees)
            {
                Attendee CheckedAttendee = new Attendee();
                CheckedAttendee = UnityCache.ResolveDefault <IRegistrationAccessor>().FindAttendee(userContext, attendee);

                registrationAttendees.Add(CheckedAttendee);
            }

            return(registrationAttendees);
        }
Beispiel #13
0
        public void BasicTest()
        {
            bool initialized  = false;
            bool debugDeleted = false;
            bool gotScripts   = false;
            bool ranScript    = false;
            bool savedHistory = false;

            UnityCache.RegisterInstance <IFaustMigrationsHistoryAccessor>(new Fakes.StubIFaustMigrationsHistoryAccessor
            {
                InitializeUserContext = (userContext) =>
                {
                    initialized = true;
                },
                DeleteDebugEntriesUserContext = (userContext) =>
                {
                    debugDeleted = true;
                    return(new FaustMigrationHistory[] { });
                }
            });

            UnityCache.RegisterInstance <IFaustEngine>(new Fakes.StubIFaustEngine
            {
                GetReleaseMigrationScriptsDirectoryInfoUserContext = (releaseDir, userContext) =>
                {
                    gotScripts = true;
                    return(new FaustMigrationScript[] { new FaustMigrationScript() });
                },
                RunMigrationScriptFaustMigrationScriptUserContext = (script, userContext) =>
                {
                    ranScript = true;
                    return(new FaustMigrationHistory());
                },
                SaveMigrationsHistoryFaustMigrationHistoryArrayUserContext = (histories, userContext) =>
                {
                    savedHistory = true;
                }
            });

            new FaustManager().RunMigration("unitTest");

            Assert.IsTrue(initialized);
            Assert.IsTrue(debugDeleted);
            Assert.IsTrue(gotScripts);
            Assert.IsTrue(ranScript);
            Assert.IsTrue(savedHistory);
        }
        public ICollection <Attendee> ProcessAttendees(UserContext userContext, ICollection <Attendee> attendees)
        {
            List <Attendee> registrationAttendees = new List <Attendee>();

            foreach (Attendee a in attendees)
            {
                if (a.Id == null)
                {
                    registrationAttendees.Add(UnityCache.ResolveDefault <IAttendeeAccessor>().AddAttendee(userContext, a));
                }
                else
                {
                    registrationAttendees.Add(a);
                }
            }

            return(registrationAttendees);
        }
        public void CreateUnitTests()
        {
            DalGeneratorConfigSection config = DalGeneratorConfigSection.current;

            UnityCache.Resolve <IDalEngine>().GenerateCodeFile(config.TemplatesPath, "DatabaseAccessorTestBase.cshtml", config.UnitTestsPath, "DatabaseAccessorTestBase");

            foreach (IncludedTablesElement table in DalGeneratorConfigSection.current.IncludedTables)
            {
                List <InformationSchemaColumn> columns = UnityCache.Resolve <IDatabaseAccessor>()
                                                         .GetColumnsForTable(table.Name, table.Schema)
                                                         .ToList();

                string tableName    = columns.First().TABLE_NAME.TrimEnd(new char[] { 's' });
                string accessorFile = string.Format("{0}AccessorTests", tableName);

                UnityCache.Resolve <IDalEngine>().GenerateCodeFile(config.TemplatesPath, "DatabaseAccessorUnitTest.cshtml", config.UnitTestsPath, accessorFile, tableName);
            }
        }
Beispiel #16
0
        public void GetReleaseMigrationScripts_TestFindOne()
        {
            bool foundMany = false;

            UnityCache.RegisterInstance <IFaustMigrationsHistoryAccessor>(new Fakes.StubIFaustMigrationsHistoryAccessor
            {
                FindManyFaustMigrationHistoryUserContext = (history, userContext) => {
                    foundMany = true;
                    return(new FaustMigrationHistory[] {});
                }
            });

            DirectoryInfo releaseDir = new DirectoryInfo(@"..\..\migrations\UnitTest\001");

            FaustMigrationScript[] results = new FaustEngine().GetReleaseMigrationScripts(releaseDir, new UserContext());

            Assert.IsTrue(foundMany);
            Assert.AreEqual(1, results.Length);
        }
Beispiel #17
0
 public static void RunMigrations(string[] args)
 {
     if (args.Length > 0)
     {
         if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings[args[0]]))
         {
             UnityCache.Resolve <IFaustManager>().RunMigration(args[0]);
         }
         else
         {
             Console.WriteLine("##teamcity[message text='Specified database does not exist in App.config' errorDetails='' status='ERROR']");
             Console.WriteLine("##teamcity[buildProblem description='FAUST Failed.  See build log for details.']");
         }
     }
     else
     {
         UnityCache.Resolve <IFaustManager>().RunMigration(ConfigurationManager.AppSettings["DefaultDatabase"]);
     }
 }
        private void LoadChangelogFromCache(string appSecret)
        {
            try
            {
                var cacheValue = new UnityCache(appSecret).GetValue("app-changelog", null);

                if (cacheValue == null)
                {
                    return;
                }

                var versions = JsonConvert.DeserializeObject <AppVersion[]>(cacheValue);

                CreateChangelog(versions);
            }
            catch (Exception)
            {
                // ignore
            }
        }
        public void CreateFluentApiEntries()
        {
            DalGeneratorConfigSection config = DalGeneratorConfigSection.current;

            // Create DbBase.cs File
            UnityCache.Resolve <IDalEngine>().GenerateCodeFile(config.TemplatesPath, "DbBase.cshtml", config.AccessorsPath, "DbBase");

            // Create DbContext class
            List <TableColumnContext> contexts = new List <TableColumnContext>();

            foreach (IncludedTablesElement table in DalGeneratorConfigSection.current.IncludedTables)
            {
                List <TablePrimaryKey> primaryKeys = UnityCache.Resolve <IDatabaseAccessor>()
                                                     .GetPrimaryKeysForTable(table.Name, table.Schema)
                                                     .ToList();

                List <InformationSchemaColumn> columns = UnityCache.Resolve <IDatabaseAccessor>()
                                                         .GetColumnsForTable(table.Name, table.Schema)
                                                         .ToList();

                List <String> allIdColumns = columns.Where(c => c.COLUMN_NAME.EndsWith("Id"))
                                             .Where(c => !primaryKeys.Any(k => k.COLUMN_NAME == c.COLUMN_NAME))
                                             .Select(c => c.COLUMN_NAME).ToList();

                contexts.Add(new TableColumnContext
                {
                    TableNamePlural   = table.Name,
                    TableNameSingular = table.Name.TrimEnd(new char[] { 's' }),
                    SchemaName        = table.Schema,
                    IdentityColumns   = columns.Where(c => c.IsIdentity).Select(c => c.COLUMN_NAME).ToList(),
                    PrimaryKeys       = primaryKeys,
                    AllIds            = allIdColumns
                });
            }

            UnityCache.Resolve <IDalEngine>().GenerateCodeFile(config.TemplatesPath, "DbContext.cshtml", config.AccessorsPath, config.DbContextClassName, contexts);
        }
Beispiel #20
0
        public FaustMigrationScript[] GetReleaseMigrationScripts(DirectoryInfo release, UserContext userContext)
        {
            Logger.Log(string.Format("FaustEngine.GetReleaseMigrationScripts:  Getting migrationscripts for release {0}.", release.Name), TraceEventType.Verbose);

            IEnumerable <FileInfo> files = release.EnumerateFiles().Where(file => file.Extension == ".sql");

            return(files.Select(file => new FaustMigrationScript
            {
                ReleaseNumber = int.Parse(file.Directory.Name),
                ScriptName = file.Name,
                FilePath = file.FullName,
                Successful = null,
                Commands = GetSqlCommands(file),
            })
                   .Where(script => UnityCache.Resolve <IFaustMigrationsHistoryAccessor>()
                          .FindMany(new FaustMigrationHistory
            {
                ReleaseNumber = script.ReleaseNumber,
                ScriptName = script.ScriptName,
                Committed = true,
            }, userContext).Length == 0)
                   .OrderBy(s => GetScriptOrdinal(s.ScriptName))
                   .ToArray());
        }
Beispiel #21
0
        public void RunMigration(string databaseName)
        {
            Logger.Log(string.Format("FaustManager.RunMigration:  Running Migrations for database {0}.", databaseName), TraceEventType.Verbose);
            Console.WriteLine("##teamcity[message text='FAUSTing Migrations']");

            UserContext userContext = UserContext.GetUserContext(databaseName);

            UnityCache.Resolve <IFaustMigrationsHistoryAccessor>().Initialize(userContext);

            List <DirectoryInfo> releaseDirs = Directory.GetDirectories(ConfigurationManager.AppSettings["MigrationsDirectory"] + databaseName)
                                               .Select(dir => new DirectoryInfo(dir))
                                               .Where(dir => int.Parse(dir.Name) > 0)
                                               .OrderBy(dir => int.Parse(dir.Name))
                                               .ToList();

            if (ConfigurationManager.AppSettings["RunDebugMigrations"] == "true")
            {
                List <DirectoryInfo> holdingDirs = Directory.GetDirectories(ConfigurationManager.AppSettings["MigrationsDirectory"] + databaseName)
                                                   .Select(dir => new DirectoryInfo(dir))
                                                   .Where(dir => int.Parse(dir.Name) < 0)
                                                   .OrderByDescending(dir => int.Parse(dir.Name))
                                                   .ToList();
                holdingDirs.ForEach(d => releaseDirs.Add(d));

                UnityCache.Resolve <IFaustMigrationsHistoryAccessor>().DeleteDebugEntries(userContext);
            }

            foreach (DirectoryInfo release in releaseDirs)
            {
                FaustMigrationScript[] scripts = UnityCache.Resolve <IFaustEngine>().GetReleaseMigrationScripts(release, userContext);

                List <FaustMigrationHistory> migrationHistories = new List <FaustMigrationHistory>();

                TransactionScopeOption scopeOption = TransactionScopeOption.Required;

                if (release.EnumerateFiles().Any(file => file.Name == "no.transaction"))
                {
                    scopeOption = TransactionScopeOption.Suppress;
                }
                TimeSpan desiredTimeout = TimeSpan.FromSeconds(int.Parse(ConfigurationManager.AppSettings["DefaultCommandTimeoutSecondsOverride"]));

                Settings.OverrideTransactionManagerMaximumTimeout(desiredTimeout);
                using (TransactionScope releaseScope = new TransactionScope(scopeOption, new TransactionOptions {
                    IsolationLevel = IsolationLevel.ReadCommitted
                }))
                {
                    foreach (FaustMigrationScript script in scripts)
                    {
                        FaustMigrationHistory migrationHistory = UnityCache.Resolve <IFaustEngine>().RunMigrationScript(script, userContext);

                        migrationHistories.Add(migrationHistory);

                        if (!migrationHistory.Successful ?? false)
                        {
                            releaseScope.Dispose();
                            migrationHistories.ForEach(m => m.Committed = false);
                            Console.WriteLine(string.Format("##teamcity[message text='{0}' errorDetails='' status='ERROR']", migrationHistory.Log));
                            Console.WriteLine("##teamcity[buildProblem description='FAUST Failed.  See build log for details.']");
                            Logger.Log(string.Format("FaustManager.RunMigration: {0}", migrationHistory.Log), TraceEventType.Error);
                            break;
                        }
                    }

                    if (Transaction.Current != null)
                    {
                        releaseScope.Complete();
                        Console.WriteLine("##teamcity[message text='FAUSTing completed without errors.']");
                    }

                    UnityCache.Resolve <IFaustEngine>().SaveMigrationsHistory(migrationHistories.ToArray(), userContext);
                }
            }
        }
Beispiel #22
0
 public ICollection <Attendee> GetAllAttendees(UserContext uc)
 {
     return(UnityCache.ResolveDefault <IRegistrationAccessor>().GetAllAttendees(uc));
 }
        ICollection <Registration> IRegistrationManager.ProcessRegistration(UserContext userContext, ICollection <Attendee> attendees)
        {
            ICollection <Attendee> CheckedAttendees = UnityCache.ResolveDefault <IRegistrationEngine>().ProcessAttendees(userContext, attendees);

            return(UnityCache.ResolveDefault <IRegistrationAccessor>().AddRegistration(userContext, CheckedAttendees));
        }