internal override void PerformValidation(List <string> countries, bool showProblemsOnly)
        {
            base.PerformValidation(countries, showProblemsOnly);
            string noHICP = string.Empty, notDollarF = string.Empty, emptyFactors = string.Empty, zeroFactors = string.Empty,
                   noYearForSystem = string.Empty, noYearForData = string.Empty, noIncomeYear = string.Empty;

            foreach (string country in countries)
            {
                CountryConfigFacade ccf = CountryAdministrator.GetCountryConfigFacade(country);
                DataConfigFacade    dcf = CountryAdministrator.GetDataConfigFacade(country);

                List <CountryConfig.UpratingIndexRow> indices       = (from ui in ccf.GetUpratingIndices() select ui).ToList();
                List <CountryConfig.SystemRow>        publicSystems = GetPublicSystems(country);
                List <DataConfig.DataBaseRow>         datasets      = (from d in dcf.GetDataBaseRows() where d.Private != DefPar.Value.YES select d).ToList();

                List <string> indexYears = ccf.GetAllUpratingIndexYears();

                RegisterProblems(country, NotDollarF(indices), ref notDollarF);
                RegisterProblems(country, NoYearForSystem(publicSystems, indexYears), ref noYearForSystem);
                RegisterProblems(country, NoYearForData(datasets, indexYears), ref noYearForData);
                RegisterProblems(country, NoIncomeYear(datasets), ref noIncomeYear);
                RegisterProblems(country, EmptyFactors(ccf, indices, false), ref emptyFactors);
                RegisterProblems(country, EmptyFactors(ccf, indices, true), ref zeroFactors);
            }
            AddDataGridRow("Factors not starting with $f_", notDollarF);
            AddDataGridRow("Systems for which factor-table does not provide year", noYearForSystem);
            AddDataGridRow("Databases for which factor-table does not provide year", noYearForData);
            AddDataGridRow("Databases with undefined income year", noIncomeYear);
            AddDataGridRow("Factors with empty values", emptyFactors);
            AddDataGridRow("Factors with zero values (warning)", zeroFactors);
        }
Example #2
0
        void cmbDatasets_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbDatasets.SelectedIndex == -1)
            {
                return; //no dataset selected
            }
            dgvFactors.Rows.Clear();

            //look up which dataset was selected to assess the data's income year, and put it into text-edit
            foreach (DataConfig.DataBaseRow dataset in _dataConfigFacade.GetDataBaseRows())
            {
                if (cmbDatasets.Text == dataset.Name)
                {
                    txtIncomeYear.Text = dataset.YearInc;
                    break;
                }
            }

            //check if the 'Raw Indices' table contains the data-year
            bool noIncomeYear = false;

            if (!GetExistingYears().Contains(txtIncomeYear.Text))
            {
                //UserInfoHandler.ShowError("Year " + txtIncomeYear.Text + " is not recorded in Raw Indices table. Factors cannot be calculated.");
                UserInfoHandler.ShowInfo("Year " + txtIncomeYear.Text + " is not recorded in Raw Indices table. Factors are set to " + _factorValueInvalid + ".");
                noIncomeYear = true;
                //return;
            }

            //fill the 'Factors ...' table for the selected dataset
            foreach (string indexName in GetIndicesNames()) //loop over all indices
            {
                //add one row to the 'Factors ...' table for each index
                DataGridViewRow factorRow = dgvFactors.Rows[dgvFactors.Rows.Add()];

                //put the name of the index (e.g. cpi) in the first column
                factorRow.Cells[colIndexName.Name].Value = indexName;

                foreach (DataGridViewColumn systemColumn in dgvFactors.Columns) //loop over the country's systems
                {
                    if (systemColumn == colIndexName)
                    {
                        continue; //name-column is already filled
                    }
                    if (noIncomeYear)
                    {
                        factorRow.Cells[systemColumn.Name].Value = _factorValueInvalid;
                    }
                    else
                    {
                        CountryConfig.SystemRow systemRow = systemColumn.Tag as CountryConfig.SystemRow;
                        string systemYear = systemRow.Year != null && systemRow.Year != string.Empty ? systemRow.Year
                                            : EM_Helpers.ExtractSystemYear((systemColumn.Tag as CountryConfig.SystemRow).Name);
                        // in the display, round the number to 4 digits - also make sure that you display dot regardless of the windows decimal separator. CalculateFactor takes care of all this...
                        factorRow.Cells[systemColumn.Name].Value = CalculateFactor(indexName, txtIncomeYear.Text, systemYear);
                    }
                }
            }
        }
Example #3
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);
            }
        }
        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;
        }
Example #5
0
        static void GetCountryInfo_BackgroundEventHandler(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker backgroundWorker = sender as BackgroundWorker;

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

            try
            {
                double i = 0; Dictionary <string, List <string> > cmpInfo = new Dictionary <string, List <string> >();
                foreach (Country cLoc in CountryAdministrator.GetCountries())
                {
                    backgroundWorker.ReportProgress(Convert.ToInt32(i / CountryAdministrator.GetCountries().Count * 100.0)); ++i;

                    CountryConfigFacade ccfLoc = cLoc.GetCountryConfigFacade(); if (ccfLoc == null)
                    {
                        continue;
                    }
                    DataConfigFacade dcfLoc = cLoc.GetDataConfigFacade(); if (dcfLoc == null)
                    {
                        continue;
                    }

                    string cmpCountryFolder = e.Argument.ToString() + cLoc._shortName; if (!Directory.Exists(cmpCountryFolder))
                    {
                        continue;
                    }
                    Country             cCmp   = new Country(); cCmp._shortName = cLoc._shortName;
                    CountryConfigFacade ccfCmp = cCmp.GetCountryConfigFacade(true, cmpCountryFolder); if (ccfCmp == null)
                    {
                        continue;
                    }
                    DataConfigFacade dcfCmp = cCmp.GetDataConfigFacade(true, cmpCountryFolder); if (dcfCmp == null)
                    {
                        continue;
                    }

                    string        addData = string.Empty, addSys = string.Empty, addPol = string.Empty, delData = string.Empty, delSys = string.Empty, delPol = string.Empty;
                    List <string> cmpData = new List <string>(), cmpSys = new List <string>(), cmpPol = new List <string>();

                    foreach (DataConfig.DataBaseRow d in dcfCmp.GetDataBaseRows())
                    {
                        cmpData.Add(d.Name.EndsWith(".txt") ? d.Name.ToLower() : (d.Name + ".txt").ToLower());
                    }
                    foreach (CountryConfig.SystemRow s in ccfCmp.GetSystemRows())
                    {
                        cmpSys.Add(s.Name.ToLower());
                    }
                    if (cmpSys.Count > 0)
                    {
                        foreach (CountryConfig.PolicyRow p in ccfCmp.GetSystemRows().First().GetPolicyRows())
                        {
                            if (!p.Name.ToLower().StartsWith(UpratingIndices.UpratingIndicesForm._policyUprateFactors_Name))
                            {
                                cmpPol.Add(p.Name.ToLower());
                            }
                        }
                    }

                    foreach (DataConfig.DataBaseRow d in dcfLoc.GetDataBaseRows())
                    {
                        string dataName = d.Name.EndsWith(".txt") ? d.Name.ToLower() : (d.Name + ".txt").ToLower();
                        if (cmpData.Contains(dataName))
                        {
                            cmpData.Remove(dataName);
                        }
                        else
                        {
                            addData += dataName + ", ";
                        }
                    }
                    foreach (string d in cmpData)
                    {
                        if (d != string.Empty)
                        {
                            delData += d + ", ";
                        }
                    }

                    foreach (CountryConfig.SystemRow s in ccfLoc.GetSystemRows())
                    {
                        if (cmpSys.Contains(s.Name.ToLower()))
                        {
                            cmpSys.Remove(s.Name.ToLower());
                        }
                        else
                        {
                            addSys += s.Name.ToLower() + ", ";
                        }
                    }
                    foreach (string s in cmpSys)
                    {
                        if (s != string.Empty)
                        {
                            delSys += s + ", ";
                        }
                    }

                    if (ccfLoc.GetSystemRows().Count > 0)
                    {
                        foreach (CountryConfig.PolicyRow p in ccfLoc.GetSystemRows().First().GetPolicyRows())
                        {
                            if (p.Name.ToLower().StartsWith(UpratingIndices.UpratingIndicesForm._policyUprateFactors_Name))
                            {
                                continue;
                            }
                            if (cmpPol.Contains(p.Name.ToLower()))
                            {
                                cmpPol.Remove(p.Name.ToLower());
                            }
                            else
                            {
                                addPol += p.Name.ToLower() + ", ";
                            }
                        }
                    }
                    foreach (string p in cmpPol)
                    {
                        if (p != string.Empty)
                        {
                            delPol += p + ", ";
                        }
                    }

                    char[] t = new char[] { ',', ' ' };
                    cmpInfo.Add(cLoc._shortName, new List <string>()
                    {
                        addData.TrimEnd(t), delData.TrimEnd(t), addSys.TrimEnd(t), delSys.TrimEnd(t), addPol.TrimEnd(t), delPol.TrimEnd(t)
                    });
                }

                backgroundWorker.ReportProgress(100);
                e.Result = cmpInfo;
            }
            catch (Exception exception) { e.Result = exception.Message; backgroundWorker.ReportProgress(100); }
        }
Example #6
0
        void AssessCountryInfo()
        {
            rvCountryInfo = new List <RVCountryInfo>();
            systemYears   = new List <int>(); systemYearsPublic = new List <int>();

            CountryConfigFacade ccfMTR = CountryAdministrator.GetCountryConfigFacade("MTR");
            CountryConfigFacade ccfLMA = CountryAdministrator.GetCountryConfigFacade("LMA");
            CountryConfigFacade ccfNRR = CountryAdministrator.GetCountryConfigFacade("NRR");

            foreach (string country in countries)
            {
                CountryConfigFacade ccf = CountryAdministrator.GetCountryConfigFacade(country);
                DataConfigFacade    dcf = CountryAdministrator.GetDataConfigFacade(country);

                RVCountryInfo ccInfo = new RVCountryInfo(country);
                List <int>    ccSystemYearsPublic = new List <int>();

                foreach (CountryConfig.SystemRow system in CountryAdministrator.GetCountryConfigFacade(country).GetSystemRows())
                {
                    int year = RVItem_SystemConfiguration.GetSystemYear(system); if (year == -1)
                    {
                        continue;
                    }
                    bool isPrivate = system.Private == DefPar.Value.YES;
                    if (!ccInfo.systemYearInfo.ContainsKey(year))
                    {
                        ccInfo.systemYearInfo.Add(year, isPrivate);
                    }
                    else if (ccInfo.systemYearInfo[year] == true)
                    {
                        ccInfo.systemYearInfo[year] = isPrivate;                                           // if there is a public and a private system for the year, let the public dominate
                    }
                    if (!systemYears.Contains(year))
                    {
                        systemYears.Add(year);
                    }
                    if (!isPrivate)
                    {
                        ccSystemYearsPublic.Add(year); if (!systemYearsPublic.Contains(year))
                        {
                            systemYearsPublic.Add(year);
                        }
                    }

                    List <DataConfig.DBSystemConfigRow> bm = (from d in dcf.GetDataConfig().DBSystemConfig
                                                              where d.SystemID == system.ID & d.BestMatch == DefPar.Value.YES
                                                              select d).ToList();
                    if (bm.Count > 0 && !ccInfo.bestMatchInfo.ContainsKey(year))
                    {
                        ccInfo.bestMatchInfo.Add(year, bm.First().DataBaseRow.Name);
                    }
                }

                //ccInfo.privateComponents = (from p in ccf.GetPolicyRowsOrderedAndDistinct()
                //                          where p.Private == DefPar.Value.YES select p.Name).ToList();
                int oPol = 0;
                foreach (CountryConfig.PolicyRow pol in ccf.GetPolicyRowsOrderedAndDistinct())
                {
                    ++oPol; int oFun = 0; string privFun = string.Empty;
                    ccInfo.idOrderInfo.Add(pol.ID, $"{oPol}");
                    if (pol.Private == DefPar.Value.YES)
                    {
                        ccInfo.privatePolicies.Add(string.Format("{0} {1}", oPol, pol.Name)); continue;
                    }
                    foreach (CountryConfig.FunctionRow fun in (from f in pol.GetFunctionRows() select f).OrderBy(f => long.Parse(f.Order)))
                    {
                        ++oFun; int oPar = 0; string privPar = string.Empty;
                        ccInfo.idOrderInfo.Add(fun.ID, $"{oPol}.{oFun}");
                        if (fun.Private == DefPar.Value.YES)
                        {
                            privFun += string.Format("{0} {1} ", oFun, fun.Name); continue;
                        }

                        foreach (CountryConfig.ParameterRow par in (from p in fun.GetParameterRows() select p).OrderBy(p => long.Parse(p.Order)))
                        {
                            ++oPar;
                            ccInfo.idOrderInfo.Add(par.ID, $"{oPol}.{oFun}.{oPar}");
                            if (par.Private == DefPar.Value.YES)
                            {
                                privPar += string.Format("{0} {1} ", oPar, par.Name); continue;
                            }
                        }
                        if (privPar != string.Empty)
                        {
                            ccInfo.privateParameters.Add(string.Format("{0}.{1} {2}/{3}/...: {4}",
                                                                       oPol.ToString(), oFun.ToString(), pol.Name, fun.Name, privPar));
                        }
                    }
                    if (privFun != string.Empty)
                    {
                        ccInfo.privateFunctions.Add(string.Format("{0} {1}/...: {2}",
                                                                  oPol, pol.Name, privFun));
                    }
                }

                foreach (DataConfig.DataBaseRow data in dcf.GetDataBaseRows())
                {
                    if (ccInfo.dataInfo.ContainsKey(data.Name))
                    {
                        continue;
                    }
                    bool isPrivate = data.Private == DefPar.Value.YES;
                    ccInfo.dataInfo.Add(data.Name, isPrivate);
                    if (data.Name.ToLower().StartsWith("training"))
                    {
                        ccInfo.hasTrainingData = true; ccInfo.isTrainingPublic = !isPrivate;
                    }
                    if (data.Name.ToLower().StartsWith("hypo"))
                    {
                        ccInfo.hasHypoData = true;
                    }

                    if (isPrivate)
                    {
                        continue;
                    }
                    ccInfo.dataNA.Add(data.Name, new List <string>());

                    if (!data.Name.ToLower().Contains("hhot"))
                    {
                        foreach (int systemYearPublic in ccSystemYearsPublic)
                        {
                            bool isAvailable = false;
                            foreach (DataConfig.DBSystemConfigRow dbs in dcf.GetDBSystemConfigRows(data.ID))
                            {
                                CountryConfig.SystemRow systemRow = CountryAdministrator.GetCountryConfigFacade(country).GetSystemRowByName(dbs.SystemName);
                                if (RVItem_SystemConfiguration.GetSystemYear(systemRow) == systemYearPublic)
                                {
                                    isAvailable = true; break;
                                }
                            }
                            if (!isAvailable)
                            {
                                ccInfo.dataNA[data.Name].Add(systemYearPublic.ToString());
                            }
                        }
                    }
                }

                foreach (string extId in (from s in dcf.GetDataConfig().PolicySwitch select s.SwitchablePolicyID).Distinct())
                {
                    AssessExtensionInfo(ccf, dcf, extId, DefPar.Value.ON, ref ccInfo.switchInfoOn);
                    AssessExtensionInfo(ccf, dcf, extId, DefPar.Value.OFF, ref ccInfo.switchInfoOff);
                }

                AssessExtensionContent(ccf, dcf, ccInfo.idOrderInfo, ref ccInfo.extensionContent);

                foreach (DataConfig.ExtensionRow er in dcf.GetDataConfig().Extension)
                {
                    ;
                }
                foreach (GlobLocExtensionRow er in ExtensionAndGroupManager.GetLocalExtensions(ccInfo.country))
                {
                    countriesExtensionInfo.Add(new Tuple <string, string, bool>(er.ID, er.Name, IsWholeContentPrivate(ccf.GetCountryConfig(), er.ID)));
                }

                ccInfo.mtrImplemented = AddOnImplemented(ccfMTR, country, "mtr");
                ccInfo.lmaImplemented = AddOnImplemented(ccfLMA, country, "lma");
                ccInfo.nrrImplemented = AddOnImplemented(ccfNRR, country, "nrr");

                rvCountryInfo.Add(ccInfo);
            }
            systemYears.Sort(); systemYearsPublic.Sort();
        }
Example #7
0
        void FillDatasetTable(List <DataConfigFacade> dataConfigFacades, List <string> countryShortNames)
        {
            dgvDatasets.Rows.Clear();
            for (int i = dgvDatasets.Columns.Count - 1; i >= 0; --i)
            {
                if (dgvDatasets.Columns[i].Name.StartsWith(_colDataYearPrefix))
                {
                    dgvDatasets.Columns.RemoveAt(i); //delete all but the fix columns (those displaying data-properties like collection year, private, ...)
                }
            }
            List <string> dataYears = new List <string>();

            //loop over countries
            for (int index = 0; index < dataConfigFacades.Count; ++index)
            {
                DataConfigFacade dataConfigFacade = dataConfigFacades.ElementAt(index);

                //loop over dataset of the country
                bool firstDatasetOfCountry = true;
                foreach (DataConfig.DataBaseRow dataset in dataConfigFacade.GetDataBaseRows())
                {
                    //if the dataset is a "standard dataset", i.e. called cc_yyyy_xx, extract the year of the name
                    string datasetName = dataset.Name.ToLower().EndsWith(".txt") ? dataset.Name.Substring(0, dataset.Name.Length - 4) : dataset.Name;
                    string dataYear    = string.Empty;
                    if (datasetName.Length >= 8 &&
                        datasetName.Substring(2, 1) == "_" && datasetName.Substring(7, 1) == "_" &&
                        EM_Helpers.IsNonNegInteger(datasetName.Substring(3, 4)))
                    {
                        dataYear = datasetName.Substring(3, 4);
                    }
                    else if (datasetName.ToLower().Contains("hypo")) //take respect of hypo-data ...
                    {
                        dataYear = "hypo";
                    }
                    else if (datasetName.ToLower().Contains("training")) //... and training data (which also exist for most countries)
                    {
                        dataYear = "training";
                    }
                    else
                    {
                        dataYear = _colHeadingNonStandard; //probably only SL_demo_vi
                    }
                    //add an entry for the dataset year, if not already existent
                    if (!dataYears.Contains(dataYear))
                    {
                        dataYears.Add(dataYear);
                    }

                    //generate a row for each dataset and equip the row's tag with information (data-year and data-properties) for the cell-filling below
                    int rowIndex = dgvDatasets.Rows.Add();
                    dgvDatasets.Rows[rowIndex].Tag = new KeyValuePair <string, DataConfig.DataBaseRow>(dataYear, dataset);

                    //put name of country in row header if first dataset for this country
                    if (firstDatasetOfCountry && index < countryShortNames.Count)
                    {
                        dgvDatasets.Rows[rowIndex].HeaderCell.Value = countryShortNames.ElementAt(index);
                        firstDatasetOfCountry = false;
                    }
                }
            }

            //sort the list of years (to get 2001, 2002, 2003, etc. instead of 2001, 2003, 2002, etc.) and generate the columns
            dataYears.Sort();
            dataYears.Reverse();
            foreach (string dataYear in dataYears)
            {
                DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
                column.Name             = _colDataYearPrefix + dataYear;
                column.HeaderCell.Value = dataYear;
                dgvDatasets.Columns.Insert(0, column); //insert before the fix columns (collection year, private, etc.)
            }

            //fill the table
            foreach (DataGridViewRow row in dgvDatasets.Rows)
            {
                KeyValuePair <string, DataConfig.DataBaseRow> rowTag = (KeyValuePair <string, DataConfig.DataBaseRow>)(row.Tag);
                DataConfig.DataBaseRow dataset = rowTag.Value;
                string dataYear = rowTag.Key;
                row.Cells[colYearCollection.Name].Value        = dataset.YearCollection;
                row.Cells[colYearIncome.Name].Value            = dataset.YearInc;
                row.Cells[colPrivate.Name].Value               = dataset.Private;
                row.Cells[_colDataYearPrefix + dataYear].Value = dataset.Name;
            }
        }
        static void RemovePrivate_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

            //then adapt the copy
            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();
                    DataConfigFacade    dataConfigFacade    = country.GetDataConfigFacade();

                    //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(EMPath.Folder_Countries(EM_AppContext.FolderEuromodFiles) + 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();
                    country.SetCountryConfigFacade(null);
                    country.SetDataConfigFacade(null);

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

                //remove private add-ons
                foreach (Country addOn in CountryAdministrator.GetAddOns())
                {
                    bool oldStyle = CountryAdministrator.ConsiderOldAddOnFileStructure(true);
                    CountryConfigFacade addOnConfigFacade = addOn.GetCountryConfigFacade();
                    if (addOnConfigFacade.GetCountryRow().Private != DefPar.Value.YES)
                    {
                        continue;
                    }
                    if (oldStyle)
                    {
                        File.Delete(EMPath.Folder_AddOns(EM_AppContext.FolderEuromodFiles) + addOn._shortName + ".xml");
                    }
                    else
                    {
                        Directory.Delete(EMPath.Folder_AddOns(EM_AppContext.FolderEuromodFiles) + addOn._shortName, true);
                    }
                    addOn.SetCountryConfigFacade(null);
                }

                // remove the "other" column from the variables file
                VarConfigFacade vcf = EM_AppContext.Instance.GetVarConfigFacade();
                foreach (VarConfig.CountryLabelRow r in from l in vcf._varConfig.CountryLabel where l.Country.ToLower() == "other" select l)
                {
                    r.Delete();
                }
                vcf.Commit(); vcf.WriteXML();

                if (backgroundWorker.CancellationPending)
                {
                    e.Cancel = true; return;
                }                                                                      //user pressed Cancel button: see above
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowException(exception);
                e.Cancel = true; //stop the process and allow progress indicator to set dialog result to Cancel
            }
        }
        static void CheckPrivateComponents_BackgroundEventHandler(object sender, System.ComponentModel.DoWorkEventArgs e)
        { //assess which datasets, systems and policies are private (as a background process of the progress indicator)
            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

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

                _privateComponents = string.Empty;
                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();
                    DataConfigFacade    dataConfigFacade    = country.GetDataConfigFacade();

                    //assess which systems are private
                    List <CountryConfig.SystemRow> privateSystems = new List <CountryConfig.SystemRow>();
                    foreach (CountryConfig.SystemRow system in countryConfigFacade.GetSystemRows())
                    {
                        if (backgroundWorker.CancellationPending)
                        {
                            e.Cancel = true; return;
                        }                                                                      //user pressed Cancel button: see above

                        if (system.Private.ToLower() == DefPar.Value.YES.ToLower())
                        {
                            privateSystems.Add(system);
                        }
                    }

                    //assess which policies are private
                    List <CountryConfig.PolicyRow>    privatePolicies   = new List <CountryConfig.PolicyRow>();
                    List <CountryConfig.FunctionRow>  privateFunctions  = new List <CountryConfig.FunctionRow>();
                    List <CountryConfig.ParameterRow> privateParameters = new List <CountryConfig.ParameterRow>();
                    if (countryConfigFacade.GetSystemRows().Count > privateSystems.Count)
                    {//only necessary to do for first system, as policies can only be marked private for all systems, but check if not all systems are private
                        foreach (CountryConfig.PolicyRow policy in countryConfigFacade.GetSystemRows()[0].GetPolicyRows())
                        {
                            if (backgroundWorker.CancellationPending)
                            {
                                e.Cancel = true; return;
                            }                                                                      //user pressed Cancel button: see above

                            if (policy.Private == DefPar.Value.YES)
                            {
                                privatePolicies.Add(policy);
                            }
                            else
                            {
                                foreach (CountryConfig.FunctionRow function in policy.GetFunctionRows())
                                {
                                    if (function.Private == DefPar.Value.YES)
                                    {
                                        privateFunctions.Add(function);
                                    }
                                    else
                                    {
                                        foreach (CountryConfig.ParameterRow parameter in function.GetParameterRows())
                                        {
                                            if (parameter.Private == DefPar.Value.YES)
                                            {
                                                privateParameters.Add(parameter);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    //assess which datasets are private
                    List <DataConfig.DataBaseRow> privateDataSets = new List <DataConfig.DataBaseRow>();
                    foreach (DataConfig.DataBaseRow dataSet in dataConfigFacade.GetDataBaseRows())
                    {
                        if (backgroundWorker.CancellationPending)
                        {
                            e.Cancel = true; return;
                        }                                                                      //user pressed Cancel button: see above

                        if (dataSet.Private.ToLower() == DefPar.Value.YES.ToLower())
                        {
                            privateDataSets.Add(dataSet);
                        }
                    }

                    backgroundWorker.ReportProgress(Convert.ToInt32((i + 1.0) / (countries.Count * 1.0) * 100.0)); //increase progress (for each country)

                    if (privateDataSets.Count == 0 && privateSystems.Count == 0 && privatePolicies.Count == 0)
                    {
                        continue;
                    }

                    //fill _privateComponents into string which is to be output in btnCheckPrivate_Click
                    _privateComponents += country._shortName.ToUpper() + Environment.NewLine;

                    if (countryConfigFacade.GetCountryRow().Private == DefPar.Value.YES)
                    {
                        _privateComponents += "\tPRIVATE COUNTRY" + Environment.NewLine;
                    }

                    if (privateDataSets.Count != 0)
                    {
                        _privateComponents += "\tPRIVATE DATASETS" + Environment.NewLine;
                        foreach (DataConfig.DataBaseRow dataSet in privateDataSets)
                        {
                            _privateComponents += "\t\t" + dataSet.Name + Environment.NewLine;
                        }
                    }
                    if (privateSystems.Count != 0)
                    {
                        _privateComponents += "\tPRIVATE SYSTEMS" + Environment.NewLine;
                        foreach (CountryConfig.SystemRow system in privateSystems)
                        {
                            _privateComponents += "\t\t" + system.Name + Environment.NewLine;
                        }
                    }
                    if (privatePolicies.Count != 0)
                    {
                        _privateComponents += "\tPRIVATE POLICIES" + Environment.NewLine;
                        foreach (CountryConfig.PolicyRow policy in privatePolicies)
                        {
                            _privateComponents += "\t\t" + policy.Name + Environment.NewLine;
                        }
                    }
                    if (privateFunctions.Count != 0)
                    {
                        _privateComponents += "\tPRIVATE FUNCTIONS" + Environment.NewLine;
                        foreach (CountryConfig.FunctionRow function in privateFunctions)
                        {
                            _privateComponents += "\t\t" + function.Name + " in policy " + function.PolicyRow.Name + " (order " + function.Order + ")" + Environment.NewLine;
                        }
                    }
                    if (privateParameters.Count != 0)
                    {
                        _privateComponents += "\tPRIVATE PARAMETERS" + Environment.NewLine;
                        foreach (CountryConfig.ParameterRow parameter in privateParameters)
                        {
                            _privateComponents += "\t\t" + parameter.Name + " in function " + parameter.FunctionRow.Name + " in policy " + parameter.FunctionRow.PolicyRow.Name +
                                                  " (function-order " + parameter.FunctionRow.Order + ", parameter-order " + parameter.Order + ")" + Environment.NewLine;
                        }
                    }
                    _privateComponents += "_________________________________________________________" + Environment.NewLine;
                }

                foreach (Country addOn in CountryAdministrator.GetAddOns())
                {
                    CountryConfigFacade addOnConfigFacade = addOn.GetCountryConfigFacade();
                    if (addOnConfigFacade.GetCountryRow().Private != DefPar.Value.YES)
                    {
                        continue;
                    }
                    _privateComponents += addOn._shortName.ToUpper() + Environment.NewLine;
                    _privateComponents += "\tPRIVATE ADD-ON" + Environment.NewLine;
                    _privateComponents += "_________________________________________________________" + Environment.NewLine;
                }
            }
            catch (Exception exception)
            {
                UserInfoHandler.ShowException(exception);
                e.Cancel = true; //stop the process and allow progress indicator to set dialog result to Cancel
            }
        }
Example #10
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
            }
        }
Example #11
0
        private void EM2_RunDecompCountry(string countryShortName)
        {
            string currentAction = "";

            try
            {
                currentAction = "getting " + countryShortName + " config files";
                DataRow row = policyDataTable.Select("Country='" + countryShortName + "'")[0];
                string  sn1 = showFull ? row["System1"].ToString() : countryShortName + "_" + comboBox1.Text;
                string  sn2 = showFull ? row["System2"].ToString() : countryShortName + "_" + comboBox2.Text;
                CountryConfig.SystemRow sr1 = CountryAdministrator.GetCountryConfigFacade(countryShortName).GetSystemRowByName(sn1);
                CountryConfig.SystemRow sr2 = CountryAdministrator.GetCountryConfigFacade(countryShortName).GetSystemRowByName(sn2);

                // make a copy of the country, to be later stored in the temp-folder
                currentAction = "copying " + countryShortName + " for decomposition";
                Country             copiedCountry     = CountryAdministrator.GetCopyOfCountry(countryShortName);
                CountryConfigFacade ccf               = copiedCountry.GetCountryConfigFacade();
                DataConfigFacade    _dataConfigFacade = copiedCountry.GetDataConfigFacade();

                DataConfig.DataBaseRow dbr1 = null;
                DataConfig.DataBaseRow dbr2 = null;
                foreach (DataConfig.DataBaseRow dataSet in _dataConfigFacade.GetDataBaseRows())
                {
                    if (dataSet.Name == row["Data1"].ToString())
                    {
                        dbr1 = dataSet;
                    }
                    if (dataSet.Name == row["Data2"].ToString())
                    {
                        dbr2 = dataSet;
                    }
                }

                // then create all required systems, depending on decomposition and Alpha selection
                currentAction = "getting " + countryShortName + "'s uprate factors";
                Dictionary <string, string> upratingFactors1 = GetUpratingFactors(sr1, dbr1, countryShortName);
                Dictionary <string, string> upratingFactors2 = GetUpratingFactors(sr2, dbr2, countryShortName);
                double alpha = 0;

                List <DecompSystem> allSystems = new List <DecompSystem>();
                bool treatAsMarket             = chkTreatAsMarket.Checked;

                // get the systems of the checked addon (if one was checked)
                string addon    = GetCheckedAddon();
                bool   hasAddon = addon != string.Empty;
                List <AddOnSystemInfo> addonSystems = hasAddon ? AddOnInfoHelper.GetAddOnSystemInfo(addon) : null;

                currentAction = "creating " + countryShortName + "'s decomposed systems";

                const double  ALPHA_CPI = double.MinValue, ALPHA_MII = double.MaxValue; // just any numbers differnt from the alphas in alphaFIX
                List <double> alphas = new List <double>();
                if (checkBoxAlphaCPI.Checked)
                {
                    alphas.Add(ALPHA_CPI);
                }
                if (checkBoxAlphaMII.Checked)
                {
                    alphas.Add(ALPHA_MII);
                }
                if (checkBoxAlphaFIX.Checked)
                {
                    alphas.AddRange(alphaFIXValues);                           // those where gathered in GetAlphaFIX
                }
                foreach (double a in alphas)
                {
                    string systemNameExt = "";
                    // first find Alpha, log text, system name extention etc.
                    if (a == ALPHA_CPI)
                    {
                        Dictionary <string, string> rawIndices = GetRawCPIindices(sr1, countryShortName);
                        if (!(rawIndices.ContainsKey(comboBox1.Text) || rawIndices.ContainsKey(comboBox2.Text)))
                        {
                            throw new Exception("The CPI raw indices ('" + FactorCPI + "') were not found for the selected years!");
                        }
                        double hicp1 = EM_Helpers.SaveConvertToDouble(rawIndices[comboBox1.Text]);
                        double hicp2 = EM_Helpers.SaveConvertToDouble(rawIndices[comboBox2.Text]);
                        alpha = hicp2 / hicp1;
                        AddToLog($"{RunLogger.PetInfo.LOGTAG_ALPHA_CPI} ({countryShortName})", $"{alpha} ({hicp2}/{hicp1})", LOGMODE.EM2);
                        systemNameExt = "_cpi";
                        alphaValues.Add(countryShortName + "_cpi", alpha);
                    }
                    else if (a == ALPHA_MII)
                    {
                        double mii1 = getAlphaFromBaselineFile(sr1.Name);
                        double mii2 = getAlphaFromBaselineFile(sr2.Name);
                        alpha = mii2 / mii1;
                        AddToLog($"{RunLogger.PetInfo.LOGTAG_ALPHA_MII} ({countryShortName})", $"{alpha} ({mii2}/{mii1})", LOGMODE.EM2);
                        systemNameExt = "_mii";
                        alphaValues.Add(countryShortName + "_mii", alpha);
                    }
                    else
                    {
                        alpha         = a;
                        systemNameExt = "_a" + GetAlphaFIXId(a);
                        alphaValues.Add(countryShortName + "_fix" + GetAlphaFIXId(a), alpha);
                    }

                    // Then actually create the required systems
                    if (checkRadioData1.Checked || checkRadioDataBoth.Checked)
                    {
                        DecompSystem ds1 = new DecompSystem();
                        ds1.sr = CountryConfigFacade.CopySystemRow(sr2.Name + "_on_" + dbr1.Name + systemNameExt, ccf.GetSystemRowByID(sr2.ID));
                        copiedCountry.GetDataConfigFacade().CopyDBSystemConfigRows(ccf.GetSystemRowByID(sr2.ID), ds1.sr);
                        ds1.dbr = dbr1;
                        if (hasAddon)
                        {
                            MergeAddOn(addonSystems, sr2.Name, ds1, copiedCountry);
                        }
                        EM2_FixUprating(ds1.sr, upratingFactors1, upratingFactors2, countryShortName, alpha, 1, treatAsMarket);
                        allSystems.Add(ds1);
                        if (checkRadioMonetary.Checked)
                        {
                            DecompSystem ds2 = new DecompSystem();
                            ds2.sr = CountryConfigFacade.CopySystemRow(sr2.Name + "ind_on_" + dbr1.Name + systemNameExt, ccf.GetSystemRowByID(sr2.ID));
                            copiedCountry.GetDataConfigFacade().CopyDBSystemConfigRows(ccf.GetSystemRowByID(sr2.ID), ds2.sr);
                            ds2.dbr = dbr1;
                            if (hasAddon)
                            {
                                MergeAddOn(addonSystems, sr2.Name, ds2, copiedCountry);
                            }
                            EM2_FixUprating(ds2.sr, upratingFactors1, upratingFactors2, countryShortName, alpha, 2, treatAsMarket);
                            allSystems.Add(ds2);
                            DecompSystem ds3 = new DecompSystem();
                            ds3.sr = CountryConfigFacade.CopySystemRow(sr1.Name + "ind" + systemNameExt, ccf.GetSystemRowByID(sr1.ID));
                            copiedCountry.GetDataConfigFacade().CopyDBSystemConfigRows(ccf.GetSystemRowByID(sr1.ID), ds3.sr);
                            ds3.dbr = dbr1;
                            if (hasAddon)
                            {
                                MergeAddOn(addonSystems, sr1.Name, ds3, copiedCountry);
                            }
                            EM2_FixUprating(ds3.sr, upratingFactors1, upratingFactors2, countryShortName, alpha, 3, treatAsMarket);
                            allSystems.Add(ds3);
                        }
                    }
                    if (checkRadioData2.Checked || checkRadioDataBoth.Checked)
                    {
                        DecompSystem ds1 = new DecompSystem();
                        ds1.sr = CountryConfigFacade.CopySystemRow(sr1.Name + "_on_" + dbr2.Name + systemNameExt, ccf.GetSystemRowByID(sr1.ID));
                        copiedCountry.GetDataConfigFacade().CopyDBSystemConfigRows(ccf.GetSystemRowByID(sr1.ID), ds1.sr);
                        ds1.dbr = dbr2;
                        if (hasAddon)
                        {
                            MergeAddOn(addonSystems, sr1.Name, ds1, copiedCountry);
                        }
                        EM2_FixUprating(ds1.sr, upratingFactors2, upratingFactors1, countryShortName, 1 / alpha, 1, treatAsMarket);
                        allSystems.Add(ds1);
                        if (checkRadioMonetary.Checked)
                        {
                            DecompSystem ds2 = new DecompSystem();
                            ds2.sr = CountryConfigFacade.CopySystemRow(sr1.Name + "ind_on_" + dbr2.Name + systemNameExt, ccf.GetSystemRowByID(sr2.ID));
                            copiedCountry.GetDataConfigFacade().CopyDBSystemConfigRows(ccf.GetSystemRowByID(sr1.ID), ds2.sr);
                            ds2.dbr = dbr2;
                            if (hasAddon)
                            {
                                MergeAddOn(addonSystems, sr1.Name, ds2, copiedCountry);
                            }
                            EM2_FixUprating(ds2.sr, upratingFactors2, upratingFactors1, countryShortName, 1 / alpha, 2, treatAsMarket);
                            allSystems.Add(ds2);
                            DecompSystem ds3 = new DecompSystem();
                            ds3.sr = CountryConfigFacade.CopySystemRow(sr2.Name + "ind" + systemNameExt, ccf.GetSystemRowByID(sr2.ID));
                            copiedCountry.GetDataConfigFacade().CopyDBSystemConfigRows(ccf.GetSystemRowByID(sr2.ID), ds3.sr);
                            ds3.dbr = dbr1;
                            if (hasAddon)
                            {
                                MergeAddOn(addonSystems, sr2.Name, ds3, copiedCountry);
                            }
                            EM2_FixUprating(ds3.sr, upratingFactors2, upratingFactors1, countryShortName, 1 / alpha, 3, treatAsMarket);
                            allSystems.Add(ds3);
                        }
                    }
                }

                currentAction = "writting decomposed " + countryShortName + " in the temp folder";

                copiedCountry.WriteXML(EMPath.Folder_Temp(EM_AppContext.FolderEuromodFiles));

                currentAction = "running " + countryShortName + "'s decomposed systems";
                foreach (DecompSystem ds in allSystems)
                {
                    workers.Add(RunSystem(countryShortName, ds.sr.Name, dbr2.Name, EM2_CreateConfig(countryShortName, textBoxOutputPath.Text, ds.dbr, ds.sr)));
                    updateInfoLabel();
                }
            }
            catch (Exception ex)
            {
                em3_petInfo.AddSystemIndependentError($"There was a problem with {currentAction}: {ex.Message}");
            }
        }
Example #12
0
        private void EM2_RunBaselineSystems()
        {
            // get the systems of the checked addon (if one was checked)
            string addon    = GetCheckedAddon();
            bool   hasAddon = addon != string.Empty;
            List <AddOnSystemInfo> addonSystems = hasAddon ? AddOnInfoHelper.GetAddOnSystemInfo(addon) : null;

            foreach (DataRow row in policyDataTable.Rows)
            {
                if (row.Field <bool>("Check"))
                {
                    string                 countryShortName = row["Country"].ToString();
                    Country                copiedCountry    = CountryAdministrator.GetCopyOfCountry(countryShortName);
                    CountryConfigFacade    ccf = copiedCountry.GetCountryConfigFacade();
                    DataConfigFacade       _dataConfigFacade = copiedCountry.GetDataConfigFacade();
                    DataConfig.DataBaseRow dbr1 = null;
                    DataConfig.DataBaseRow dbr2 = null;
                    foreach (DataConfig.DataBaseRow dataSet in _dataConfigFacade.GetDataBaseRows())
                    {
                        if (dataSet.Name == row["Data1"].ToString())
                        {
                            dbr1 = dataSet;
                        }
                        if (dataSet.Name == row["Data2"].ToString())
                        {
                            dbr2 = dataSet;
                        }
                    }

                    string sn1 = showFull ? row["System1"].ToString() : countryShortName + "_" + comboBox1.Text;
                    string sn2 = showFull ? row["System2"].ToString() : countryShortName + "_" + comboBox2.Text;
                    CountryConfig.SystemRow sr1 = ccf.GetSystemRowByName(sn1);
                    CountryConfig.SystemRow sr2 = ccf.GetSystemRowByName(sn2);

                    if (sr1 == null)
                    {
                        throw new Exception("System '" + sn1 + "' does not exist!");
                    }
                    if (sr2 == null)
                    {
                        throw new Exception("System '" + sn2 + "' does not exist!");
                    }

                    if (hasAddon)
                    {
                        if (checkRadioData1.Checked || checkRadioDataBoth.Checked)
                        {
                            MergeAddOn(addonSystems, copiedCountry, ref sr1);
                        }
                        if (checkRadioData2.Checked || checkRadioDataBoth.Checked)
                        {
                            MergeAddOn(addonSystems, copiedCountry, ref sr2);
                        }
                    }

                    copiedCountry.WriteXML(EMPath.Folder_Temp(EM_AppContext.FolderEuromodFiles));

                    if (checkBoxAlphaMII.Checked)
                    {
                        SystemBackgroundWorker w1, w2;
                        w1                = RunSystem(countryShortName, sr1.Name, dbr1.Name, EM2_CreateConfig(countryShortName, textBoxOutputPath.Text, dbr1, sr1, true));
                        w2                = RunSystem(countryShortName, sr2.Name, dbr2.Name, EM2_CreateConfig(countryShortName, textBoxOutputPath.Text, dbr2, sr2, true));
                        w1.isBaseline     = true;
                        w2.isBaseline     = true;
                        w1.secondBaseline = w2;
                        w2.secondBaseline = w1;
                        workers.Add(w1);
                        workers.Add(w2);
                        updateInfoLabel();
                    }
                    else
                    {
                        SystemBackgroundWorker w1 = null, w2 = null;
                        if (checkRadioData1.Checked || checkRadioDataBoth.Checked)
                        {
                            w1            = RunSystem(countryShortName, sr1.Name, dbr1.Name, EM2_CreateConfig(countryShortName, textBoxOutputPath.Text, dbr1, sr1, hasAddon));
                            w1.isBaseline = true;
                        }
                        if (checkRadioData2.Checked || checkRadioDataBoth.Checked)
                        {
                            w2            = RunSystem(countryShortName, sr2.Name, dbr2.Name, EM2_CreateConfig(countryShortName, textBoxOutputPath.Text, dbr2, sr2, hasAddon));
                            w2.isBaseline = true;
                        }

                        if (hasAddon && checkRadioDataBoth.Checked)
                        {
                            w1.secondBaseline = w2;
                            w2.secondBaseline = w1;
                        }
                        if (checkRadioData1.Checked || checkRadioDataBoth.Checked)
                        {
                            workers.Add(w1);
                        }
                        if (checkRadioData2.Checked || checkRadioDataBoth.Checked)
                        {
                            workers.Add(w2);
                        }
                        updateInfoLabel();
                    }
                }
            }
        }
Example #13
0
        internal override void PerformAction()
        {
            ConfigureDataForm configureDataForm = new ConfigureDataForm(_countryShortName);

            //firstly provide dialog with the information it needs to display (i.e. info on datasets and available system-dataset combinations) ...
            foreach (CountryConfig.SystemRow systemRow in CountryAdministrator.GetCountryConfigFacade(_countryShortName).GetSystemRows().OrderBy(s => long.Parse(s.Order)))
            {
                configureDataForm._systemInfo.Add(systemRow.ID, systemRow.Name);
            }

            foreach (DataConfig.DataBaseRow dataBaseRow in _dataConfigFacade.GetDataBaseRows())
            {
                ConfigureDataForm.RowTag rowTag = new ConfigureDataForm.RowTag();
                rowTag.ID                   = dataBaseRow.ID;
                rowTag.Name                 = dataBaseRow.Name;
                rowTag.Comment              = dataBaseRow.Comment;
                rowTag.YearCollection       = dataBaseRow.YearCollection;
                rowTag.YearInc              = dataBaseRow.YearInc;
                rowTag.Currency             = dataBaseRow.Currency;
                rowTag.FilePath             = dataBaseRow.FilePath;
                rowTag.DecimalSign          = dataBaseRow.DecimalSign;
                rowTag.Private              = dataBaseRow.Private;
                rowTag.UseCommonDefault     = dataBaseRow.UseCommonDefault;
                rowTag.ReadXVariables       = string.IsNullOrEmpty(dataBaseRow.ReadXVariables) ? DefPar.Value.NO : dataBaseRow.ReadXVariables;
                rowTag.IsCommonDefaultNull  = dataBaseRow.IsUseCommonDefaultNull();
                rowTag.ListStringOutVar     = dataBaseRow.ListStringOutVar;
                rowTag.IndirectTaxTableYear = dataBaseRow.IndirectTaxTableYear;

                foreach (DataConfig.DBSystemConfigRow dbSystemConfigRow in _dataConfigFacade.GetDBSystemConfigRows(dataBaseRow.ID))
                {
                    ConfigureDataForm.CellTag cellTag = new ConfigureDataForm.CellTag();
                    cellTag.SystemID         = dbSystemConfigRow.SystemID;
                    cellTag.UseDefault       = dbSystemConfigRow.UseDefault;
                    cellTag.UseCommonDefault = dbSystemConfigRow.UseCommonDefault;
                    cellTag.Uprate           = dbSystemConfigRow.Uprate;
                    cellTag.BestMatch        = dbSystemConfigRow.BestMatch;
                    rowTag.CellTags.Add(dbSystemConfigRow.SystemID, cellTag);
                }
                configureDataForm._dataBaseInfo.Add(rowTag);
            }

            //... then show the dialog ...
            if (configureDataForm.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                _actionIsCanceled = true;
                return;
            }

            //... finally store the modified information
            List <DataConfig.DataBaseRow>       dataBaseRowsToDelete       = new List <DataConfig.DataBaseRow>();
            List <DataConfig.DBSystemConfigRow> dbSystemConfigRowsToDelete = new List <DataConfig.DBSystemConfigRow>();

            foreach (ConfigureDataForm.RowTag dataBaseInfo in configureDataForm._dataBaseInfo)
            {
                DataConfig.DataBaseRow dataBaseRow = _dataConfigFacade.GetDataBaseRow(dataBaseInfo.ID);
                if (dataBaseInfo.ChangeState == ConfigureDataForm.ChangeStates.removed)
                {
                    dataBaseRowsToDelete.Add(dataBaseRow);
                    continue;
                }

                if (dataBaseInfo.ChangeState == ConfigureDataForm.ChangeStates.added)
                {
                    dataBaseRow   = _dataConfigFacade.AddDataBaseRow(dataBaseInfo.Name, dataBaseInfo.FilePath);
                    _datasetAdded = true;
                }

                if (dataBaseInfo.ChangeState != ConfigureDataForm.ChangeStates.unchanged)
                {
                    dataBaseRow.ID                   = dataBaseInfo.ID;
                    dataBaseRow.Name                 = dataBaseInfo.Name;
                    dataBaseRow.Comment              = dataBaseInfo.Comment;
                    dataBaseRow.YearCollection       = dataBaseInfo.YearCollection;
                    dataBaseRow.YearInc              = dataBaseInfo.YearInc;
                    dataBaseRow.Currency             = dataBaseInfo.Currency;
                    dataBaseRow.FilePath             = dataBaseInfo.FilePath;
                    dataBaseRow.DecimalSign          = dataBaseInfo.DecimalSign;
                    dataBaseRow.Private              = dataBaseInfo.Private;
                    dataBaseRow.UseCommonDefault     = dataBaseInfo.UseCommonDefault;
                    dataBaseRow.ReadXVariables       = dataBaseInfo.ReadXVariables;
                    dataBaseRow.ListStringOutVar     = dataBaseInfo.ListStringOutVar;
                    dataBaseRow.IndirectTaxTableYear = dataBaseInfo.IndirectTaxTableYear;
                }

                foreach (ConfigureDataForm.CellTag dbSystemCombination in dataBaseInfo.CellTags.Values)
                {
                    DataConfig.DBSystemConfigRow dbSystemConfigRow = _dataConfigFacade.GetDBSystemConfigRow(dataBaseInfo.ID, dbSystemCombination.SystemID);
                    if (dbSystemCombination.ChangeState == ConfigureDataForm.ChangeStates.removed)
                    {
                        dbSystemConfigRowsToDelete.Add(dbSystemConfigRow);
                        continue;
                    }

                    if (dbSystemCombination.ChangeState == ConfigureDataForm.ChangeStates.added)
                    {
                        dbSystemConfigRow = _dataConfigFacade.AddDBSystemConfigRow(dbSystemCombination.SystemID,
                                                                                   CountryAdministrator.GetCountryConfigFacade(_countryShortName).GetSystemRowByID(dbSystemCombination.SystemID).Name,
                                                                                   dataBaseRow);
                    }

                    if (dbSystemCombination.ChangeState != ConfigureDataForm.ChangeStates.unchanged)
                    {
                        dbSystemConfigRow.SystemID         = dbSystemCombination.SystemID;
                        dbSystemConfigRow.UseDefault       = dbSystemCombination.UseDefault;
                        dbSystemConfigRow.UseCommonDefault = dbSystemCombination.UseCommonDefault;
                        dbSystemConfigRow.Uprate           = dbSystemCombination.Uprate;
                        dbSystemConfigRow.BestMatch        = dbSystemCombination.BestMatch;
                    }
                }
            }

            foreach (DataConfig.DataBaseRow dataBaseRowToDelete in dataBaseRowsToDelete)
            {
                dataBaseRowToDelete.Delete();
            }
            foreach (DataConfig.DBSystemConfigRow dbSystemConfigRowToDelete in dbSystemConfigRowsToDelete)
            {
                dbSystemConfigRowToDelete.Delete();
            }
        }