private static void SetPrivate_BackgroundEventHandler(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker backgroundWorker = sender as BackgroundWorker; if (backgroundWorker.CancellationPending)
            {
                e.Cancel = true; return;
            }
            Tuple <string, bool> settings = e.Argument as Tuple <string, bool>; string extName = settings.Item1; bool set = settings.Item2;

            try
            {
                List <Country> countries = CountryAdministrator.GetCountries();
                for (int i = 0; i < countries.Count; ++i)
                {
                    if (backgroundWorker.CancellationPending)
                    {
                        e.Cancel = true; return;
                    }
                    Country country = countries[i]; CountryConfigFacade ccf = country.GetCountryConfigFacade();
                    ExtensionSetPrivateAction action = new ExtensionSetPrivateAction(extName, countries[i]._shortName, set);
                    action.PerformAction();
                    if (!action.ActionIsCanceled()) // happens if extension has no content
                    {
                        country.WriteXML(); country.SetCountryConfigFacade(null); country.SetDataConfigFacade(null);
                    }
                    backgroundWorker.ReportProgress(Convert.ToInt32((i + 1.0) / (countries.Count * 1.0) * 100.0));
                }
                if (backgroundWorker.CancellationPending)
                {
                    e.Cancel = true; return;
                }
            }
            catch (Exception exception) { UserInfoHandler.ShowException(exception); e.Cancel = true; }
        }
        private bool AddYear(int year = -1)
        {
            try
            {
                bool showWarning = false;
                if (year == -1)
                {
                    showWarning = true;
                    year        = Convert.ToInt32(updwnYearToAdd.Value);
                    if (GetExistingYears().Contains(year))
                    {
                        UserInfoHandler.ShowError(year + " already exits."); return(false);
                    }
                }
                int preCount = GetExistingYears().Where(y => y < year).ToList().Count();

                if (!dgvHICP.AddColumn(showWarning, year.ToString(), typeof(double), preCount + 1))
                {
                    ShowGridLastError(); return(false);
                }
                dgvHICP.pasteableColumns.Add(year.ToString());
                updwnYearToAdd.Value = year + 1;
                cmbYearToDelete.Items.Add(year);

                FormatGridViewColumns(year.ToString());
                return(true);
            }
            catch (Exception exception) { UserInfoHandler.ShowException(exception); return(false); }
        }
 private void btnSave_Click(object sender, EventArgs e)
 {
     try
     {
         string path = Path.Combine(EM_AppContext.FolderOutput, "ReleaseValidation_HHVarInfo.txt");
         using (StreamWriter sw = new StreamWriter(path))
         {
             foreach (DataGridViewRow row in dgvVar.Rows)
             {
                 string line = $"{row.Cells[0].Value.ToString()}\t";
                 string info = row.Cells[1].Value.ToString();
                 if (!info.Contains(SEPARATOR))
                 {
                     line += info;
                 }
                 else
                 {
                     foreach (string i in info.Split(SEPARATOR.First()))
                     {
                         line += $"{i.Trim()}\t";
                     }
                 }
                 sw.WriteLine(line.Trim());
             }
         }
         UserInfoHandler.ShowSuccess($"Saved to {path}");
     }
     catch (Exception exception) { UserInfoHandler.ShowException(exception); }
 }
        void btnOK_Click(object sender, EventArgs e)
        {
            if (!dgvHICP.verifyNumericValues(out string problems))
            {
                UserInfoHandler.ShowError("There are cells with invalid values!" + Environment.NewLine + problems);
                return;
            }

            updatedHICPs = new List <Tuple <string, int, double, string> >();
            DataTable dtHICP = dgvHICP.GetDataTable();

            foreach (DataRow r in dtHICP.Rows)
            {
                foreach (DataColumn c in dtHICP.Columns)
                {
                    if (c.Caption == colCountry || c.Caption == colComment || c.Caption == colID || r.IsNull(c.Caption))
                    {
                        continue;
                    }
                    try
                    {
                        updatedHICPs.Add(new Tuple <string, int, double, string>(
                                             r.Field <string>(colCountry),          // country
                                             Convert.ToInt32(c.Caption),            // year
                                             double.Parse(r[c.Caption].ToString()), // value
                                             r.Field <string>(colComment)));        // comment
                    }
                    catch (Exception exception) { UserInfoHandler.ShowException(exception, $"{r.Field<string>(colCountry)} / {c.Caption}", false); return; }
                }
            }

            DialogResult = DialogResult.OK;
            Close();
        }
        void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgvSwitchablePolicies.SelectedRows.Count != 1)
            {
                return;
            }

            try
            {
                //deleting an existing switchable policy may need to require an update of country files (which is too complex here)
                //example: delete bun*_??: all switches defined for the matching policies of the country would have to be changed from 'switch' to 'toggle'
                //removal in the country files however only takes place on closing the SetPolicySwitchesForm with 'OK' - thus this warning
                VarConfig.SwitchablePolicyRow switchablePolicyRow = (dgvSwitchablePolicies.SelectedRows[0].Tag as VarConfig.SwitchablePolicyRow);
                if (switchablePolicyRow.RowState != DataRowState.Added && UserInfoHandler.GetInfo(_noUpdateInCountriesWarning, MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.Cancel)
                {
                    return;
                }

                switchablePolicyRow.Delete();
                dgvSwitchablePolicies.Rows.Remove(dgvSwitchablePolicies.SelectedRows[0]);
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowException(exception);
            }

            dgvSwitchablePolicies.Update(); //if gridview is not updated it looks weired (text of two rows are displayed in one)
        }
        void GetFromClipboard()
        {
            try
            {
                string   clipboardText          = Clipboard.GetText();
                string[] clipboardLines         = clipboardText.Split('\n');
                int      indexRow               = table.CurrentCell.RowIndex;
                bool     addedExtraLine         = (indexRow == dataTable.Rows.Count);
                int      currentCellColumnIndex = table.Columns[table.CurrentCell.ColumnIndex].DisplayIndex;
                foreach (string line in clipboardLines)
                {
                    if (line.Length > 0)
                    {
                        DataRow row;
                        if (indexRow == dataTable.Rows.Count)
                        {
                            row = dataTable.NewRow();
                            dataTable.Rows.Add(row);
                        }
                        else
                        {
                            row = dataTable.Rows[indexRow];
                        }

                        string[] clipboardCells = line.Split('\t').Select(p => p.Trim()).ToArray(); // trim cells to avoid unwanted new lines and spaces at the end
                        for (int indexColumn = 0; indexColumn < clipboardCells.GetLength(0); ++indexColumn)
                        {
                            if (currentCellColumnIndex + indexColumn < table.ColumnCount)
                            {
                                // if one of the default columns
                                if (currentCellColumnIndex + indexColumn == table.Columns[colName.Name].DisplayIndex ||
                                    currentCellColumnIndex + indexColumn == table.Columns[colComment.Name].DisplayIndex)
                                {
                                    row[GetYearColumnIndexByDisplayIndex(currentCellColumnIndex + indexColumn)] = clipboardCells[indexColumn];
                                }
                                else                                                                                                                             // if one of the system columns
                                {
                                    row[GetYearColumnIndexByDisplayIndex(currentCellColumnIndex + indexColumn)] = clipboardCells[indexColumn].Replace(',', '.'); // fix decimal separator
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                        (table[0, indexRow].OwningRow.DataBoundItem as DataRowView).Row.EndEdit();
                        indexRow++;
                    }
                    else
                    {
                        break;
                    }
                }
                if (addedExtraLine)
                {
                    table.Rows.RemoveAt(table.Rows.Count - 2);                    // get rid of the extra line added by the grid
                }
            }
            catch (Exception exception) { UserInfoHandler.ShowException(exception); return; }
        }
        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);
            }
        }
        internal IndirectTaxesForm(EM_UI_MainForm _mainForm)
        {
            InitializeComponent();

            try
            {
                mainForm = _mainForm;

                dataSet.Tables.Add(dataTable);
                table.DataSource = dataSet;
                table.DataMember = "IttDataTable";

                LoadTableContent();

                // only after all the data is loaded, add the row numbers and the refresh listeners
                table.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
                table.RowsAdded   += new DataGridViewRowsAddedEventHandler(table_RefreshRowNumbers);
                table.RowsRemoved += new DataGridViewRowsRemovedEventHandler(table_RefreshRowNumbers);

                table_RefreshRowNumbers(null, null);
                colName.Frozen = true;
                //colComment.Frozen = true; // this can only happen if it is not the last row!
            }
            catch (Exception exception) { UserInfoHandler.ShowException(exception); }
        }
Beispiel #9
0
        internal void GenerateInfo(string outputFilePath, List <string> _countries)
        {
            EM_UI_MainForm mainForm = EM_AppContext.Instance.GetActiveCountryMainForm(); if (mainForm != null)

            {
                mainForm.Cursor = Cursors.WaitCursor;
            }

            try
            {
                countries = _countries;
                AssessCountryInfo();
                InitExcelFile(outputFilePath);
                FillExcelFile();
                spreadsheetControl.SaveDocument();
                UserInfoHandler.ShowSuccess(string.Format("Successfully generated Release info file '{0}'.", outputFilePath)); // perhaps open ???
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowException(exception, string.Format("Failed to generate Release info file '{0}'.", outputFilePath), false);
            }
            finally { if (mainForm != null)
                      {
                          mainForm.Cursor = Cursors.Default;
                      }
            }
        }
        private void menuItemDelSys_Click(object sender, EventArgs e = null)
        {
            string system; DataGridViewRow clickedRow; if (!menuItem_GetActionInfo(sender, out system, out clickedRow))

            {
                return;
            }

            try
            { // just try to remove the system from any row of this country, thus move can be realised as del+add
                string country = clickedRow.Cells[colCountry.Name].Value.ToString().ToLower();
                foreach (DataGridViewRow row in dgvRates.Rows)
                {
                    if (row.Cells[colCountry.Name].Value.ToString().ToLower() != country || row.Cells[colValidFor.Name].Value == null)
                    {
                        continue;
                    }
                    bool calledFromMove = e == null; // if called from Move suppress storing undo action, to store it together with the following Add
                    if (!dgvRates.SetCellValue(row, colValidFor.Name,
                                               ExchangeRate.RemoveFromValidFor(row.Cells[colValidFor.Name].Value.ToString(), system),
                                               !calledFromMove))
                    {
                        ShowGridLastError();
                    }
                }
            }
            catch (Exception exception) { UserInfoHandler.ShowException(exception); }
        }
Beispiel #11
0
        void SetAllDatasetsTo(string value)
        {
            try
            {
                int systemColumn = GetHitColumn();

                if (systemColumn == -1)
                {
                    UserInfoHandler.ShowInfo("Please open the menu via a position within the respective system's column.");
                    return;
                }

                foreach (DataGridViewRow row in dgvSwitches.Rows)
                {
                    if (row.Cells[systemColumn].ReadOnly == false)
                    {
                        row.Cells[systemColumn].Value = value;
                    }
                }
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowException(exception);
            }
        }
Beispiel #12
0
        void SetAllSystemsTo(string value)
        {
            try
            {
                int datasetRow = GetHitRow();
                if (datasetRow == -1)
                {
                    UserInfoHandler.ShowInfo("Please open the menu via a position within the respective dataset's row.");
                    return;
                }

                DataGridViewRow row = dgvSwitches.Rows[datasetRow];
                foreach (DataGridViewColumn column in dgvSwitches.Columns)
                {
                    if (row.Cells[column.Index].ReadOnly == false)
                    {
                        row.Cells[column.Index].Value = value;
                    }
                }
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowException(exception);
            }
        }
        void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridViewRow row in dgvSwitchablePolicies.Rows)
                {
                    object valueLongName    = row.Cells[colLongName.Name].Value;
                    object valueNamePattern = row.Cells[colNamePattern.Name].Value;
                    if (valueLongName == null || valueLongName.ToString().Trim() == string.Empty ||
                        valueNamePattern == null || valueNamePattern.ToString().Trim() == string.Empty)
                    {
                        UserInfoHandler.ShowError("Row " + row.Index.ToString() + " is not completely defined. Please complete or delete the row.");
                        return;
                    }
                }

                _varConfigFacade._varConfig.AcceptChanges();
                _varConfigFacade.WriteXML();
                DialogResult = DialogResult.OK;
                Close();
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowException(exception);
            }
        }
        internal bool RefreshExchangeRates(List <ExchangeRate> exRates)
        {
            try
            {
                for (int i = 0; i < exRates.Count; ++i) // "make efficient", i.e. if country, rates and default are equal, gather the concerned systems in one rate
                {
                    for (int j = i - 1; j >= 0; --j)
                    {
                        if (exRates[i].Equals(exRates[j]))
                        {
                            exRates[i].AddToValidFor(exRates[j].ValidFor); exRates[j].ValidFor = string.Empty; break;
                        }
                    }
                }

                _exchangeRatesConfig.ExchangeRates.Rows.Clear();
                _exchangeRatesConfig.AcceptChanges();
                foreach (ExchangeRate exRate in exRates)
                {
                    if (exRate.ValidFor != string.Empty)
                    {
                        _exchangeRatesConfig.ExchangeRates.AddExchangeRatesRow(
                            exRate.Country, exRate.June30, exRate.YearAverage, exRate.FirstSemester, exRate.SecondSemester, exRate.Default, exRate.ValidFor);
                    }
                }
                _exchangeRatesConfig.AcceptChanges();
                return(true);
            }
            catch (Exception exception) { UserInfoHandler.ShowException(exception); return(false); }
        }
 void CopyToClipboard()
 {
     if (table.GetCellCount(DataGridViewElementStates.Selected) > 0)
     {
         try { Clipboard.SetDataObject(table.GetClipboardContent()); }
         catch (Exception exception) { UserInfoHandler.ShowException(exception); }
     }
 }
Beispiel #16
0
        internal UpratingIndicesForm(EM_UI_MainForm mainForm)
        {
            InitializeComponent();

            try
            {
                _mainForm            = mainForm;
                _countryConfigFacade = EM_UI.CountryAdministration.CountryAdministrator.GetCountryConfigFacade(_mainForm.GetCountryShortName());
                _dataConfigFacade    = EM_UI.CountryAdministration.CountryAdministrator.GetDataConfigFacade(_mainForm.GetCountryShortName());

                dgvDataSet.Tables.Add(dgvDataTable);
                dgvIndices.DataSource = dgvDataSet;
                dgvIndices.DataMember = "dgvDataTable";

                //load the information for the 'Raw Indices' tab
                LoadIndices();

                //load the information for the 'Factors per Data and System' tab ...
                //... datasets (for selection by the user)
                foreach (DataConfig.DataBaseRow dataSet in _dataConfigFacade.GetDataBaseRows())
                {
                    cmbDatasets.Items.Add(dataSet.Name);
                }
                //... and systems (for the table)
                foreach (CountryConfig.SystemRow system in _countryConfigFacade.GetSystemRowsOrdered())
                {
                    bool showSystem = false;
                    foreach (DevExpress.XtraTreeList.Columns.TreeListColumn c in mainForm.treeList.VisibleColumns)
                    {
                        showSystem = showSystem || (c.Name.ToLower() == system.Name.ToLower());
                    }
                    if (showSystem)
                    {
                        DataGridViewColumn headerColumn = colIndexName.Clone() as DataGridViewColumn; //clone the factorname-column to overtake the settings
                        headerColumn.Name       = system.ID;                                          //to be able to identify each system column, when the table is filled
                        headerColumn.HeaderText = system.Name;
                        int index = dgvFactors.Columns.Add(headerColumn);
                        dgvFactors.Columns[index].Tag = system;
                    }
                }

                // only after all the data is loaded, add the row numbers and the refresh listeners
                dgvIndices.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
                dgvIndices.RowsAdded   += new System.Windows.Forms.DataGridViewRowsAddedEventHandler(dgvIndices_RefreshRowNumbers);
                dgvIndices.RowsRemoved += new System.Windows.Forms.DataGridViewRowsRemovedEventHandler(dgvIndices_RefreshRowNumbers);

                dgvIndices_RefreshRowNumbers(null, null);
                colIndexDescription.Frozen = true;
                colReference.Frozen        = true;
//                colComment.Frozen = true;     // this can only happen if it is not the last row!
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowException(exception);
            }
        }
Beispiel #17
0
        internal static void StoreSettings(EM_UI_MainForm mainForm)
        {
            if (!keepMode)
            {
                return;
            }
            CountryViewSetting setting = new CountryViewSetting();
            string             cc      = mainForm.GetCountryShortName();

            try
            {
                foreach (TreeListColumn col in mainForm.treeList.Columns)
                {
                    setting.systemWidths.Add(col.Caption, col.Width);
                    if (!col.Visible)
                    {
                        setting.hiddenSystems.AddUnique(col.Caption, true);
                    }
                }
                foreach (TreeListNode polNode in mainForm.treeList.Nodes)
                {
                    AddHiddenNode(ref setting.hiddenNodes, polNode);
                    foreach (TreeListNode funcNode in polNode.Nodes)
                    {
                        AddHiddenNode(ref setting.hiddenNodes, funcNode);
                        foreach (TreeListNode parNode in funcNode.Nodes)
                        {
                            AddHiddenNode(ref setting.hiddenNodes, parNode);
                        }
                    }
                }
                if (mainForm.GetTreeListBuilder() != null)
                {
                    setting.textSize = mainForm.GetTreeListBuilder().GetTextSize();
                }

                if (countryViewSettings.ContainsKey(cc))
                {
                    countryViewSettings[cc] = setting;
                }
                else
                {
                    countryViewSettings.Add(cc, setting);
                }
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowException(exception, "Failed to store view settings for " + cc + ". Settings are set back to default.", false);
                if (countryViewSettings.ContainsKey(cc))
                {
                    countryViewSettings.Remove(cc);
                }
            }
        }
Beispiel #18
0
        internal static void DoAdmin()
        {
            SwitchablePolicyConfigFacade globalExtensionConfigFacade = EM_AppContext.Instance.GetSwitchablePolicyConfigFacade();
            SwitchablePolicyConfig       globalExtensionConfig       = globalExtensionConfigFacade.GetSwitchablePolicyConfig();

            try
            {
                List <ExtensionOrGroup> extensions = new List <ExtensionOrGroup>();
                foreach (var sp in globalExtensionConfig.SwitchablePolicy)
                {
                    extensions.Add(new ExtensionOrGroup(sp));
                }

                AdminExtensionsOrGroupsForm adminDialog = new AdminExtensionsOrGroupsForm("Administrate Global Extensions", extensions, true);

                if (adminDialog.ShowDialog() == DialogResult.Cancel)
                {
                    return;
                }

                foreach (ExtensionOrGroup add in adminDialog.added)
                {
                    globalExtensionConfig.SwitchablePolicy.AddSwitchablePolicyRow(Guid.NewGuid().ToString(), add.name, add.shortName, add.look.ToXml());
                }

                foreach (ExtensionOrGroup change in adminDialog.changed)
                {
                    SwitchablePolicyConfig.SwitchablePolicyRow changeRow = (from ext in globalExtensionConfig.SwitchablePolicy where ext.ID == change.id select ext).First();
                    changeRow.LongName = change.name; changeRow.NamePattern = change.shortName; changeRow.Look = change.look.ToXml();
                }

                List <SwitchablePolicyConfig.SwitchablePolicyRow> delRow = (from ext in globalExtensionConfig.SwitchablePolicy select ext).ToList();
                for (int i = delRow.Count - 1; i >= 0; --i)
                {
                    if (adminDialog.deletedIds.Contains(delRow[i].ID))
                    {
                        delRow[i].Delete();
                    }
                }

                globalExtensionConfigFacade.AcceptChanges();
                globalExtensionConfigFacade.WriteXML();

                foreach (EM_UI_MainForm mainForm in EM_AppContext.Instance.GetOpenCountriesMainForms())
                {
                    mainForm.treeList.Refresh();                                                                                     // update look if necessary
                }
            }
            catch (Exception exception)
            {
                globalExtensionConfigFacade.RejectChanges();
                UserInfoHandler.ShowException(exception);
            }
        }
 internal bool WriteXML()
 {
     try
     {
         _exchangeRatesConfig.AcceptChanges();
         Stream fileStream = new FileStream(new EMPath(EM_AppContext.FolderEuromodFiles).GetExRatesFilePath(true), FileMode.Create);
         using (XmlTextCDATAWriter xmlWriter = new XmlTextCDATAWriter(fileStream, DefGeneral.DEFAULT_ENCODING, _cDataElements))
             _exchangeRatesConfig.WriteXml(xmlWriter);
         return(true);
     }
     catch (Exception exception) { UserInfoHandler.ShowException(exception); return(false); }
 }
 void btnAdd_Click(object sender, EventArgs e)
 {
     try
     {
         int index = dgvSwitchablePolicies.Rows.Add(string.Empty, string.Empty);
         dgvSwitchablePolicies.Rows[index].Tag = _varConfigFacade.AddSwitchablePolicy();
     }
     catch (Exception exception)
     {
         UserInfoHandler.ShowException(exception);
     }
 }
        private void RVHHLevelVarForm_Shown(object sender, EventArgs e)
        {
            try
            {
                // get all HH-level variables from the variables file
                List <string> hhVars = (from v in EM_AppContext.Instance.GetVarConfigFacade().GetVarConfig().Variable
                                        where VariablesManager.IsHHLevel(v) && v.Name.ToLower() != DefVarName.IDHH.ToLower()
                                        select v.Name.ToLower()).ToList();
                // gather the files to check: those fulfilling the pattern and the custom ones
                if (Directory.Exists(dataPath))
                {
                    foreach (string f in Directory.GetFiles(dataPath, namePattern))
                    {
                        dataToCheck.Add(Path.Combine(dataPath, f));
                    }
                }

                // do the checking, showing a progress bar
                // the background-worker gets 2 parameters:
                // - the list of HH-level variables and
                // - the list of files to check
                ProgressIndicator progressIndicator = new ProgressIndicator(CheckData_BackgroundEventHandler, "Checking Data ...",
                                                                            new Tuple <List <string>, List <string> >(hhVars, dataToCheck));
                if (progressIndicator.ShowDialog() != DialogResult.OK)
                {
                    Close(); return;
                }                                                                           // user pressed Cancel

                // interpret the results
                // the background-worker returns 2 results:
                // - the list of variables, each variable with a list of the file(s) that caused problems, and an empty list if there are no problems
                // - a (hopefully empty) list of critical errors, i.e. one for each file that could not be analysed
                Dictionary <string, List <string> > hhVarResults = (progressIndicator.Result as Tuple <Dictionary <string, List <string> >, List <string> >).Item1;
                List <string> problemData = (progressIndicator.Result as Tuple <Dictionary <string, List <string> >, List <string> >).Item2;

                if (problemData.Count > 0)
                {
                    UserInfoHandler.ShowError("The following data could not be checked:" + Environment.NewLine + string.Join(Environment.NewLine, problemData));
                    if (problemData.Count == dataToCheck.Count)
                    {
                        Close(); return;
                    }                                                                // checking failed for all data-files
                }

                // show the results in the grid
                foreach (var result in hhVarResults)
                {
                    string problems = result.Value.Count == 0 ? "No problems found for the checked files" : string.Join(SEPARATOR, result.Value);
                    dgvVar.Rows.Add(result.Key, problems);
                }
            }
            catch (Exception exception) { UserInfoHandler.ShowException(exception); Close(); }
        }
 internal bool WriteXML(string filePath = null)
 {
     try
     {
         AcceptChanges();
         Stream fileStream = new FileStream(filePath ?? _pathSwitchablePolicyConfig, FileMode.Create);
         using (XmlTextCDATAWriter xmlWriter = new XmlTextCDATAWriter(fileStream, DefGeneral.DEFAULT_ENCODING, _cDataElements))
             _switchablePolicyConfig.WriteXml(xmlWriter);
         return(true);
     }
     catch (Exception exception) { UserInfoHandler.ShowException(exception); return(false); }
 }
 private bool LoadSwitchablePolicyConfig()
 {
     try
     {
         _switchablePolicyConfig = new SwitchablePolicyConfig();
         using (StreamReader streamReader = new StreamReader(_pathSwitchablePolicyConfig, DefGeneral.DEFAULT_ENCODING))
             _switchablePolicyConfig.ReadXml(streamReader);
         AcceptChanges();
         return(true);
     }
     catch (Exception exception) { UserInfoHandler.ShowException(exception); return(false); }
 }
        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                if (!dgvRates.verifyNumericValues(out string problems))
                {
                    UserInfoHandler.ShowError("There are cells with invalid values!" + Environment.NewLine + problems);
                    return;
                }
                updatedExRates = new List <ExchangeRate>();
                DataTable dtExRates = dgvRates.GetDataTable();
                foreach (DataRow row in dtExRates.Rows)
                {
                    if (row[colValidFor.Name] == DBNull.Value || row.Field <string>(colValidFor.Name).ToString() == string.Empty)
                    {
                        continue;
                    }
                    string defaultCol = string.Empty;
                    switch (row.Field <string>(colDefault.Name))
                    {
                    case ExchangeRate.JUNE30: defaultCol = colJune30.Name; break;

                    case ExchangeRate.YEARAVERAGE: defaultCol = colYearAverage.Name; break;

                    case ExchangeRate.FIRSTSEMESTER: defaultCol = colFirstSemester.Name; break;

                    case ExchangeRate.SECONDSEMESTER: defaultCol = colSecondSemester.Name; break;
                    }
                    if (row[defaultCol] == DBNull.Value)
                    {
                        UserInfoHandler.ShowInfo(string.Format("{0} ({1}): Default ({2}) must not be empty.",
                                                               row.Field <string>(colCountry.Name), row.Field <string>(colValidFor.Name), defaultCol)); return;
                    }
                    updatedExRates.Add(new ExchangeRate()
                    {
                        Country        = row.Field <string>(colCountry.Name),
                        June30         = row[colJune30.Name] == DBNull.Value ? -1 : double.Parse(row[colJune30.Name].ToString()),
                        YearAverage    = row[colYearAverage.Name] == DBNull.Value ? -1 : double.Parse(row[colYearAverage.Name].ToString()),
                        FirstSemester  = row[colFirstSemester.Name] == DBNull.Value ? -1 : double.Parse(row[colFirstSemester.Name].ToString()),
                        SecondSemester = row[colSecondSemester.Name] == DBNull.Value ? -1 : double.Parse(row[colSecondSemester.Name].ToString()),
                        Default        = row.Field <string>(colDefault.Name),
                        ValidFor       = row.Field <string>(colValidFor.Name)
                    });
                }

                AssessChanges(); // check whether any country files need to be updated
            }
            catch (Exception exception) { UserInfoHandler.ShowException(exception); return; }

            DialogResult = DialogResult.OK;
            Close();
        }
Beispiel #25
0
 void btnOK_Click(object sender, EventArgs e)
 {
     try
     {
         StoreDisplayedSwitches(); //before leaving the dialog, overtake potential changes in the currently displayed switch-table into the buffer-table
         DialogResult = DialogResult.OK;
     }
     catch (Exception exception)
     {
         UserInfoHandler.ShowException(exception);
     }
     Close();
 }
        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 btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                _varConfigFacade.RejectSwitchablePolicyChanges();
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowException(exception);
            }

            DialogResult = DialogResult.Cancel;
            Close();
        }
 internal bool RefreshHICPs(List <Tuple <string, int, double, string> > hicps)
 {
     try
     {
         _HICPConfig.HICP.Rows.Clear();
         _HICPConfig.AcceptChanges();
         foreach (var hicp in hicps)
         {
             _HICPConfig.HICP.AddHICPRow(hicp.Item1, hicp.Item2, hicp.Item3, hicp.Item4);
         }
         _HICPConfig.AcceptChanges();
         return(true);
     }
     catch (Exception exception) { UserInfoHandler.ShowException(exception); return(false); }
 }
Beispiel #29
0
        void btnGenerate_Click(object sender, EventArgs e)
        {
            try
            {
                List <string> selectedCountries = new List <string>();
                foreach (object checkedItem in lstCountries.CheckedItems)
                {
                    selectedCountries.Add(checkedItem as string);
                }

                //outsource the time-consuming reading of country files to a backgroundworker showhing progress
                ProgressIndicator progressIndicator = new ProgressIndicator(Generate_BackgroundEventHandler, "Generating required info ...", selectedCountries);
                if (progressIndicator.ShowDialog() == DialogResult.Cancel)
                {
                    return;
                }

                //fill the tables (rather done here than in the backgroundworker is the latter causes problems with access to the tables (which belong to another process)
                Cursor = Cursors.WaitCursor;

                List <object> configFacades = progressIndicator.Result as List <object>;
                List <CountryConfigFacade> countryConfigFacades = configFacades.ElementAt(0) as List <CountryConfigFacade>;
                List <DataConfigFacade>    dataConfigFacades    = configFacades.ElementAt(1) as List <DataConfigFacade>;

                if (chkGenerateSystemProgress.Checked) //fill system progress table
                {
                    FillSystemTable(countryConfigFacades);
                }
                if (chkGenerateDatasetProgress.Checked) //fill dataset progress table
                {
                    FillDatasetTable(dataConfigFacades, selectedCountries);
                }
                if (chkGenerateCombinations.Checked) //fill combination table
                {
                    FillCombinationsTable(dataConfigFacades);
                }

                UserInfoHandler.ShowSuccess("Tables successfully generated.");
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowException(exception);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
Beispiel #30
0
        void lvSwitchablePolicies_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            try
            {
                StoreDisplayedSwitches();          //overtake potential changes in the currently displayed switch-table into the dataconfig-table
                UpdateSwitchTable(e.Item.Checked); //set switches-tabel to the values of the now selected switchable policy

                if (e.Item.Checked)
                {
                    e.Item.Selected = true; //without doing this an item can be checked but not selected (blue background color)
                }
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowException(exception);
            }
        }