예제 #1
0
        void Database.ExportToFile(string filePath)
        {
            Directory.CreateDirectory(dataPumpFolderPath);
            try {
                executeMethodWithDbExceptionHandling(
                    delegate {
                    try {
                        // We pass an enter keystroke as input in an attempt to kill the program if it gets stuck on a username prompt because of a bad logon string.
                        EwlStatics.RunProgram(
                            "expdp",
                            getLogonString() + " DIRECTORY=" + dataPumpOracleDirectoryName + " DUMPFILE=\"\"\"" + getDumpFileName() + "\"\"\" NOLOGFILE=y VERSION=12.1",
                            Environment.NewLine,
                            true);
                    }
                    catch (Exception e) {
                        throwUserCorrectableExceptionIfNecessary(e);
                        throw DataAccessMethods.CreateDbConnectionException(info, "exporting (to file)", e);
                    }
                });

                IoMethods.ExecuteWithTempFolder(
                    folderPath => {
                    IoMethods.CopyFile(getDumpFilePath(), EwlStatics.CombinePaths(folderPath, databaseFileDumpFileName));
                    File.WriteAllText(EwlStatics.CombinePaths(folderPath, databaseFileSchemaNameFileName), info.UserAndSchema);
                    ZipOps.ZipFolderAsFile(folderPath, filePath);
                });
            }
            finally {
                IoMethods.DeleteFile(getDumpFilePath());
            }
        }
        private void deleteAndReCreateFromFile(DBConnection cn, string filePath)
        {
            // NOTE: Instead of catching exceptions, figure out if the database exists by querying.
            try {
                // Gets rid of existing connections. This doesn't need to be executed against the master database, but it's convenient because it saves us from needing
                // a second database connection.
                executeLongRunningCommand(cn, "ALTER DATABASE " + info.Database + " SET SINGLE_USER WITH ROLLBACK IMMEDIATE");

                executeLongRunningCommand(cn, "DROP DATABASE " + info.Database);
            }
            catch (Exception) {
                // The database did not exist. That's fine.
            }

            Directory.CreateDirectory(sqlServerFilesFolderPath);

            try {
                IoMethods.CopyFile(filePath, backupFilePath);
                try {
                    // WITH MOVE is required so that multiple instances of the same system's database (RsisDev and RsisTesting, for example) can exist on the same machine
                    // without their physical files colliding.
                    executeLongRunningCommand(
                        cn,
                        "RESTORE DATABASE " + info.Database + " FROM DISK = '" + backupFilePath + "'" + " WITH MOVE '" + dataLogicalFileName + "' TO '" +
                        EwlStatics.CombinePaths(sqlServerFilesFolderPath, info.Database + ".mdf") + "', MOVE '" + logLogicalFileName + "' TO '" +
                        EwlStatics.CombinePaths(sqlServerFilesFolderPath, info.Database + ".ldf") + "'");
                }
                catch (Exception e) {
                    throw new UserCorrectableException("Failed to create database from file. Please try the operation again after obtaining a new database file.", e);
                }
            }
            finally {
                IoMethods.DeleteFile(backupFilePath);
            }
        }
예제 #3
0
        private void copyInWebProjectFiles(Installation installation, WebProject webProject)
        {
            var webProjectFilesFolderPath = StandardLibraryMethods.CombinePaths(AppTools.InstallationPath, AppStatics.WebProjectFilesFolderName);
            var webProjectPath            = StandardLibraryMethods.CombinePaths(installation.GeneralLogic.Path, webProject.name);

            // Copy Ewf folder and customize namespaces in .aspx, .ascx, .master, and .cs files.
            var webProjectEwfFolderPath = StandardLibraryMethods.CombinePaths(webProjectPath, StaticFileHandler.EwfFolderName);

            IoMethods.DeleteFolder(webProjectEwfFolderPath);
            IoMethods.CopyFolder(StandardLibraryMethods.CombinePaths(webProjectFilesFolderPath, StaticFileHandler.EwfFolderName), webProjectEwfFolderPath, false);
            IoMethods.RecursivelyRemoveReadOnlyAttributeFromItem(webProjectEwfFolderPath);
            var matchingFiles = new List <string>();

            matchingFiles.AddRange(Directory.GetFiles(webProjectEwfFolderPath, "*.aspx", SearchOption.AllDirectories));
            matchingFiles.AddRange(Directory.GetFiles(webProjectEwfFolderPath, "*.ascx", SearchOption.AllDirectories));
            matchingFiles.AddRange(Directory.GetFiles(webProjectEwfFolderPath, "*.master", SearchOption.AllDirectories));
            matchingFiles.AddRange(Directory.GetFiles(webProjectEwfFolderPath, "*.cs", SearchOption.AllDirectories));
            foreach (var filePath in matchingFiles)
            {
                File.WriteAllText(filePath, customizeNamespace(File.ReadAllText(filePath), webProject));
            }

            IoMethods.CopyFile(
                StandardLibraryMethods.CombinePaths(webProjectFilesFolderPath, AppStatics.StandardLibraryFilesFileName),
                StandardLibraryMethods.CombinePaths(webProjectPath, AppStatics.StandardLibraryFilesFileName));
            IoMethods.RecursivelyRemoveReadOnlyAttributeFromItem(StandardLibraryMethods.CombinePaths(webProjectPath, AppStatics.StandardLibraryFilesFileName));
        }
예제 #4
0
        internal static byte[] CreateEwlNuGetPackage(DevelopmentInstallation installation, bool useDebugAssembly, string outputFolderPath, bool?prerelease)
        {
            var localExportDateAndTime = prerelease.HasValue ? null as DateTime? : DateTime.Now;

            IoMethods.ExecuteWithTempFolder(folderPath => {
                var ewlOutputFolderPath = StandardLibraryMethods.CombinePaths(installation.GeneralLogic.Path,
                                                                              "Standard Library",
                                                                              StandardLibraryMethods.GetProjectOutputFolderPath(useDebugAssembly));
                var libFolderPath = StandardLibraryMethods.CombinePaths(folderPath, @"lib\net451-full");
                foreach (var fileName in new[] { "dll", "pdb", "xml" }.Select(i => "EnterpriseWebLibrary." + i))
                {
                    IoMethods.CopyFile(StandardLibraryMethods.CombinePaths(ewlOutputFolderPath, fileName), StandardLibraryMethods.CombinePaths(libFolderPath, fileName));
                }

                IoMethods.CopyFile(StandardLibraryMethods.CombinePaths(installation.GeneralLogic.Path, @"Development Utility\Package Manager Console Commands.ps1"),
                                   StandardLibraryMethods.CombinePaths(folderPath, @"tools\init.ps1"));

                var webSitePath = StandardLibraryMethods.CombinePaths(installation.GeneralLogic.Path, "Web Site");
                var webProjectFilesFolderPath = StandardLibraryMethods.CombinePaths(folderPath, AppStatics.WebProjectFilesFolderName);
                IoMethods.CopyFolder(StandardLibraryMethods.CombinePaths(webSitePath, AppStatics.EwfFolderName),
                                     StandardLibraryMethods.CombinePaths(webProjectFilesFolderPath, AppStatics.EwfFolderName),
                                     false);
                IoMethods.CopyFile(StandardLibraryMethods.CombinePaths(webSitePath, AppStatics.StandardLibraryFilesFileName),
                                   StandardLibraryMethods.CombinePaths(webProjectFilesFolderPath, AppStatics.StandardLibraryFilesFileName));

                const string duProjectAndFolderName = "Development Utility";
                IoMethods.CopyFolder(
                    StandardLibraryMethods.CombinePaths(installation.GeneralLogic.Path,
                                                        duProjectAndFolderName,
                                                        StandardLibraryMethods.GetProjectOutputFolderPath(useDebugAssembly)),
                    StandardLibraryMethods.CombinePaths(folderPath, duProjectAndFolderName),
                    false);
                packageGeneralFiles(installation, folderPath, false);
                IoMethods.CopyFolder(
                    StandardLibraryMethods.CombinePaths(installation.ExistingInstallationLogic.RuntimeConfiguration.ConfigurationFolderPath,
                                                        InstallationConfiguration.InstallationConfigurationFolderName,
                                                        InstallationConfiguration.InstallationsFolderName,
                                                        (!prerelease.HasValue || prerelease.Value ? "Testing" : "Live")),
                    StandardLibraryMethods.CombinePaths(folderPath,
                                                        InstallationConfiguration.ConfigurationFolderName,
                                                        InstallationConfiguration.InstallationConfigurationFolderName),
                    false);

                var manifestPath = StandardLibraryMethods.CombinePaths(folderPath, "Package.nuspec");
                using (var writer = IoMethods.GetTextWriterForWrite(manifestPath))
                    writeNuGetPackageManifest(installation, prerelease, localExportDateAndTime, writer);

                StatusStatics.SetStatus(StandardLibraryMethods.RunProgram(StandardLibraryMethods.CombinePaths(installation.GeneralLogic.Path, @"Solution Files\nuget"),
                                                                          "pack \"" + manifestPath + "\" -OutputDirectory \"" + outputFolderPath + "\"",
                                                                          "",
                                                                          true));
            });

            return
                (File.ReadAllBytes(StandardLibraryMethods.CombinePaths(outputFolderPath,
                                                                       EwlNuGetPackageSpecificationStatics.GetNuGetPackageFileName(installation.ExistingInstallationLogic.RuntimeConfiguration.SystemShortName,
                                                                                                                                   installation.CurrentMajorVersion,
                                                                                                                                   !prerelease.HasValue || prerelease.Value ? installation.NextBuildNumber as int? : null,
                                                                                                                                   localExportDateAndTime: localExportDateAndTime))));
        }
예제 #5
0
        private void copyInEwlFiles(DevelopmentInstallation installation)
        {
            if (installation is RecognizedDevelopmentInstallation recognizedInstallation)
            {
                recognizedInstallation.KnownSystemLogic.DownloadAsposeLicenses(installation.ExistingInstallationLogic.RuntimeConfiguration.ConfigurationFolderPath);
            }

            if (installation.DevelopmentInstallationLogic.SystemIsEwl)
            {
                foreach (var fileName in GlobalStatics.ConfigurationXsdFileNames)
                {
                    IoMethods.CopyFile(
                        EwlStatics.CombinePaths(installation.GeneralLogic.Path, AppStatics.CoreProjectName, "Configuration", fileName + FileExtensions.Xsd),
                        EwlStatics.CombinePaths(
                            InstallationFileStatics.GetGeneralFilesFolderPath(installation.GeneralLogic.Path, true),
                            InstallationFileStatics.FilesFolderName,
                            fileName + FileExtensions.Xsd));
                }
            }
            else
            {
                // If web projects exist for this installation, copy appropriate files into them.
                if (installation.DevelopmentInstallationLogic.DevelopmentConfiguration.webProjects != null)
                {
                    foreach (var webProject in installation.DevelopmentInstallationLogic.DevelopmentConfiguration.webProjects)
                    {
                        copyInWebProjectFiles(installation, webProject);
                    }
                }
            }
        }
        private void copyInEwlFiles(DevelopmentInstallation installation)
        {
            if (installation is RecognizedDevelopmentInstallation recognizedInstallation)
            {
                recognizedInstallation.KnownSystemLogic.DownloadAsposeLicenses(installation.ExistingInstallationLogic.RuntimeConfiguration.ConfigurationFolderPath);
            }

            if (installation.DevelopmentInstallationLogic.SystemIsEwl)
            {
                foreach (var fileName in GlobalStatics.ConfigurationXsdFileNames)
                {
                    IoMethods.CopyFile(
                        EwlStatics.CombinePaths(installation.GeneralLogic.Path, EwlStatics.CoreProjectName, "Configuration", fileName + FileExtensions.Xsd),
                        EwlStatics.CombinePaths(
                            InstallationFileStatics.GetGeneralFilesFolderPath(installation.GeneralLogic.Path, true),
                            InstallationFileStatics.FilesFolderName,
                            fileName + FileExtensions.Xsd));
                }
            }
            else
            {
                // If web projects exist for this installation, copy in web-framework static files.
                if (installation.DevelopmentInstallationLogic.DevelopmentConfiguration.webProjects != null)
                {
                    var webFrameworkStaticFilesFolderPath = EwlStatics.CombinePaths(
                        installation.GeneralLogic.Path,
                        InstallationFileStatics.WebFrameworkStaticFilesFolderName);
                    IoMethods.DeleteFolder(webFrameworkStaticFilesFolderPath);
                    IoMethods.CopyFolder(
                        EwlStatics.CombinePaths(ConfigurationStatics.InstallationPath, InstallationFileStatics.WebFrameworkStaticFilesFolderName),
                        webFrameworkStaticFilesFolderPath,
                        false);
                }
            }
        }
 void Database.ExportToFile(string filePath)
 {
     try {
         ExecuteDbMethod(cn => executeLongRunningCommand(cn, "BACKUP DATABASE " + info.Database + " TO DISK = '" + backupFilePath + "'"));
         IoMethods.CopyFile(backupFilePath, filePath);
     }
     finally {
         IoMethods.DeleteFile(backupFilePath);
     }
 }
예제 #8
0
        private void copyInWebProjectFiles(Installation installation, WebProject webProject)
        {
            var webProjectFilesFolderPath = EwlStatics.CombinePaths(ConfigurationStatics.InstallationPath, AppStatics.WebProjectFilesFolderName);
            var webProjectPath            = EwlStatics.CombinePaths(installation.GeneralLogic.Path, webProject.name);

            // Copy Ewf folder and customize namespaces in .aspx, .ascx, .master, and .cs files.
            var webProjectEwfFolderPath = EwlStatics.CombinePaths(webProjectPath, StaticFileHandler.EwfFolderName);

            IoMethods.DeleteFolder(webProjectEwfFolderPath);
            IoMethods.CopyFolder(EwlStatics.CombinePaths(webProjectFilesFolderPath, StaticFileHandler.EwfFolderName), webProjectEwfFolderPath, false);
            IoMethods.RecursivelyRemoveReadOnlyAttributeFromItem(webProjectEwfFolderPath);
            var matchingFiles = new List <string>();

            matchingFiles.AddRange(Directory.GetFiles(webProjectEwfFolderPath, "*.aspx", SearchOption.AllDirectories));
            matchingFiles.AddRange(Directory.GetFiles(webProjectEwfFolderPath, "*.ascx", SearchOption.AllDirectories));
            matchingFiles.AddRange(Directory.GetFiles(webProjectEwfFolderPath, "*.master", SearchOption.AllDirectories));
            matchingFiles.AddRange(Directory.GetFiles(webProjectEwfFolderPath, "*.cs", SearchOption.AllDirectories));
            foreach (var filePath in matchingFiles)
            {
                File.WriteAllText(filePath, customizeNamespace(File.ReadAllText(filePath), webProject));
            }

            IoMethods.CopyFile(
                EwlStatics.CombinePaths(webProjectFilesFolderPath, AppStatics.StandardLibraryFilesFileName),
                EwlStatics.CombinePaths(webProjectPath, AppStatics.StandardLibraryFilesFileName));
            IoMethods.RecursivelyRemoveReadOnlyAttributeFromItem(EwlStatics.CombinePaths(webProjectPath, AppStatics.StandardLibraryFilesFileName));

            // Add the Import element to the project file if it's not already present.
            var projectDocument = new XmlDocument {
                PreserveWhitespace = true
            };
            var projectDocumentPath = EwlStatics.CombinePaths(webProjectPath, "{0}.csproj".FormatWith(webProject.name));

            projectDocument.Load(projectDocumentPath);
            var          projectElement          = projectDocument["Project"];
            const string webProjectFilesFileName = "Standard Library Files.xml";
            var          namespaceManager        = new XmlNamespaceManager(projectDocument.NameTable);
            const string ns = "http://schemas.microsoft.com/developer/msbuild/2003";

            namespaceManager.AddNamespace("p", ns);
            if (projectElement.SelectSingleNode("p:Import[ @Project = \"{0}\" ]".FormatWith(webProjectFilesFileName), namespaceManager) == null)
            {
                var importElement = projectDocument.CreateElement("Import", ns);
                importElement.SetAttribute("Project", webProjectFilesFileName);
                projectElement.AppendChild(importElement);
                projectDocument.Save(projectDocumentPath);
            }
        }
예제 #9
0
        private void copyInEwlFiles(DevelopmentInstallation installation)
        {
            if (installation.DevelopmentInstallationLogic.SystemIsEwl)
            {
                foreach (var fileName in GlobalStatics.ConfigurationXsdFileNames)
                {
                    IoMethods.CopyFile(
                        EwlStatics.CombinePaths(installation.GeneralLogic.Path, AppStatics.CoreProjectName, "Configuration", fileName + FileExtensions.Xsd),
                        EwlStatics.CombinePaths(
                            InstallationFileStatics.GetGeneralFilesFolderPath(installation.GeneralLogic.Path, true),
                            InstallationFileStatics.FilesFolderName,
                            fileName + FileExtensions.Xsd));
                }
            }
            else
            {
                var recognizedInstallation = installation as RecognizedDevelopmentInstallation;
                if (recognizedInstallation == null || !recognizedInstallation.SystemIsEwlCacheCoordinator)
                {
                    foreach (var asposeLicenseFileName in asposeLicenseFileNames)
                    {
                        var asposeLicenseFilePath = EwlStatics.CombinePaths(ConfigurationStatics.ConfigurationFolderPath, asposeLicenseFileName);
                        if (File.Exists(asposeLicenseFilePath))
                        {
                            IoMethods.CopyFile(
                                asposeLicenseFilePath,
                                EwlStatics.CombinePaths(
                                    InstallationFileStatics.GetGeneralFilesFolderPath(installation.GeneralLogic.Path, true),
                                    InstallationFileStatics.FilesFolderName,
                                    asposeLicenseFileName));
                        }
                    }
                }

                // If web projects exist for this installation, copy appropriate files into them.
                if (installation.DevelopmentInstallationLogic.DevelopmentConfiguration.webProjects != null)
                {
                    foreach (var webProject in installation.DevelopmentInstallationLogic.DevelopmentConfiguration.webProjects)
                    {
                        copyInWebProjectFiles(installation, webProject);
                    }
                }
            }
        }
        /// <summary>
        /// Gets a data package, either by downloading one or using the last one that was downloaded. Returns the path to the ZIP file for the package. Also
        /// archives downloaded data packages and deletes those that are too old to be useful. Installation Support Utility use only.
        /// </summary>
        public string GetDataPackage(bool forceNewPackageDownload, OperationResult operationResult)
        {
            var dataExportToRsisWebSiteNotPermitted = InstallationTypeElements is LiveInstallationElements liveInstallationElements &&
                                                      liveInstallationElements.DataExportToRsisWebSiteNotPermitted;

            if (dataExportToRsisWebSiteNotPermitted ? !File.Exists(IsuStatics.GetDataPackageZipFilePath(FullName)) : !DataPackageSize.HasValue)
            {
                return("");
            }

            var downloadedPackagesFolder = EwlStatics.CombinePaths(ConfigurationLogic.DownloadedDataPackagesFolderPath, FullName);

            var packageZipFilePath = "";

            // See if we can re-use an existing package.
            if (!forceNewPackageDownload && Directory.Exists(downloadedPackagesFolder))
            {
                var downloadedPackages = IoMethods.GetFilePathsInFolder(downloadedPackagesFolder);
                if (downloadedPackages.Any())
                {
                    packageZipFilePath = downloadedPackages.First();
                }
            }

            // Download a package from RSIS if the user forces this behavior or if there is no package available on disk.
            if (forceNewPackageDownload || packageZipFilePath.Length == 0)
            {
                packageZipFilePath = EwlStatics.CombinePaths(downloadedPackagesFolder, "{0}-Package.zip".FormatWith(DateTime.Now.ToString("yyyy-MM-dd")));

                // If the update data installation is a live installation for which data export to the RSIS web site is not permitted, get the data package from disk.
                if (dataExportToRsisWebSiteNotPermitted)
                {
                    IoMethods.CopyFile(IsuStatics.GetDataPackageZipFilePath(FullName), packageZipFilePath);
                }
                else
                {
                    operationResult.TimeSpentWaitingForNetwork =
                        EwlStatics.ExecuteTimedRegion(() => operationResult.NumberOfBytesTransferred = downloadDataPackage(packageZipFilePath));
                }
            }

            deleteOldFiles(downloadedPackagesFolder, InstallationTypeElements is LiveInstallationElements);
            return(packageZipFilePath);
        }
        /// <summary>
        /// This is the code to install and start the SeleniumRC service.
        /// </summary>
        public static void InstallSeleniumServiceIfNecessary()
        {
            var          supportFilesDestinationPath = StandardLibraryMethods.CombinePaths(ConfigurationStatics.RedStaplerFolderPath, "Selenium Support");
            const string serviceName     = "SeleniumRC";
            const string seleniumJarFile = "selenium-server.jar";
            const string srvany          = "srvany.exe";

            var seleniumServerService = ServiceController.GetServices().Where(s => s.DisplayName == serviceName).SingleOrDefault();

            if (!Directory.Exists(supportFilesDestinationPath) || seleniumServerService == null)
            {
                // Wipe out any possible pre-existing configuration.
                IoMethods.DeleteFolder(supportFilesDestinationPath);
                if (seleniumServerService != null)
                {
                    // Delete the service and remove the registry values.
                    StandardLibraryMethods.RunProgram("sc", "delete " + serviceName, "", true);
                    seleniumServerService = null;
                }


                // NOTE: This will work because the only machines running tests are dev machines and integration machines, and both of those not only should have this in their Vault
                // tree, but they are guaranteed to have gotten latest on the Standard Library system before attempting to run a test (since you can't run a test until you've built).
                // Still, there may be a more robust way to do this in the future.
                // If we do keep this solution, you have to ask yourself why it makes sense to store the files here just to copy them to Red Stapler/Selenium Support. The only good reason
                // may be that the Vault tree could be prone to full deletion/re-getting, and that would fail if a service was referencing a file inside the tree.

                // NOTE: This path is probably wrong, and should not be hard-coded.
                const string supportFilesSourcePath = @"C:\Red Stapler Vault\Supporting Files\Standard Library\Solution Files\Selenium Support";

                var srvanyDestinationPath = StandardLibraryMethods.CombinePaths(supportFilesDestinationPath, srvany);
                // Create c:\Red Stapler\Selenium Support
                Directory.CreateDirectory(supportFilesDestinationPath);
                IoMethods.CopyFile(StandardLibraryMethods.CombinePaths(supportFilesSourcePath, srvany), srvanyDestinationPath);
                IoMethods.CopyFile(StandardLibraryMethods.CombinePaths(supportFilesSourcePath, seleniumJarFile),
                                   StandardLibraryMethods.CombinePaths(supportFilesDestinationPath, seleniumJarFile));


                const string serviceRegCmd = @"ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\" + serviceName + "\\Parameters  /v ";
                const string regDataType   = " /t REG_SZ /d ";
                const string javaFolder    = @"C:\Program Files\Java\jre6\bin";
                var          parametersToSeleniumServer = "";
                if (AppTools.IsDevelopmentInstallation)
                {
                    var firefoxProfileFolderPath = StandardLibraryMethods.CombinePaths(supportFilesDestinationPath, "Firefox");
                    Directory.CreateDirectory(firefoxProfileFolderPath);
                    parametersToSeleniumServer = " -firefoxProfileTemplate \\\"" + firefoxProfileFolderPath + "\\\"";
                }

                // This is the code to add the registry parameters to the Selenium Server.  This only needs to be run once.
                StandardLibraryMethods.RunProgram("sc", "create " + serviceName + " binPath= \"" + srvanyDestinationPath + "\" start= auto", "", true);
                StandardLibraryMethods.RunProgram("REG",
                                                  serviceRegCmd + "Application" + regDataType + "\"" + StandardLibraryMethods.CombinePaths(javaFolder, "java.exe") + "\"",
                                                  "",
                                                  true);
                StandardLibraryMethods.RunProgram("REG", serviceRegCmd + "AppDirectory" + regDataType + "\"" + supportFilesDestinationPath + "\" ", "", true);
                StandardLibraryMethods.RunProgram("REG",
                                                  serviceRegCmd + "AppParameters" + regDataType + "\"-Xrs -jar " + seleniumJarFile + parametersToSeleniumServer + "\"",
                                                  "",
                                                  true);

                // Wait for the service to be created
                while (seleniumServerService == null)
                {
                    seleniumServerService = ServiceController.GetServices().Where(s => s.DisplayName == serviceName).SingleOrDefault();
                }
            }

            if (seleniumServerService.Status != ServiceControllerStatus.Running)
            {
                seleniumServerService.Start();
                seleniumServerService.WaitForStatus(ServiceControllerStatus.Running);
            }
        }
예제 #12
0
        void Database.DeleteAndReCreateFromFile(string filePath)
        {
            executeDbMethodWithSpecifiedDatabaseInfo(
                new OracleInfo(
                    (info as DatabaseInfo).SecondaryDatabaseName,
                    info.DataSource,
                    "sys",
                    ConfigurationLogic.OracleSysPassword,
                    info.SupportsConnectionPooling,
                    info.SupportsLinguisticIndexes),
                cn => {
                executeLongRunningCommand(cn, "CREATE OR REPLACE DIRECTORY " + dataPumpOracleDirectoryName + " AS '" + dataPumpFolderPath + "'");
                deleteAndReCreateUser(cn);
            });

            try {
                IoMethods.ExecuteWithTempFolder(
                    tempFolderPath => {
                    var folderPath = EwlStatics.CombinePaths(tempFolderPath, "Database File");
                    ZipOps.UnZipFileAsFolder(filePath, folderPath);
                    try {
                        IoMethods.CopyFile(EwlStatics.CombinePaths(folderPath, databaseFileDumpFileName), getDumpFilePath());

                        executeMethodWithDbExceptionHandling(
                            delegate {
                            try {
                                EwlStatics.RunProgram(
                                    "impdp",
                                    getLogonString() + " DIRECTORY=" + dataPumpOracleDirectoryName + " DUMPFILE=\"\"\"" + getDumpFileName() + "\"\"\" NOLOGFILE=y REMAP_SCHEMA=" +
                                    File.ReadAllText(EwlStatics.CombinePaths(folderPath, databaseFileSchemaNameFileName)) + ":" + info.UserAndSchema,
                                    "",
                                    true);
                            }
                            catch (Exception e) {
                                throwUserCorrectableExceptionIfNecessary(e);
                                if (e is FileNotFoundException)
                                {
                                    throw new UserCorrectableException("The schema name file was not found, probably because of a corrupt database file in the data package.", e);
                                }

                                // Secondary databases such as RLE cause procedure compilation errors when imported, and since we have no way of
                                // distinguishing these from legitimate import problems, we have no choice but to ignore all exceptions.
                                if ((info as DatabaseInfo).SecondaryDatabaseName.Length == 0)
                                {
                                    throw DataAccessMethods.CreateDbConnectionException(info, "re-creating (from file)", e);
                                }
                            }
                        });
                    }
                    finally {
                        IoMethods.DeleteFile(getDumpFilePath());
                    }
                });
            }
            catch {
                // We don't want to leave a partial user/schema on the machine since it may confuse future ISU operations.
                executeDbMethodWithSpecifiedDatabaseInfo(
                    new OracleInfo(
                        (info as DatabaseInfo).SecondaryDatabaseName,
                        info.DataSource,
                        "sys",
                        ConfigurationLogic.OracleSysPassword,
                        info.SupportsConnectionPooling,
                        info.SupportsLinguisticIndexes),
                    deleteUser);

                throw;
            }
        }
예제 #13
0
        private void deleteAndReCreateFromFile(DBConnection cn, string filePath)
        {
            // NOTE: Instead of catching exceptions, figure out if the database exists by querying.
            try {
                // Gets rid of existing connections. These don't need to be executed against the master database, but it's convenient because it saves us from needing
                // a second database connection.
                executeLongRunningCommand(cn, "ALTER DATABASE {0} SET AUTO_UPDATE_STATISTICS_ASYNC OFF".FormatWith(info.Database));
                executeLongRunningCommand(cn, "ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE".FormatWith(info.Database));

                executeLongRunningCommand(cn, "DROP DATABASE " + info.Database);
            }
            catch (Exception) {
                // The database did not exist. That's fine.
            }

            var sqlServerFilesFolderPath = EwlStatics.CombinePaths(ConfigurationStatics.EwlFolderPath, "SQL Server Databases");

            Directory.CreateDirectory(sqlServerFilesFolderPath);

            var dataFilePath = EwlStatics.CombinePaths(sqlServerFilesFolderPath, info.Database + ".mdf");
            var logFilePath  = EwlStatics.CombinePaths(sqlServerFilesFolderPath, info.Database + ".ldf");

            if (filePath.Any())
            {
                try {
                    IoMethods.CopyFile(filePath, backupFilePath);
                    try {
                        // WITH MOVE is required so that multiple instances of the same system's database (RsisDev and RsisTesting, for example) can exist on the same machine
                        // without their physical files colliding.
                        executeLongRunningCommand(
                            cn,
                            "RESTORE DATABASE " + info.Database + " FROM DISK = '" + backupFilePath + "'" + " WITH MOVE '" + dataLogicalFileName + "' TO '" + dataFilePath +
                            "', MOVE '" + logLogicalFileName + "' TO '" + logFilePath + "'");
                    }
                    catch (Exception e) {
                        throw new UserCorrectableException("Failed to create database from file. Please try the operation again after obtaining a new database file.", e);
                    }
                }
                finally {
                    IoMethods.DeleteFile(backupFilePath);
                }
            }
            else
            {
                executeLongRunningCommand(
                    cn,
                    @"CREATE DATABASE {0}
ON (
	NAME = {1},
	FILENAME = '{2}',
	SIZE = 100MB,
	FILEGROWTH = 15%
)
LOG ON (
	NAME = {3},
	FILENAME = '{4}',
	SIZE = 10MB,
	MAXSIZE = 1000MB,
	FILEGROWTH = 100MB
)".FormatWith(info.Database, dataLogicalFileName, dataFilePath, logLogicalFileName, logFilePath));
            }
        }
예제 #14
0
        internal static IReadOnlyCollection <(string id, IReadOnlyList <byte[]> packages)> CreateEwlNuGetPackages(
            DevelopmentInstallation installation, PackagingConfiguration packagingConfiguration, bool useDebugAssembly, string outputFolderPath,
            IEnumerable <bool?> prereleaseValues)
        {
            var now      = DateTime.Now;
            var packages = new List <(string, IReadOnlyList <byte[]>)>();

            var mainId       = packagingConfiguration.SystemShortName;
            var mainPackages = prereleaseValues.Select(
                prerelease => {
                var localExportDateAndTime = prerelease.HasValue ? (DateTime?)null : now;

                IoMethods.ExecuteWithTempFolder(
                    folderPath => {
                    var ewlOutputFolderPath = EwlStatics.CombinePaths(
                        installation.GeneralLogic.Path,
                        EwlStatics.CoreProjectName,
                        EwlStatics.GetProjectOutputFolderPath(useDebugAssembly));
                    var libFolderPath = EwlStatics.CombinePaths(folderPath, @"lib\net472-full");
                    foreach (var fileName in new[] { "dll", "pdb", "xml" }.Select(i => "EnterpriseWebLibrary." + i))
                    {
                        IoMethods.CopyFile(EwlStatics.CombinePaths(ewlOutputFolderPath, fileName), EwlStatics.CombinePaths(libFolderPath, fileName));
                    }

                    IoMethods.CopyFile(
                        EwlStatics.CombinePaths(installation.GeneralLogic.Path, @"Development Utility\Package Manager Console Commands.ps1"),
                        EwlStatics.CombinePaths(folderPath, @"tools\init.ps1"));

                    IoMethods.CopyFolder(
                        EwlStatics.CombinePaths(installation.GeneralLogic.Path, EwlStatics.CoreProjectName, StaticFile.FrameworkStaticFilesSourceFolderPath),
                        EwlStatics.CombinePaths(folderPath, InstallationFileStatics.WebFrameworkStaticFilesFolderName),
                        false);
                    IoMethods.DeleteFolder(
                        EwlStatics.CombinePaths(folderPath, InstallationFileStatics.WebFrameworkStaticFilesFolderName, AppStatics.StaticFileLogicFolderName));

                    const string duProjectAndFolderName = "Development Utility";
                    IoMethods.CopyFolder(
                        EwlStatics.CombinePaths(installation.GeneralLogic.Path, duProjectAndFolderName, EwlStatics.GetProjectOutputFolderPath(useDebugAssembly)),
                        EwlStatics.CombinePaths(folderPath, duProjectAndFolderName),
                        false);
                    packageGeneralFiles(installation, folderPath, false);
                    IoMethods.CopyFolder(
                        EwlStatics.CombinePaths(
                            installation.ExistingInstallationLogic.RuntimeConfiguration.ConfigurationFolderPath,
                            InstallationConfiguration.InstallationConfigurationFolderName,
                            InstallationConfiguration.InstallationsFolderName,
                            !prerelease.HasValue || prerelease.Value ? "Testing" : "Live"),
                        EwlStatics.CombinePaths(
                            folderPath,
                            InstallationConfiguration.ConfigurationFolderName,
                            InstallationConfiguration.InstallationConfigurationFolderName),
                        false);
                    if (File.Exists(installation.ExistingInstallationLogic.RuntimeConfiguration.InstallationSharedConfigurationFilePath))
                    {
                        IoMethods.CopyFile(
                            installation.ExistingInstallationLogic.RuntimeConfiguration.InstallationSharedConfigurationFilePath,
                            EwlStatics.CombinePaths(
                                folderPath,
                                InstallationConfiguration.ConfigurationFolderName,
                                InstallationConfiguration.InstallationConfigurationFolderName,
                                InstallationConfiguration.InstallationSharedConfigurationFileName));
                    }

                    var manifestPath = EwlStatics.CombinePaths(folderPath, "Package.nuspec");
                    using (var writer = IoMethods.GetTextWriterForWrite(manifestPath))
                        writeNuGetPackageManifest(
                            writer,
                            installation,
                            mainId,
                            "",
                            w => {
                            var lines = from line in File.ReadAllLines(
                                EwlStatics.CombinePaths(installation.GeneralLogic.Path, EwlStatics.CoreProjectName, "packages.config"))
                                        let trimmedLine = line.Trim()
                                                          where trimmedLine.StartsWith("<package ")
                                                          select trimmedLine;
                            foreach (var line in lines)
                            {
                                w.WriteLine(Regex.Replace(line.Replace("package", "dependency"), @" targetFramework=""[\w]+""", ""));
                            }
                        },
                            prerelease,
                            localExportDateAndTime);

                    StatusStatics.SetStatus(
                        TewlContrib.ProcessTools.RunProgram(
                            EwlStatics.CombinePaths(installation.GeneralLogic.Path, @"Solution Files\nuget"),
                            "pack \"" + manifestPath + "\" -OutputDirectory \"" + outputFolderPath + "\"",
                            "",
                            true));
                });

                return(File.ReadAllBytes(
                           EwlStatics.CombinePaths(
                               outputFolderPath,
                               EwlNuGetPackageSpecificationStatics.GetNuGetPackageFileName(
                                   mainId,
                                   installation.CurrentMajorVersion,
                                   !prerelease.HasValue || prerelease.Value ? installation.NextBuildNumber as int? : null,
                                   localExportDateAndTime: localExportDateAndTime))));
            })
                               .MaterializeAsList();

            packages.Add((mainId, mainPackages));

            var samlId       = mainId + ".Saml";
            var samlPackages = prereleaseValues.Select(
                prerelease => {
                var localExportDateAndTime = prerelease.HasValue ? (DateTime?)null : now;

                IoMethods.ExecuteWithTempFolder(
                    folderPath => {
                    foreach (var fileName in new[] { "dll", "pdb" }.Select(i => "EnterpriseWebLibrary.Saml." + i))
                    {
                        IoMethods.CopyFile(
                            EwlStatics.CombinePaths(
                                installation.GeneralLogic.Path,
                                EwlStatics.SamlProviderProjectPath,
                                EwlStatics.GetProjectOutputFolderPath(useDebugAssembly),
                                fileName),
                            EwlStatics.CombinePaths(folderPath, @"lib\net472-full", fileName));
                    }

                    var manifestPath = EwlStatics.CombinePaths(folderPath, "Package.nuspec");
                    using (var writer = IoMethods.GetTextWriterForWrite(manifestPath))
                        writeNuGetPackageManifest(
                            writer,
                            installation,
                            samlId,
                            "SAML Provider",
                            w => {
                            w.WriteLine(
                                "<dependency id=\"{0}\" version=\"[{1}]\" />".FormatWith(
                                    mainId,
                                    EwlNuGetPackageSpecificationStatics.GetNuGetPackageVersionString(
                                        installation.CurrentMajorVersion,
                                        !prerelease.HasValue || prerelease.Value ? (int?)installation.NextBuildNumber : null,
                                        localExportDateAndTime: localExportDateAndTime)));
                            w.WriteLine("<dependency id=\"ComponentSpace.Saml2.Net.Licensed\" version=\"5.0.0\" />");
                        },
                            prerelease,
                            localExportDateAndTime);

                    StatusStatics.SetStatus(
                        TewlContrib.ProcessTools.RunProgram(
                            EwlStatics.CombinePaths(installation.GeneralLogic.Path, @"Solution Files\nuget"),
                            "pack \"" + manifestPath + "\" -OutputDirectory \"" + outputFolderPath + "\"",
                            "",
                            true));
                });

                return(File.ReadAllBytes(
                           EwlStatics.CombinePaths(
                               outputFolderPath,
                               EwlNuGetPackageSpecificationStatics.GetNuGetPackageFileName(
                                   samlId,
                                   installation.CurrentMajorVersion,
                                   !prerelease.HasValue || prerelease.Value ? installation.NextBuildNumber as int? : null,
                                   localExportDateAndTime: localExportDateAndTime))));
            })
                               .MaterializeAsList();

            packages.Add((samlId, samlPackages));

            return(packages);
        }
예제 #15
0
        void Operation.Execute(Installation genericInstallation, IReadOnlyList <string> arguments, OperationResult operationResult)
        {
            var installation           = genericInstallation as DevelopmentInstallation;
            var packagingConfiguration = GetPackagingConfiguration(installation);

            var logicPackagesFolderPath = EwlStatics.CombinePaths(installation.GeneralLogic.Path, "Logic Packages");

            IoMethods.DeleteFolder(logicPackagesFolderPath);

            // Set up the main (build) object in the build message.
            var build = new InstallationSupportUtility.SystemManagerInterface.Messages.BuildMessage.Build();

            build.SystemName      = packagingConfiguration.SystemName;
            build.SystemShortName = packagingConfiguration.SystemShortName;
            build.MajorVersion    = installation.CurrentMajorVersion;
            build.BuildNumber     = installation.NextBuildNumber;

            var hgOutput = Directory.Exists(EwlStatics.CombinePaths(installation.GeneralLogic.Path, AppStatics.MercurialRepositoryFolderName))
                                               ? TewlContrib.ProcessTools.RunProgram(
                @"C:\Program Files\TortoiseHg\hg",
                "--debug identify --id \"{0}\"".FormatWith(installation.GeneralLogic.Path),
                "",
                true)
                           .Trim()
                                               : "";

            build.HgChangesetId = hgOutput.Length == 40 ? hgOutput : "";

            build.LogicSize = AppStatics.NDependIsPresent && !installation.DevelopmentInstallationLogic.SystemIsEwl
                                                  ? GetLogicSize.GetNDependLocCount(installation, false) as int?
                                                  : null;
            var serverSideLogicFolderPath = EwlStatics.CombinePaths(logicPackagesFolderPath, "Server Side Logic");

            packageWebApps(installation, serverSideLogicFolderPath);
            packageWindowsServices(installation, serverSideLogicFolderPath);
            packageServerSideConsoleApps(installation, serverSideLogicFolderPath);
            packageGeneralFiles(installation, serverSideLogicFolderPath, true);
            build.ServerSideLogicPackage             = ZipOps.ZipFolderAsByteArray(serverSideLogicFolderPath);
            operationResult.NumberOfBytesTransferred = build.ServerSideLogicPackage.LongLength;

            // Set up the client side application object in the build message, if necessary.
            if (installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject != null)
            {
                build.ClientSideApp              = new InstallationSupportUtility.SystemManagerInterface.Messages.BuildMessage.Build.ClientSideAppType();
                build.ClientSideApp.Name         = installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject.name;
                build.ClientSideApp.AssemblyName = installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject.assemblyName;
                var clientSideAppFolder = EwlStatics.CombinePaths(logicPackagesFolderPath, "Client Side Application");
                packageClientSideApp(installation, clientSideAppFolder);
                packageGeneralFiles(installation, clientSideAppFolder, false);
                build.ClientSideApp.Package = ZipOps.ZipFolderAsByteArray(clientSideAppFolder);
                operationResult.NumberOfBytesTransferred += build.ClientSideApp.Package.LongLength;
            }

            // Set up the list of installation objects in the build message.
            build.Installations = new InstallationSupportUtility.SystemManagerInterface.Messages.BuildMessage.Build.InstallationsType();
            foreach (var installationConfigurationFolderPath in Directory.GetDirectories(
                         EwlStatics.CombinePaths(
                             installation.ExistingInstallationLogic.RuntimeConfiguration.ConfigurationFolderPath,
                             InstallationConfiguration.InstallationConfigurationFolderName,
                             InstallationConfiguration.InstallationsFolderName)))
            {
                if (!new[] { InstallationConfiguration.DevelopmentInstallationFolderName, AppStatics.MercurialRepositoryFolderName }.Contains(
                        Path.GetFileName(installationConfigurationFolderPath)))
                {
                    var buildMessageInstallation = new InstallationSupportUtility.SystemManagerInterface.Messages.BuildMessage.Installation();

                    // Do not perform schema validation since the schema file on disk may not match this version of the ISU.
                    var installationConfigurationFile = XmlOps.DeserializeFromFile <InstallationStandardConfiguration>(
                        EwlStatics.CombinePaths(installationConfigurationFolderPath, InstallationConfiguration.InstallationStandardConfigurationFileName),
                        false);

                    buildMessageInstallation.Id                 = installationConfigurationFile.rsisInstallationId;
                    buildMessageInstallation.Name               = installationConfigurationFile.installedInstallation.name;
                    buildMessageInstallation.ShortName          = installationConfigurationFile.installedInstallation.shortName;
                    buildMessageInstallation.IsLiveInstallation =
                        installationConfigurationFile.installedInstallation.InstallationTypeConfiguration is LiveInstallationConfiguration;

                    var packageFolderPath = EwlStatics.CombinePaths(
                        logicPackagesFolderPath,
                        $"{installationConfigurationFile.installedInstallation.name} Configuration");
                    IoMethods.CopyFolder(installationConfigurationFolderPath, packageFolderPath, false);
                    if (File.Exists(installation.ExistingInstallationLogic.RuntimeConfiguration.InstallationSharedConfigurationFilePath))
                    {
                        IoMethods.CopyFile(
                            installation.ExistingInstallationLogic.RuntimeConfiguration.InstallationSharedConfigurationFilePath,
                            EwlStatics.CombinePaths(packageFolderPath, InstallationConfiguration.InstallationSharedConfigurationFileName));
                    }
                    buildMessageInstallation.ConfigurationPackage = ZipOps.ZipFolderAsByteArray(packageFolderPath);

                    build.Installations.Add(buildMessageInstallation);
                    operationResult.NumberOfBytesTransferred += buildMessageInstallation.ConfigurationPackage.LongLength;
                }
            }

            build.NuGetPackages = new InstallationSupportUtility.SystemManagerInterface.Messages.BuildMessage.Build.NuGetPackagesType();
            if (installation.DevelopmentInstallationLogic.SystemIsEwl)
            {
                build.NuGetPackages.AddRange(packageEwl(installation, packagingConfiguration, logicPackagesFolderPath));
            }

            var recognizedInstallation = installation as RecognizedDevelopmentInstallation;

            if (recognizedInstallation == null)
            {
                return;
            }

            build.SystemId = recognizedInstallation.KnownSystemLogic.RsisSystem.Id;

            operationResult.TimeSpentWaitingForNetwork = EwlStatics.ExecuteTimedRegion(
                delegate {
                using (var memoryStream = new MemoryStream()) {
                    // Understand that by doing this, we are not really taking advantage of streaming, but at least it will be easier to do it the right way some day (probably by implementing our own BuildMessageStream)
                    XmlOps.SerializeIntoStream(build, memoryStream);
                    memoryStream.Position = 0;

                    ConfigurationLogic.ExecuteIsuServiceMethod(
                        channel => channel.UploadBuild(
                            new InstallationSupportUtility.SystemManagerInterface.Messages.BuildUploadMessage
                    {
                        AuthenticationKey = ConfigurationLogic.SystemManagerAccessToken, BuildDocument = memoryStream
                    }),
                        "build upload");
                }
            });
        }