Beispiel #1
0
        /// <summary>
        /// Resets the database by using the specified path to a database archive file.
        /// </summary>
        /// <param name="archivePath">The archive path that contains the MDF and LDF files.</param>
        public static void ResetDatabase(string archivePath)
        {
            try
            {
                var cs  = ConfigurationManager.ConnectionStrings["RockContext"].ConnectionString;
                var csb = new SqlConnectionStringBuilder(cs);

                //
                // We need to connect to the master database, but track the target database
                // for use later.
                //
                var dbName = csb.InitialCatalog;
                csb.InitialCatalog = "master";

                //
                // If this is a URL, download it.
                //
                if (archivePath.ToUpper().StartsWith("HTTP"))
                {
                    archivePath = DownloadUrl(archivePath);
                }

                using (var archive = new ZipArchive(File.Open(archivePath, FileMode.Open)))
                {
                    using (var connection = new SqlConnection(csb.ConnectionString))
                    {
                        connection.Open();

                        //
                        // Check if the database already exists as if something went horribly wrong
                        // then it may not have been deleted.
                        //
                        using (var cmd = connection.CreateCommand())
                        {
                            cmd.CommandText = "SELECT COUNT(*) FROM [sysdatabases] WHERE [name] = @dbName";
                            cmd.Parameters.AddWithValue("dbName", dbName);

                            if (( int )cmd.ExecuteScalar() != 0)
                            {
                                DeleteDatabase(connection, dbName);
                            }
                        }

                        CreateDatabase(connection, dbName, archive);
                    }
                }

                RockCache.ClearAllCachedItems();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #2
0
        public IActionResult btnClearCache_Click()
        {
            var msgs = RockCache.ClearAllCachedItems();

            // Flush today's Check-in Codes
            Rock.Model.AttendanceCodeService.FlushTodaysCodes();

#if false
            string webAppPath = Server.MapPath( "~" );

            // Check for any unregistered entity types, field types, and block types
            EntityTypeService.RegisterEntityTypes( webAppPath );
            FieldTypeService.RegisterFieldTypes( webAppPath );
            BlockTypeService.RegisterBlockTypes( webAppPath, Page, false );
            msgs.Add( "EntityTypes, FieldTypes, BlockTypes have been re-registered" );

            // Delete all cached files
            try
            {
                var dirInfo = new DirectoryInfo( Path.Combine( webAppPath, "App_Data/Cache" ) );
                foreach ( var childDir in dirInfo.GetDirectories() )
                {
                    childDir.Delete( true );
                }
                foreach ( var file in dirInfo.GetFiles().Where( f => f.Name != ".gitignore" ) )
                {
                    file.Delete();
                }
                msgs.Add( "Cached files have been deleted" );
            }
            catch ( Exception ex )
            {
                return new OkObjectResult( new {
                    Error = true,
                    Messages = new [] { $"The following error occurred when attempting to delete cahced files: {ex.Message}"
                } );
            }
#endif

            return new OkObjectResult( new {
                Error = false,
                Messages = msgs
            } );
        }

        #endregion
    }
Beispiel #3
0
        /// <summary>
        /// Handles the Click event of btnClearCache and clears the selected cache type.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnClearCache_Click(object sender, EventArgs e)
        {
            List <string> result = new List <string>();

            if (ddlCacheTypes.SelectedValue == "all")
            {
                result = RockCache.ClearAllCachedItems();
            }
            else
            {
                result.Add(RockCache.ClearCachedItemsForType(ddlCacheTypes.SelectedValue));
            }

            PopulateCacheStatistics();

            DisplayNotification(nbMessage, "All cached items have been cleared.", NotificationBoxType.Success);
        }
        public override void Up()
        {
            // Make sure this is unique
            if (DefinedTypeCache.Get(new Guid("0913F7A9-A2BF-479C-96EC-6CDB56310A83")) == null)
            {
                RockMigrationHelper.AddDefinedType("Global", "Hospitals", "Hospital List", "0913F7A9-A2BF-479C-96EC-6CDB56310A83", @"");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "City", "Qualifier2", "", 0, "", "CEDC60C1-0F9E-4FE2-BE62-41716813C968");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Notes", "Qualifier8", "", 0, "", "C47A879E-F737-4156-A1FF-B7C465FDB9BC");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Phone", "Qualifier5", "", 0, "", "A4E41679-2CE6-479F-84D4-6821B25E3648");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Speed Dial", "Qualifier6", "", 0, "", "D97EC9DE-5D6A-42FD-B4CE-0516FD5455F6");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "State", "Qualifier3", "", 0, "", "239E507C-7C1B-4B4D-84D4-33C368843F04");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Street Address", "Qualifier1", "", 0, "", "73AC0DCE-CE90-4835-AAE7-E98B08F52E9C");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Zip", "Qualifier4", "", 0, "", "46A83E00-D530-48AD-B935-52C015DCA901");
                RockMigrationHelper.AddDefinedValue("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "Sample Hospital", "", "0997ACB6-A4B4-4766-B573-3C44D14DF342", false);
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "239E507C-7C1B-4B4D-84D4-33C368843F04", @"KY");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "46A83E00-D530-48AD-B935-52C015DCA901", @"40023");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "73AC0DCE-CE90-4835-AAE7-E98B08F52E9C", @"1 Main St");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "A4E41679-2CE6-479F-84D4-6821B25E3648", @"(502) 111-1111");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "C47A879E-F737-4156-A1FF-B7C465FDB9BC", @"");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "CEDC60C1-0F9E-4FE2-BE62-41716813C968", @"Louisville");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "D97EC9DE-5D6A-42FD-B4CE-0516FD5455F6", @"");
            }

            // Make sure this is unique
            if (DefinedTypeCache.Get(new Guid("4573E600-4E00-4BE9-BA92-D17093C735D6")) == null)
            {
                RockMigrationHelper.AddDefinedType("Global", "Nursing Homes", "Nursing Home List", "4573E600-4E00-4BE9-BA92-D17093C735D6", @"");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "City", "Qualifier2", "", 0, "", "CEDC60C1-0F9E-4FE2-BE62-41716813C969");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Notes", "Qualifier8", "", 0, "", "C47A879E-F737-4156-A1FF-B7C465FDB9BD");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Phone", "Qualifier5", "", 0, "", "A4E41679-2CE6-479F-84D4-6821B25E3649");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Pastoral Minister", "Qualifier6", "", 0, "", "D97EC9DE-5D6A-42FD-B4CE-0516FD5455F7");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "State", "Qualifier3", "", 0, "", "239E507C-7C1B-4B4D-84D4-33C368843F05");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Street Address", "Qualifier1", "", 0, "", "73AC0DCE-CE90-4835-AAE7-E98B08F52E9D");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Zip", "Qualifier4", "", 0, "", "46A83E00-D530-48AD-B935-52C015DCA902");
                RockMigrationHelper.AddDefinedValue("4573E600-4E00-4BE9-BA92-D17093C735D6", "Sample Nursing Home", "", "0997ACB6-A4B4-4766-B573-3C44D14DF343", false);
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "239E507C-7C1B-4B4D-84D4-33C368843F05", @"KY");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "46A83E00-D530-48AD-B935-52C015DCA902", @"40023");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "73AC0DCE-CE90-4835-AAE7-E98B08F52E9D", @"2 Main St");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "A4E41679-2CE6-479F-84D4-6821B25E3649", @"(502) 111-1111");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "C47A879E-F737-4156-A1FF-B7C465FDB9BD", @"");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "CEDC60C1-0F9E-4FE2-BE62-41716813C969", @"Louisville");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "D97EC9DE-5D6A-42FD-B4CE-0516FD5455F7", @"John Adams");
            }
            // Make sure to clear the Rock Cache so the defined type above will be there
            RockCache.ClearAllCachedItems();
        }
Beispiel #5
0
        /// <summary>
        /// Used to manually flush the attribute cache.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnClearCache_Click(object sender, EventArgs e)
        {
            var msgs = RockCache.ClearAllCachedItems();

            // Flush today's Check-in Codes
            Rock.Model.AttendanceCodeService.FlushTodaysCodes();

            string webAppPath = Server.MapPath("~");

            // Check for any unregistered entity types, field types, and block types
            EntityTypeService.RegisterEntityTypes();
            FieldTypeService.RegisterFieldTypes();

            BlockTypeService.FlushRegistrationCache();
            BlockTypeService.RegisterBlockTypes(webAppPath, Page, false);

            msgs.Add("EntityTypes, FieldTypes, BlockTypes have been re-registered");

            // Delete all cached files
            try
            {
                var dirInfo = new DirectoryInfo(Path.Combine(webAppPath, "App_Data/Cache"));
                foreach (var childDir in dirInfo.GetDirectories())
                {
                    childDir.Delete(true);
                }
                foreach (var file in dirInfo.GetFiles().Where(f => f.Name != ".gitignore"))
                {
                    file.Delete();
                }
                msgs.Add("Cached files have been deleted");
            }
            catch (Exception ex)
            {
                nbMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Warning;
                nbMessage.Visible             = true;
                nbMessage.Text = "The following error occurred when attempting to delete cached files: " + ex.Message;
                return;
            }

            nbMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Success;
            nbMessage.Visible             = true;
            nbMessage.Title = "Clear Cache";
            nbMessage.Text  = string.Format("<p>{0}</p>", msgs.AsDelimited("<br />"));
        }
Beispiel #6
0
        /// <summary>
        /// Resets the database by using the specified path to a database archive file.
        /// </summary>
        /// <param name="archivePath">The archive path that contains the MDF and LDF files.</param>
        public static void ResetDatabase(string archivePath)
        {
            var cs  = ConfigurationManager.ConnectionStrings["RockContext"].ConnectionString;
            var csb = new SqlConnectionStringBuilder(cs);

            //
            // We need to connect to the master database, but track the target database
            // for use later.
            //
            var dbName = csb.InitialCatalog;

            csb.InitialCatalog = "master";

            //
            // If this is a URL, download it.
            //
            if (archivePath.ToUpper().StartsWith("HTTP"))
            {
                archivePath = DownloadUrl(archivePath);
            }

            using (var archive = new ZipArchive(File.Open(archivePath, FileMode.Open)))
            {
                using (var connection = new SqlConnection(csb.ConnectionString))
                {
                    connection.Open();

                    //
                    // If the database exists, that means something probably went
                    // horribly wrong on a previous run so we need to manually
                    // delete the database.
                    if (DoesDatabaseExist(dbName, connection))
                    {
                        DeleteDatabase(connection, dbName);
                    }

                    RestoreDatabase(connection, dbName, archive);
                }
            }

            RockCache.ClearAllCachedItems();
        }
        /// <summary>
        /// Runs various startup operations that need to run prior to RockWeb startup
        /// </summary>
        internal static void RunApplicationStartup()
        {
            // Indicate to always log to file during initialization.
            ExceptionLogService.AlwaysLogToFile = true;

            StartDateTime = RockDateTime.Now;

            RockApplicationStartupHelper.LogStartupMessage("Application Starting");

            var runMigrationFileInfo = new FileInfo(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data\\Run.Migration"));

            bool hasPendingEFMigrations = runMigrationFileInfo.Exists || HasPendingEFMigrations();

            bool ranEFMigrations = MigrateDatabase(hasPendingEFMigrations);

            ShowDebugTimingMessage("EF Migrations");

            // Now that EF Migrations have gotten the Schema in sync with our Models,
            // get the RockContext initialized (which can take several seconds)
            // This will help reduce the chances of multiple instances RockWeb causing problems,
            // like creating duplicate attributes, or running the same migration in parallel
            using (var rockContext = new RockContext())
            {
                new AttributeService(rockContext).Get(0);
                ShowDebugTimingMessage("Initialize RockContext");
            }

            if (runMigrationFileInfo.Exists)
            {
                // fileInfo.Delete() won't do anything if the file doesn't exist (it doesn't throw an exception if it is not there )
                // but do the fileInfo.Exists to make this logic more readable
                runMigrationFileInfo.Delete();
            }

            // Run any plugin migrations
            bool anyPluginMigrations = MigratePlugins();

            ShowDebugTimingMessage("Plugin Migrations");

            /* 2020-05-20 MDP
             * Plugins use Direct SQL to update data,
             * or other things could have done data updates
             * So, just in case, clear the cache (which could be Redis) since anything that is in there could be stale
             */

            RockCache.ClearAllCachedItems(false);

            using (var rockContext = new RockContext())
            {
                LoadCacheObjects(rockContext);

                ShowDebugTimingMessage("Load Cache Objects");

                UpdateAttributesFromRockConfig(rockContext);
            }

            if (ranEFMigrations || anyPluginMigrations)
            {
                // If any migrations ran (version was likely updated)
                SendVersionUpdateNotifications();
                ShowDebugTimingMessage("Send Version Update Notifications");
            }

            RegisterHttpModules();

            // Get Lava set up
            InitializeLava();

            ShowDebugTimingMessage("Startup Components");

            // setup and launch the jobs infrastructure if running under IIS
            bool runJobsInContext = Convert.ToBoolean(ConfigurationManager.AppSettings["RunJobsInIISContext"]);

            if (runJobsInContext)
            {
                StartJobScheduler();
                ShowDebugTimingMessage("Start Job Scheduler");
            }
        }
        private void ProcessInstall(PurchaseResponse purchaseResponse)
        {
            var currentlyInstalledPackageVersion = GetCurrentlyInstalledPackageVersion(purchaseResponse.PackageName);

            if (purchaseResponse.PackageInstallSteps != null)
            {
                RockSemanticVersion rockVersion = RockSemanticVersion.Parse(VersionInfo.GetRockSemanticVersionNumber());

                var packageInstallSteps = purchaseResponse.PackageInstallSteps
                                          .Where(s => s.RequiredRockSemanticVersion <= rockVersion)
                                          .Where(s => s.VersionId > currentlyInstalledPackageVersion);

                foreach (var installStep in packageInstallSteps)
                {
                    string appRoot            = Server.MapPath("~/");
                    string rockShopWorkingDir = appRoot + "App_Data/RockShop";
                    string packageDirectory   = string.Format("{0}/{1} - {2}", rockShopWorkingDir, purchaseResponse.PackageId, purchaseResponse.PackageName);
                    string sourceFile         = installStep.InstallPackageUrl;
                    string destinationFile    = string.Format("{0}/{1} - {2}.plugin", packageDirectory, installStep.VersionId, installStep.VersionLabel);

                    // check that the RockShop directory exists
                    if (!Directory.Exists(rockShopWorkingDir))
                    {
                        Directory.CreateDirectory(rockShopWorkingDir);
                    }

                    // create package directory
                    if (!Directory.Exists(packageDirectory))
                    {
                        Directory.CreateDirectory(packageDirectory);
                    }

                    // download file
                    try
                    {
                        WebClient wc = new WebClient();
                        wc.DownloadFile(sourceFile, destinationFile);
                    }
                    catch (Exception ex)
                    {
                        CleanUpPackage(destinationFile);
                        lMessages.Text = string.Format("<div class='alert alert-warning margin-t-md'><strong>Error Downloading Package</strong> An error occurred while downloading package from the store. Please try again later. <br><em>Error: {0}</em></div>", ex.Message);
                        return;
                    }

                    // process zip folder
                    try
                    {
                        using (ZipArchive packageZip = ZipFile.OpenRead(destinationFile))
                        {
                            // unzip content folder and process xdts
                            foreach (ZipArchiveEntry entry in packageZip.Entries.Where(e => e.FullName.StartsWith("content/", StringComparison.OrdinalIgnoreCase)))
                            {
                                if (entry.FullName.EndsWith(_xdtExtension, StringComparison.OrdinalIgnoreCase))
                                {
                                    // process xdt
                                    string filename            = entry.FullName.ReplaceFirstOccurrence("content/", string.Empty);
                                    string transformTargetFile = appRoot + filename.Substring(0, filename.LastIndexOf(_xdtExtension));

                                    // process transform
                                    using (XmlTransformableDocument document = new XmlTransformableDocument())
                                    {
                                        document.PreserveWhitespace = true;
                                        document.Load(transformTargetFile);

                                        using (XmlTransformation transform = new XmlTransformation(entry.Open(), null))
                                        {
                                            if (transform.Apply(document))
                                            {
                                                document.Save(transformTargetFile);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    // process all content files
                                    string fullpath  = Path.Combine(appRoot, entry.FullName.ReplaceFirstOccurrence("content/", string.Empty));
                                    string directory = Path.GetDirectoryName(fullpath).ReplaceFirstOccurrence("content/", string.Empty);

                                    // if entry is a directory ignore it
                                    if (entry.Length != 0)
                                    {
                                        if (!Directory.Exists(directory))
                                        {
                                            Directory.CreateDirectory(directory);
                                        }

                                        entry.ExtractToFile(fullpath, true);
                                    }
                                }
                            }

                            // process install.sql
                            try
                            {
                                var sqlInstallEntry = packageZip.Entries.Where(e => e.FullName == "install/run.sql").FirstOrDefault();
                                if (sqlInstallEntry != null)
                                {
                                    string sqlScript = System.Text.Encoding.Default.GetString(sqlInstallEntry.Open().ReadBytesToEnd());

                                    if (!string.IsNullOrWhiteSpace(sqlScript))
                                    {
                                        using (var context = new RockContext())
                                        {
                                            context.Database.ExecuteSqlCommand(sqlScript);
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                lMessages.Text = string.Format("<div class='alert alert-warning margin-t-md'><strong>Error Updating Database</strong> An error occurred while updating the database. <br><em>Error: {0}</em></div>", ex.Message);
                                return;
                            }

                            // process deletefile.lst
                            try
                            {
                                var deleteListEntry = packageZip.Entries.Where(e => e.FullName == "install/deletefile.lst").FirstOrDefault();
                                if (deleteListEntry != null)
                                {
                                    string deleteList = System.Text.Encoding.Default.GetString(deleteListEntry.Open().ReadBytesToEnd());

                                    string[] itemsToDelete = deleteList.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

                                    foreach (string deleteItem in itemsToDelete)
                                    {
                                        if (!string.IsNullOrWhiteSpace(deleteItem))
                                        {
                                            string deleteItemFullPath = appRoot + deleteItem;

                                            if (Directory.Exists(deleteItemFullPath))
                                            {
                                                Directory.Delete(deleteItemFullPath, true);
                                            }

                                            if (File.Exists(deleteItemFullPath))
                                            {
                                                File.Delete(deleteItemFullPath);
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                lMessages.Text = string.Format("<div class='alert alert-warning margin-t-md'><strong>Error Modifying Files</strong> An error occurred while modifying files. <br><em>Error: {0}</em></div>", ex.Message);
                                return;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        lMessages.Text = string.Format("<div class='alert alert-warning margin-t-md'><strong>Error Extracting Package</strong> An error occurred while extracting the contents of the package. <br><em>Error: {0}</em></div>", ex.Message);
                        return;
                    }

                    // update package install json file
                    InstalledPackageService.SaveInstall(purchaseResponse.PackageId, purchaseResponse.PackageName, installStep.VersionId, installStep.VersionLabel, purchaseResponse.VendorId, purchaseResponse.VendorName, purchaseResponse.InstalledBy);

                    // Clear all cached items
                    RockCache.ClearAllCachedItems();

                    // Hide store login on success
                    lInstallMessage.Visible = false;
                    txtUsername.Visible     = false;
                    txtPassword.Visible     = false;
                    cbAgreeToTerms.Visible  = false;
                    btnInstall.Visible      = false;
                    // show result message
                    lMessages.Text = string.Format("<div class='alert alert-success margin-t-md'><strong>Package Installed</strong><p>{0}</p>", installStep.PostInstallInstructions);
                }
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning margin-t-md'><strong>Error</strong> Install package was not valid. Please try again later.";
            }
        }
Beispiel #9
0
        /// <summary>
        /// Runs various startup operations that need to run prior to RockWeb startup
        /// </summary>
        internal static void RunApplicationStartup()
        {
            // Indicate to always log to file during initialization.
            ExceptionLogService.AlwaysLogToFile = true;

            InitializeRockOrgTimeZone();

            StartDateTime = RockDateTime.Now;
            RockInstanceConfig.SetApplicationStartedDateTime(StartDateTime);

            // If there are Task.Runs that don't handle their exceptions, this will catch those
            // so that we can log it. Note that this event won't fire until the Task is disposed.
            // In most cases, that'll be when GC is collected. So it won't happen immediately.
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

            LogStartupMessage("Application Starting");

            var runMigrationFileInfo = new FileInfo(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data\\Run.Migration"));

            bool hasPendingEFMigrations = runMigrationFileInfo.Exists || HasPendingEFMigrations();

            bool ranEFMigrations = MigrateDatabase(hasPendingEFMigrations);

            ShowDebugTimingMessage("EF Migrations");

            ConfigureEntitySaveHooks();

            ShowDebugTimingMessage("Configure Entity SaveHooks");

            // Now that EF Migrations have gotten the Schema in sync with our Models,
            // get the RockContext initialized (which can take several seconds)
            // This will help reduce the chances of multiple instances RockWeb causing problems,
            // like creating duplicate attributes, or running the same migration in parallel
            using (var rockContext = new RockContext())
            {
                new AttributeService(rockContext).Get(0);
                ShowDebugTimingMessage("Initialize RockContext");
            }

            // Configure the values for RockDateTime.
            RockDateTime.FirstDayOfWeek = Rock.Web.SystemSettings.StartDayOfWeek;
            InitializeRockGraduationDate();

            if (runMigrationFileInfo.Exists)
            {
                // fileInfo.Delete() won't do anything if the file doesn't exist (it doesn't throw an exception if it is not there )
                // but do the fileInfo.Exists to make this logic more readable
                runMigrationFileInfo.Delete();
            }

            // Run any plugin migrations
            bool anyPluginMigrations = MigratePlugins();

            ShowDebugTimingMessage("Plugin Migrations");

            /* 2020-05-20 MDP
             * Plugins use Direct SQL to update data,
             * or other things could have done data updates
             * So, just in case, clear the cache (which could be Redis) since anything that is in there could be stale
             */

            RockCache.ClearAllCachedItems(false);

            using (var rockContext = new RockContext())
            {
                LoadCacheObjects(rockContext);

                ShowDebugTimingMessage("Load Cache Objects");

                UpdateAttributesFromRockConfig(rockContext);
            }

            if (ranEFMigrations || anyPluginMigrations)
            {
                // If any migrations ran (version was likely updated)
                SendVersionUpdateNotifications();
                ShowDebugTimingMessage("Send Version Update Notifications");
            }

            // Start the message bus
            RockMessageBus.StartAsync().Wait();
            var busTransportName = RockMessageBus.GetTransportName();

            if (busTransportName.IsNullOrWhiteSpace())
            {
                ShowDebugTimingMessage("Message Bus");
            }
            else
            {
                ShowDebugTimingMessage($"Message Bus ({busTransportName})");
            }

            // Start stage 1 of the web farm
            RockWebFarm.StartStage1();
            ShowDebugTimingMessage("Web Farm (stage 1)");

            RegisterHttpModules();
            ShowDebugTimingMessage("Register HTTP Modules");

            // Initialize the Lava engine.
            InitializeLava();
            ShowDebugTimingMessage($"Initialize Lava Engine ({LavaService.CurrentEngineName})");

            // setup and launch the jobs infrastructure if running under IIS
            bool runJobsInContext = Convert.ToBoolean(ConfigurationManager.AppSettings["RunJobsInIISContext"]);

            if (runJobsInContext)
            {
                StartJobScheduler();
                ShowDebugTimingMessage("Start Job Scheduler");
            }

            // Start stage 2 of the web farm
            RockWebFarm.StartStage2();
            ShowDebugTimingMessage("Web Farm (stage 2)");
        }
Beispiel #10
0
 public void TestInitialize()
 {
     RockCache.ClearAllCachedItems();
 }
        /// <summary>
        /// Processes the package.
        /// </summary>
        /// <param name="destinationFile">The destination file.</param>
        private void ProcessPackage(string destinationFile)
        {
            string appRoot = Server.MapPath("~/");

            // process zip folder
            try
            {
                using (ZipArchive packageZip = ZipFile.OpenRead(destinationFile))
                {
                    // unzip content folder and process xdts
                    foreach (ZipArchiveEntry entry in packageZip.Entries.Where(e => e.FullName.StartsWith("content/", StringComparison.OrdinalIgnoreCase)))
                    {
                        if (entry.FullName.EndsWith(_xdtExtension, StringComparison.OrdinalIgnoreCase))
                        {
                            // process xdt
                            string filename            = entry.FullName.Replace("content/", "");
                            string transformTargetFile = appRoot + filename.Substring(0, filename.LastIndexOf(_xdtExtension));

                            // process transform
                            using (XmlTransformableDocument document = new XmlTransformableDocument())
                            {
                                document.PreserveWhitespace = true;
                                document.Load(transformTargetFile);

                                using (XmlTransformation transform = new XmlTransformation(entry.Open(), null))
                                {
                                    if (transform.Apply(document))
                                    {
                                        document.Save(transformTargetFile);
                                    }
                                }
                            }
                        }
                        else
                        {
                            // process all content files
                            string fullpath  = Path.Combine(appRoot, entry.FullName.Replace("content/", ""));
                            string directory = Path.GetDirectoryName(fullpath).Replace("content/", "");

                            // if entry is a directory ignore it
                            if (entry.Length != 0)
                            {
                                if (!Directory.Exists(directory))
                                {
                                    Directory.CreateDirectory(directory);
                                }

                                entry.ExtractToFile(fullpath, true);
                            }
                        }
                    }

                    // process install.sql
                    try
                    {
                        var sqlInstallEntry = packageZip.Entries.Where(e => e.FullName == "install/run.sql").FirstOrDefault();
                        if (sqlInstallEntry != null)
                        {
                            string sqlScript = System.Text.Encoding.Default.GetString(sqlInstallEntry.Open().ReadBytesToEnd());

                            if (!string.IsNullOrWhiteSpace(sqlScript))
                            {
                                using (var context = new RockContext())
                                {
                                    context.Database.ExecuteSqlCommand(sqlScript);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        nbWarning.Text = string.Format("<strong>Error Updating Database</strong> An error occurred while updating the database. <br><em>Error: {0}</em>", ex.Message);
                        return;
                    }

                    // process deletefile.lst
                    try
                    {
                        var deleteListEntry = packageZip.Entries.Where(e => e.FullName == "install/deletefile.lst").FirstOrDefault();
                        if (deleteListEntry != null)
                        {
                            string deleteList = System.Text.Encoding.Default.GetString(deleteListEntry.Open().ReadBytesToEnd());

                            string[] itemsToDelete = deleteList.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

                            foreach (string deleteItem in itemsToDelete)
                            {
                                if (!string.IsNullOrWhiteSpace(deleteItem))
                                {
                                    string deleteItemFullPath = appRoot + deleteItem;

                                    if (Directory.Exists(deleteItemFullPath))
                                    {
                                        Directory.Delete(deleteItemFullPath, true);
                                    }

                                    if (File.Exists(deleteItemFullPath))
                                    {
                                        File.Delete(deleteItemFullPath);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        nbWarning.Text = string.Format("<strong>Error Modifying Files</strong> An error occurred while modifying files. <br><em>Error: {0}</em>", ex.Message);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                nbWarning.Text = string.Format("<strong>Error Extracting Package</strong> An error occurred while extracting the contents of the package. <br><em>Error: {0}</em>", ex.Message);
                return;
            }

            // cleanup whether we could read the file or not
            File.Delete(destinationFile);

            // Clear all cached items
            RockCache.ClearAllCachedItems();

            // show result message
            nbWarning.Text = "<strong>Package Installed</strong>";
        }