Esempio n. 1
0
        private static void writeNuGetPackageManifest(DevelopmentInstallation installation, bool prerelease, DateTime localExportDateAndTime, TextWriter writer)
        {
            writer.WriteLine("<?xml version=\"1.0\"?>");
            writer.WriteLine("<package>");
            writer.WriteLine("<metadata>");
            writer.WriteLine(
                "<id>" + EwlNuGetPackageSpecificationStatics.GetNuGetPackageId(installation.ExistingInstallationLogic.RuntimeConfiguration.SystemShortName) + "</id>");
            writer.WriteLine(
                "<version>" + EwlNuGetPackageSpecificationStatics.GetNuGetPackageVersionString(prerelease, localExportDateAndTime: localExportDateAndTime) +
                "</version>");
            writer.WriteLine("<title>" + installation.ExistingInstallationLogic.RuntimeConfiguration.SystemName + "</title>");
            writer.WriteLine("<authors>William Gross, Greg Smalter, Sam Rueby</authors>");
            writer.WriteLine(
                "<description>The Enterprise Web Library (EWL) is an extremely opinionated library for web applications that trades off performance, scalability, and development flexibility for an ease of maintenance you won't find anywhere else.</description>");
            writer.WriteLine("<projectUrl>http://enterpriseweblibrary.org</projectUrl>");
            writer.WriteLine("<licenseUrl>http://opensource.org/licenses/MIT</licenseUrl>");
            writer.WriteLine("<requireLicenseAcceptance>false</requireLicenseAcceptance>");
            writer.WriteLine("<dependencies>");

            var lines = from line in File.ReadAllLines(StandardLibraryMethods.CombinePaths(installation.GeneralLogic.Path, @"Standard Library\packages.config"))
                        let trimmedLine = line.Trim()
                                          where trimmedLine.StartsWith("<package ")
                                          select trimmedLine;

            foreach (var line in lines)
            {
                writer.WriteLine(line.Replace("package", "dependency").Replace(" targetFramework=\"net451\"", ""));
            }

            writer.WriteLine("</dependencies>");
            writer.WriteLine("<tags>C# ASP.NET DAL SQL-Server MySQL Oracle</tags>");
            writer.WriteLine("</metadata>");
            writer.WriteLine("</package>");
        }
Esempio n. 2
0
        private void copyInWebProjectFiles(Installation installation, WebProject webProject)
        {
            var webProjectFilesFolderPath = StandardLibraryMethods.CombinePaths(AppTools.InstallationPath, AppStatics.WebProjectFilesFolderName);
            var webProjectPath            = StandardLibraryMethods.CombinePaths(installation.GeneralLogic.Path, webProject.name);

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

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

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

            IoMethods.CopyFile(
                StandardLibraryMethods.CombinePaths(webProjectFilesFolderPath, AppStatics.StandardLibraryFilesFileName),
                StandardLibraryMethods.CombinePaths(webProjectPath, AppStatics.StandardLibraryFilesFileName));
            IoMethods.RecursivelyRemoveReadOnlyAttributeFromItem(StandardLibraryMethods.CombinePaths(webProjectPath, AppStatics.StandardLibraryFilesFileName));
        }
Esempio n. 3
0
        void Database.DeleteAndReCreateFromFile(string filePath, bool keepDbInStandbyMode)
        {
            using (var sw = new StringWriter()) {
                sw.WriteLine("DROP DATABASE IF EXISTS {0};".FormatWith(info.Database));
                sw.WriteLine("CREATE DATABASE {0};".FormatWith(info.Database));
                sw.WriteLine("use {0}".FormatWith(info.Database));
                sw.Write(File.ReadAllText(filePath));
                sw.WriteLine("quit");

                executeMethodWithDbExceptionHandling(
                    delegate {
                    try {
                        StandardLibraryMethods.RunProgram(
                            StandardLibraryMethods.CombinePaths(binFolderPath, "mysql"),
                            getHostAndAuthenticationArguments() + " --disable-reconnect --batch --disable-auto-rehash",
                            sw.ToString(),
                            true);
                    }
                    catch (Exception e) {
                        if (e.Message.Contains("ERROR") && e.Message.Contains("at line"))
                        {
                            throw new UserCorrectableException("Failed to create database from file. Please try the operation again after obtaining a new database file.", e);
                        }
                        throw DataAccessMethods.CreateDbConnectionException(info, "re-creating (from file)", e);
                    }
                });
            }
        }
        private static void packageGeneralFiles(DevelopmentInstallation installation, string folderPath, bool includeDatabaseUpdates)
        {
            // configuration files
            var configurationFolderPath = StandardLibraryMethods.CombinePaths(folderPath, InstallationConfiguration.ConfigurationFolderName);

            IoMethods.CopyFolder(installation.ExistingInstallationLogic.RuntimeConfiguration.ConfigurationFolderPath, configurationFolderPath, false);
            IoMethods.RecursivelyRemoveReadOnlyAttributeFromItem(configurationFolderPath);
            IoMethods.DeleteFolder(StandardLibraryMethods.CombinePaths(configurationFolderPath, InstallationConfiguration.InstallationConfigurationFolderName));
            IoMethods.DeleteFolder(StandardLibraryMethods.CombinePaths(configurationFolderPath, ConfigurationStatics.ProvidersFolderAndNamespaceName));
            if (!includeDatabaseUpdates)
            {
                IoMethods.DeleteFile(StandardLibraryMethods.CombinePaths(configurationFolderPath, ExistingInstallationLogic.SystemDatabaseUpdatesFileName));
            }
            IoMethods.DeleteFile(StandardLibraryMethods.CombinePaths(configurationFolderPath, InstallationConfiguration.SystemDevelopmentConfigurationFileName));
            IoMethods.DeleteFolder(StandardLibraryMethods.CombinePaths(configurationFolderPath, ".hg"));                          // EWL uses a nested repository for configuration.
            IoMethods.DeleteFile(StandardLibraryMethods.CombinePaths(configurationFolderPath, "Update All Dependent Logic.bat")); // EWL has this file.

            // other files
            var filesFolderInInstallationPath =
                StandardLibraryMethods.CombinePaths(
                    InstallationFileStatics.GetGeneralFilesFolderPath(installation.GeneralLogic.Path, true),
                    InstallationFileStatics.FilesFolderName);

            if (Directory.Exists(filesFolderInInstallationPath))
            {
                IoMethods.CopyFolder(filesFolderInInstallationPath, StandardLibraryMethods.CombinePaths(folderPath, InstallationFileStatics.FilesFolderName), false);
            }
        }
 private void copyServerSideProject(DevelopmentInstallation installation, string serverSideLogicFolderPath, string project)
 {
     IoMethods.CopyFolder(
         StandardLibraryMethods.CombinePaths(installation.GeneralLogic.Path, project, StandardLibraryMethods.GetProjectOutputFolderPath(false)),
         StandardLibraryMethods.CombinePaths(serverSideLogicFolderPath, project),
         false);
 }
        internal static byte[] CreateEwlNuGetPackage(DevelopmentInstallation installation, bool useDebugAssembly, string outputFolderPath, bool?prerelease)
        {
            var localExportDateAndTime = prerelease.HasValue ? null as DateTime? : DateTime.Now;

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

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

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

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

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

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

            return
                (File.ReadAllBytes(StandardLibraryMethods.CombinePaths(outputFolderPath,
                                                                       EwlNuGetPackageSpecificationStatics.GetNuGetPackageFileName(installation.ExistingInstallationLogic.RuntimeConfiguration.SystemShortName,
                                                                                                                                   installation.CurrentMajorVersion,
                                                                                                                                   !prerelease.HasValue || prerelease.Value ? installation.NextBuildNumber as int? : null,
                                                                                                                                   localExportDateAndTime: localExportDateAndTime))));
        }
Esempio n. 7
0
        void Database.ExportToFile(string filePath)
        {
            Directory.CreateDirectory(dataPumpFolderPath);
            try {
                executeMethodWithDbExceptionHandling(
                    delegate {
                    try {
                        // We pass an enter keystroke as input in an attempt to kill the program if it gets stuck on a username prompt because of a bad logon string.
                        StandardLibraryMethods.RunProgram(
                            "expdp",
                            getLogonString() + " DIRECTORY=" + dataPumpOracleDirectoryName + " DUMPFILE=\"\"\"" + getDumpFileName() + "\"\"\" NOLOGFILE=y VERSION=12.1",
                            Environment.NewLine,
                            true);
                    }
                    catch (Exception e) {
                        throwUserCorrectableExceptionIfNecessary(e);
                        throw DataAccessMethods.CreateDbConnectionException(info, "exporting (to file)", e);
                    }
                });

                IoMethods.ExecuteWithTempFolder(
                    folderPath => {
                    IoMethods.CopyFile(getDumpFilePath(), StandardLibraryMethods.CombinePaths(folderPath, databaseFileDumpFileName));
                    File.WriteAllText(StandardLibraryMethods.CombinePaths(folderPath, databaseFileSchemaNameFileName), info.UserAndSchema);
                    ZipOps.ZipFolderAsFile(folderPath, filePath);
                });
            }
            finally {
                IoMethods.DeleteFile(getDumpFilePath());
            }
        }
 private static IEnumerable <string> getAssemblyPaths(DevelopmentInstallation installation, bool debug)
 {
     return(StandardLibraryMethods.CombinePaths(installation.DevelopmentInstallationLogic.LibraryPath,
                                                StandardLibraryMethods.GetProjectOutputFolderPath(debug),
                                                installation.DevelopmentInstallationLogic.DevelopmentConfiguration.LibraryNamespaceAndAssemblyName + ".dll")
            .ToSingleElementArray()
            .Concat(from i in installation.DevelopmentInstallationLogic.DevelopmentConfiguration.webProjects ?? new WebProject[0]
                    select StandardLibraryMethods.CombinePaths(installation.GeneralLogic.Path, i.name, "bin", i.NamespaceAndAssemblyName + ".dll"))
            .Concat(from i in installation.ExistingInstallationLogic.RuntimeConfiguration.WindowsServices
                    select
                    StandardLibraryMethods.CombinePaths(installation.ExistingInstallationLogic.GetWindowsServiceFolderPath(i, debug),
                                                        i.NamespaceAndAssemblyName + ".exe"))
            .Concat(from i in installation.DevelopmentInstallationLogic.DevelopmentConfiguration.ServerSideConsoleProjectsNonNullable
                    select
                    StandardLibraryMethods.CombinePaths(installation.GeneralLogic.Path,
                                                        i.Name,
                                                        StandardLibraryMethods.GetProjectOutputFolderPath(debug),
                                                        i.NamespaceAndAssemblyName + ".exe"))
            .Concat(installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject != null
                                          ? StandardLibraryMethods.CombinePaths(installation.GeneralLogic.Path,
                                                                                installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject.name,
                                                                                StandardLibraryMethods.GetProjectOutputFolderPath(debug),
                                                                                installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject.assemblyName + ".exe").ToSingleElementArray()
                                          : new string[0]));
 }
Esempio n. 9
0
        private void generateWebConfigAndCodeForWebProject(DevelopmentInstallation installation, WebProject webProject)
        {
            var webProjectPath = StandardLibraryMethods.CombinePaths(installation.GeneralLogic.Path, webProject.name);

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

            var webProjectGeneratedCodeFolderPath = StandardLibraryMethods.CombinePaths(webProjectPath, "Generated Code");

            Directory.CreateDirectory(webProjectGeneratedCodeFolderPath);
            var webProjectIsuFilePath = StandardLibraryMethods.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 RedStapler.StandardLibrary;");
                writer.WriteLine("using RedStapler.StandardLibrary.DataAccess;");
                writer.WriteLine("using RedStapler.StandardLibrary.EnterpriseWebFramework;");
                writer.WriteLine("using RedStapler.StandardLibrary.EnterpriseWebFramework.Controls;");
                writer.WriteLine("using RedStapler.StandardLibrary.Validation;");
                writer.WriteLine();
                writeAssemblyInfo(writer, installation, webProject.name);
                writer.WriteLine();
                CodeGeneration.WebMetaLogic.WebMetaLogicStatics.Generate(writer, webProjectPath, webProject);
            }
        }
        internal static void GenerateWebConfig(WebProject webProject, string webProjectPath)
        {
            var sections = new XmlDocument {
                PreserveWhitespace = true
            };

            using (var reader = new StringReader(getSectionString(webProject)))
                sections.Load(reader);

            if (!File.Exists(StandardLibraryMethods.CombinePaths(webProjectPath, "Web.config")))
            {
                throw new UserCorrectableException("The Web.config file is missing.");
            }
            var webConfig = new XmlDocument {
                PreserveWhitespace = true
            };

            webConfig.Load(StandardLibraryMethods.CombinePaths(webProjectPath, "Web.config"));

            replaceSection(sections, webConfig, "appSettings");
            replaceSection(sections, webConfig, "system.web");
            replaceSection(sections, webConfig, "system.webServer");

            try {
                webConfig.Save(StandardLibraryMethods.CombinePaths(webProjectPath, "Web.config"));
            }
            catch (Exception e) {
                const string message = "Failed to write web configuration file.";
                if (e is UnauthorizedAccessException)
                {
                    throw new UserCorrectableException(message, e);
                }
                throw new ApplicationException(message, e);
            }
        }
        internal WebItemGeneralData(string webProjectPath, string pathRelativeToProject, bool includeFileExtensionInClassName, WebProject webProjectConfiguration)
        {
            this.pathRelativeToProject = pathRelativeToProject;

            // Get the URL for this item. "Plain old class" entity setups do not have URLs.
            urlRelativeToProject = pathRelativeToProject.EndsWith(".cs") ? "" : pathRelativeToProject.Replace(System.IO.Path.DirectorySeparatorChar, '/');

            // Load this item's code if it exists.
            path = StandardLibraryMethods.CombinePaths(webProjectPath, pathRelativeToProject);
            var codePath = path.EndsWith(".cs") ? path : path + ".cs";

            code = File.Exists(codePath) ? File.ReadAllText(codePath) : "";

            // Attempt to get the namespace from the code. If this fails, use a namespace based on the item's path in the project.
            foreach (Match match in Regex.Matches(code, @"namespace\s(?<namespace>.*)\s{"))
            {
                itemNamespace = match.Groups["namespace"].Value;
            }
            if (itemNamespace == null)
            {
                itemNamespace = getNamespaceFromFilePath(webProjectConfiguration.NamespaceAndAssemblyName, pathRelativeToProject);
            }

            className =
                StandardLibraryMethods.GetCSharpIdentifier(
                    System.IO.Path.GetFileNameWithoutExtension(path) + (includeFileExtensionInClassName ? System.IO.Path.GetExtension(path).CapitalizeString() : ""));
            this.webProjectConfiguration = webProjectConfiguration;
        }
Esempio n. 12
0
 /// <summary>
 /// Internal and Red Stapler Information System use only.
 /// </summary>
 public static string GetGeneralFilesFolderPath(string installationPath, bool isDevelopmentInstallation)
 {
     if (isDevelopmentInstallation)
     {
         return(StandardLibraryMethods.CombinePaths(installationPath, "Library"));
     }
     return(installationPath);
 }
Esempio n. 13
0
 protected override void init()
 {
     FilePath = StandardLibraryMethods.CombinePaths(AppTools.FilesFolderPath, FileName + FileExtensions.Xsd);
     if (!File.Exists(FilePath))
     {
         throw new ApplicationException("File does not exist.");
     }
 }
Esempio n. 14
0
 public static string GetBuildFilePath(int systemId)
 {
     return(StandardLibraryMethods.CombinePaths(
                DataPackageRepositoryPath
                /*NOTE: Make this the generic web-site-accessible folder and change this and DataPackageRepositoryPath to be a subfolder of that.*/,
                "Latest Builds",
                systemId.ToString()));
 }
 private void packageClientSideApp(DevelopmentInstallation installation, string clientSideAppFolder)
 {
     IoMethods.CopyFolder(
         StandardLibraryMethods.CombinePaths(installation.GeneralLogic.Path,
                                             installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject.name,
                                             StandardLibraryMethods.GetProjectOutputFolderPath(false)),
         StandardLibraryMethods.CombinePaths(clientSideAppFolder, installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject.name),
         false);
 }
 private void packageWindowsServices(DevelopmentInstallation installation, string serverSideLogicFolderPath)
 {
     foreach (var service in installation.ExistingInstallationLogic.RuntimeConfiguration.WindowsServices)
     {
         IoMethods.CopyFolder(installation.ExistingInstallationLogic.GetWindowsServiceFolderPath(service, false),
                              StandardLibraryMethods.CombinePaths(serverSideLogicFolderPath, service.Name),
                              false);
     }
 }
        public string GetWindowsServiceFolderPath(WindowsService service, bool useDebugFolderIfDevelopmentInstallation)
        {
            var path = StandardLibraryMethods.CombinePaths(generalInstallationLogic.Path, service.Name);

            if (runtimeConfiguration.InstallationType == InstallationType.Development)
            {
                path = StandardLibraryMethods.CombinePaths(path, StandardLibraryMethods.GetProjectOutputFolderPath(useDebugFolderIfDevelopmentInstallation));
            }
            return(path);
        }
        void Operation.Execute(Installation genericInstallation, OperationResult operationResult)
        {
            var installation             = genericInstallation as RecognizedDevelopmentInstallation;
            var localNuGetFeedFolderPath = StandardLibraryMethods.CombinePaths(ConfigurationStatics.RedStaplerFolderPath, "Local NuGet Feed");

            // NuGet.exe has problems if the folder doesn't exist.
            Directory.CreateDirectory(localNuGetFeedFolderPath);

            ExportLogic.CreateEwlNuGetPackage(installation, true, localNuGetFeedFolderPath, null);
        }
Esempio n. 19
0
        internal static void Test()
        {
            // NOTE: This path is probably wrong, and should not be hard-coded.
            const string sourceFolderPath = @"C:\Red Stapler Vault\Supporting Files\Standard Library\Standard Library\MailMerging";

            var outputFolderPath = TestStatics.OutputFolderPath;

            IoMethods.DeleteFolder(outputFolderPath);

            // Create and extract empty zip file
            var emptyFolderPath = StandardLibraryMethods.CombinePaths(outputFolderPath, "Empty");

            Directory.CreateDirectory(emptyFolderPath);
            var emptyZipPath = StandardLibraryMethods.CombinePaths(outputFolderPath, "empty.zip");

            ZipFolderAsFile(emptyFolderPath, emptyZipPath);
            using (var memoryStream = new MemoryStream()) {
                ZipFolderAsStream(emptyFolderPath, memoryStream);
                memoryStream.Reset();
                UnZipStreamIntoFolder(memoryStream, StandardLibraryMethods.CombinePaths(outputFolderPath, "Empty from stream"));
            }

            // File-based
            var zipFilePath   = StandardLibraryMethods.CombinePaths(outputFolderPath, "file.zip");
            var extractedPath = StandardLibraryMethods.CombinePaths(outputFolderPath, "Extracted from File");

            ZipFolderAsFile(sourceFolderPath, zipFilePath);
            UnZipFileAsFolder(zipFilePath, extractedPath);

            // Byte-array-based
            var bytes           = ZipFolderAsByteArray(sourceFolderPath);
            var byteZipFilePath = StandardLibraryMethods.CombinePaths(outputFolderPath, "fileFromBytes.zip");

            File.WriteAllBytes(byteZipFilePath, bytes);
            UnZipByteArrayAsFolder(File.ReadAllBytes(byteZipFilePath), StandardLibraryMethods.CombinePaths(outputFolderPath, "Extracted from Byte Array"));

            // Stream-based
            var streamedFilePath = StandardLibraryMethods.CombinePaths(outputFolderPath, "fileFromStream.zip");

            using (var fs = new FileStream(streamedFilePath, FileMode.Create))
                ZipFolderAsStream(sourceFolderPath, fs);

            var streamedExtractedPath = StandardLibraryMethods.CombinePaths(outputFolderPath, "Extracted from Stream");

            using (var memoryStream = new MemoryStream()) {
                ZipFolderAsStream(sourceFolderPath, memoryStream);
                memoryStream.Reset();
                UnZipStreamIntoFolder(memoryStream, streamedExtractedPath);
            }

            using (var fs = File.OpenRead(streamedFilePath)) {
                var files = UnZipStreamAsFileObjects(fs);
                ZipFileObjectsAsStream(files, File.OpenWrite(StandardLibraryMethods.CombinePaths(outputFolderPath, "fileFromStreamedFileObjects.zip")));
            }
        }
Esempio n. 20
0
        private void generateCodeForProject(DevelopmentInstallation installation, string projectName, Action <TextWriter> codeWriter)
        {
            var generatedCodeFolderPath = StandardLibraryMethods.CombinePaths(installation.GeneralLogic.Path, projectName, "Generated Code");

            Directory.CreateDirectory(generatedCodeFolderPath);
            var isuFilePath = StandardLibraryMethods.CombinePaths(generatedCodeFolderPath, "ISU.cs");

            IoMethods.DeleteFile(isuFilePath);
            using (TextWriter writer = new StreamWriter(isuFilePath))
                codeWriter(writer);
        }
Esempio n. 21
0
        private static void generateCodeForWebItemsInFolder(
            TextWriter writer, string webProjectPath, string folderPathRelativeToProject, WebProject webProjectConfiguration)
        {
            var folderPath = StandardLibraryMethods.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(StandardLibraryMethods.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, webProjectConfiguration));
                entitySetup.GenerateCode(writer);
            }

            // Generate code for pages and user controls in the current folder.
            foreach (var fileName in IoMethods.GetFileNamesInFolder(folderPath, "*.aspx"))
            {
                var filePathRelativeToProject = Path.Combine(folderPathRelativeToProject, fileName);
                new Page(new WebItemGeneralData(webProjectPath, filePathRelativeToProject, webProjectConfiguration), entitySetup).GenerateCode(writer);
            }
            foreach (var fileName in IoMethods.GetFileNamesInFolder(folderPath, "*.ascx"))
            {
                if (fileName != entitySetupFileName)
                {
                    var filePathRelativeToProject = Path.Combine(folderPathRelativeToProject, fileName);
                    new UserControl(new WebItemGeneralData(webProjectPath, filePathRelativeToProject, webProjectConfiguration)).GenerateCode(writer);
                }
            }

            foreach (var fileName in IoMethods.GetFileNamesInFolder(folderPath, "*.css"))
            {
                var filePathRelativeToProject = Path.Combine(folderPathRelativeToProject, fileName);
                new CssFile(new WebItemGeneralData(webProjectPath, filePathRelativeToProject, webProjectConfiguration)).GenerateCode(writer);
            }

            // Delve into sub folders.
            foreach (var subFolderName in IoMethods.GetFolderNamesInFolder(folderPath))
            {
                generateCodeForWebItemsInFolder(writer, webProjectPath, Path.Combine(folderPathRelativeToProject, subFolderName), webProjectConfiguration);
            }
        }
Esempio n. 22
0
        private void generateXmlSchemaLogicForCustomInstallationConfigurationXsd(DevelopmentInstallation installation)
        {
            const string customInstallationConfigSchemaPathInProject = @"Configuration\Installation\Custom.xsd";

            if (File.Exists(StandardLibraryMethods.CombinePaths(installation.DevelopmentInstallationLogic.LibraryPath, customInstallationConfigSchemaPathInProject)))
            {
                generateXmlSchemaLogic(
                    installation.DevelopmentInstallationLogic.LibraryPath,
                    customInstallationConfigSchemaPathInProject,
                    installation.DevelopmentInstallationLogic.DevelopmentConfiguration.LibraryNamespaceAndAssemblyName + ".Configuration.Installation",
                    "Installation Custom Configuration.cs",
                    true);
            }
        }
Esempio n. 23
0
 private void generateXmlSchemaLogicForOtherXsdFiles(DevelopmentInstallation installation)
 {
     if (installation.DevelopmentInstallationLogic.DevelopmentConfiguration.xmlSchemas != null)
     {
         foreach (var xmlSchema in installation.DevelopmentInstallationLogic.DevelopmentConfiguration.xmlSchemas)
         {
             generateXmlSchemaLogic(
                 StandardLibraryMethods.CombinePaths(installation.GeneralLogic.Path, xmlSchema.project),
                 xmlSchema.pathInProject,
                 xmlSchema.@namespace,
                 xmlSchema.codeFileName,
                 xmlSchema.useSvcUtil);
         }
     }
 }
        private void packageServerSideConsoleApps(DevelopmentInstallation installation, string serverSideLogicFolderPath)
        {
            foreach (var project in installation.DevelopmentInstallationLogic.DevelopmentConfiguration.ServerSideConsoleProjectsNonNullable)
            {
                copyServerSideProject(installation, serverSideLogicFolderPath, project.Name);
            }

            // Always copy special projects.
            var testRunnerFolder = StandardLibraryMethods.CombinePaths(installation.GeneralLogic.Path, StandardLibraryMethods.TestRunnerProjectName);

            if (Directory.Exists(testRunnerFolder))
            {
                copyServerSideProject(installation, serverSideLogicFolderPath, StandardLibraryMethods.TestRunnerProjectName);
            }
        }
        /// <summary>
        /// Gets a new system list from RSIS.
        /// </summary>
        public static void RefreshSystemList()
        {
            // When deserializing the system list below, do not perform schema validation since we don't want to be forced into redeploying Program Runner after every
            // schema change. We also don't have access to the schema on non-development machines.
            var cachedSystemListFilePath = StandardLibraryMethods.CombinePaths(ConfigurationStatics.RedStaplerFolderPath, "RSIS System List.xml");

            try {
                var serializedSystemList =
                    ConfigurationLogic.ExecuteProgramRunnerUnstreamedServiceMethod(
                        channel => channel.GetSystemList(ConfigurationLogic.AuthenticationKey),
                        "system list download");
                RsisSystemList = XmlOps.DeserializeFromString <SystemList>(serializedSystemList, false);

                // Cache the system list so something is available in the future if the machine is offline.
                try {
                    XmlOps.SerializeIntoFile(RsisSystemList, cachedSystemListFilePath);
                }
                catch (Exception e) {
                    const string generalMessage = "The RSIS system list cannot be cached on disk.";
                    if (e is UnauthorizedAccessException)
                    {
                        throw new UserCorrectableException(generalMessage + " If the program is running as a non built in administrator, you may need to disable UAC.", e);
                    }

                    // An IOException probably means the file is locked. In this case we want to ignore the problem and move on.
                    if (!(e is IOException))
                    {
                        throw new UserCorrectableException(generalMessage, e);
                    }
                }
            }
            catch (UserCorrectableException e) {
                if (e.InnerException == null || !(e.InnerException is EndpointNotFoundException))
                {
                    throw;
                }

                // Use the cached version of the system list if it is available.
                if (File.Exists(cachedSystemListFilePath))
                {
                    RsisSystemList = XmlOps.DeserializeFromFile <SystemList>(cachedSystemListFilePath, false);
                }
                else
                {
                    throw new UserCorrectableException("RSIS cannot be reached to download the system list and a cached version is not available.", e);
                }
            }
        }
        private static void sendEmailWithSmtpServer(SmtpServer smtpServer, EmailMessage message)
        {
            // We used to cache the SmtpClient object. It turned out not to be thread safe, so now we create a new one for every email.
            var smtpClient = new System.Net.Mail.SmtpClient();

            try {
                if (smtpServer != null)
                {
                    smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    smtpClient.Host           = smtpServer.Server;
                    if (smtpServer.PortSpecified)
                    {
                        smtpClient.Port = smtpServer.Port;
                    }
                    if (smtpServer.Credentials != null)
                    {
                        smtpClient.Credentials = new System.Net.NetworkCredential(smtpServer.Credentials.UserName, smtpServer.Credentials.Password);
                        smtpClient.EnableSsl   = true;
                    }
                }
                else
                {
                    smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;

                    var pickupFolderPath = StandardLibraryMethods.CombinePaths(ConfigurationStatics.RedStaplerFolderPath, "Outgoing Dev Mail");
                    Directory.CreateDirectory(pickupFolderPath);
                    smtpClient.PickupDirectoryLocation = pickupFolderPath;
                }

                using (var m = new System.Net.Mail.MailMessage()) {
                    message.ConfigureMailMessage(m);
                    try {
                        smtpClient.Send(m);
                    }
                    catch (System.Net.Mail.SmtpException e) {
                        throw new EmailSendingException("Failed to send an email message using an SMTP server.", e);
                    }
                }
            }
            finally {
                // Microsoft's own dispose method fails to work if Host is not specified, even though Host doesn't need to be specified for operation.
                if (!string.IsNullOrEmpty(smtpClient.Host))
                {
                    smtpClient.Dispose();
                }
            }
        }
Esempio n. 27
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 = StandardLibraryMethods.CombinePaths(serverSideLogicFolderPath, webProject.name);

                // Pre-compile the web project.
                try {
                    StandardLibraryMethods.RunProgram(
                        StandardLibraryMethods.CombinePaths(RuntimeEnvironment.GetRuntimeDirectory(), "aspnet_compiler"),
                        "-v \"/" + webProject.name + ".csproj\" -p \"" + StandardLibraryMethods.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 {
                    StandardLibraryMethods.RunProgram(
                        StandardLibraryMethods.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(StandardLibraryMethods.CombinePaths(webAppPath, "Generated Code"));
                IoMethods.DeleteFolder(StandardLibraryMethods.CombinePaths(webAppPath, "obj"));
                IoMethods.DeleteFile(StandardLibraryMethods.CombinePaths(webAppPath, webProject.name + ".csproj"));
                IoMethods.DeleteFile(StandardLibraryMethods.CombinePaths(webAppPath, webProject.name + ".csproj.user"));
                IoMethods.DeleteFile(StandardLibraryMethods.CombinePaths(webAppPath, webProject.name + ".csproj.vspscc"));
                IoMethods.DeleteFile(StandardLibraryMethods.CombinePaths(webAppPath, AppStatics.StandardLibraryFilesFileName));

                var webConfigPath = StandardLibraryMethods.CombinePaths(webAppPath, "Web.config");
                File.WriteAllText(
                    webConfigPath,
                    File.ReadAllText(webConfigPath)
                    .Replace("debug=\"true\"", "debug=\"false\"")
                    .Replace("<!--<add name=\"HttpCacheModule\" />-->", "<add name=\"HttpCacheModule\" />"));
            }
        }
Esempio n. 28
0
        private void generateXmlSchemaLogic(string projectPath, string schemaPathInProject, string nameSpace, string codeFileName, bool useSvcUtil)
        {
            var projectGeneratedCodeFolderPath = StandardLibraryMethods.CombinePaths(projectPath, "Generated Code");

            if (useSvcUtil)
            {
                try {
                    StandardLibraryMethods.RunProgram(
                        StandardLibraryMethods.CombinePaths(AppStatics.DotNetToolsFolderPath, "SvcUtil"),
                        "/d:\"" + projectGeneratedCodeFolderPath + "\" /noLogo \"" + StandardLibraryMethods.CombinePaths(projectPath, schemaPathInProject) + "\" /o:\"" +
                        codeFileName + "\" /dconly /n:*," + nameSpace + " /ser:DataContractSerializer",
                        "",
                        true);
                }
                catch (Exception e) {
                    throw new UserCorrectableException("Failed to generate XML schema logic using SvcUtil.", e);
                }
            }
            else
            {
                Directory.CreateDirectory(projectGeneratedCodeFolderPath);
                try {
                    StandardLibraryMethods.RunProgram(
                        StandardLibraryMethods.CombinePaths(AppStatics.DotNetToolsFolderPath, "xsd"),
                        "/nologo \"" + StandardLibraryMethods.CombinePaths(projectPath, schemaPathInProject) + "\" /c /n:" + nameSpace + " /o:\"" +
                        projectGeneratedCodeFolderPath + "\"",
                        "",
                        true);
                }
                catch (Exception e) {
                    throw new UserCorrectableException("Failed to generate XML schema logic using xsd.", e);
                }
                var outputCodeFilePath = StandardLibraryMethods.CombinePaths(
                    projectGeneratedCodeFolderPath,
                    Path.GetFileNameWithoutExtension(schemaPathInProject) + ".cs");
                var desiredCodeFilePath = StandardLibraryMethods.CombinePaths(projectGeneratedCodeFolderPath, codeFileName);
                if (outputCodeFilePath != desiredCodeFilePath)
                {
                    try {
                        IoMethods.MoveFile(outputCodeFilePath, desiredCodeFilePath);
                    }
                    catch (IOException e) {
                        throw new UserCorrectableException("Failed to move the generated code file for an XML schema. Please try the operation again.", e);
                    }
                }
            }
        }
Esempio n. 29
0
 void Database.ExportToFile(string filePath)
 {
     executeMethodWithDbExceptionHandling(
         delegate {
         try {
             // The --hex-blob option prevents certain BLOBs from causing errors during database re-creation.
             StandardLibraryMethods.RunProgram(
                 StandardLibraryMethods.CombinePaths(binFolderPath, "mysqldump"),
                 getHostAndAuthenticationArguments() + " --single-transaction --hex-blob --result-file=\"{0}\" ".FormatWith(filePath) + info.Database,
                 "",
                 true);
         }
         catch (Exception e) {
             throw DataAccessMethods.CreateDbConnectionException(info, "exporting (to file)", e);
         }
     });
 }
Esempio n. 30
0
        private void deleteAndReCreateUser(DBConnection cn)
        {
            // Delete the existing user and schema.
            deleteUser(cn);

            // Re-create the user with the minimally required privileges.
            executeLongRunningCommand(cn, "CREATE USER " + info.UserAndSchema + " IDENTIFIED BY " + info.Password + " ACCOUNT UNLOCK");

            // This allows the user to connect to the database.
            executeLongRunningCommand(cn, "GRANT CREATE SESSION TO " + info.UserAndSchema);

            // This overrides all tablespace quotas for this user, which default to 0 and therefore prevent the user from creating any tables or other objects.
            executeLongRunningCommand(cn, "GRANT UNLIMITED TABLESPACE TO " + info.UserAndSchema);

            executeLongRunningCommand(cn, "GRANT CREATE PROCEDURE TO " + info.UserAndSchema);               // Necessary for RLE Personnel secondary databases.
            executeLongRunningCommand(cn, "GRANT CREATE SEQUENCE TO " + info.UserAndSchema);
            executeLongRunningCommand(cn, "GRANT CREATE TABLE TO " + info.UserAndSchema);
            executeLongRunningCommand(cn, "GRANT CREATE TRIGGER TO " + info.UserAndSchema);               // Necessary for RLE Personnel secondary databases.
            executeLongRunningCommand(cn, "GRANT READ, WRITE ON DIRECTORY " + dataPumpOracleDirectoryName + " TO " + info.UserAndSchema);

            // Get all tablespaces currently in the database.
            var command = cn.DatabaseInfo.CreateCommand();

            command.CommandText = "SELECT tablespace_name FROM dba_tablespaces";
            var currentTableSpaces = new List <string>();

            cn.ExecuteReaderCommand(
                command,
                reader => {
                while (reader.Read())
                {
                    currentTableSpaces.Add(reader.GetString(0).ToLower());
                }
            });

            // Create necessary tablespaces that don't already exist.
            foreach (var nonExistentTs in latestTableSpaces.Select(s => s.ToLower()).Except(currentTableSpaces))
            {
                var tableSpaceFolderPath = StandardLibraryMethods.CombinePaths(ConfigurationStatics.RedStaplerFolderPath, "Oracle Tablespaces");
                Directory.CreateDirectory(tableSpaceFolderPath);
                executeLongRunningCommand(
                    cn,
                    "CREATE TABLESPACE " + nonExistentTs + " DATAFILE '" + StandardLibraryMethods.CombinePaths(tableSpaceFolderPath, nonExistentTs + ".dbf") + "' SIZE 100M");
            }
        }