コード例 #1
0
        private void copyInEwlFiles(DevelopmentInstallation installation)
        {
            if (installation.DevelopmentInstallationLogic.SystemIsEwl)
            {
                foreach (var fileName in GlobalStatics.ConfigurationXsdFileNames)
                {
                    IoMethods.CopyFile(
                        StandardLibraryMethods.CombinePaths(installation.GeneralLogic.Path, "Standard Library", "Configuration", fileName + FileExtensions.Xsd),
                        StandardLibraryMethods.CombinePaths(
                            InstallationFileStatics.GetGeneralFilesFolderPath(installation.GeneralLogic.Path, true),
                            InstallationFileStatics.FilesFolderName,
                            fileName + FileExtensions.Xsd));
                }
            }
            else
            {
                var recognizedInstallation = installation as RecognizedDevelopmentInstallation;
                if (recognizedInstallation == null || !recognizedInstallation.SystemIsEwlCacheCoordinator)
                {
                    var asposeLicenseFilePath = StandardLibraryMethods.CombinePaths(AppTools.ConfigurationFolderPath, asposeLicenseFileName);
                    if (File.Exists(asposeLicenseFilePath))
                    {
                        IoMethods.CopyFile(
                            asposeLicenseFilePath,
                            StandardLibraryMethods.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);
                    }
                }
            }
        }
コード例 #2
0
        private void deleteAndReCreateFromFile(DBConnection cn, string filePath, bool keepDbInStandbyMode)
        {
            // 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.
                    var restoreCommand = "RESTORE DATABASE " + info.Database + " FROM DISK = '" + backupFilePath + "'" + " WITH MOVE '" + dataLogicalFileName + "' TO '" +
                                         StandardLibraryMethods.CombinePaths(sqlServerFilesFolderPath, info.Database + ".mdf") + "', MOVE '" + logLogicalFileName + "' TO '" +
                                         StandardLibraryMethods.CombinePaths(sqlServerFilesFolderPath, info.Database + ".ldf") + "'";

                    if (keepDbInStandbyMode)
                    {
                        restoreCommand += ", STANDBY = '" + getStandbyFilePath() + "'";
                    }

                    executeLongRunningCommand(cn, restoreCommand);
                }
                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 static void createStaticFileLogicTemplate(string folderPath, string itemNamespace, string className)
        {
            var templateFilePath = EwlStatics.CombinePaths(folderPath, className + DataAccess.DataAccessStatics.CSharpTemplateFileExtension);

            IoMethods.DeleteFile(templateFilePath);

            // If a real file exists, don’t create a template.
            if (File.Exists(EwlStatics.CombinePaths(folderPath, className + ".cs")))
            {
                return;
            }

            using (var writer = new StreamWriter(templateFilePath, false, Encoding.UTF8)) {
                writer.WriteLine("namespace {0} {{".FormatWith(itemNamespace));
                writer.WriteLine("	partial class {0} {{".FormatWith(className));
                writer.WriteLine(
                    "		// IMPORTANT: Change extension from \"{0}\" to \".cs\" before including in project and editing.".FormatWith(
                        DataAccess.DataAccessStatics.CSharpTemplateFileExtension));
                writer.WriteLine("	}");
                writer.WriteLine("}");
            }
        }
コード例 #4
0
        private void createSystemFilesInFolder(string templateFolderPath, string tempFolderPath, string relativeFolderPath)
        {
            var sourceFolderPath = EwlStatics.CombinePaths(templateFolderPath, relativeFolderPath);

            foreach (var fileName in IoMethods.GetFileNamesInFolder(sourceFolderPath))
            {
                var filePath            = EwlStatics.CombinePaths(relativeFolderPath, fileName);
                var destinationFilePath = EwlStatics.CombinePaths(tempFolderPath, filePath == "Solution.sln" ? "{0}.sln".FormatWith(systemName.Value) : filePath);
                Directory.CreateDirectory(Path.GetDirectoryName(destinationFilePath));
                File.WriteAllText(
                    destinationFilePath,
                    File.ReadAllText(EwlStatics.CombinePaths(templateFolderPath, filePath), Encoding.UTF8)
                    .Replace("@@SystemName", systemName.Value)
                    .Replace("@@SystemShortNameLowercase", systemShortName.Value.ToLowerInvariant())
                    .Replace("@@SystemShortName", systemShortName.Value)
                    .Replace("@@BaseNamespace", baseNamespace.Value),
                    Encoding.UTF8);
            }
            foreach (var subFolderName in IoMethods.GetFolderNamesInFolder(sourceFolderPath))
            {
                createSystemFilesInFolder(templateFolderPath, tempFolderPath, Path.Combine(relativeFolderPath, subFolderName));
            }
        }
コード例 #5
0
        internal static void WritePartialClass(DBConnection cn, string libraryBasePath, string namespaceDeclaration, IDatabase database, string tableName)
        {
            var folderPath       = Utility.CombinePaths(libraryBasePath, "DataAccess", "TableRetrieval");
            var templateFilePath = Utility.CombinePaths(folderPath, GetClassName(cn, tableName) + DataAccessStatics.CSharpTemplateFileExtension);

            IoMethods.DeleteFile(templateFilePath);

            // If a real file exists, don't create a template.
            if (File.Exists(Utility.CombinePaths(folderPath, GetClassName(cn, tableName) + ".cs")))
            {
                return;
            }

            using (var writer = IoMethods.GetTextWriterForWrite(templateFilePath)) {
                writer.WriteLine(namespaceDeclaration);
                writer.WriteLine("	partial class "+ GetClassName(cn, tableName) + " {");
                writer.WriteLine(
                    "		// IMPORTANT: Change extension from \"{0}\" to \".cs\" before including in project and editing.".FormatWith(
                        DataAccessStatics.CSharpTemplateFileExtension));
                writer.WriteLine("	}");                      // class
                writer.WriteLine("}");                   // namespace
            }
        }
コード例 #6
0
        private void generateWebConfigAndCodeForWebProject(DevelopmentInstallation installation, WebProject project)
        {
            var application = installation.ExistingInstallationLogic.RuntimeConfiguration.WebApplications.Single(i => i.Name == project.name);

            // This must be done before web meta logic generation, which can be affected by the contents of Web.config files.
            WebConfigStatics.GenerateWebConfig(application, project);

            var webProjectGeneratedCodeFolderPath = EwlStatics.CombinePaths(application.Path, "Generated Code");

            Directory.CreateDirectory(webProjectGeneratedCodeFolderPath);
            var webProjectIsuFilePath = EwlStatics.CombinePaths(webProjectGeneratedCodeFolderPath, "ISU.cs");

            IoMethods.DeleteFile(webProjectIsuFilePath);
            using (TextWriter writer = new StreamWriter(webProjectIsuFilePath)) {
                writer.WriteLine("using System;");
                writer.WriteLine("using System.Collections.Generic;");
                writer.WriteLine("using System.Collections.ObjectModel;");
                writer.WriteLine("using System.Globalization;");
                writer.WriteLine("using System.Linq;");
                writer.WriteLine("using System.Reflection;");
                writer.WriteLine("using System.Runtime.InteropServices;");
                writer.WriteLine("using System.Web;");
                writer.WriteLine("using System.Web.UI;");
                writer.WriteLine("using System.Web.UI.WebControls;");
                writer.WriteLine("using EnterpriseWebLibrary;");
                writer.WriteLine("using EnterpriseWebLibrary.DataAccess;");
                writer.WriteLine("using EnterpriseWebLibrary.EnterpriseWebFramework;");
                writer.WriteLine("using EnterpriseWebLibrary.EnterpriseWebFramework.Controls;");
                writer.WriteLine("using NodaTime;");
                writer.WriteLine("using Tewl.InputValidation;");
                writer.WriteLine("using Tewl.Tools;");
                writer.WriteLine();
                writeAssemblyInfo(writer, installation, project.name);
                writer.WriteLine();
                CodeGeneration.WebMetaLogic.WebMetaLogicStatics.Generate(writer, application.Path, project);
            }
        }
コード例 #7
0
        internal static void WritePartialClass(
            DBConnection cn, string libraryBasePath, string namespaceDeclaration, Database database, string tableName, bool isRevisionHistoryTable)
        {
            // We do not create templates for direct modification classes.
            var folderPath = StandardLibraryMethods.CombinePaths( libraryBasePath, "DataAccess", database.SecondaryDatabaseName + "Modification" );
            var templateFilePath = StandardLibraryMethods.CombinePaths(
                folderPath,
                GetClassName( cn, tableName, isRevisionHistoryTable, isRevisionHistoryTable ) + DataAccessStatics.CSharpTemplateFileExtension );
            IoMethods.DeleteFile( templateFilePath );

            // If a real file exists, don't create a template.
            if( File.Exists( StandardLibraryMethods.CombinePaths( folderPath, GetClassName( cn, tableName, isRevisionHistoryTable, isRevisionHistoryTable ) + ".cs" ) ) )
                return;

            using( var templateWriter = IoMethods.GetTextWriterForWrite( templateFilePath ) ) {
                templateWriter.WriteLine( namespaceDeclaration );
                templateWriter.WriteLine( "	partial class " + GetClassName( cn, tableName, isRevisionHistoryTable, isRevisionHistoryTable ) + " {" );
                templateWriter.WriteLine(
                    "		// IMPORTANT: Change extension from \"{0}\" to \".cs\" before including in project and editing.".FormatWith(
                        DataAccessStatics.CSharpTemplateFileExtension ) );
                templateWriter.WriteLine( "	}" ); // class
                templateWriter.WriteLine( "}" ); // namespace
            }
        }
コード例 #8
0
        /// <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);
            }
        }
コード例 #9
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;
            }
        }
コード例 #10
0
        public static Action DownloadDataPackageAndGetDataUpdateMethod(
            ExistingInstallation installation, bool installationIsStandbyDb, RsisInstallation source, bool forceNewPackageDownload,
            OperationResult operationResult)
        {
            var recognizedInstallation = installation as RecognizedInstallation;
            var packageZipFilePath     = recognizedInstallation != null?source.GetDataPackage(forceNewPackageDownload, operationResult) : "";

            return(() => {
                IoMethods.ExecuteWithTempFolder(
                    tempFolderPath => {
                    var packageFolderPath = EwlStatics.CombinePaths(tempFolderPath, "Package");
                    if (packageZipFilePath.Any())
                    {
                        ZipOps.UnZipFileAsFolder(packageZipFilePath, packageFolderPath);
                    }

                    // Delete and re-create databases.
                    DatabaseOps.DeleteAndReCreateDatabaseFromFile(
                        installation.ExistingInstallationLogic.Database,
                        databaseHasMinimumDataRevision(installation.ExistingInstallationLogic.RuntimeConfiguration.PrimaryDatabaseSystemConfiguration),
                        packageFolderPath);
                    if (recognizedInstallation != null)
                    {
                        foreach (var secondaryDatabase in recognizedInstallation.RecognizedInstallationLogic.SecondaryDatabasesIncludedInDataPackages)
                        {
                            DatabaseOps.DeleteAndReCreateDatabaseFromFile(
                                secondaryDatabase,
                                databaseHasMinimumDataRevision(
                                    installation.ExistingInstallationLogic.RuntimeConfiguration.GetSecondaryDatabaseSystemConfiguration(
                                        secondaryDatabase.SecondaryDatabaseName)),
                                packageFolderPath);
                        }
                    }
                });

                DatabaseOps.WaitForDatabaseRecovery(installation.ExistingInstallationLogic.Database);
                if (recognizedInstallation != null)
                {
                    recompileProceduresInSecondaryOracleDatabases(recognizedInstallation);
                }

                if (!installationIsStandbyDb)
                {
                    // Bring database logic up to date with the rest of the logic in this installation. In other words, reapply changes lost when we deleted the database.
                    StatusStatics.SetStatus("Updating database logic...");
                    DatabaseOps.UpdateDatabaseLogicIfUpdateFileExists(
                        installation.ExistingInstallationLogic.Database,
                        installation.ExistingInstallationLogic.DatabaseUpdateFilePath,
                        installation.ExistingInstallationLogic.RuntimeConfiguration.InstallationType == InstallationType.Development);
                }

                // If we're an intermediate installation and we are getting data from a live installation, sanitize the data and do other conversion commands.
                if (installation is RecognizedInstalledInstallation recognizedInstalledInstallation &&
                    recognizedInstalledInstallation.KnownInstallationLogic.RsisInstallation.InstallationTypeElements is IntermediateInstallationElements &&
                    source.InstallationTypeElements is LiveInstallationElements)
                {
                    StatusStatics.SetStatus("Executing live -> intermediate conversion commands...");
                    doDatabaseLiveToIntermediateConversionIfCommandsExist(
                        installation.ExistingInstallationLogic.Database,
                        installation.ExistingInstallationLogic.RuntimeConfiguration.PrimaryDatabaseSystemConfiguration);
                    foreach (var secondaryDatabase in recognizedInstallation.RecognizedInstallationLogic.SecondaryDatabasesIncludedInDataPackages)
                    {
                        doDatabaseLiveToIntermediateConversionIfCommandsExist(
                            secondaryDatabase,
                            installation.ExistingInstallationLogic.RuntimeConfiguration.GetSecondaryDatabaseSystemConfiguration(secondaryDatabase.SecondaryDatabaseName));
                    }
                }
            });
        }
コード例 #11
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 = EwlStatics.CombinePaths(
                    installation.GeneralLogic.Path,
                    AppStatics.CoreProjectName,
                    EwlStatics.GetProjectOutputFolderPath(useDebugAssembly));
                var libFolderPath = EwlStatics.CombinePaths(folderPath, @"lib\net451-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"));

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

                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);

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

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

            return
                (File.ReadAllBytes(
                     EwlStatics.CombinePaths(
                         outputFolderPath,
                         EwlNuGetPackageSpecificationStatics.GetNuGetPackageFileName(
                             installation.ExistingInstallationLogic.RuntimeConfiguration.SystemShortName,
                             installation.CurrentMajorVersion,
                             !prerelease.HasValue || prerelease.Value ? installation.NextBuildNumber as int? : null,
                             localExportDateAndTime: localExportDateAndTime))));
        }
コード例 #12
0
        void Operation.Execute(Installation genericInstallation, OperationResult operationResult)
        {
            var installation = genericInstallation as DevelopmentInstallation;

            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.RsisInterface.Messages.BuildMessage.Build();

            build.SystemName      = installation.ExistingInstallationLogic.RuntimeConfiguration.SystemName;
            build.SystemShortName = installation.ExistingInstallationLogic.RuntimeConfiguration.SystemShortName;
            build.MajorVersion    = installation.CurrentMajorVersion;
            build.BuildNumber     = installation.NextBuildNumber;
            build.LogicSize       = ConfigurationLogic.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.RsisInterface.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.RsisInterface.Messages.BuildMessage.Build.InstallationsType();
            foreach (var installationConfigurationFolderPath in
                     Directory.GetDirectories(
                         EwlStatics.CombinePaths(
                             installation.ExistingInstallationLogic.RuntimeConfiguration.ConfigurationFolderPath,
                             InstallationConfiguration.InstallationConfigurationFolderName,
                             InstallationConfiguration.InstallationsFolderName)))
            {
                if (Path.GetFileName(installationConfigurationFolderPath) != InstallationConfiguration.DevelopmentInstallationFolderName)
                {
                    var buildMessageInstallation = new InstallationSupportUtility.RsisInterface.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;
                    buildMessageInstallation.ConfigurationPackage = ZipOps.ZipFolderAsByteArray(installationConfigurationFolderPath);
                    build.Installations.Add(buildMessageInstallation);
                    operationResult.NumberOfBytesTransferred += buildMessageInstallation.ConfigurationPackage.LongLength;
                }
            }

            if (installation.DevelopmentInstallationLogic.SystemIsEwl)
            {
                build.NuGetPackages = packageEwl(installation, 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 BuildUploadMessage {
                        AuthenticationKey = ConfigurationLogic.AuthenticationKey, BuildDocument = memoryStream
                    }),
                        "build upload");
                }
            });
        }
コード例 #13
0
        private void updateMercurialIgnoreFile(DevelopmentInstallation installation)
        {
            var filePath = EwlStatics.CombinePaths(installation.GeneralLogic.Path, ".hgignore");
            var lines    = File.Exists(filePath) ? File.ReadAllLines(filePath) : new string[0];

            IoMethods.DeleteFile(filePath);
            using (TextWriter writer = new StreamWriter(filePath)) {
                const string regionBegin = "# EWL-REGION";
                const string regionEnd   = "# END-EWL-REGION";

                writer.WriteLine(regionBegin);
                writer.WriteLine("syntax: glob");
                writer.WriteLine();
                writer.WriteLine(".vs/{0}/v15/.suo".FormatWith(installation.ExistingInstallationLogic.RuntimeConfiguration.SystemName));
                writer.WriteLine(".vs/{0}/v15/sqlite3/storage.ide".FormatWith(installation.ExistingInstallationLogic.RuntimeConfiguration.SystemName));
                writer.WriteLine("packages/");
                writer.WriteLine(installation.ExistingInstallationLogic.RuntimeConfiguration.SystemName + ".sln.DotSettings.user");
                writer.WriteLine("Error Log.txt");
                writer.WriteLine("*.csproj.user");
                writer.WriteLine("*" + CodeGeneration.DataAccess.DataAccessStatics.CSharpTemplateFileExtension);
                writer.WriteLine();
                writer.WriteLine("Solution Files/bin/");
                writer.WriteLine("Solution Files/obj/");
                writer.WriteLine();
                writer.WriteLine("Library/bin/");
                writer.WriteLine("Library/obj/");
                writer.WriteLine("Library/Generated Code/");
                foreach (var asposeLicenseFileName in asposeLicenseFileNames)
                {
                    writer.WriteLine("Library/" + InstallationFileStatics.FilesFolderName + "/" + asposeLicenseFileName);
                }

                foreach (var webProject in installation.DevelopmentInstallationLogic.DevelopmentConfiguration.webProjects ?? new WebProject[0])
                {
                    writer.WriteLine();
                    writer.WriteLine(webProject.name + "/bin/");
                    writer.WriteLine(webProject.name + "/obj/");
                    writer.WriteLine(webProject.name + "/" + StaticFileHandler.EwfFolderName + "/");
                    writer.WriteLine(webProject.name + "/" + AppStatics.StandardLibraryFilesFileName);
                    writer.WriteLine(webProject.name + "/Generated Code/");
                }

                foreach (var service in installation.ExistingInstallationLogic.RuntimeConfiguration.WindowsServices)
                {
                    writer.WriteLine();
                    writer.WriteLine(service.Name + "/bin/");
                    writer.WriteLine(service.Name + "/obj/");
                    writer.WriteLine(service.Name + "/Generated Code/");
                }

                foreach (var project in installation.DevelopmentInstallationLogic.DevelopmentConfiguration.ServerSideConsoleProjectsNonNullable)
                {
                    writer.WriteLine();
                    writer.WriteLine(project.Name + "/bin/");
                    writer.WriteLine(project.Name + "/obj/");
                    writer.WriteLine(project.Name + "/Generated Code/");
                }

                if (installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject != null)
                {
                    writer.WriteLine();
                    writer.WriteLine(installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject.name + "/bin/");
                    writer.WriteLine(installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject.name + "/obj/");
                    writer.WriteLine(installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject.name + "/Generated Code/");
                }

                writer.WriteLine();
                writer.WriteLine(regionEnd);

                var skipping = false;
                foreach (var line in lines)
                {
                    if (line == regionBegin)
                    {
                        skipping = true;
                    }
                    if (!skipping)
                    {
                        writer.WriteLine(line);
                    }
                    if (line == regionEnd)
                    {
                        skipping = false;
                    }
                }
            }
        }
コード例 #14
0
        private void generateWindowsServiceCode(DevelopmentInstallation installation, WindowsService service)
        {
            var serviceProjectGeneratedCodeFolderPath = EwlStatics.CombinePaths(installation.GeneralLogic.Path, service.Name, "Generated Code");

            Directory.CreateDirectory(serviceProjectGeneratedCodeFolderPath);
            var isuFilePath = EwlStatics.CombinePaths(serviceProjectGeneratedCodeFolderPath, "ISU.cs");

            IoMethods.DeleteFile(isuFilePath);
            using (TextWriter writer = new StreamWriter(isuFilePath)) {
                writer.WriteLine("using System;");
                writer.WriteLine("using System.ComponentModel;");
                writer.WriteLine("using System.Reflection;");
                writer.WriteLine("using System.Runtime.InteropServices;");
                writer.WriteLine("using System.ServiceProcess;");
                writer.WriteLine("using System.Threading;");
                writer.WriteLine("using EnterpriseWebLibrary;");
                writer.WriteLine("using EnterpriseWebLibrary.DataAccess;");
                writer.WriteLine("using EnterpriseWebLibrary.WindowsServiceFramework;");
                writer.WriteLine();
                writeAssemblyInfo(writer, installation, service.Name);
                writer.WriteLine();
                writer.WriteLine("namespace " + service.NamespaceAndAssemblyName + " {");

                writer.WriteLine("internal static partial class Program {");

                writer.WriteLine("[ MTAThread ]");
                writer.WriteLine("private static void Main() {");
                writer.WriteLine("InitStatics();");
                writer.WriteLine("try {");
                writer.WriteLine(
                    "TelemetryStatics.ExecuteBlockWithStandardExceptionHandling( () => ServiceBase.Run( new ServiceBaseAdapter( new " + service.Name.EnglishToPascal() +
                    "() ) ) );");
                writer.WriteLine("}");
                writer.WriteLine("finally {");
                writer.WriteLine("GlobalInitializationOps.CleanUpStatics();");
                writer.WriteLine("}");
                writer.WriteLine("}");

                writer.WriteLine("internal static void InitStatics() {");
                writer.WriteLine("SystemInitializer globalInitializer = null;");
                writer.WriteLine("initGlobalInitializer( ref globalInitializer );");
                writer.WriteLine("var dataAccessState = new ThreadLocal<DataAccessState>( () => new DataAccessState() );");
                writer.WriteLine(
                    "GlobalInitializationOps.InitStatics( globalInitializer, \"" + service.Name +
                    "\" + \" Executable\", false, mainDataAccessStateGetter: () => dataAccessState.Value );");
                writer.WriteLine("}");

                writer.WriteLine("static partial void initGlobalInitializer( ref SystemInitializer globalInitializer );");

                writer.WriteLine("}");

                writer.WriteLine("[ RunInstaller( true ) ]");
                writer.WriteLine("public class Installer: System.Configuration.Install.Installer {");

                writer.WriteLine("public Installer() {");
                writer.WriteLine("Program.InitStatics();");
                writer.WriteLine("try {");
                writer.WriteLine("var code = GlobalInitializationOps.ExecuteAppWithStandardExceptionHandling( delegate {");
                writer.WriteLine("Installers.Add( WindowsServiceMethods.CreateServiceProcessInstaller() );");
                writer.WriteLine("Installers.Add( WindowsServiceMethods.CreateServiceInstaller( new " + service.Name.EnglishToPascal() + "() ) );");
                writer.WriteLine("} );");
                writer.WriteLine("if( code != 0 )");
                writer.WriteLine(
                    "throw new ApplicationException( \"Service installer objects could not be created. More information should be available in a separate error email from the service executable.\" );");
                writer.WriteLine("}");
                writer.WriteLine("finally {");
                writer.WriteLine("GlobalInitializationOps.CleanUpStatics();");
                writer.WriteLine("}");
                writer.WriteLine("}");

                writer.WriteLine("}");

                writer.WriteLine("internal partial class " + service.Name.EnglishToPascal() + ": WindowsServiceBase {");
                writer.WriteLine("internal " + service.Name.EnglishToPascal() + "() {}");
                writer.WriteLine("string WindowsServiceBase.Name { get { return \"" + service.Name + "\"; } }");
                writer.WriteLine("}");

                writer.WriteLine("}");
            }
        }
コード例 #15
0
        private void generateLibraryCode(DevelopmentInstallation installation)
        {
            var libraryGeneratedCodeFolderPath = EwlStatics.CombinePaths(installation.DevelopmentInstallationLogic.LibraryPath, "Generated Code");

            Directory.CreateDirectory(libraryGeneratedCodeFolderPath);
            var isuFilePath = EwlStatics.CombinePaths(libraryGeneratedCodeFolderPath, "ISU.cs");

            IoMethods.DeleteFile(isuFilePath);
            using (TextWriter writer = new StreamWriter(isuFilePath)) {
                // Don't add "using System" here. It will create a huge number of ReSharper warnings in the generated code file.
                writer.WriteLine("using System.Collections.Generic;");
                writer.WriteLine("using System.Data;");                   // Necessary for stored procedure logic
                writer.WriteLine("using System.Data.Common;");
                writer.WriteLine("using System.Diagnostics;");            // Necessary for ServerSideConsoleAppStatics
                writer.WriteLine("using System.Linq;");
                writer.WriteLine("using System.Reflection;");
                writer.WriteLine("using System.Runtime.InteropServices;");
                writer.WriteLine("using System.Web.UI;");
                writer.WriteLine("using System.Web.UI.WebControls;");
                writer.WriteLine("using EnterpriseWebLibrary;");
                writer.WriteLine("using EnterpriseWebLibrary.Caching;");
                writer.WriteLine("using EnterpriseWebLibrary.Collections;");                   // Necessary for row constants
                writer.WriteLine("using EnterpriseWebLibrary.Configuration;");
                writer.WriteLine("using EnterpriseWebLibrary.DataAccess;");
                writer.WriteLine("using EnterpriseWebLibrary.DataAccess.CommandWriting;");
                writer.WriteLine("using EnterpriseWebLibrary.DataAccess.CommandWriting.Commands;");
                writer.WriteLine("using EnterpriseWebLibrary.DataAccess.CommandWriting.InlineConditionAbstraction;");
                writer.WriteLine("using EnterpriseWebLibrary.DataAccess.CommandWriting.InlineConditionAbstraction.Conditions;");
                writer.WriteLine("using EnterpriseWebLibrary.DataAccess.RetrievalCaching;");
                writer.WriteLine("using EnterpriseWebLibrary.DataAccess.RevisionHistory;");
                writer.WriteLine("using EnterpriseWebLibrary.DataAccess.StandardModification;");
                writer.WriteLine("using EnterpriseWebLibrary.Email;");
                writer.WriteLine("using EnterpriseWebLibrary.EnterpriseWebFramework;");
                writer.WriteLine("using EnterpriseWebLibrary.EnterpriseWebFramework.Controls;");
                writer.WriteLine("using EnterpriseWebLibrary.InputValidation;");

                writer.WriteLine();
                writeAssemblyInfo(writer, installation, "Library");
                writer.WriteLine();
                var recognizedInstallation = installation as RecognizedDevelopmentInstallation;
                if (ConfigurationLogic.SystemProviderExists && !installation.DevelopmentInstallationLogic.SystemIsEwl &&
                    (recognizedInstallation == null || !recognizedInstallation.SystemIsEwlCacheCoordinator))
                {
                    generateGeneralProvider(writer, installation);
                }
                if (installation.ExistingInstallationLogic.RuntimeConfiguration.WebApplications.Any())
                {
                    writer.WriteLine();
                    writer.WriteLine("namespace " + installation.DevelopmentInstallationLogic.DevelopmentConfiguration.LibraryNamespaceAndAssemblyName + " {");
                    writer.WriteLine("public static class WebApplicationNames {");
                    foreach (var i in installation.ExistingInstallationLogic.RuntimeConfiguration.WebApplications)
                    {
                        writer.WriteLine("public const string {0} = \"{1}\";".FormatWith(EwlStatics.GetCSharpIdentifier(i.Name.EnglishToPascal()), i.Name));
                    }
                    writer.WriteLine("}");
                    writer.WriteLine("}");
                }
                writer.WriteLine();
                TypedCssClassStatics.Generate(
                    installation.GeneralLogic.Path,
                    installation.DevelopmentInstallationLogic.DevelopmentConfiguration.LibraryNamespaceAndAssemblyName,
                    writer);
                writer.WriteLine();
                generateServerSideConsoleAppStatics(writer, installation);
                generateDataAccessCode(writer, installation);

                var emailTemplateFolderPath = EwlStatics.CombinePaths(
                    InstallationFileStatics.GetGeneralFilesFolderPath(installation.GeneralLogic.Path, true),
                    InstallationFileStatics.FilesFolderName,
                    EmailTemplate.TemplateFolderName);
                if (Directory.Exists(emailTemplateFolderPath))
                {
                    writer.WriteLine();
                    writer.WriteLine("namespace " + installation.DevelopmentInstallationLogic.DevelopmentConfiguration.LibraryNamespaceAndAssemblyName + " {");
                    writer.WriteLine("public static class EmailTemplates {");
                    foreach (var i in IoMethods.GetFileNamesInFolder(emailTemplateFolderPath, searchPattern: "*.html"))
                    {
                        writer.WriteLine(
                            "public static readonly EmailTemplateName {0} = new EmailTemplateName( \"{1}\" );".FormatWith(
                                EwlStatics.GetCSharpIdentifier(Path.GetFileNameWithoutExtension(i).EnglishToPascal()),
                                i));
                    }
                    writer.WriteLine("}");
                    writer.WriteLine("}");
                }
            }
        }
コード例 #16
0
        private static void generateForFolder(
            TextWriter writer, string projectPath, string projectNamespace, bool projectContainsFramework, ImmutableHashSet <string> ignoredFolderPaths,
            string staticFilesFolderPath, string staticFilesFolderUrlParentExpression, string folderPathRelativeToProject)
        {
            if (ignoredFolderPaths.Contains(folderPathRelativeToProject))
            {
                return;
            }

            if (folderPathRelativeToProject == staticFilesFolderPath)
            {
                generateStaticFileLogic(
                    writer,
                    projectPath,
                    projectNamespace,
                    projectContainsFramework,
                    null,
                    folderPathRelativeToProject,
                    staticFilesFolderUrlParentExpression);
                return;
            }

            var folderPath = EwlStatics.CombinePaths(projectPath, folderPathRelativeToProject);

            // Generate code for the entity setup if one exists in this folder.
            var entitySetupFileName = "";

            foreach (var fileName in new[] { "EntitySetup.cs" })
            {
                if (File.Exists(EwlStatics.CombinePaths(folderPath, fileName)))
                {
                    entitySetupFileName = fileName;
                    break;
                }
            }
            EntitySetup entitySetup = null;

            if (entitySetupFileName.Length > 0)
            {
                var filePathRelativeToProject = Path.Combine(folderPathRelativeToProject, entitySetupFileName);
                entitySetup = new EntitySetup(projectContainsFramework, new WebItemGeneralData(projectPath, projectNamespace, filePathRelativeToProject, false));
                entitySetup.GenerateCode(writer);
            }

            if (legacyUrlStatics != null)
            {
                var files = new List <WebItemGeneralData>();
                foreach (var fileName in IoMethods.GetFileNamesInFolder(folderPath, searchPattern: "*.aspx").OrderBy(i => i))
                {
                    var filePath = EwlStatics.CombinePaths(projectPath, folderPathRelativeToProject, fileName);

                    var aspxLines = File.ReadAllLines(filePath);
                    if (aspxLines.Length != 1 || !Regex.IsMatch(aspxLines[0], "^<%@ .+ %>$"))
                    {
                        throw new Exception("Invalid ASPX file: \"{0}\"".FormatWith(EwlStatics.CombinePaths(folderPathRelativeToProject, fileName)));
                    }

                    var newCsLines = new List <string>();
                    var pageNeeded = true;
                    foreach (var line in File.ReadAllLines(EwlStatics.CombinePaths(projectPath, folderPathRelativeToProject, fileName + ".cs")))
                    {
                        if (pageNeeded && !line.StartsWith("using "))
                        {
                            newCsLines.Add("");
                            newCsLines.Add("// EwlPage");
                            pageNeeded = false;
                        }
                        newCsLines.Add(line.Replace(": EwfPage {", " {").Replace(": EwfPage,", ":"));
                    }
                    var newCsFilePath = EwlStatics.CombinePaths(folderPathRelativeToProject, Path.GetFileNameWithoutExtension(fileName) + ".cs");
                    File.WriteAllText(
                        EwlStatics.CombinePaths(projectPath, newCsFilePath),
                        newCsLines.Aggregate((text, line) => text + Environment.NewLine + line),
                        Encoding.UTF8);
                    files.Add(new WebItemGeneralData(projectPath, projectNamespace, newCsFilePath, false));

                    aspxFilePaths.Add(filePath);
                    aspxFilePaths.Add(filePath + ".cs");
                    aspxFilePaths.Add(filePath + ".designer.cs");
                }

                const string folderSetupClassName = "LegacyUrlFolderSetup";
                var          childPatterns        = files.Select(
                    file =>
                    "new UrlPattern( encoder => encoder is {0}.UrlEncoder ? EncodingUrlSegment.Create( {1} ) : null, url => string.Equals( url.Segment, {1}, StringComparison.OrdinalIgnoreCase ) ? new {0}.UrlDecoder() : null )"
                    .FormatWith(file.ClassName, "\"{0}.aspx\"".FormatWith(Path.GetFileNameWithoutExtension(file.FileName))))
                                                    .Concat(
                    IoMethods.GetFolderNamesInFolder(folderPath)
                    .Where(
                        subfolderName => {
                    var subfolderPath = EwlStatics.CombinePaths(folderPathRelativeToProject, subfolderName);
                    if (subfolderPath == "bin" || subfolderPath == "obj")
                    {
                        return(false);
                    }

                    bool folderContainsAspxFiles(string path) =>
                    IoMethods.GetFileNamesInFolder(path, searchPattern: "*.aspx").Any() || IoMethods.GetFolderNamesInFolder(path)
                    .Any(i => folderContainsAspxFiles(EwlStatics.CombinePaths(path, i)));
                    return(folderContainsAspxFiles(EwlStatics.CombinePaths(projectPath, subfolderPath)));
                })
                    .Select(
                        subfolderName => "{0}.{1}.UrlPatterns.Literal( \"{2}\" )".FormatWith(
                            WebItemGeneralData.GetNamespaceFromPath(projectNamespace, EwlStatics.CombinePaths(folderPathRelativeToProject, subfolderName), false)
                            .Separate(".", false)
                            .Last(),
                            folderSetupClassName,
                            subfolderName)))
                                                    .Materialize();

                if (folderPathRelativeToProject.Length == 0)
                {
                    legacyUrlStatics.AppendLine("using System;");
                    legacyUrlStatics.AppendLine("using System.Collections.Generic;");
                    legacyUrlStatics.AppendLine("using EnterpriseWebLibrary.EnterpriseWebFramework;");
                    legacyUrlStatics.AppendLine();
                    legacyUrlStatics.AppendLine("namespace {0} {{".FormatWith(projectNamespace));
                    legacyUrlStatics.AppendLine("internal static class LegacyUrlStatics {");
                    legacyUrlStatics.AppendLine("public static IReadOnlyCollection<UrlPattern> GetPatterns() {");
                    legacyUrlStatics.AppendLine("var patterns = new List<UrlPattern>();");
                    foreach (var i in childPatterns)
                    {
                        legacyUrlStatics.AppendLine("patterns.Add( {0} );".FormatWith(i));
                    }
                    legacyUrlStatics.AppendLine("return patterns;");
                    legacyUrlStatics.AppendLine("}");
                    legacyUrlStatics.AppendLine("public static UrlHandler GetParent() => new YourRootHandler();");
                    legacyUrlStatics.AppendLine("}");
                    legacyUrlStatics.Append("}");
                }
                else if (childPatterns.Any())
                {
                    var folderSetup = new StringBuilder();
                    folderSetup.AppendLine("using System;");
                    folderSetup.AppendLine("using System.Collections.Generic;");
                    folderSetup.AppendLine("using EnterpriseWebLibrary.EnterpriseWebFramework;");
                    folderSetup.AppendLine();
                    folderSetup.AppendLine("// EwlResource");
                    folderSetup.AppendLine();
                    var folderNamespace = WebItemGeneralData.GetNamespaceFromPath(projectNamespace, folderPathRelativeToProject, false);
                    folderSetup.AppendLine("namespace {0} {{".FormatWith(folderNamespace));
                    folderSetup.AppendLine("partial class {0} {{".FormatWith(folderSetupClassName));

                    var namespaces = folderNamespace.Substring(projectNamespace.Length + ".".Length).Separate(".", false);
                    folderSetup.AppendLine(
                        "protected override UrlHandler getUrlParent() => {0};".FormatWith(
                            namespaces.Count == 1
                                                                ? "LegacyUrlStatics.GetParent()"
                                                                : "new {0}.{1}()".FormatWith(namespaces[namespaces.Count - 2], folderSetupClassName)));

                    folderSetup.AppendLine("protected override ConnectionSecurity ConnectionSecurity => ConnectionSecurity.MatchingCurrentRequest;");

                    folderSetup.AppendLine("protected override IEnumerable<UrlPattern> getChildUrlPatterns() {");
                    folderSetup.AppendLine("var patterns = new List<UrlPattern>();");
                    foreach (var i in childPatterns)
                    {
                        folderSetup.AppendLine("patterns.Add( {0} );".FormatWith(i));
                    }
                    folderSetup.AppendLine("return patterns;");
                    folderSetup.AppendLine("}");

                    folderSetup.AppendLine("}");
                    folderSetup.Append("}");
                    Directory.CreateDirectory(EwlStatics.CombinePaths(projectPath, folderPathRelativeToProject, "Legacy URLs"));
                    File.WriteAllText(
                        EwlStatics.CombinePaths(projectPath, folderPathRelativeToProject, "Legacy URLs", "{0}.cs".FormatWith(folderSetupClassName)),
                        folderSetup.ToString(),
                        Encoding.UTF8);
                }

                foreach (var file in files)
                {
                    var parentCode = new StringBuilder();
                    parentCode.AppendLine();
                    parentCode.AppendLine();
                    parentCode.AppendLine("namespace {0} {{".FormatWith(file.Namespace));
                    parentCode.AppendLine("partial class {0} {{".FormatWith(file.ClassName));
                    parentCode.AppendLine(
                        "protected override UrlHandler getUrlParent() => {0};".FormatWith(
                            folderPathRelativeToProject.Length == 0 ? "LegacyUrlStatics.GetParent()" : "new {0}()".FormatWith(folderSetupClassName)));
                    parentCode.AppendLine("}");
                    parentCode.Append("}");
                    File.AppendAllText(EwlStatics.CombinePaths(projectPath, file.PathRelativeToProject), parentCode.ToString(), Encoding.UTF8);
                }
            }

            // Generate code for files in the current folder.
            foreach (var fileName in IoMethods.GetFileNamesInFolder(folderPath))
            {
                if (legacyUrlStatics != null &&
                    aspxFilePaths.Any(i => i.EqualsIgnoreCase(EwlStatics.CombinePaths(projectPath, folderPathRelativeToProject, fileName))))
                {
                    continue;
                }

                if (Path.GetExtension(fileName).ToLowerInvariant() != ".cs")
                {
                    continue;
                }
                var generalData = new WebItemGeneralData(projectPath, projectNamespace, EwlStatics.CombinePaths(folderPathRelativeToProject, fileName), false);
                if (!generalData.IsResource())
                {
                    continue;
                }
                new Resource(projectContainsFramework, generalData, entitySetup).GenerateCode(writer);
            }

            // Delve into sub folders.
            foreach (var subFolderName in IoMethods.GetFolderNamesInFolder(folderPath))
            {
                var subFolderPath = Path.Combine(folderPathRelativeToProject, subFolderName);
                if (subFolderPath == "bin" || subFolderPath == "obj")
                {
                    continue;
                }
                generateForFolder(
                    writer,
                    projectPath,
                    projectNamespace,
                    projectContainsFramework,
                    ignoredFolderPaths,
                    staticFilesFolderPath,
                    staticFilesFolderUrlParentExpression,
                    subFolderPath);
            }
        }
コード例 #17
0
        private void packageWebApps(DevelopmentInstallation installation, string serverSideLogicFolderPath)
        {
            // NOTE: When packaging web apps, try to find a way to exclude data files. Apparently web deployment projects include these in their output even though
            // they aren't part of the source web projects. NOTE ON NOTE: We don't use WDPs anymore, so maybe we can eliminate this note.
            foreach (var webProject in installation.DevelopmentInstallationLogic.DevelopmentConfiguration.webProjects ?? new WebProject[0])
            {
                var webAppPath = EwlStatics.CombinePaths(serverSideLogicFolderPath, webProject.name);

                // Pre-compile the web project.
                try {
                    TewlContrib.ProcessTools.RunProgram(
                        EwlStatics.CombinePaths(RuntimeEnvironment.GetRuntimeDirectory(), "aspnet_compiler"),
                        "-v \"/" + webProject.name + ".csproj\" -p \"" + EwlStatics.CombinePaths(installation.GeneralLogic.Path, webProject.name) + "\" " +
                        (webProject.IsUpdateableWhenInstalledSpecified && webProject.IsUpdateableWhenInstalled ? "-u " : "") + "-f \"" + webAppPath + "\"",
                        "",
                        true);
                }
                catch (Exception e) {
                    throw new UserCorrectableException("ASP.NET pre-compilation failed for web project " + webProject.name + ".", e);
                }
                try {
                    TewlContrib.ProcessTools.RunProgram(
                        EwlStatics.CombinePaths(AppStatics.DotNetToolsFolderPath, "aspnet_merge"),
                        "\"" + webAppPath + "\" -o " + webProject.NamespaceAndAssemblyName + ".Package -a -copyattrs",
                        "",
                        true);
                }
                catch (Exception e) {
                    throw new UserCorrectableException("ASP.NET Merge Tool failed for web project " + webProject.name + ".", e);
                }

                // Delete files and folders that aren't necessary for installed installations.
                IoMethods.DeleteFolder(EwlStatics.CombinePaths(webAppPath, "Generated Code"));
                IoMethods.DeleteFolder(EwlStatics.CombinePaths(webAppPath, "obj"));
                IoMethods.DeleteFile(EwlStatics.CombinePaths(webAppPath, webProject.name + ".csproj"));
                IoMethods.DeleteFile(EwlStatics.CombinePaths(webAppPath, webProject.name + ".csproj.user"));
                IoMethods.DeleteFile(EwlStatics.CombinePaths(webAppPath, webProject.name + ".csproj.vspscc"));

                var webConfigPath = EwlStatics.CombinePaths(webAppPath, WebApplication.WebConfigFileName);
                File.WriteAllText(webConfigPath, File.ReadAllText(webConfigPath).Replace("debug=\"true\"", "debug=\"false\""));
            }

            if (installation.DevelopmentInstallationLogic.SystemIsEwl)
            {
                IoMethods.CopyFolder(
                    EwlStatics.CombinePaths(installation.GeneralLogic.Path, EwlStatics.CoreProjectName, StaticFile.FrameworkStaticFilesSourceFolderPath),
                    EwlStatics.CombinePaths(serverSideLogicFolderPath, InstallationFileStatics.WebFrameworkStaticFilesFolderName),
                    false);
                IoMethods.DeleteFolder(
                    EwlStatics.CombinePaths(
                        serverSideLogicFolderPath,
                        InstallationFileStatics.WebFrameworkStaticFilesFolderName,
                        AppStatics.StaticFileLogicFolderName));
            }
            else
            {
                var frameworkStaticFilesFolderPath = EwlStatics.CombinePaths(
                    installation.GeneralLogic.Path,
                    InstallationFileStatics.WebFrameworkStaticFilesFolderName);
                if (Directory.Exists(frameworkStaticFilesFolderPath))
                {
                    IoMethods.CopyFolder(
                        frameworkStaticFilesFolderPath,
                        EwlStatics.CombinePaths(serverSideLogicFolderPath, InstallationFileStatics.WebFrameworkStaticFilesFolderName),
                        false);
                }
            }
        }
コード例 #18
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);
        }
コード例 #19
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));
            }
        }
コード例 #20
0
        private static void generateCodeForWebItemsInFolder(
            TextWriter writer, string webProjectPath, string folderPathRelativeToProject, WebProject webProjectConfiguration)
        {
            var folderPath = EwlStatics.CombinePaths(webProjectPath, folderPathRelativeToProject);

            // Generate code for the entity setup if one exists in this folder.
            var entitySetupFileName = "";

            foreach (var fileName in new[] { "EntitySetup.ascx", "EntitySetup.cs" })
            {
                if (File.Exists(EwlStatics.CombinePaths(folderPath, fileName)))
                {
                    entitySetupFileName = fileName;
                    break;
                }
            }
            EntitySetup entitySetup = null;

            if (entitySetupFileName.Length > 0)
            {
                var filePathRelativeToProject = Path.Combine(folderPathRelativeToProject, entitySetupFileName);
                entitySetup = new EntitySetup(new WebItemGeneralData(webProjectPath, filePathRelativeToProject, false, webProjectConfiguration));
                entitySetup.GenerateCode(writer);
            }

            // Generate code for files in the current folder.
            foreach (var fileName in IoMethods.GetFileNamesInFolder(folderPath))
            {
                if (!folderPathRelativeToProject.Any() && (fileName.Contains(".csproj") || fileName == AppStatics.StandardLibraryFilesFileName))
                {
                    continue;
                }
                var fileExtension = Path.GetExtension(fileName).ToLowerInvariant();
                if (new[] { ".cs", ".asax", ".master", ".config", ".svc" }.Contains(fileExtension))
                {
                    continue;
                }

                var filePathRelativeToProject = Path.Combine(folderPathRelativeToProject, fileName);
                if (fileExtension == ".aspx")
                {
                    new Page(new WebItemGeneralData(webProjectPath, filePathRelativeToProject, false, webProjectConfiguration), entitySetup).GenerateCode(writer);
                }
                else if (fileExtension == ".ascx")
                {
                    if (fileName != entitySetupFileName)
                    {
                        new UserControl(new WebItemGeneralData(webProjectPath, filePathRelativeToProject, false, webProjectConfiguration)).GenerateCode(writer);
                    }
                }
                else
                {
                    new StaticFile(new WebItemGeneralData(webProjectPath, filePathRelativeToProject, true, webProjectConfiguration)).GenerateCode(writer);
                }
            }

            // Delve into sub folders.
            foreach (var subFolderName in IoMethods.GetFolderNamesInFolder(folderPath))
            {
                var subFolderPath = Path.Combine(folderPathRelativeToProject, subFolderName);
                if (subFolderPath == "bin" || subFolderPath == "obj")
                {
                    continue;
                }
                generateCodeForWebItemsInFolder(writer, webProjectPath, subFolderPath, webProjectConfiguration);
            }
        }
コード例 #21
0
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            var url = EwfApp.GetRequestAppRelativeUrl(context.Request);

            var queryIndex = url.IndexOf("?", StringComparison.Ordinal);

            if (queryIndex >= 0)
            {
                url = url.Remove(queryIndex);
            }

            var extensionIndex = url.LastIndexOf(".", StringComparison.Ordinal);

            var versionStringOrFileExtensionIndex = extensionIndex;
            var urlVersionString = "";

            if (url.StartsWith(VersionedFilesFolderName + "/") || url.StartsWith(EwfFolderName + "/" + VersionedFilesFolderName + "/"))
            {
                urlVersionString = "invariant";
            }
            else
            {
                // We assume that all URL version strings will have the same length as the format string.
                var prefixedVersionStringIndex = extensionIndex - (urlVersionStringPrefix.Length + EwfSafeResponseWriter.UrlVersionStringFormat.Length);

                if (prefixedVersionStringIndex >= 0)
                {
                    DateTimeOffset dateAndTime;
                    var            versionString = url.Substring(prefixedVersionStringIndex + urlVersionStringPrefix.Length, EwfSafeResponseWriter.UrlVersionStringFormat.Length);
                    if (DateTimeOffset.TryParseExact(
                            versionString,
                            EwfSafeResponseWriter.UrlVersionStringFormat,
                            DateTimeFormatInfo.InvariantInfo,
                            DateTimeStyles.None,
                            out dateAndTime))
                    {
                        versionStringOrFileExtensionIndex = prefixedVersionStringIndex;
                        urlVersionString = versionString;
                    }
                }
            }

            if (versionStringOrFileExtensionIndex < 0)
            {
                throw new ResourceNotAvailableException("Failed to find the extension in the URL.", null);
            }
            var extension      = url.Substring(extensionIndex);
            var staticFileInfo =
                EwfApp.GlobalType.Assembly.CreateInstance(
                    CombineNamespacesAndProcessEwfIfNecessary(
                        EwfApp.GlobalType.Namespace,
                        (url.Remove(versionStringOrFileExtensionIndex) + extension.CapitalizeString()).Separate("/", false)
                        .Select(StandardLibraryMethods.GetCSharpIdentifier)
                        .Aggregate((a, b) => a + "." + b) + "+Info")) as StaticFileInfo;

            if (staticFileInfo == null)
            {
                throw new ResourceNotAvailableException("Failed to create an Info object for the request.", null);
            }

            var mediaTypeOverride = EwfApp.Instance.GetMediaTypeOverrides().SingleOrDefault(i => i.FileExtension == extension);
            var contentType       = mediaTypeOverride != null ? mediaTypeOverride.MediaType : MimeTypeMap.MimeTypeMap.GetMimeType(extension);

            Func <string>         cacheKeyGetter = () => staticFileInfo.GetUrl(false, false, false);
            EwfSafeResponseWriter responseWriter;

            if (contentType == ContentTypes.Css)
            {
                Func <string> cssGetter = () => File.ReadAllText(staticFileInfo.FilePath);
                responseWriter = urlVersionString.Any()
                                                         ? new EwfSafeResponseWriter(
                    cssGetter,
                    urlVersionString,
                    () => new ResponseMemoryCachingSetup(cacheKeyGetter(), staticFileInfo.GetResourceLastModificationDateAndTime()))
                                                         : new EwfSafeResponseWriter(
                    () => new EwfResponse(ContentTypes.Css, new EwfResponseBodyCreator(() => CssPreprocessor.TransformCssFile(cssGetter()))),
                    staticFileInfo.GetResourceLastModificationDateAndTime(),
                    memoryCacheKeyGetter: cacheKeyGetter);
            }
            else
            {
                Func <EwfResponse> responseCreator = () => new EwfResponse(
                    contentType,
                    new EwfResponseBodyCreator(
                        responseStream => {
                    using (var fileStream = File.OpenRead(staticFileInfo.FilePath))
                        IoMethods.CopyStream(fileStream, responseStream);
                }));
                responseWriter = urlVersionString.Any()
                                                         ? new EwfSafeResponseWriter(
                    responseCreator,
                    urlVersionString,
                    memoryCachingSetupGetter:
                    () => new ResponseMemoryCachingSetup(cacheKeyGetter(), staticFileInfo.GetResourceLastModificationDateAndTime()))
                                                         : new EwfSafeResponseWriter(
                    responseCreator,
                    staticFileInfo.GetResourceLastModificationDateAndTime(),
                    memoryCacheKeyGetter: cacheKeyGetter);
            }
            responseWriter.WriteResponse();
        }
コード例 #22
0
        private static int Main(string[] args)
        {
            GlobalInitializationOps.InitStatics(new GlobalInitializer(), "Development Utility", true);
            try {
                return(GlobalInitializationOps.ExecuteAppWithStandardExceptionHandling(
                           () => {
                    try {
                        AppStatics.Init();

                        if (args.Length < 2)
                        {
                            throw new UserCorrectableException("You must specify the installation path as the first argument and the operation name as the second.");
                        }

                        // Create installations folder from template if necessary.
                        var installationPath = args[0];
                        var templateFolderPath = getInstallationsFolderPath(installationPath, true);
                        var message = "";
                        if (!Directory.Exists(templateFolderPath))
                        {
                            message = "No installation-configuration template exists.";
                        }
                        else
                        {
                            var configurationFolderPath = getInstallationsFolderPath(installationPath, false);
                            if (IoMethods.GetFilePathsInFolder(configurationFolderPath, searchOption: SearchOption.AllDirectories).Any())
                            {
                                message = "Installation configuration already exists.";
                            }
                            else
                            {
                                IoMethods.CopyFolder(templateFolderPath, configurationFolderPath, false);
                                Console.WriteLine("Created installation configuration from template.");
                            }
                        }

                        if (args[1] == "CreateInstallationConfiguration")
                        {
                            if (message.Any())
                            {
                                throw new UserCorrectableException(message);
                            }
                            return;
                        }

                        // Get installation.
                        DevelopmentInstallation installation;
                        try {
                            installation = getInstallation(installationPath);
                        }
                        catch (Exception e) {
                            throw new UserCorrectableException("The installation at \"" + installationPath + "\" is invalid.", e);
                        }

                        // Get operation.
                        var operations = AssemblyTools.BuildSingletonDictionary <Operation, string>(Assembly.GetExecutingAssembly(), i => i.GetType().Name);
                        var operationName = args[1];
                        if (!operations.ContainsKey(operationName))
                        {
                            throw new UserCorrectableException(operationName + " is not a known operation.");
                        }
                        var operation = operations[operationName];

                        if (!operation.IsValid(installation))
                        {
                            throw new UserCorrectableException("The " + operation.GetType().Name + " operation cannot be performed on this installation.");
                        }
                        operation.Execute(installation, args.Skip(2).ToImmutableArray(), new OperationResult());
                    }
                    catch (Exception e) {
                        Output.WriteTimeStampedError(e.ToString());
                        if (e is UserCorrectableException)
                        {
                            throw new DoNotEmailOrLogException();
                        }
                        throw;
                    }
                }));
            }
            finally {
                GlobalInitializationOps.CleanUpStatics();
            }
        }
コード例 #23
0
        internal static void Test()
        {
            const string outputFolderName = "MergeOps";
            var          outputFolder     = StandardLibraryMethods.CombinePaths(TestStatics.OutputFolderPath, outputFolderName);

            IoMethods.DeleteFolder(outputFolder);
            Directory.CreateDirectory(outputFolder);

            var inputTestFiles = StandardLibraryMethods.CombinePaths(TestStatics.InputTestFilesFolderPath, outputFolderName);
            var wordDocx       = StandardLibraryMethods.CombinePaths(inputTestFiles, "word.docx");
            var pdf            = StandardLibraryMethods.CombinePaths(inputTestFiles, "pdf.pdf");

            MergeStatics.Init();
            var singleTestRow      = new PseudoTableRow(1).ToSingleElementArray();
            var testRows           = new[] { new PseudoTableRow(1), new PseudoTableRow(2), new PseudoTableRow(3) };
            var singleRowTree      = MergeStatics.CreatePseudoTableRowTree(singleTestRow);
            var pseudoTableRowTree = MergeStatics.CreatePseudoTableRowTree(testRows);

            var explanations = new List <Tuple <String, String> >();

            // Single row to merge against

            // Word files

            const string singleRowWordDoc = "SingleRowMsWordDoc" + FileExtensions.WordDocx;

            using (var outputFile = File.OpenWrite(StandardLibraryMethods.CombinePaths(outputFolder, singleRowWordDoc))) {
                using (var word = File.OpenRead(wordDocx))
                    CreateMsWordDoc(singleRowTree, false, word, outputFile);
                explanations.Add(Tuple.Create(singleRowWordDoc, "Should be {0} with only one page, and FullName merged in the upper left.".FormatWith(wordDocx)));
            }

            const string singleRowWordDocAsPdf = "SingleRowMsWordDoc" + FileExtensions.Pdf;

            using (var outputFile = File.OpenWrite(StandardLibraryMethods.CombinePaths(outputFolder, singleRowWordDocAsPdf)))
                CreatePdfFromMsWordDoc(singleRowTree, false, wordDocx, outputFile);
            explanations.Add(
                Tuple.Create(singleRowWordDocAsPdf, "Should be {0} with only one page, FullName merged in the upper left, saved as a PDF.".FormatWith(wordDocx)));

            //Excel
            const string singleRowExcel = "SingleRowExcel" + FileExtensions.ExcelXlsx;

            using (var outputFile = File.OpenWrite(StandardLibraryMethods.CombinePaths(outputFolder, singleRowExcel)))
                CreateExcelWorkbook(singleRowTree, GetExcelSupportedMergeFields(singleRowTree), outputFile);
            explanations.Add(
                Tuple.Create(
                    singleRowExcel,
                    "An Excel file with the first row frozen and bold with the merge field names. Note that only supported field types may be dispalyed. One more row with data should be present."));

            // Pdf
            const string singleRowPdf = "SingleRowPdf" + FileExtensions.Pdf;

            using (var outputFile = File.OpenWrite(StandardLibraryMethods.CombinePaths(outputFolder, singleRowPdf)))
                CreatePdf(singleRowTree, false, pdf, outputFile);
            explanations.Add(Tuple.Create(singleRowPdf, "Should be {0} with only one page, FullName filled in and 'Test' displayed.".FormatWith(pdf)));

            // Multiple rows to merge against

            // Word files
            const string multipleRowsWordDoc = "MultipleRowMsWordDoc" + FileExtensions.WordDocx;

            using (var outputFile = File.OpenWrite(StandardLibraryMethods.CombinePaths(outputFolder, multipleRowsWordDoc))) {
                using (var word = File.OpenRead(wordDocx))
                    CreateMsWordDoc(pseudoTableRowTree, false, word, outputFile);
                explanations.Add(Tuple.Create(multipleRowsWordDoc, "Should be {0} with three pages, and FullName merged in the upper left.".FormatWith(wordDocx)));
            }

            const string multipleRowsWordDocAsPdf = "MultipleRowMsWordDoc" + FileExtensions.Pdf;

            using (var outputFile = File.OpenWrite(StandardLibraryMethods.CombinePaths(outputFolder, multipleRowsWordDocAsPdf)))
                CreatePdfFromMsWordDoc(pseudoTableRowTree, false, wordDocx, outputFile);
            explanations.Add(
                Tuple.Create(multipleRowsWordDocAsPdf, "Should be {0} with three pages, FullName merged in the upper left, saved as a PDF.".FormatWith(wordDocx)));

            // Excel
            const string multipleRowExcel = "MultipleRowExcel" + FileExtensions.ExcelXlsx;

            using (var outputFile = File.OpenWrite(StandardLibraryMethods.CombinePaths(outputFolder, multipleRowExcel)))
                CreateExcelWorkbook(pseudoTableRowTree, GetExcelSupportedMergeFields(pseudoTableRowTree), outputFile);
            explanations.Add(
                Tuple.Create(
                    multipleRowExcel,
                    "An Excel file with the first row frozen and bold with the merge field names. Note that only supported field types may be dispalyed. Three more row with data should be present."));

            // Pdf
            const string multipleRowPdf = "MultipleRowPdf" + FileExtensions.Pdf;

            using (var outputFile = File.OpenWrite(StandardLibraryMethods.CombinePaths(outputFolder, multipleRowPdf)))
                CreatePdf(pseudoTableRowTree, false, pdf, outputFile);
            explanations.Add(Tuple.Create(multipleRowPdf, "Should be {0} with three pages, FullName filled in and 'Test' displayed.".FormatWith(pdf)));

            TestStatics.OutputReadme(outputFolder, explanations);
        }
コード例 #24
0
        private static void generateStaticFileLogic(
            TextWriter writer, string projectPath, string projectNamespace, bool inFramework, bool?inVersionedFolder, string folderPathRelativeToProject,
            string folderParentExpression)
        {
            var isRootFolder = !inVersionedFolder.HasValue;
            var folderPath   = EwlStatics.CombinePaths(projectPath, folderPathRelativeToProject);

            var          folderNamespace      = WebItemGeneralData.GetNamespaceFromPath(projectNamespace, folderPathRelativeToProject, false);
            const string folderSetupClassName = "FolderSetup";
            var          files = IoMethods.GetFileNamesInFolder(folderPath)
                                 .Select(i => new WebItemGeneralData(projectPath, projectNamespace, EwlStatics.CombinePaths(folderPathRelativeToProject, i), true))
                                 .Materialize();
            var subfolderNames = IoMethods.GetFolderNamesInFolder(folderPath)
                                 .Where(i => !isRootFolder || i != AppStatics.StaticFileLogicFolderName)
                                 .Materialize();

            generateStaticFileFolderSetup(
                writer,
                inFramework,
                isRootFolder,
                folderPathRelativeToProject,
                folderNamespace,
                folderSetupClassName,
                folderParentExpression,
                files.Select(i => "{0}.UrlPatterns.Literal( \"{1}\" )".FormatWith(i.ClassName, i.FileName))
                .Concat(
                    subfolderNames.Select(
                        subfolderName => "{0}.{1}.UrlPatterns.Literal( \"{2}\" )".FormatWith(
                            WebItemGeneralData.GetNamespaceFromPath(projectNamespace, EwlStatics.CombinePaths(folderPathRelativeToProject, subfolderName), false)
                            .Separate(".", false)
                            .Last(),
                            folderSetupClassName,
                            subfolderName)))
                .Materialize());

            foreach (var file in files)
            {
                new StaticFile(file, inFramework, inVersionedFolder == true, folderSetupClassName).GenerateCode(writer);
            }

            var staticFilesFolderPath = inFramework
                                                            ? EnterpriseWebFramework.StaticFile.FrameworkStaticFilesSourceFolderPath
                                                            : EnterpriseWebFramework.StaticFile.AppStaticFilesFolderName;
            var logicFolderPath = EwlStatics.CombinePaths(
                projectPath,
                staticFilesFolderPath,
                AppStatics.StaticFileLogicFolderName,
                folderPathRelativeToProject.Substring((staticFilesFolderPath + (isRootFolder ? "" : Path.DirectorySeparatorChar.ToString())).Length));

            Directory.CreateDirectory(logicFolderPath);
            createStaticFileLogicTemplate(logicFolderPath, folderNamespace, folderSetupClassName);
            foreach (var i in files)
            {
                createStaticFileLogicTemplate(logicFolderPath, i.Namespace, i.ClassName);
            }

            foreach (var subfolderName in subfolderNames)
            {
                generateStaticFileLogic(
                    writer,
                    projectPath,
                    projectNamespace,
                    inFramework,
                    inVersionedFolder ?? subfolderName == "versioned",
                    EwlStatics.CombinePaths(folderPathRelativeToProject, subfolderName),
                    "new {0}.{1}()".FormatWith(folderNamespace.Separate(".", false).Last(), folderSetupClassName));
            }
        }