static bool FolderRecursivly(string sourceFolderPath, string destinationFolderPath, ref bool undo, string renameFolderTo = "")
        {
            sourceFolderPath      = EMPath.AddSlash(sourceFolderPath);
            destinationFolderPath = EMPath.AddSlash(destinationFolderPath);

            try
            {
                DirectoryInfo sourceFolder = new DirectoryInfo(sourceFolderPath);
                if (renameFolderTo == string.Empty)
                {
                    destinationFolderPath = EMPath.AddSlash(destinationFolderPath + sourceFolder.Name);
                }
                else
                {
                    destinationFolderPath = EMPath.AddSlash(destinationFolderPath + renameFolderTo);
                }

                //check if trying to copy in same parent folder
                if (destinationFolderPath.ToLower() == sourceFolderPath.ToLower())
                {
                    UserInfoHandler.ShowError("Cannot duplicate folder '" + sourceFolder.Name + "' in its parent folder.");
                    return(false);
                }

                //check if source folder already exists at destination path
                if (Directory.Exists(destinationFolderPath))
                {
                    if (UserInfoHandler.GetInfo("Folder '" + destinationFolderPath + "' already exists. Should it be deleted?", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                    {
                        return(false);
                    }
                    Directory.Delete(destinationFolderPath, true);
                }

                //create source folder at destination path
                Directory.CreateDirectory(destinationFolderPath);
                undo = true;

                //copy all files directly under this folder
                FileInfo[] subFiles = sourceFolder.GetFiles("*.*");
                if (subFiles != null)
                {
                    foreach (FileInfo subFile in subFiles)
                    {
                        File.Copy(subFile.FullName, destinationFolderPath + subFile.Name);
                    }
                }
                //find all subfolders under this folder for recursive call
                foreach (DirectoryInfo subFolder in sourceFolder.GetDirectories())
                {
                    FolderRecursivly(subFolder.FullName, destinationFolderPath, ref undo);
                }
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowException(exception, "Close and reopen the user interface and try again.");
                return(false);
            }
            return(true);
        }
        internal static string StoreFile(string filePath)
        {
            CleanBackupFolder(); //delete all folders which are older than 3 days to avoid that the backup folder gets too big

            try
            {
                FileInfo fileInfo = new FileInfo(filePath);

                //create a backup by copying file to a dated folder (see below) in BackUps-folder
                if (!Directory.Exists(EMPath.Folder_BackUps(EM_AppContext.FolderEuromodFiles)))
                {
                    Directory.CreateDirectory(EMPath.Folder_BackUps(EM_AppContext.FolderEuromodFiles));
                }
                string backUpFolder = fileInfo.Name + "_" + DateTime.Now.ToString("yyyy-MM-dd_H-mm-ss");       //backup-folder is name e.g. VarConfig.xml_2013-12-08_10-30-23
                if (!Directory.Exists(EMPath.Folder_BackUps(EM_AppContext.FolderEuromodFiles) + backUpFolder)) //is actually rather unlikely
                {
                    Directory.CreateDirectory(EMPath.Folder_BackUps(EM_AppContext.FolderEuromodFiles) + backUpFolder);
                }

                File.Copy(filePath, EMPath.AddSlash(EMPath.Folder_BackUps(EM_AppContext.FolderEuromodFiles) + backUpFolder) + fileInfo.Name);
                return(backUpFolder);
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowException(exception);
                return(string.Empty);
            }
        }
Exemplo n.º 3
0
        void btnOK_Click(object sender, EventArgs e)
        {
            if (lstSystems.CheckedItems.Count == 0)
            {
                Tools.UserInfoHandler.ShowError("Please select at least one system.");
                return;
            }
            _selectedSystems = new List <string>();
            foreach (object selectedSystem in lstSystems.CheckedItems)
            {
                _selectedSystems.Add(selectedSystem.ToString());
            }

            if (txtExportFolder.Text == string.Empty || !System.IO.Directory.Exists(txtExportFolder.Text))
            {
                Tools.UserInfoHandler.ShowError("Please select a valid export path.");
                return;
            }
            _selectedPath = EMPath.AddSlash(txtExportFolder.Text);

            if (radExportAndDelete.Checked)
            {
                _deleteExportedSystems = true;
            }

            DialogResult = DialogResult.OK;
            Close();
        }
        internal bool GetInstalledFilePath(out string installedFilePath, string localPath, string oldPath = "")
        {
            // NOTE: This function should only ever be used by the two functions above to retrieve the help & funcConfig paths

            //Application.ExecutablePath should be something like 'C:\Program Files (x86)\EUROMOD\EM_UI\EM_UI.exe'
            //to assess the base installation path we need to extract 'C:\Program Files (x86)\EUROMOD\' and add the local path (e.g. 'executable\\euromod.exe')
            string installationPath = EMPath.AddSlash((new FileInfo(Application.ExecutablePath)).Directory.Parent.FullName);

            if (EnvironmentInfo.isCompilerEnvironment)
            {
                installationPath = EMPath.AddSlash(Directory.GetParent(Directory.GetParent(installationPath).FullName).FullName);
            }
            installedFilePath = installationPath + localPath;
            if (File.Exists(installedFilePath))
            {
                return(true);
            }

            //try if the 'old path' exists, i.e. the path within the EUROMOD bundle (e.g. '...\EuromodFiles\Executable\Euromod.exe')
            if (oldPath != string.Empty && File.Exists(oldPath))
            {
                installedFilePath = oldPath;
                return(true);
            }

            EM_UI.Tools.UserInfoHandler.ShowError("File not found: '" + installedFilePath + "'.");
            return(false);
        }
        static bool IsValidCountryXMLFile(string folderPath, string countryShortName, out string errorMessage, bool checkForCountryConsistence = false)
        {
            try
            {
                CountryConfig countryConfig = new CountryConfig();
                string        fileName      = EMPath.AddSlash(folderPath) + GetCountryXMLFileName(countryShortName);
                if (!File.Exists(fileName))
                {
                    errorMessage = string.Format($"File '{fileName}' not found."); return(false);
                }                                                                                                            // this is for whatever reason not catched by the error handler and leads to a crash if not handled here
                using (StreamReader streamReader = new StreamReader(fileName, DefGeneral.DEFAULT_ENCODING))
                    countryConfig.ReadXml(streamReader);

                //trying to access country leads to an exception if this is not a valid country xml-file
                string xmlCountryShortName = countryConfig.Country.First().ShortName;

                if (checkForCountryConsistence)
                {
                    if (xmlCountryShortName.ToLower() != countryShortName.ToLower())
                    {
                        throw new System.ArgumentException("Name of country within file (" + xmlCountryShortName +
                                                           ") does not correspond with name used for country file (" + countryShortName + ").");
                    }
                }

                errorMessage = string.Empty;
                return(true);
            }
            catch (Exception exception)
            {
                errorMessage = exception.Message;
                return(false);
            }
        }
Exemplo n.º 6
0
        static internal string GenerateProjectSettings(string projectPath)
        {
            UserSettings settings = ReadSettings(GetCurrentSettingsFullName()); //read UserSetting.txt if available, otherwise get empty settings

            projectPath = EMPath.AddSlash(projectPath);

            //adapt EuromodFolder (= project-path) as well as default input- and output-folder, but the latter only if they were "standard" before, i.e. EuromodFolder\output resp. EuromodFolder\input
            string currentProjectPath     = EMPath.AddSlash(settings.Settings.First().EuromodFolder).ToLower();
            bool   useDefaultOutputFolder = settings.Settings.First().OutputFolder == string.Empty || settings.Settings.First().OutputFolder.ToLower().Contains(currentProjectPath);
            bool   useDefaultInputFolder  = settings.Settings.First().InputFolder == string.Empty || settings.Settings.First().InputFolder.ToLower().Contains(currentProjectPath);

            settings.Settings.First().EuromodFolder = projectPath; //change the project path
            if (useDefaultOutputFolder)
            {
                settings.Settings.First().OutputFolder = projectPath + "output";
            }
            if (useDefaultInputFolder)
            {
                settings.Settings.First().InputFolder = projectPath + "input";
            }

            string settingsPath = GetAnySettingsFullName();

            //MessageBox.Show(settingsPath);
            SaveSettings(settings, settingsPath); //store as GuidUserSetting.txt
            return(settingsPath);
        }
        internal void WriteXml(string filePath, string fileName, bool saveWithLineBreaks = true)
        {
            Stream fileStream = new FileStream(EMPath.AddSlash(filePath) + fileName, FileMode.Create);

            using (XmlTextCDATAWriter xmlWriter = new XmlTextCDATAWriter(fileStream,
                                                                         DefGeneral.DEFAULT_ENCODING, CountryConfigFacade._cDataElements, saveWithLineBreaks))
                _dataConfig.WriteXml(xmlWriter);
        }
 internal DataConfig ReadXml(string filePath, string fileName)
 {
     _dataConfig = new DataConfig();
     using (StreamReader streamReader = new StreamReader(EMPath.AddSlash(filePath) + fileName, DefGeneral.DEFAULT_ENCODING))
         _dataConfig.ReadXml(streamReader);
     _dataConfig.AcceptChanges();
     return(_dataConfig);
 }
Exemplo n.º 9
0
 void UpdateOutputFieldOnRunDialoguesIfDefault()
 {
     // if the output folder changed, check if any loaded Run Dialogues also need to be updated
     if (Get().OutputFolder != bkupGet().OutputFolder)
     {
         EM_AppContext.Instance.UpdateOutputFieldOnRunDialoguesIfDefault(EMPath.AddSlash(bkupGet().OutputFolder), EMPath.AddSlash(Get().OutputFolder));
     }
 }
 static internal string GetFlagPath(string shortName, bool addOn)
 { //get "official" flag/symbol path, i.e. the path where country-flag/add-on-symbol ought to be stored from now on (even if it is not yet actually stored there)
     if (ConsiderOldAddOnFileStructure(addOn))
     {
         return(new EMPath(EM_AppContext.FolderEuromodFiles).GetFolderImages()); //if add-ons are still stored "loosely" (not in folders) the symbols are still best stored in the Flags-folder (instead of also loosely in the AddOns-folder)
     }
     //otherwise the official flag/symbol path is the folder of the country/add-on
     return(EMPath.AddSlash((addOn ? EMPath.Folder_AddOns(EM_AppContext.FolderEuromodFiles) : EMPath.Folder_Countries(EM_AppContext.FolderEuromodFiles)) + shortName));
 }
        void ConfigurePathsForm_Load(object sender, EventArgs e)
        {
            string helpPath; EM_AppContext.Instance.GetHelpPath(out helpPath); helpProvider.HelpNamespace = helpPath;

            cmbEuromodFolder.Text = EM_AppContext.Instance.GetUserSettingsAdministrator().Get().EuromodFolder;
            foreach (string projectPath in UserSettingsAdministrator.GetAvailableProjectPaths(out _pathsUserSettings))
            {
                cmbEuromodFolder.Items.Add(EMPath.AddSlash(projectPath).ToLower());
            }
        }
 internal string GetPath()
 {
     if (CountryAdministrator.ConsiderOldAddOnFileStructure(_isAddOn))
     {
         return(EMPath.Folder_AddOns(EM_AppContext.FolderEuromodFiles));
     }
     else
     {
         return(EMPath.AddSlash((_isAddOn ? EMPath.Folder_AddOns(EM_AppContext.FolderEuromodFiles) : EMPath.Folder_Countries(EM_AppContext.FolderEuromodFiles)) + _shortName));
     }
 }
 static bool IsValidDataConfigXMLFile(string folderPath, string countryShortName, out string errorMessage)
 {
     try
     {
         DataConfig dataConfig = new DataConfig();
         using (StreamReader streamReader = new StreamReader(EMPath.AddSlash(folderPath) + GetDataConfigXMLFileName(countryShortName), DefGeneral.DEFAULT_ENCODING))
             dataConfig.ReadXml(streamReader); //this catches actually only if it's not a readable xml-file, but not it is no data-config file
         errorMessage = string.Empty;
         return(true);
     }
     catch (Exception exception)
     {
         errorMessage = exception.Message;
         return(false);
     }
 }
        static internal void WriteErrorLogFile(string errlogPath, string errors)
        {
            string dateTimePrefix = string.Format("{0:yyyyMMddHHmm}", DateTime.Now);
            string fileName       = EMPath.AddSlash(errlogPath) + dateTimePrefix + EM_XmlHandler.TAGS.EM2CONFIG_errLogAddOnFileName;

            string heading = "=====================================================================================================================" + Environment.NewLine;

            heading += DefGeneral.BRAND_TITLE + " ADD-ON ERROR LOG" + Environment.NewLine;
            heading += "=====================================================================================================================" + Environment.NewLine;

            System.IO.TextWriter textWriter = new System.IO.StreamWriter(fileName);
            textWriter.Write(heading + errors);
            textWriter.Close();

            Tools.UserInfoHandler.ShowError(errors);
        }
Exemplo n.º 15
0
        internal RVCompareVersionsForm(string compareCountryFolder)
        {
            InitializeComponent();

            ProgressIndicator progressIndicator = new ProgressIndicator(GetCountryInfo_BackgroundEventHandler, "Comparing ...",
                                                                        EMPath.AddSlash(compareCountryFolder));

            if (progressIndicator.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;                                                                         // user pressed Cancel
            }
            foreach (var c in progressIndicator.Result as Dictionary <string, List <string> > )
            {
                dataGrid.Rows.Add(c.Key, c.Value[0], c.Value[1], c.Value[2], c.Value[3], c.Value[4], c.Value[5]);
            }
        }
Exemplo n.º 16
0
        void btnCompareVersions_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists(txtFolderVersion.Text))
            {
                UserInfoHandler.ShowError("Please select an existing folder for the version to compare with."); return;
            }

            compareCountryFolder = EMPath.AddSlash(txtFolderVersion.Text) + EMPath.Folder_Countries_withoutPath();
            if (!Directory.Exists(compareCountryFolder))
            {
                UserInfoHandler.ShowError("Folder '" + txtFolderVersion.Text + "' does not contain folder 'Countries'."); return;
            }

            selectedFunction = COMPARE_VERSIONS;
            DialogResult     = System.Windows.Forms.DialogResult.OK;
            Close();
        }
        void ReloadUserSettings()
        {
            string pathUserSettings = string.Empty;
            string pathNewProject   = EMPath.AddSlash(cmbEuromodFolder.Text).ToLower();

            if (cmbEuromodFolder.Items.Contains(pathNewProject)) //loading a project with existing user-settings
            {
                pathUserSettings = _pathsUserSettings.ElementAt(cmbEuromodFolder.Items.IndexOf(pathNewProject));
            }
            else //loading a 'lose' project, i.e. file-structure on disk, but no user settings available yet
            {
                pathUserSettings = UserSettingsAdministrator.GenerateProjectSettings(pathNewProject);
            }

            EM_AppContext.Instance.StoreViewSettings();
            EM_AppContext.Instance.GetUserSettingsAdministrator().LoadCurrentSettings(pathUserSettings);
            EM_AppContext.Instance.InitViewKeeper();
        }
        internal static bool RestoreFile(string filePath, string backUpFolder)
        {
            backUpFolder = EMPath.AddSlash(EMPath.Folder_BackUps(EM_AppContext.FolderEuromodFiles) + backUpFolder);

            try
            {
                FileInfo fileInfo = new FileInfo(filePath);
                File.Copy(backUpFolder + fileInfo.Name, filePath, true);
                return(true);
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowError("Restore failed because of the error stated below." + Environment.NewLine +
                                          "You may want to try a manual restore by copying the file in '" + backUpFolder + "'." + Environment.NewLine + Environment.NewLine +
                                          exception.Message);
                return(false);
            }
        }
        void btnOK_Click(object sender, EventArgs e)
        {
            bool reload = false;

            if (EMPath.AddSlash(EM_AppContext.Instance.GetUserSettingsAdministrator().Get().EuromodFolder).ToLower() != EMPath.AddSlash(cmbEuromodFolder.Text).ToLower())
            {
                if (!EM_AppContext.Instance.CloseAnythingOpen())
                {
                    return;                                              // if there are any countries/add-ons/variables open, try to close them
                }
                reload = true;
            }

            if (!Directory.Exists(cmbEuromodFolder.Text))
            {
                UserInfoHandler.ShowError(cmbEuromodFolder.Text + " is not a valid path.");
                return;
            }

            if (!Directory.Exists(EMPath.AddSlash(cmbEuromodFolder.Text) + EMPath.Folder_Countries_withoutPath()))
            {
                if (UserInfoHandler.GetInfo($"'{cmbEuromodFolder.Text}' does not (yet) contain the {DefGeneral.BRAND_TITLE} file structure."
                                            + Environment.NewLine + Environment.NewLine + "Do you want to change the 'Project Folder'?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    return;
                }
            }

            if (reload)
            {
                ReloadUserSettings();
                CountryAdministration.CountryAdministrator.ClearCountryList();
                EM_AppContext.Instance.SetBrand();                          // allow UI to show another look, i.e. present a brand alternative to EUROMOD
                EM_AppContext.Instance.UpdateAllCountryMainFormGalleries(); //only the empty main form is open and must be updated
                EM_AppContext.Instance.UpdateMainFormCaption();             //set title (of single open mainform) to "EUROMOD Version (Path)"
                EM_AppContext.Instance.UnloadVarConfigFacade();
                EM_AppContext.Instance.UnloadHICPConfigFacade();
                EM_AppContext.Instance.UnloadExchangeRatesConfigFacade();
                EM_AppContext.Instance.UnloadSwitchablePolicyConfigFacade();
            }

            Close();
        }
Exemplo n.º 20
0
        static internal void Generate()
        {
            //get the necessary information from the user (path and version number)
            PublicVersionForm publicVersionForm = new PublicVersionForm();

            if (publicVersionForm.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            _publicVersionPath   = EMPath.AddSlash(publicVersionForm.GetPath());
            _publicVersionNumber = publicVersionForm.GetVersionNumber();

            ProgressIndicator progressIndicator = new ProgressIndicator(Generate_BackgroundEventHandler, //the handler passed to the progress indicator will do the work (see below)
                                                                        "Generating Public Version");

            if (progressIndicator.ShowDialog() == System.Windows.Forms.DialogResult.OK) //regular termination, i.e user did not cancel the procedure
            {
                UserInfoHandler.ShowSuccess("Pulic version successfully stored at '" + _publicVersionPath + ".'" + Environment.NewLine +
                                            "Change user interface's current project (via the menu item 'Open Project') to check the result.");
            }
        }
        internal static bool IsOldAddOnFileStructure()
        {
            if (!Directory.Exists(EMPath.Folder_AddOns(EM_AppContext.FolderEuromodFiles)))
            {
                return(false); //probably does not happen
            }
            //try to find a folder within folder AddOns that contains an xml file named like the folder (e.g. MTR-folder containing MTR.xml)
            DirectoryInfo addOnContainerFolder = new DirectoryInfo(EMPath.Folder_AddOns(EM_AppContext.FolderEuromodFiles));

            if (addOnContainerFolder.GetFiles().Count() == 0)
            {
                return(false); //no info - assume "new style"
            }
            foreach (DirectoryInfo potentialAddOnFolder in addOnContainerFolder.GetDirectories())
            {
                if (File.Exists(EMPath.AddSlash(potentialAddOnFolder.FullName) + potentialAddOnFolder.Name + ".xml"))
                {
                    return(false); //if such a folder is found it is assumed that "new style" file structure is already in place
                }
            }
            return(true);
        }
        internal DataConfig.DataBaseRow GetDataBaseRowByDataFile(string filePath, string fileName)
        {
            List <DataConfig.DataBaseRow> dataBaseRows = (from dataBase in _dataConfig.DataBase
                                                          where EMPath.AddSlash(dataBase.FilePath).ToLower() == EMPath.AddSlash(filePath).ToLower() &&
                                                          AddExtensionToFileName(dataBase.Name, "txt").ToLower() == AddExtensionToFileName(fileName, "txt").ToLower()
                                                          select dataBase).ToList();

            if (dataBaseRows.Count > 0)
            {
                return(dataBaseRows.First());
            }
            return(null);

            string AddExtensionToFileName(string fn, string extension)
            {
                if (extension.Count() > 0 && !extension.StartsWith("."))
                {
                    extension = "." + extension;
                }
                return(fn.Count() >= extension.Count() && fn.ToLower().EndsWith(extension.ToLower()) ? fn : fn + extension);
            }
        }
        internal static bool CopyXMLFiles(string shortName, out string errorMessage,
                                          string sourceFolder = "", string destinationFolder = "", int addOn = -1)
        {
            try
            {
                bool   isAddOn       = addOn == -1 ? CountryAdministrator.IsAddOn(shortName) : (addOn == 0 ? false : true);
                string defaultFolder = isAddOn ? EMPath.Folder_AddOns(EM_AppContext.FolderEuromodFiles) : EMPath.Folder_Countries(EM_AppContext.FolderEuromodFiles);
                if (!CountryAdministrator.ConsiderOldAddOnFileStructure(isAddOn))
                {
                    defaultFolder += shortName;
                }

                if (destinationFolder == string.Empty)
                {
                    destinationFolder = defaultFolder;
                }
                if (sourceFolder == string.Empty)
                {
                    sourceFolder = defaultFolder;
                }

                File.Copy(EMPath.AddSlash(sourceFolder) + GetCountryXMLFileName(shortName),
                          EMPath.AddSlash(destinationFolder) + GetCountryXMLFileName(shortName), true);
                if (!isAddOn)
                {
                    File.Copy(EMPath.AddSlash(sourceFolder) + GetDataConfigXMLFileName(shortName),
                              EMPath.AddSlash(destinationFolder) + GetDataConfigXMLFileName(shortName), true);
                }

                errorMessage = string.Empty;
                return(true);
            }
            catch (Exception exception)
            {
                errorMessage = exception.Message;
                return(false);
            }
        }
Exemplo n.º 24
0
        void btnOK_Click(object sender, EventArgs e)
        {
            if (GetSelectedCountries().Count == 0)
            {
                UserInfoHandler.ShowError("Please select one or more countries.");
                return;
            }

            try
            {
                string exportPath = EMPath.AddSlash(txtFolder.Text);
                if (!Directory.Exists(exportPath))
                {
                    UserInfoHandler.ShowError("'" + txtFolder.Text + "' is not a valid path.");
                    return;
                }

                List <string> arguments = new List <string>();
                arguments.Add(txtFolder.Text);
                arguments.Add(radTextFormat.Checked ? textFormat : withLineBreaks);
                arguments.AddRange(GetSelectedCountries());
                ProgressIndicator progressIndicator = new ProgressIndicator(SaveAsText_BackgroundEventHandler, "Saving parameter files formatted ...", arguments);
                if (progressIndicator.ShowDialog() == DialogResult.Cancel)
                {
                    return;
                }

                if (EM_Helpers.SaveConvertToBoolean(progressIndicator.Result) == true)
                {
                    UserInfoHandler.ShowSuccess("Successfully stored parameter files formatted at " + txtFolder.Text + ".");
                }
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowException(exception);
            }
        }
        //Helper
        internal static bool Folder(string sourceFolderPath, string destinationFolderPath, string renameFolderTo = "")
        {
            bool undo = false;

            if (!FolderRecursivly(sourceFolderPath, destinationFolderPath, ref undo, renameFolderTo))
            {
                if (!undo)
                {
                    return(false);
                }
                try
                {
                    //undo any copying that already happened
                    DirectoryInfo sourceFolder = new DirectoryInfo(sourceFolderPath);
                    if (renameFolderTo == string.Empty)
                    {
                        destinationFolderPath = EMPath.AddSlash(destinationFolderPath + sourceFolder.Name);
                    }
                    else
                    {
                        destinationFolderPath = EMPath.AddSlash(destinationFolderPath + renameFolderTo);
                    }

                    if (Directory.Exists(destinationFolderPath))
                    {
                        Directory.Delete(destinationFolderPath, true);
                    }
                }
                catch (Exception exception)
                {
                    UserInfoHandler.ShowException(exception);
                }
                return(false);
            }
            return(true);
        }
Exemplo n.º 26
0
        void btnSelectVersion_Click(object sender, EventArgs e)
        {
            string shortName_varFileName, path, textToDisplay;

            if (_getVariablesChoices)
            {
                if (!GetImportVariablesPath(out path, out shortName_varFileName))
                {
                    return;
                }
                textToDisplay = EMPath.AddSlash(path) + shortName_varFileName;
            }
            else
            {
                bool oldStyle = CountryAdministrator.ConsiderOldAddOnFileStructure(_isAddOn);
                if (!(oldStyle ? ImportExportAdministrator.GetImportAddOnPath_OldStyle(out path, out shortName_varFileName, out string fileNameNew)
                           : ImportExportAdministrator.GetImportCountryPath(_isAddOn, out path, out shortName_varFileName)))
                {
                    return;
                }
                textToDisplay = !oldStyle ? path : EMPath.AddSlash(path) + Country.GetCountryXMLFileName(shortName_varFileName);
            }

            if (sender == btnSelectRemoteVersion)
            {
                txtRemoteVersion.Text = textToDisplay;
                _pathRemoteVersion    = path;
                _nameRemoteVersion    = shortName_varFileName;
            }
            else
            {
                txtParentVersion.Text = textToDisplay;
                _pathParentVersion    = path;
                _nameParentVersion    = shortName_varFileName;
            }
        }
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (lstCountries.SelectedItems.Count == 0 && lstSystems.SelectedItems.Count == 0)
            {
                UserInfoHandler.ShowInfo("Please select the countries and/or systems you want to include into the project."); return;
            }

            if (txtProjectName.Text == string.Empty || txtProjectPath.Text == string.Empty)
            {
                UserInfoHandler.ShowError("Please select a valid Project Name and/or Project Path."); return;
            }
            projectPath = EMPath.AddSlash(EMPath.AddSlash(txtProjectPath.Text) + txtProjectName.Text);
            if (!EM_Helpers.IsValidFileName(projectPath))
            {
                UserInfoHandler.ShowInfo(projectPath + " is not a valid folder name for the new project."); return;
            }

            Cursor = Cursors.WaitCursor; bool undo = false;
            try
            {
                // first copy the whole EuromodFiles folder to the respective path, to then adapt the copy
                if (!XCopy.Folder(EM_AppContext.FolderEuromodFiles, txtProjectPath.Text, txtProjectName.Text))
                {
                    Cursor = Cursors.Default; return;
                }
                undo = true;

                // delete all unnecessary files and folders (but do not report or stop if any of this fails)
                EMPath emPath = new EMPath(EM_AppContext.FolderEuromodFiles);
                DeleteFolder(ReplacePath(emPath.GetFolderLog()));
                ClearFolder(ReplacePath(EM_AppContext.FolderOutput));
                ClearFolder(ReplacePath(emPath.GetFolderTemp()));
                DeleteFile(ReplacePath(Path.Combine(emPath.GetFolderConfig(true), "VersionControl.xml")));

                string        folderCountries = ReplacePath(EMPath.Folder_Countries(EM_AppContext.FolderEuromodFiles));
                List <string> selCountries    = new List <string>(); foreach (var item in lstCountries.SelectedItems)
                {
                    selCountries.Add(item.ToString().ToLower());
                }
                ClearFolder(folderCountries, selCountries);

                // delete all unnecessary systems
                List <string> selSystems = null;
                if (lstSystems.SelectedItems.Count > 0 && lstSystems.SelectedItems.Count != lstSystems.Items.Count)
                {
                    selSystems = new List <string>(); foreach (var item in lstSystems.SelectedItems)
                    {
                        selSystems.Add(item.ToString().ToLower());
                    }
                }
                foreach (string cc in selCountries)
                {
                    DeleteFile(EMPath.AddSlash(projectPath + cc) + cc + "_in_use.txt");

                    if (selSystems == null)
                    {
                        continue;                     // if all system/years are selected or nothing is selected, assume that user does not want to "reduce" systems
                    }
                    Country             country = new Country(cc);
                    CountryConfigFacade ccf     = country.GetCountryConfigFacade(true, folderCountries + country._shortName);
                    DataConfigFacade    dcf     = country.GetDataConfigFacade(true, folderCountries + country._shortName);

                    List <CountryConfig.SystemRow> delSystems = new List <CountryConfig.SystemRow>();
                    foreach (CountryConfig.SystemRow system in ccf.GetSystemRows())
                    {
                        if (radShowSystems.Checked)
                        {
                            if (!selSystems.Contains(system.Name.ToLower()))
                            {
                                delSystems.Add(system);
                            }
                        }
                        else
                        {
                            string systemYear = system.Year == null || system.Year == string.Empty ? EM_Helpers.ExtractSystemYear(system.Name) : system.Year;
                            if (!selSystems.Contains(systemYear))
                            {
                                delSystems.Add(system);
                            }
                        }
                    }

                    List <DataConfig.DBSystemConfigRow> delDBSysCons = new List <DataConfig.DBSystemConfigRow>();
                    List <string> delSystemIds = (from d in delSystems select d.ID).ToList();
                    foreach (DataConfig.DataBaseRow dataSet in dcf.GetDataBaseRows())
                    {
                        foreach (DataConfig.DBSystemConfigRow dbSystemConfig in dcf.GetDBSystemConfigRows(dataSet.ID))
                        {
                            if (delSystemIds.Contains(dbSystemConfig.SystemID))
                            {
                                delDBSysCons.Add(dbSystemConfig);
                            }
                        }
                    }

                    foreach (CountryConfig.SystemRow delSystem in delSystems)
                    {
                        delSystem.Delete();
                    }
                    foreach (DataConfig.DBSystemConfigRow delDBSysCon in delDBSysCons)
                    {
                        delDBSysCon.Delete();
                    }

                    country.WriteXML(folderCountries + country._shortName);
                }
                UserInfoHandler.ShowSuccess("Successfully created project folder " + projectPath + ".");
                Close();
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowError(exception.Message);
                if (undo)
                {
                    try { if (Directory.Exists(projectPath))
                          {
                              Directory.Delete(projectPath, true);
                          }
                    } catch { }
                }
            }
            Cursor = Cursors.Default;
        }
 private string ReplacePath(string emSubFolder)
 {
     return(EMPath.AddSlash(emSubFolder.Replace(EM_AppContext.FolderEuromodFiles, projectPath)));
 }
Exemplo n.º 29
0
        static bool ExportView(string exportFolder, string exportFile, DataGridView dataGridView = null, ListView listView = null)
        {
            try
            {
                string exportPath = EMPath.AddSlash(exportFolder);
                if (!Directory.Exists(exportPath))
                {
                    UserInfoHandler.ShowError("'" + exportFolder + "' is not a valid path.");
                    return(false);
                }

                if (exportFile.Length > 3 && exportFile.Substring(exportFile.Length - 4, 1) != ".")
                {
                    exportFile += ".txt";
                }
                string   exportFileFullName = EMPath.AddSlash(exportFolder) + exportFile;
                FileInfo fileInfo           = new FileInfo(exportFileFullName); //to throw an exception if invalid name (e.g. using characters like *?)

                System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(exportFileFullName);

                if (dataGridView != null)
                {
                    if (dataGridView.ColumnHeadersVisible)
                    {
                        string line = (dataGridView.RowHeadersVisible) ? "\t" : string.Empty;
                        foreach (DataGridViewColumn column in dataGridView.Columns)
                        {
                            line += ((column.HeaderCell.Value == null) ? string.Empty : column.HeaderCell.Value.ToString()) + "\t";
                        }
                        line = line.TrimEnd();
                        streamWriter.WriteLine(line);
                    }
                    foreach (DataGridViewRow row in dataGridView.Rows)
                    {
                        string line = string.Empty;
                        if (dataGridView.RowHeadersVisible)
                        {
                            line = ((row.HeaderCell.Value == null) ? string.Empty : row.HeaderCell.Value.ToString()) + "\t";
                        }
                        foreach (DataGridViewColumn column in dataGridView.Columns)
                        {
                            line += ((row.Cells[column.Index].Value == null) ? string.Empty : row.Cells[column.Index].Value.ToString()) + "\t";
                        }
                        line = line.TrimEnd();
                        streamWriter.WriteLine(line);
                    }
                }
                else if (listView != null)
                {
                    string line = string.Empty;
                    foreach (ColumnHeader columnHeader in listView.Columns)
                    {
                        line += columnHeader.Text + "\t";
                    }
                    line = line.TrimEnd();
                    streamWriter.WriteLine(line);

                    foreach (ListViewItem row in listView.Items)
                    {
                        line = string.Empty;
                        foreach (ListViewItem.ListViewSubItem column in row.SubItems)
                        {
                            line += column.Text + "\t";
                        }
                        line = line.TrimEnd();
                        streamWriter.WriteLine(line);
                    }
                }

                streamWriter.Close();

                return(true);
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowException(exception);
                return(false);
            }
        }
Exemplo n.º 30
0
        static void Generate_BackgroundEventHandler(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            BackgroundWorker backgroundWorker = sender as BackgroundWorker;

            if (backgroundWorker.CancellationPending)
            {
                e.Cancel = true; return;
            }                                                                      //user pressed Cancel button: stop the process and allow progress indicator to set dialog result to Cancel

            //assess the name of the new EuromodFiles-folder in accordance to the version number
            DirectoryInfo sourceFolder = new DirectoryInfo(EM_AppContext.FolderEuromodFiles);
            string        folderEMF    = "EuromodFiles_" + _publicVersionNumber;

            if (!EM_Helpers.IsValidFileName(folderEMF))
            {
                UserInfoHandler.ShowInfo(folderEMF + " is not a valid folder name. Please change the version number.");
                e.Cancel = true; return;
            }

            //first copy the whole EuromodFiles folder to the respective path
            if (!XCopy.Folder(EM_AppContext.FolderEuromodFiles, _publicVersionPath, folderEMF))
            {
                e.Cancel = true; return;
            }

            string fullPublicPath = _publicVersionPath + EMPath.AddSlash(folderEMF);

            //then adapt the copy
            string folderCountries =
                EMPath.AddSlash( //at the new path assess the folder that contains the files (usually EuromodFiles)
                    EMPath.Folder_Countries(EM_AppContext.FolderEuromodFiles).Replace(EM_AppContext.FolderEuromodFiles, fullPublicPath));

            try
            {
                List <Country> countries = CountryAdministrator.GetCountries();

                //remove private systems, policies and datasets of each country
                for (int i = 0; i < countries.Count; ++i)
                {
                    if (backgroundWorker.CancellationPending)
                    {
                        e.Cancel = true; return;
                    }                                                                      //user pressed Cancel button: see above

                    Country             country             = countries[i];
                    CountryConfigFacade countryConfigFacade = country.GetCountryConfigFacade(true, folderCountries + country._shortName);
                    DataConfigFacade    dataConfigFacade    = country.GetDataConfigFacade(true, folderCountries + country._shortName);

                    //assess which systems, policies and datasets are private
                    List <CountryConfig.SystemRow>    privateSystems    = new List <CountryConfig.SystemRow>();    //systems
                    List <CountryConfig.PolicyRow>    privatePolicies   = new List <CountryConfig.PolicyRow>();    //policies
                    List <CountryConfig.FunctionRow>  privateFunctions  = new List <CountryConfig.FunctionRow>();  //functions
                    List <CountryConfig.ParameterRow> privateParameters = new List <CountryConfig.ParameterRow>(); //parameters
                    List <string> privateSystemIDs = new List <string>();                                          //necessary for afterwards identifying database-connections of private systems
                    foreach (CountryConfig.SystemRow system in countryConfigFacade.GetSystemRows())
                    {
                        if (system.Private.ToLower() == DefPar.Value.YES.ToLower())
                        {
                            privateSystems.Add(system);
                            privateSystemIDs.Add(system.ID);
                        }
                        else
                        {
                            foreach (CountryConfig.PolicyRow policy in system.GetPolicyRows())
                            {
                                if (policy.Private == DefPar.Value.YES)
                                {
                                    privatePolicies.Add(policy);
                                }
                                else
                                {
                                    if (policy.PrivateComment != null && policy.PrivateComment != string.Empty)
                                    {
                                        policy.PrivateComment = string.Empty; //remove private policy-comment if there is any
                                    }
                                    foreach (CountryConfig.FunctionRow function in policy.GetFunctionRows())
                                    {
                                        if (function.Private == DefPar.Value.YES)
                                        {
                                            privateFunctions.Add(function);
                                        }
                                        else
                                        {
                                            if (function.PrivateComment != null && function.PrivateComment != string.Empty)
                                            {
                                                function.PrivateComment = string.Empty; //remove private function-comment if there is any
                                            }
                                            foreach (CountryConfig.ParameterRow parameter in function.GetParameterRows())
                                            {
                                                if (parameter.Private == DefPar.Value.YES)
                                                {
                                                    privateParameters.Add(parameter);
                                                }
                                                else if (parameter.PrivateComment != null && parameter.PrivateComment != string.Empty)
                                                {
                                                    parameter.PrivateComment = string.Empty; //remove private parameter-comment if there is any
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    List <DataConfig.DataBaseRow>       privateDataSets        = new List <DataConfig.DataBaseRow>();       //datasets
                    List <DataConfig.DBSystemConfigRow> privateDBSystemConfigs = new List <DataConfig.DBSystemConfigRow>(); //database-connections of private systems
                    foreach (DataConfig.DataBaseRow dataSet in dataConfigFacade.GetDataBaseRows())
                    {
                        if (dataSet.Private.ToLower() == DefPar.Value.YES.ToLower())
                        {
                            privateDataSets.Add(dataSet);
                        }
                        else
                        {
                            foreach (DataConfig.DBSystemConfigRow dbSystemConfig in dataConfigFacade.GetDBSystemConfigRows(dataSet.ID))
                            {
                                if (privateSystemIDs.Contains(dbSystemConfig.SystemID))
                                {
                                    privateDBSystemConfigs.Add(dbSystemConfig);
                                }
                            }
                        }
                    }

                    //remove user-set node colors
                    countryConfigFacade.RemoveAllNodeColors();

                    //restore or install default base-system-colouring
                    countryConfigFacade.setAutomaticConditionalFormatting(true);

                    //remove private systems
                    if (countryConfigFacade.GetCountryRow().Private == DefPar.Value.YES || //if country is private or
                        privateSystems.Count == countryConfigFacade.GetSystemRows().Count) //there are no systems left, delete country
                    {
                        Directory.Delete(folderCountries + country._shortName, true);
                        country.SetCountryConfigFacade(null);
                        country.SetDataConfigFacade(null);
                        continue;
                    }
                    else //otherwise delete private systems
                    {
                        foreach (CountryConfig.SystemRow privateSystem in privateSystems)
                        {
                            privateSystem.Delete();
                        }
                    }

                    //remove private parameters
                    foreach (CountryConfig.ParameterRow privateParameter in privateParameters)
                    {
                        privateParameter.Delete();
                    }

                    //remove private functions
                    foreach (CountryConfig.FunctionRow privateFunction in privateFunctions)
                    {
                        privateFunction.Delete();
                    }

                    //remove private policies
                    foreach (CountryConfig.PolicyRow privatePolicy in privatePolicies)
                    {
                        privatePolicy.Delete();
                    }

                    //remove private datasets
                    foreach (DataConfig.DataBaseRow privateDataSet in privateDataSets)
                    {
                        privateDataSet.Delete();
                    }

                    //remove database-connections of private systems
                    foreach (DataConfig.DBSystemConfigRow privateDBSystemConfig in privateDBSystemConfigs)
                    {
                        privateDBSystemConfig.Delete();
                    }

                    country.WriteXML(folderCountries + country._shortName);
                    country.SetCountryConfigFacade(null);
                    country.SetDataConfigFacade(null);

                    backgroundWorker.ReportProgress(Convert.ToInt32((i + 1.0) / (countries.Count * 1.0) * 80.0));
                }

                //remove private add-ons
                string folderAddOns = EMPath.AddSlash( //at the new path assess the folder that contains the files (usually EuromodFiles)
                    EMPath.Folder_AddOns(EM_AppContext.FolderEuromodFiles).Replace(EM_AppContext.FolderEuromodFiles, fullPublicPath));
                foreach (Country addOn in CountryAdministrator.GetAddOns())
                {
                    bool oldStyle = CountryAdministrator.ConsiderOldAddOnFileStructure(true);
                    CountryConfigFacade addOnConfigFacade = addOn.GetCountryConfigFacade(true, folderAddOns + (oldStyle ? string.Empty : addOn._shortName));
                    if (addOnConfigFacade.GetCountryRow().Private != DefPar.Value.YES)
                    {
                        continue;
                    }
                    if (oldStyle)
                    {
                        File.Delete(folderAddOns + addOn._shortName + ".xml");
                    }
                    else
                    {
                        Directory.Delete(folderAddOns + addOn._shortName, true);
                    }
                    addOn.SetCountryConfigFacade(null);
                }

                // remove the "other" column from the variables file
                string          pathVarConfig = new EMPath(EM_AppContext.FolderEuromodFiles).GetVarFilePath(true).Replace(EM_AppContext.FolderEuromodFiles, fullPublicPath);
                VarConfigFacade vcf           = new VarConfigFacade(pathVarConfig);
                if (vcf.LoadVarConfig())
                {
                    foreach (VarConfig.CountryLabelRow r in
                             from l in vcf._varConfig.CountryLabel where l.Country.ToLower() == "other" select l)
                    {
                        r.Delete();
                    }
                    vcf.Commit(); vcf.WriteXML(pathVarConfig);
                }

                if (backgroundWorker.CancellationPending)
                {
                    e.Cancel = true; return;
                }                                                                      //user pressed Cancel button: see above

                //change version number
                string txtVersionPath = EMPath.Folder_Config(EM_AppContext.FolderEuromodFiles) + "EuromodVersion.txt";
                txtVersionPath = txtVersionPath.Replace(EM_AppContext.FolderEuromodFiles, fullPublicPath);
                using (StreamWriter versionFile = new StreamWriter(txtVersionPath))
                {
                    versionFile.WriteLine(_publicVersionNumber);
                    versionFile.WriteLine("PUBLIC VERSION");
                }

                //remove private rows from log file
                string logFile = new EMPath(EM_AppContext.FolderEuromodFiles).GetEmLogFilePath(); // determine the path of the em_log-file in the public folder
                logFile = logFile.Replace(EM_AppContext.FolderEuromodFiles, fullPublicPath);
                backgroundWorker.ReportProgress(100);
                if (File.Exists(logFile))
                {
                    AdaptLogFile(logFile);
                }

                //take care to not have any "xx_in_use.txt" files in the release
                try
                {
                    foreach (string inUseFile in Directory.GetFiles(fullPublicPath, "*_in_use.txt", SearchOption.AllDirectories))
                    {
                        File.Delete(inUseFile);
                    }
                }
                catch (Exception exception)
                {
                    //do nothing if this fails
                    UserInfoHandler.RecordIgnoredException("PublicVersion.Generate_BackgroundEventHandler", exception);
                }
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowException(exception);
                e.Cancel = true; //stop the process and allow progress indicator to set dialog result to Cancel
            }
        }