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       = EwlStatics.CombinePaths(libraryBasePath, "DataAccess", database.SecondaryDatabaseName + "Modification");
            var templateFilePath = EwlStatics.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(EwlStatics.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
            }
        }
Example #2
0
        internal static void Generate(
            TextWriter writer, string projectPath, string projectNamespace, bool projectContainsFramework, IEnumerable <string> ignoredFolderPaths,
            string staticFilesFolderPath, string staticFilesFolderUrlParentExpression)
        {
            var legacyUrlStaticsFilePath = EwlStatics.CombinePaths(projectPath, "LegacyUrlStatics.cs");

            if (File.Exists(legacyUrlStaticsFilePath) && File.ReadAllText(legacyUrlStaticsFilePath).Length == 0)
            {
                legacyUrlStatics = new StringBuilder();
                aspxFilePaths    = new List <string>();
            }

            generateForFolder(
                writer,
                projectPath,
                projectNamespace,
                projectContainsFramework,
                ignoredFolderPaths.ToImmutableHashSet(StringComparer.Ordinal),
                staticFilesFolderPath,
                staticFilesFolderUrlParentExpression,
                "");

            if (legacyUrlStatics != null)
            {
                File.WriteAllText(legacyUrlStaticsFilePath, legacyUrlStatics.ToString(), Encoding.UTF8);
                foreach (var i in aspxFilePaths)
                {
                    File.Delete(i);
                }
            }
        }
        private void deleteAndReCreateFromFile(DBConnection cn, string filePath)
        {
            // NOTE: Instead of catching exceptions, figure out if the database exists by querying.
            try {
                // Gets rid of existing connections. This doesn't need to be executed against the master database, but it's convenient because it saves us from needing
                // a second database connection.
                executeLongRunningCommand(cn, "ALTER DATABASE " + info.Database + " SET SINGLE_USER WITH ROLLBACK IMMEDIATE");

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

            Directory.CreateDirectory(sqlServerFilesFolderPath);

            try {
                IoMethods.CopyFile(filePath, backupFilePath);
                try {
                    // WITH MOVE is required so that multiple instances of the same system's database (RsisDev and RsisTesting, for example) can exist on the same machine
                    // without their physical files colliding.
                    executeLongRunningCommand(
                        cn,
                        "RESTORE DATABASE " + info.Database + " FROM DISK = '" + backupFilePath + "'" + " WITH MOVE '" + dataLogicalFileName + "' TO '" +
                        EwlStatics.CombinePaths(sqlServerFilesFolderPath, info.Database + ".mdf") + "', MOVE '" + logLogicalFileName + "' TO '" +
                        EwlStatics.CombinePaths(sqlServerFilesFolderPath, info.Database + ".ldf") + "'");
                }
                catch (Exception e) {
                    throw new UserCorrectableException("Failed to create database from file. Please try the operation again after obtaining a new database file.", e);
                }
            }
            finally {
                IoMethods.DeleteFile(backupFilePath);
            }
        }
        private void copyInEwlFiles(DevelopmentInstallation installation)
        {
            if (installation is RecognizedDevelopmentInstallation recognizedInstallation)
            {
                recognizedInstallation.KnownSystemLogic.DownloadAsposeLicenses(installation.ExistingInstallationLogic.RuntimeConfiguration.ConfigurationFolderPath);
            }

            if (installation.DevelopmentInstallationLogic.SystemIsEwl)
            {
                foreach (var fileName in GlobalStatics.ConfigurationXsdFileNames)
                {
                    IoMethods.CopyFile(
                        EwlStatics.CombinePaths(installation.GeneralLogic.Path, EwlStatics.CoreProjectName, "Configuration", fileName + FileExtensions.Xsd),
                        EwlStatics.CombinePaths(
                            InstallationFileStatics.GetGeneralFilesFolderPath(installation.GeneralLogic.Path, true),
                            InstallationFileStatics.FilesFolderName,
                            fileName + FileExtensions.Xsd));
                }
            }
            else
            {
                // If web projects exist for this installation, copy in web-framework static files.
                if (installation.DevelopmentInstallationLogic.DevelopmentConfiguration.webProjects != null)
                {
                    var webFrameworkStaticFilesFolderPath = EwlStatics.CombinePaths(
                        installation.GeneralLogic.Path,
                        InstallationFileStatics.WebFrameworkStaticFilesFolderName);
                    IoMethods.DeleteFolder(webFrameworkStaticFilesFolderPath);
                    IoMethods.CopyFolder(
                        EwlStatics.CombinePaths(ConfigurationStatics.InstallationPath, InstallationFileStatics.WebFrameworkStaticFilesFolderName),
                        webFrameworkStaticFilesFolderPath,
                        false);
                }
            }
        }
        private static void packageGeneralFiles(DevelopmentInstallation installation, string folderPath, bool includeDatabaseUpdates)
        {
            // configuration files
            var configurationFolderPath = EwlStatics.CombinePaths(folderPath, InstallationConfiguration.ConfigurationFolderName);

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

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

            if (Directory.Exists(filesFolderInInstallationPath))
            {
                IoMethods.CopyFolder(filesFolderInInstallationPath, EwlStatics.CombinePaths(folderPath, InstallationFileStatics.FilesFolderName), false);
            }
        }
 private void copyServerSideProject(DevelopmentInstallation installation, string serverSideLogicFolderPath, string project)
 {
     IoMethods.CopyFolder(
         EwlStatics.CombinePaths(installation.GeneralLogic.Path, project, EwlStatics.GetProjectOutputFolderPath(false)),
         EwlStatics.CombinePaths(serverSideLogicFolderPath, project),
         false);
 }
        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 = EwlStatics.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 = EwlStatics.GetCSharpIdentifier(
                System.IO.Path.GetFileNameWithoutExtension(path).CapitalizeString() +
                (includeFileExtensionInClassName ? System.IO.Path.GetExtension(path).CapitalizeString() : ""));
            this.webProjectConfiguration = webProjectConfiguration;
        }
Example #8
0
        private void copyInEwlFiles(DevelopmentInstallation installation)
        {
            if (installation is RecognizedDevelopmentInstallation recognizedInstallation)
            {
                recognizedInstallation.KnownSystemLogic.DownloadAsposeLicenses(installation.ExistingInstallationLogic.RuntimeConfiguration.ConfigurationFolderPath);
            }

            if (installation.DevelopmentInstallationLogic.SystemIsEwl)
            {
                foreach (var fileName in GlobalStatics.ConfigurationXsdFileNames)
                {
                    IoMethods.CopyFile(
                        EwlStatics.CombinePaths(installation.GeneralLogic.Path, AppStatics.CoreProjectName, "Configuration", fileName + FileExtensions.Xsd),
                        EwlStatics.CombinePaths(
                            InstallationFileStatics.GetGeneralFilesFolderPath(installation.GeneralLogic.Path, true),
                            InstallationFileStatics.FilesFolderName,
                            fileName + FileExtensions.Xsd));
                }
            }
            else
            {
                // If web projects exist for this installation, copy appropriate files into them.
                if (installation.DevelopmentInstallationLogic.DevelopmentConfiguration.webProjects != null)
                {
                    foreach (var webProject in installation.DevelopmentInstallationLogic.DevelopmentConfiguration.webProjects)
                    {
                        copyInWebProjectFiles(installation, webProject);
                    }
                }
            }
        }
 private static IEnumerable <string> getAssemblyPaths(DevelopmentInstallation installation, bool debug)
 {
     return(EwlStatics
            .CombinePaths(
                installation.DevelopmentInstallationLogic.LibraryPath,
                EwlStatics.GetProjectOutputFolderPath(debug),
                installation.DevelopmentInstallationLogic.DevelopmentConfiguration.LibraryNamespaceAndAssemblyName + ".dll")
            .ToCollection()
            .Concat(
                from i in installation.DevelopmentInstallationLogic.DevelopmentConfiguration.webProjects ?? new WebProject[0]
                select EwlStatics.CombinePaths(installation.GeneralLogic.Path, i.name, "bin", i.NamespaceAndAssemblyName + ".dll"))
            .Concat(
                from i in installation.ExistingInstallationLogic.RuntimeConfiguration.WindowsServices
                select EwlStatics.CombinePaths(
                    installation.ExistingInstallationLogic.GetWindowsServiceFolderPath(i, debug),
                    i.NamespaceAndAssemblyName + ".exe"))
            .Concat(
                from i in installation.DevelopmentInstallationLogic.DevelopmentConfiguration.ServerSideConsoleProjectsNonNullable
                select EwlStatics.CombinePaths(
                    installation.GeneralLogic.Path,
                    i.Name,
                    EwlStatics.GetProjectOutputFolderPath(debug),
                    i.NamespaceAndAssemblyName + ".exe"))
            .Concat(
                installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject != null
                                         ? EwlStatics.CombinePaths(
                    installation.GeneralLogic.Path,
                    installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject.name,
                    EwlStatics.GetProjectOutputFolderPath(debug),
                    installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject.assemblyName + ".exe")
                .ToCollection()
                                         : new string[0]));
 }
Example #10
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 {
                        EwlStatics.RunProgram(
                            EwlStatics.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);
                    }
                });
            }
        }
Example #11
0
        private static string getSectionString(WebProject project)
        {
            var sections = File.ReadAllText(EwlStatics.CombinePaths(ConfigurationStatics.FilesFolderPath, "Template.config"));

            if (project.UsesEntityFrameworkSpecified && project.UsesEntityFramework)
            {
                sections = sections.Replace(
                    "<compilation debug=\"true\" targetFramework=\"4.7.2\" />",
                    "<compilation debug=\"true\" targetFramework=\"4.7.2\"><buildProviders><remove extension=\".edmx\" /></buildProviders></compilation>");
            }

            sections = sections.Replace("@@SessionTimeout", ((int)AuthenticationStatics.SessionDuration.TotalMinutes).ToString());

            var useCertificateAuth = project.useCertificateAuthenticationSpecified && project.useCertificateAuthentication;

            sections = sections.Replace(
                "@@CertificateAuthenticationModulePlace",
                useCertificateAuth
                                        ? "<add name=\"CertificateAuthentication\" type=\"EnterpriseWebLibrary.CertificateAuthenticationModule, EnterpriseWebLibrary\"/>"
                                        : "");

            const string cacheTimeoutTimeSpan = "10:00:00";             // 10 hours

            sections = sections.Replace("@@CacheTimeout", cacheTimeoutTimeSpan);

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

                IoMethods.ExecuteWithTempFolder(
                    folderPath => {
                    IoMethods.CopyFile(getDumpFilePath(), EwlStatics.CombinePaths(folderPath, databaseFileDumpFileName));
                    File.WriteAllText(EwlStatics.CombinePaths(folderPath, databaseFileSchemaNameFileName), info.UserAndSchema);
                    ZipOps.ZipFolderAsFile(folderPath, filePath);
                });
            }
            finally {
                IoMethods.DeleteFile(getDumpFilePath());
            }
        }
Example #13
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 EnterpriseWebLibrary.InputValidation;");
                writer.WriteLine();
                writeAssemblyInfo(writer, installation, project.name);
                writer.WriteLine();
                CodeGeneration.WebMetaLogic.WebMetaLogicStatics.Generate(writer, application.Path, project);
            }
        }
Example #14
0
 protected override void init()
 {
     FilePath = EwlStatics.CombinePaths(ConfigurationStatics.FilesFolderPath, FileName + FileExtensions.Xsd);
     if (!File.Exists(FilePath))
     {
         throw new ApplicationException("File does not exist.");
     }
 }
Example #15
0
 public static string GetBuildFilePath(int systemId)
 {
     return(EwlStatics.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()));
 }
Example #16
0
 private void createAndZipSystem(Stream stream)
 {
     IoMethods.ExecuteWithTempFolder(
         folderPath => {
         createSystemFilesInFolder(EwlStatics.CombinePaths(ConfigurationStatics.FilesFolderPath, "System Template"), folderPath, "");
         ZipOps.ZipFolderAsStream(folderPath, stream);
     });
 }
Example #17
0
 /// <summary>
 /// Internal and Red Stapler Information System use only.
 /// </summary>
 public static string GetGeneralFilesFolderPath(string installationPath, bool isDevelopmentInstallation)
 {
     if (isDevelopmentInstallation)
     {
         return(EwlStatics.CombinePaths(installationPath, "Library"));
     }
     return(installationPath);
 }
 private void packageWindowsServices(DevelopmentInstallation installation, string serverSideLogicFolderPath)
 {
     foreach (var service in installation.ExistingInstallationLogic.RuntimeConfiguration.WindowsServices)
     {
         IoMethods.CopyFolder(
             installation.ExistingInstallationLogic.GetWindowsServiceFolderPath(service, false),
             EwlStatics.CombinePaths(serverSideLogicFolderPath, service.Name),
             false);
     }
 }
        void Operation.Execute(Installation genericInstallation, OperationResult operationResult)
        {
            var installation             = genericInstallation as RecognizedDevelopmentInstallation;
            var localNuGetFeedFolderPath = EwlStatics.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);
        }
 private void packageClientSideApp(DevelopmentInstallation installation, string clientSideAppFolder)
 {
     IoMethods.CopyFolder(
         EwlStatics.CombinePaths(
             installation.GeneralLogic.Path,
             installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject.name,
             EwlStatics.GetProjectOutputFolderPath(false)),
         EwlStatics.CombinePaths(clientSideAppFolder, installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject.name),
         false);
 }
Example #21
0
        public string GetWindowsServiceFolderPath(WindowsService service, bool useDebugFolderIfDevelopmentInstallation)
        {
            var path = EwlStatics.CombinePaths(generalInstallationLogic.Path, service.Name);

            if (runtimeConfiguration.InstallationType == InstallationType.Development)
            {
                path = EwlStatics.CombinePaths(path, EwlStatics.GetProjectOutputFolderPath(useDebugFolderIfDevelopmentInstallation));
            }
            return(path);
        }
        /// <summary>
        /// Gets a new system list.
        /// </summary>
        public static void RefreshSystemList()
        {
            // 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 cacheFilePath = EwlStatics.CombinePaths(ConfigurationStatics.EwlFolderPath, "System List.xml");
            var cacheUsed     = false;

            try {
                ConfigurationLogic.ExecuteWithSystemManagerClient(
                    client => {
                    Task.Run(
                        async() => {
                        using (var response = await client.GetAsync("system-list", HttpCompletionOption.ResponseHeadersRead)) {
                            response.EnsureSuccessStatusCode();
                            using (var stream = await response.Content.ReadAsStreamAsync())
                                RsisSystemList = XmlOps.DeserializeFromStream <SystemList>(stream, false);
                        }
                    })
                    .Wait();
                });
            }
            catch (Exception e) {
                // Use the cached version of the system list if it is available.
                if (File.Exists(cacheFilePath))
                {
                    RsisSystemList = XmlOps.DeserializeFromFile <SystemList>(cacheFilePath, false);
                    cacheUsed      = true;
                }
                else
                {
                    throw new UserCorrectableException("Failed to download the system list and a cached version is not available.", e);
                }
            }

            StatusStatics.SetStatus(
                cacheUsed ? "Failed to download the system list; loaded a cached version from \"{0}\".".FormatWith(cacheFilePath) : "Downloaded the system list.");

            // Cache the system list so something is available in the future if the machine is offline.
            try {
                XmlOps.SerializeIntoFile(RsisSystemList, cacheFilePath);
            }
            catch (Exception e) {
                const string generalMessage = "Failed to cache the system list 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);
                }
            }
        }
Example #23
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 = EwlStatics.CombinePaths(outputFolderPath, "Empty");

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

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

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

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

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

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

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

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

            var streamedExtractedPath = EwlStatics.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(EwlStatics.CombinePaths(outputFolderPath, "fileFromStreamedFileObjects.zip")));
            }
        }
        private void generateWindowsServiceCode(DevelopmentInstallation installation, WindowsService service)
        {
            var serviceProjectGeneratedCodeFolderPath = EwlStatics.CombinePaths(installation.GeneralLogic.Path, service.Name, generatedCodeFolderName);

            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("SystemInitializer globalInitializer = null;");
                writer.WriteLine("initGlobalInitializer( ref globalInitializer );");
                writer.WriteLine("var dataAccessState = new ThreadLocal<DataAccessState>( () => new DataAccessState() );");
                writer.WriteLine(
                    "GlobalInitializationOps.InitStatics( globalInitializer, \"{0}\", false, mainDataAccessStateGetter: () => dataAccessState.Value, useLongDatabaseTimeouts: true );"
                    .FormatWith(service.Name));
                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("static partial void initGlobalInitializer( ref SystemInitializer globalInitializer );");

                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("}");
            }
        }
Example #25
0
        private void generateCodeForProject(DevelopmentInstallation installation, string projectName, Action <TextWriter> codeWriter)
        {
            var generatedCodeFolderPath = EwlStatics.CombinePaths(installation.GeneralLogic.Path, projectName, "Generated Code");

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

            IoMethods.DeleteFile(isuFilePath);
            using (TextWriter writer = new StreamWriter(isuFilePath))
                codeWriter(writer);
        }
Example #26
0
        private void generateServerSideConsoleProjectCode(DevelopmentInstallation installation, ServerSideConsoleProject project)
        {
            var projectGeneratedCodeFolderPath = EwlStatics.CombinePaths(installation.GeneralLogic.Path, project.Name, "Generated Code");

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

            IoMethods.DeleteFile(isuFilePath);
            using (TextWriter writer = new StreamWriter(isuFilePath)) {
                writer.WriteLine("using System;");
                writer.WriteLine("using System.Collections.Generic;");
                writer.WriteLine("using System.Collections.Immutable;");
                writer.WriteLine("using System.IO;");
                writer.WriteLine("using System.Reflection;");
                writer.WriteLine("using System.Runtime.InteropServices;");
                writer.WriteLine("using System.Threading;");
                writer.WriteLine("using EnterpriseWebLibrary;");
                writer.WriteLine("using EnterpriseWebLibrary.DataAccess;");
                writer.WriteLine();
                writeAssemblyInfo(writer, installation, project.Name);
                writer.WriteLine();
                writer.WriteLine("namespace " + project.NamespaceAndAssemblyName + " {");
                writer.WriteLine("internal static partial class Program {");

                writer.WriteLine("[ MTAThread ]");
                writer.WriteLine("private static int Main( string[] args ) {");
                writer.WriteLine("SystemInitializer globalInitializer = null;");
                writer.WriteLine("initGlobalInitializer( ref globalInitializer );");
                writer.WriteLine("var dataAccessState = new ThreadLocal<DataAccessState>( () => new DataAccessState() );");
                writer.WriteLine(
                    "GlobalInitializationOps.InitStatics( globalInitializer, \"" + project.Name +
                    "\", false, mainDataAccessStateGetter: () => dataAccessState.Value );");
                writer.WriteLine("try {");
                writer.WriteLine("return GlobalInitializationOps.ExecuteAppWithStandardExceptionHandling( () => {");

                // See https://stackoverflow.com/a/44135529/35349.
                writer.WriteLine("Console.SetIn( new StreamReader( Console.OpenStandardInput(), Console.InputEncoding, false, 4096 ) );");

                writer.WriteLine("ewlMain( Newtonsoft.Json.JsonConvert.DeserializeObject<ImmutableArray<string>>( Console.ReadLine() ) );");
                writer.WriteLine("} );");
                writer.WriteLine("}");
                writer.WriteLine("finally {");
                writer.WriteLine("GlobalInitializationOps.CleanUpStatics();");
                writer.WriteLine("}");
                writer.WriteLine("}");

                writer.WriteLine("static partial void initGlobalInitializer( ref SystemInitializer globalInitializer );");
                writer.WriteLine("static partial void ewlMain( IReadOnlyList<string> arguments );");

                writer.WriteLine("}");
                writer.WriteLine("}");
            }
        }
        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);

            Directory.CreateDirectory(EwlStatics.CombinePaths(application.Path, StaticFile.AppStaticFilesFolderName));

            var webProjectGeneratedCodeFolderPath = EwlStatics.CombinePaths(application.Path, generatedCodeFolderName);

            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.Threading;");
                writer.WriteLine("using EnterpriseWebLibrary;");
                writer.WriteLine("using EnterpriseWebLibrary.DataAccess;");
                writer.WriteLine("using EnterpriseWebLibrary.EnterpriseWebFramework;");
                writer.WriteLine("using NodaTime;");
                writer.WriteLine("using Tewl.InputValidation;");
                writer.WriteLine("using Tewl.Tools;");
                writer.WriteLine();
                writeAssemblyInfo(writer, installation, project.name);
                writer.WriteLine();
                writer.WriteLine("namespace {0}.Providers {{".FormatWith(project.NamespaceAndAssemblyName));
                writer.WriteLine("internal partial class RequestDispatching: AppRequestDispatchingProvider {");
                writer.WriteLine(
                    "protected override UrlPattern GetStaticFilesFolderUrlPattern( string urlSegment ) => StaticFiles.FolderSetup.UrlPatterns.Literal( urlSegment );");
                writer.WriteLine("}");
                writer.WriteLine("}");
                writer.WriteLine();
                CodeGeneration.WebFramework.WebFrameworkStatics.Generate(
                    writer,
                    application.Path,
                    project.NamespaceAndAssemblyName,
                    false,
                    generatedCodeFolderName.ToCollection(),
                    StaticFile.AppStaticFilesFolderName,
                    "RequestDispatchingStatics.AppProvider.GetFrameworkUrlParent()");
            }
        }
Example #28
0
        private void generateXmlSchemaLogicForInstallationConfigurationFile(DevelopmentInstallation installation, string schemaFileName)
        {
            var schemaPathInProject = EwlStatics.CombinePaths(@"Configuration\Installation", schemaFileName + FileExtensions.Xsd);

            if (File.Exists(EwlStatics.CombinePaths(installation.DevelopmentInstallationLogic.LibraryPath, schemaPathInProject)))
            {
                generateXmlSchemaLogic(
                    installation.DevelopmentInstallationLogic.LibraryPath,
                    schemaPathInProject,
                    installation.DevelopmentInstallationLogic.DevelopmentConfiguration.LibraryNamespaceAndAssemblyName + ".Configuration.Installation",
                    $"Installation {schemaFileName} Configuration.cs",
                    true);
            }
        }
Example #29
0
        private void generateXmlSchemaLogicForCustomInstallationConfigurationXsd(DevelopmentInstallation installation)
        {
            const string customInstallationConfigSchemaPathInProject = @"Configuration\Installation\Custom.xsd";

            if (File.Exists(EwlStatics.CombinePaths(installation.DevelopmentInstallationLogic.LibraryPath, customInstallationConfigSchemaPathInProject)))
            {
                generateXmlSchemaLogic(
                    installation.DevelopmentInstallationLogic.LibraryPath,
                    customInstallationConfigSchemaPathInProject,
                    installation.DevelopmentInstallationLogic.DevelopmentConfiguration.LibraryNamespaceAndAssemblyName + ".Configuration.Installation",
                    "Installation Custom Configuration.cs",
                    true);
            }
        }
        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 = EwlStatics.CombinePaths(installation.GeneralLogic.Path, EwlStatics.TestRunnerProjectName);

            if (Directory.Exists(testRunnerFolder))
            {
                copyServerSideProject(installation, serverSideLogicFolderPath, EwlStatics.TestRunnerProjectName);
            }
        }