/// <summary> transfers all components of an EM2 content into EM3 structure </summary> /// <param name="emPath"> EuromodFiles folder (containing EM2-files in XMLParam and (will contain) EM3-files in EM3Translation\XMLParam) </param> /// <param name="errors"> list of errors, only critical errors lead to returning false, i.e. there may be errors on "success" </param> /// <param name="checkEmptyPath"> if true and e3Path is not an empty folder the function returns false and puts an error into the list </param> /// <param name="report"> optional function for progress reporting, with the form 'void fName(string successfullyWrittenFile)' </param> /// <param name="cancelSrc"> optional cancellation item </param> public static bool Transform(string emPath, out List <string> errors, bool checkEmptyPath = false, Action <string> report = null, CancellationTokenSource cancelSrc = null) { errors = new List <string>(); try { string em3TranslationFolder = new EMPath(emPath).GetFolderEM3Translation(); if (!Directory.Exists(em3TranslationFolder)) { Directory.CreateDirectory(em3TranslationFolder); } else if (checkEmptyPath) { DirectoryInfo di = new DirectoryInfo(em3TranslationFolder); if (di.GetDirectories().Length > 0 || di.GetFiles().Length > 0) { throw new Exception($"Destination path is not empty: {em3TranslationFolder}"); } } // read EM2 files: includes STRUCTURE changes // i.e. essentially from n pol/fun/par for n systems in EM2 to (initially) 1 pol/fun/par for all systems in EM3 List <string> wErrors = new List <string>(); EM2All.Content emContent = EM2All.Read(emPath, out errors, report, cancelSrc); // write EM3 files: includes CONTENT changes (performed by the EM23Adapt class) // e.g. dropping outdated properties, other treatment of private, global switches, ... bool success = emContent == null ? false : Write(emContent, emPath, out wErrors, report, cancelSrc); errors.AddRange(wErrors); return(success); } catch (Exception exception) { errors.Add(exception.Message); return(false); } }
void btnOK_Click(object sender, EventArgs e) { if (!Directory.Exists(txtCountryFolder.Text)) { UserInfoHandler.ShowError("Import Country Folder does not exist."); return; } if (Directory.Exists(EMPath.Folder_Countries(EM_AppContext.FolderEuromodFiles) + txtShortName.Text)) { UserInfoHandler.ShowError("Country folder '" + txtShortName.Text + "' already exists at '" + EMPath.Folder_Countries(EM_AppContext.FolderEuromodFiles) + "'."); return; } if (txtFlag.Text != string.Empty && !CountryAdministrator.IsValidFlagFilePath(txtFlag.Text)) { return; } //out-commented as it does not really make sense to not allow for longer country-short-names //if (txtShortName.Text.Length != 2) //{ // if (UserInfoHandler.GetInfo("Short Name is supposed to have two characters. Do you want to correct?", MessageBoxButtons.YesNo) == DialogResult.Yes) // return; //} DialogResult = DialogResult.OK; Close(); }
// note: this assumes an existing EM3Translation-folder (as sub-folder of emPath) and takes only the translated countries in there into account public static bool GetInfoCountries(string emPath, out List <CountryInfo> countryInfo, out string errorsAndWarnings, bool getDatasets = true, bool getRunOptions = true) { errorsAndWarnings = string.Empty; countryInfo = new List <CountryInfo>(); EMPath pathHelper = new EMPath(emPath); try { if (!Directory.Exists(pathHelper.GetFolderCountries())) { errorsAndWarnings = $"Folder {pathHelper.GetFolderCountries()} not found"; return(false); } object writeLock = new object(); List <CountryInfo> localCountryInfo = new List <CountryInfo>(); string localErrors = string.Empty; Parallel.ForEach(new DirectoryInfo(pathHelper.GetFolderCountries()).GetDirectories(), folder => { lock (writeLock) { if (GetInfoCountry(pathHelper.GetCountryFilePath(folder.Name), out CountryInfo ci, out string error, getDatasets, getRunOptions)) { localCountryInfo.Add(ci); } else { localErrors += error + Environment.NewLine; } }
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); }
/// <summary> /// reads the EM2 variables file and transfers it to EM3 style /// creates the config folder, if it does not exist, and overwrites any existing variables file /// note: the intended usage is "single variables transformation" /// the EM3All class is responsible for complete EM-content transformation (using the EM3Variables.Write functions) /// </summary> /// <param name="emPath"> EuromodFiles folder (containing EM2-files in XMLParam and (will contain) EM3-files in EM3Translation\XMLParam) </param> /// <param name="errors"> critical and non-critical erros during the transformation-process, empty structure for no errors </param> public static bool Transform(string emPath, out List <string> errors) { errors = new List <string>(); EMPath pathHandler = new EMPath(emPath); try { DirectoryInfo di = Directory.CreateDirectory(pathHandler.GetFolderConfig()); if (TransformerCommon.IsFileUpToDate(pathHandler.GetVarFilePath(em2: true), di.FullName, out string hashCode)) { return(true); } // read EM2-file EM2Variables.Content content = EM2Variables.Read(pathHandler.GetFolderConfig(em2: true), out List <string> rErrors); if (content == null) { errors = rErrors; return(false); } // transfer to EM3-structure bool success = Write(content, emPath, out List <string> wErrors); errors.AddRange(wErrors); if (success && errors.Count == 0) { TransformerCommon.WriteUpToDate(pathHandler.GetVarFilePath(em2: true), di.FullName, hashCode); } return(success); } catch (Exception exception) { errors.Add($"Variables: {exception.Message}"); return(false); } }
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 static void CleanLogFile() { string logFile = new EMPath(EM_AppContext.FolderEuromodFiles).GetEmLogFilePath(); EM_UI_MainForm mainForm = EM_AppContext.Instance.GetActiveCountryMainForm(); if (mainForm != null) { mainForm.Cursor = Cursors.WaitCursor; } string error = AdaptLogFile(logFile); if (mainForm != null) { mainForm.Cursor = Cursors.Default; } if (error == string.Empty) { UserInfoHandler.ShowSuccess("Successfully cleaned " + logFile + "."); } else { UserInfoHandler.ShowError("Failed to clean " + logFile + ":" + Environment.NewLine + error); } }
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 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); } }
public static bool IsUpToDate(string emPath, string country) { EMPath pathHandler = new EMPath(emPath); return(TransformerCommon.IsFileUpToDate(pathHandler.GetCountryFilePath(country, true), pathHandler.GetCountryFolderPath(country), out string hash1) && TransformerCommon.IsFileUpToDate(pathHandler.GetEM2DataConfigFilePath(country), pathHandler.GetCountryFolderPath(country), out string hash2)); }
internal static void ReportSuccessAndInfo(string successfulAction, string backUpFolder, bool autoRestore = true) { UserInfoHandler.ShowSuccess(successfulAction + " succeeded!" + Environment.NewLine + Environment.NewLine + "Please note that a back-up of the version before the action is stored under " + Environment.NewLine + EMPath.Folder_BackUps(EM_AppContext.FolderEuromodFiles) + backUpFolder + "." + Environment.NewLine + Environment.NewLine + (autoRestore ? "You may restore it via the button 'Restore' in the ribbon 'Country Tools'." : string.Empty)); }
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 internal void LoadAddOns() { if (!Directory.Exists(EMPath.Folder_AddOns(EM_AppContext.FolderEuromodFiles))) { return; } DirectoryInfo folderAddOns = new DirectoryInfo(EMPath.Folder_AddOns(EM_AppContext.FolderEuromodFiles)); foreach (FileInfo addOnFile in folderAddOns.GetFiles("*.xml")) { string addOnShortName = addOnFile.Name.Substring(0, addOnFile.Name.Length - addOnFile.Extension.Length); if (_countries.Keys.Contains(addOnShortName.ToLower())) { continue; //add-on already in countries list } Country addOn = new Country(); addOn._shortName = addOnShortName; string flagPathAndFileName = new EMPath(EM_AppContext.FolderEuromodFiles).GetFolderImages() + addOn._shortName + _imageExtension; addOn._flag = GetImageFromFile(flagPathAndFileName, global::EM_UI.Properties.Resources.NoAddOnImage); addOn._isAddOn = true; _countries.Add(addOn._shortName.ToLower(), addOn); } }
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); } }
/// <summary> /// reads EM2 global files (for ex-rates, hicp, glo-switches) and transfers them to EM3 style /// creates the config folder, if it does not exist, and overwrites any existing global file /// note: the intended usage is "single transformation of global files" /// the EM3All class is responsible for complete EM-content transformation (using the EM3Global.WriteXXX functions) /// </summary> /// <param name="emPath"> EuromodFiles folder (containing EM2-files in XMLParam and (will contain) EM3-files in EM3Translation\XMLParam) </param> /// <param name="errors"> critical and non-critical erros during the transformation-process, empty structure for no errors </param> /// <param name="mustExist"> if false, the non-existence of any global file does not produce an error </param> public static bool Transform(string emPath, out List <string> errors, bool mustExist = false) { errors = new List <string>(); EMPath pathHandler = new EMPath(emPath); try { DirectoryInfo di = Directory.CreateDirectory(pathHandler.GetFolderConfig()); // read EM2-files List <List <MultiProp> > exRates = EM2Global.ReadExRates(pathHandler.GetFolderConfig(em2: true), out List <string> _errors, mustExist); errors.AddRange(_errors); List <List <MultiProp> > hicp = EM2Global.ReadHICP(pathHandler.GetFolderConfig(em2: true), out _errors, mustExist); errors.AddRange(_errors); List <List <MultiProp> > switches = EM2Global.ReadSwitchPol(pathHandler.GetFolderConfig(em2: true), out _errors, mustExist); errors.AddRange(_errors); // transfer to EM3-structure bool success = WriteExRates(exRates, emPath, out _errors); errors.AddRange(_errors); success &= WriteHICP(hicp, emPath, out _errors); errors.AddRange(_errors); success &= WriteExtensions(switches, emPath, out _errors); errors.AddRange(_errors); return(success); } catch (Exception exception) { errors.Add($"Global files: {exception.Message}"); return(false); } }
private void btnOK_Click(object sender, EventArgs e) { int selCount = listFiles.SelectedIndices.Count; if (selCount < templateInfo.minFiles || selCount > templateInfo.maxFiles) { if (templateInfo.maxFiles == 1) { MessageBox.Show("Please select a file."); // is the same as selCount=0 (as list is in single-selection mode) } else if (templateInfo.minFiles == templateInfo.maxFiles) { MessageBox.Show(string.Format("Please select {0} files.", templateInfo.maxFiles)); } else if (templateInfo.maxFiles == int.MaxValue) { MessageBox.Show(string.Format("Please select at least {0} files.", templateInfo.minFiles)); } else { MessageBox.Show(string.Format("Please select {0} to {1} files.", templateInfo.minFiles, templateInfo.maxFiles)); } return; } filePackages = new List <FilePackageContent>(); foreach (var file in selectedIndices.Select(i => listFiles.Items[i])) { string fileFullPath = Path.Combine(textPath.Text, file.ToString()); if (templateInfo.templateType == HardDefinitions.TemplateType.Default) { filePackages.Add(new FilePackageContent() { PathBase = fileFullPath }); } else // MULTI_ALT { if (filePackages.Count == 0) { filePackages.Add(new FilePackageContent()); } filePackages[0].PathsAlt.Add(fileFullPath); } } // save selected paths in UI-user-settings (see EM_UI.PlugInService.SessionInfo.cs, about why not using an own settings-file) if (!EMPath.IsSamePath(textPath.Text.ToLower(), UISessionInfo.GetOutputFolder().ToLower())) // if the path was changed: save in user-settings ... { UISessionInfo.SetRetainedUserSetting(StatisticsPresenter.USER_SETTINGS_ID, StatisticsPresenter.BASE_OUTPUT_FOLDER, textPath.Text); } else // ... if path corresponds with default-output-folder: remove from user-settings, to avoid that it will remain, if user changes the default-path in project settings { UISessionInfo.RemoveRetainedUserSetting(StatisticsPresenter.USER_SETTINGS_ID, StatisticsPresenter.BASE_OUTPUT_FOLDER); } DialogResult = DialogResult.OK; Close(); }
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); }
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)); } }
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); }
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)); }
internal static bool RestoreCountry(EM_UI_MainForm mainForm, string backUpFolder = "") { bool reportSuccess = false; if (backUpFolder == string.Empty) //called via button in MainForm { FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog(); folderBrowserDialog.SelectedPath = EMPath.Folder_BackUps(EM_AppContext.FolderEuromodFiles); folderBrowserDialog.Description = "Please select the back-up folder"; if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) { return(true); } backUpFolder = folderBrowserDialog.SelectedPath; reportSuccess = true; } else //called from a catch-branch, i.e. using just generated back-up in Temp/BackUp { backUpFolder = EMPath.Folder_BackUps(EM_AppContext.FolderEuromodFiles) + backUpFolder; } string countryShortName = mainForm.GetCountryShortName(); bool isAddOn = CountryAdministrator.IsAddOn(countryShortName); try { //check if backUpFolder contains the necessary files and if the files actually contain a backup of the loaded country/add-on ... string errorMessage; if (!Country.DoesFolderContainValidXMLFiles(countryShortName, out errorMessage, backUpFolder, isAddOn, true)) //check if countryShortName corresponds to country's short name as stored in the XML-file { throw new System.ArgumentException(errorMessage); } //... if yes, copy files form backup-folder to Countries-folder if (!Country.CopyXMLFiles(countryShortName, out errorMessage, backUpFolder)) { throw new System.ArgumentException(errorMessage); } mainForm.ReloadCountry(); if (reportSuccess) //report success only if called via button (and not if called by a failed function) { UserInfoHandler.ShowSuccess("Successfully restored using back-up stored in" + Environment.NewLine + backUpFolder + "."); } 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 via the button in the ribbon 'Country Tools'." + Environment.NewLine + Environment.NewLine + exception.Message); return(false); } }
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()); } }
static internal System.Drawing.Image GetFlag(string shortName, bool addOn) { string flagName = shortName + _imageExtension; string flagPath = GetFlagPath(shortName, addOn); //first search at the "new" storage place if (!File.Exists(flagPath + flagName)) { flagPath = new EMPath(EM_AppContext.FolderEuromodFiles).GetFolderImages(); //if not found, try the "old" storage place } return(GetImageFromFile(flagPath + flagName, addOn ? global::EM_UI.Properties.Resources.NoAddOnImage : global::EM_UI.Properties.Resources.NoFlag)); }
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)); } }
internal static string StoreCountry(EM_UI_MainForm mainForm, bool storeChanges = true) { CleanBackupFolder(); //delete all folders which are older than 3 days to avoid that the backup folder gets too big //outcommented as it is probably more confusing to inform the user than that one cannot undo actions before this (probably big) action ... //if (undoManager.HasChanges() && Tools.UserInfoHandler.GetInfo("Please note that the action generates a backup and therefore must reset the undo list. That means no undoing of actions up until now will be possible.", // MessageBoxButtons.OKCancel) == DialogResult.Cancel) // return false; //... instead pose this easier to understand question (i.e. only ask for saving unsaved changes, but not for any undo-stuff) if (storeChanges && mainForm.HasChanges() && Tools.UserInfoHandler.GetInfo("Do you want to save changes?", MessageBoxButtons.OKCancel) == DialogResult.Cancel) { return(string.Empty); } try { //the action will directly operate the XML-files therefore changes need to be commited and saved, unless explicitly not wished if (storeChanges) { SaveDirectXMLAction(mainForm); } //create a backup by copying files from Countries-folder 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 countryShortName = mainForm.GetCountryShortName(); string backUpFolder = countryShortName + "_" + DateTime.Now.ToString("yyyy-MM-dd_H-mm-ss"); //backup-folder is name e.g. uk_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); } //copy XML-files (e.g. uk.xml + uk_DataConfig.xml or LMA.xml) string errorMessage; if (!Country.CopyXMLFiles(countryShortName, out errorMessage, string.Empty, EMPath.AddSlash(EMPath.Folder_BackUps(EM_AppContext.FolderEuromodFiles) + backUpFolder))) { throw new System.ArgumentException(errorMessage); } return(backUpFolder); } catch (Exception exception) { UserInfoHandler.ShowException(exception); return(string.Empty); } }
void UpdateSwitchTable(bool reportInvalid = true) { _selectedPolicyID = string.Empty; if (lvSwitchablePolicies.CheckedItems.Count == 0) { return; //leave table empty if no switchable policy is available } //find out which switchable policy is selected _selectedPolicyID = (lvSwitchablePolicies.CheckedItems[0].Tag != null) ? lvSwitchablePolicies.CheckedItems[0].Tag.ToString() : string.Empty; txtSelectedSwitchPolicy.Text = lvSwitchablePolicies.CheckedItems[0].Text; string invalidDefaultSwiches = string.Empty; foreach (DataGridViewRow dgvRow in dgvSwitches.Rows) { for (int columnIndex = 0; columnIndex < dgvSwitches.Columns.Count; ++columnIndex) { //run over available dataset-system combinations dgvRow.Cells[columnIndex].Value = string.Empty; //if dataset is not applicable for the system put an emtpy string, which is overwritten, if a db-system-combination is found dgvRow.Cells[columnIndex].ReadOnly = true; foreach (DataConfig.DBSystemConfigRow dbSystemConfigRow in from ds in _dataConfig.DBSystemConfig where ds.DataBaseID == dgvRow.Tag as string select ds) { //if dataset is applicable for the system, get (if exists) the policy-switch value for this switchable policy (i.e. the selected switchable policy), system and dataset if (dbSystemConfigRow.SystemID == (dgvSwitches.Columns[columnIndex].Tag as CountryConfig.SystemRow).ID) { string defaultSwitch = GetExtensionDefaultSwitch(dbSystemConfigRow, _selectedPolicyID); if (defaultSwitch != DefPar.Value.ON && defaultSwitch != DefPar.Value.OFF && defaultSwitch != DefPar.Value.NA) { invalidDefaultSwiches += Environment.NewLine + $"Invalid Switch: '{defaultSwitch}' for {txtSelectedSwitchPolicy.Text}/{dbSystemConfigRow.DataBaseRow.Name}/{dbSystemConfigRow.SystemName}"; } else { dgvRow.Cells[columnIndex].Value = defaultSwitch; } dgvRow.Cells[columnIndex].ReadOnly = false; dgvRow.Cells[columnIndex].Tag = dbSystemConfigRow; break; } } } } if (reportInvalid && !string.IsNullOrEmpty(invalidDefaultSwiches)) { UserInfoHandler.ShowError( $"{EMPath.GetEM2DataConfigFileName(_countryShortName)} contains invalid default switches!!!" + Environment.NewLine + (invalidDefaultSwiches.Length > 1500 ? invalidDefaultSwiches.Substring(0, 1500) + "..." : invalidDefaultSwiches)); } }
private void EM3_Transform(string country, string addOn) { try { EMPath emPath = new EMPath(EM_AppContext.FolderEuromodFiles); lock (transformLock) { bool success = TransformCountry() && TransformAddOn() && (em3_transformGlobals == false || (TransformGlobals() && TransformVariables())); } bool TransformCountry() { bool ok = EM3Country.Transform(emPath.GetFolderEuromodFiles(), country, out List <string> transErrors); AddErrorRange(transErrors); return(ok); } bool TransformGlobals() { bool ok = EM3Global.Transform(emPath.GetFolderEuromodFiles(), out List <string> transErrors); AddErrorRange(transErrors); return(ok); } bool TransformVariables() { bool ok = EM3Variables.Transform(emPath.GetFolderEuromodFiles(), out List <string> transErrors); AddErrorRange(transErrors); return(ok); } bool TransformAddOn() { if (string.IsNullOrEmpty(addOn)) { return(true); } bool ok = EM3Country.TransformAddOn(emPath.GetFolderEuromodFiles(), addOn, out List <string> transErrors); AddErrorRange(transErrors); return(ok); } } catch (Exception exception) { em3_petInfo.AddSystemIndependentError(exception.Message); } void AddErrorRange(List <string> errors) { foreach (string error in errors) { em3_petInfo.AddSystemIndependentError(error); } } }
/// <summary> /// reads a country's EM2 country- and dataconfig-XML-files and transfers them to EM3 style /// creates the country folder, if it does not exist, and overwrites any existing country file /// note: the intended usage is "single country transformation" /// the EM3All class is responsible for complete EM-content transformation (using the EM3Country.Write function) /// </summary> /// <param name="emPath"> EuromodFiles folder (containing EM2-files in XMLParam and (will contain) EM3-files in EM3Translation\XMLParam) </param> /// <param name="country"> short-name of country </param> /// <param name="errors"> critical and non-critical erros during the transformation-process, empty structure for no errors </param> public static bool Transform(string emPath, string country, out List <string> errors) { errors = new List <string>(); EMPath pathHandler = new EMPath(emPath); string em2CountryFile = string.Empty, em2DataFile = string.Empty; try { DirectoryInfo di = Directory.CreateDirectory(pathHandler.GetCountryFolderPath(country)); // read EM2-files em2CountryFile = pathHandler.GetCountryFilePath(country: country, em2: true); em2DataFile = pathHandler.GetEM2DataConfigFilePath(country); bool up2D1 = TransformerCommon.IsFileUpToDate(em2CountryFile, pathHandler.GetCountryFolderPath(country), out string hash1); bool up2D2 = TransformerCommon.IsFileUpToDate(em2DataFile, pathHandler.GetCountryFolderPath(country), out string hash2); if (up2D1 && up2D2) { return(true); // do not combine in one if, to make sure that both hash-files (for country and dataconfig) are generated } EM2Country.Content ctryContent = EM2Country.Read(em2CountryFile, out List <string> cErrors); EM2Data.Content dataContent = EM2Data.Read(em2DataFile, out List <string> dErrors); // need the global file with policy-switches for proper transformation of local policy switches List <List <MultiProp> > extensions = EM2Global.ReadSwitchPol(pathHandler.GetFolderConfig(em2: true), out List <string> gErrors); errors.AddRange(cErrors); errors.AddRange(dErrors); errors.AddRange(gErrors); if (ctryContent == null || dataContent == null || extensions == null) { return(false); } // write EM3-file (includes EM2->EM3 adaptations, via EM23Adapt class) string em3CountryFile = pathHandler.GetCountryFilePath(country); bool success = Write(ctryContent, dataContent, extensions, em3CountryFile, out List <string> wErrors); errors.AddRange(wErrors); if (success && errors.Count == 0) { TransformerCommon.WriteUpToDate(em2CountryFile, pathHandler.GetCountryFolderPath(country), hash1); TransformerCommon.WriteUpToDate(em2DataFile, pathHandler.GetCountryFolderPath(country), hash2); } return(success); } catch (Exception exception) { errors.Add($"{country}: {exception.Message}"); return(false); } }
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]); } }
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); }