internal CountryConfig.SystemRow PerformAddOnGeneration(string newSystemName, string countryShortName, string addOnShortName,
                                                                string baseSystemName, string addOnSystemName)
        {
            //get the county's and add-on's data
            CountryConfigFacade baseCountryConfigFacade = CountryAdministrator.GetCountryConfigFacade(countryShortName);

            _addOnCountryConfigFacade = CountryAdministrator.GetCountryConfigFacade(addOnShortName);

            //get the base-system and the add-on-system
            CountryConfig.SystemRow baseSystemRow = baseCountryConfigFacade.GetSystemRowByName(baseSystemName);
            _addOnSystemRow = _addOnCountryConfigFacade.GetSystemRowByName(addOnSystemName);

            //add-on-system will be stored in an CountryConfig generated for the purpose of storing it
            _mergeCountryConfigFacade = new CountryConfigFacade(countryShortName);

            //generate a copy of the base-system, by keeping all ids except the system id identically: otherwise the id-references (e.g. in ChangeParam, AddOn_Par, etc. would not work)
            _mergeSystemRow = CountryConfigFacade.CopySystemRowToAnotherCountry(baseSystemRow, _addOnSystemRow.Name,
                                                                                _mergeCountryConfigFacade.GetCountryConfig(), true);
            _mergeSystemRow.Name = newSystemName;

            //add policies following instructions in AddOn_Pol-functions
            AddPolicies();

            //add functions following instructions in AddOn_Func-functions
            AddFunctions();

            //add parameters following instructions in AddOn_Par-functions
            AddParameters();

            //replace e.g. yse_uk_#2 respectively yse_uk_#2.4 by the actual id of this function respectively parameter
            ReplaceSymbolicIDsInChangeParam();

            return(_errorMessages == string.Empty ? _mergeSystemRow : null);
        }
        private void ChangeNameInExchangeRatesConfig(CountryConfig.SystemRow systemRow, string oldSystemName)
        {
            ExchangeRatesConfigFacade excf = EM_AppContext.Instance.GetExchangeRatesConfigFacade(false); if (excf == null)
            {
                return;
            }
            bool anyChange = false;

            foreach (ExchangeRatesConfig.ExchangeRatesRow exchangeRate in
                     from er in excf.GetExchangeRates() where er.Country.ToLower() == systemRow.CountryRow.ShortName.ToLower() &&
                     ExchangeRate.ValidForToList(er.ValidFor).Contains(oldSystemName.ToLower()) select er)
            {
                if (!anyChange && UserInfoHandler.GetInfo("Do you want to update the system name in the global exchange rate table?" + Environment.NewLine + Environment.NewLine +
                                                          "Note that, if no exchange rate is found for a system name, the exchange rate is assumed to be 1.", MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return;
                }
                exchangeRate.ValidFor = ExchangeRate.RemoveFromValidFor(exchangeRate.ValidFor, oldSystemName);
                exchangeRate.ValidFor = ExchangeRate.AddToValidFor(exchangeRate.ValidFor, systemRow.Name); anyChange = true;
            }
            if (anyChange)
            {
                excf.WriteXML();
            }
        }
        internal override void PerformAction()
        {
            CountryConfig.SystemRow systemRow = (_senderColumn.Tag as SystemTreeListTag).GetSystemRow();

            string newSystemName = systemRow.Name, oldSystemName = systemRow.Name, newSystemYear = systemRow.Year;

            if (!SystemValidation.GetSystemNameAndYear(_dataConfigFacade != null, ref newSystemName, ref newSystemYear, _senderColumn.TreeList))
            {
                _actionIsCanceled = true;
                return;
            }

            // main action: rename system
            systemRow.Name = newSystemName; systemRow.Year = newSystemYear;
            // rename references in database-system-connection (if 'country' isn't an add-on)
            if (_dataConfigFacade != null)
            {
                _dataConfigFacade.RenameSystemInDBSystemConfigRows(systemRow.ID, newSystemName);
            }
            // rename references in conditional formatting
            _countryConfigFacade.RenameSystemInConditionalFormats(oldSystemName, newSystemName);

            if (_dataConfigFacade != null)
            {
                // rename standard-output-files (last parameter (request): ask user if she actually wants this to happen)
                CopySystemAction.RenameOutputFiles(_countryConfigFacade, systemRow, oldSystemName, true);
                // change name in global exchange rate file
                ChangeNameInExchangeRatesConfig(systemRow, oldSystemName);
                // warn about not-adaptation of AddOn_Applic-policy
                OptionalWarningsManager.Show(OptionalWarningsManager._renameSystemWarning);
            }
        }
示例#4
0
        internal override void PerformAction()
        {
            CountryConfig.SystemRow systemRow = (_senderColumn.Tag as SystemTreeListTag).GetSystemRow();

            if (_showRequest && Tools.UserInfoHandler.GetInfo("Are you sure you want to delete system '" + _senderColumn.Caption + "'?", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                _actionIsCanceled = true;
                return;
            }

            //adapt exchange-rate in global table
            //note that the exchange-rate-config is not included in the undo-procedure, thus this will not be undone
            ExchangeRatesConfigFacade excf = EM_AppContext.Instance.GetExchangeRatesConfigFacade(false);

            if (excf != null)
            {
                excf.RemoveSystems(systemRow.CountryRow.ShortName, new List <string>()
                {
                    systemRow.Name
                });
            }

            if (_dataConfigFacade != null)                                //if 'country' is an add-on it does not have a dataConfig
            {
                _dataConfigFacade.DeleteDBSystemConfigRows(systemRow.ID); //first delete all references of the system with datasets
            }
            CountryConfigFacade.DeleteSystemRow(systemRow);               //then delete the system itself
        }
示例#5
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);
                    }
                }
            }
        }
        void btnOK_Click(object sender, EventArgs e)
        {
            if (!CheckSystemYear())
            {
                return;
            }
            bool haveChanges = false;

            foreach (DataGridViewRow dataGridViewRow in dgvSystems.Rows)
            {
                CountryConfig.SystemRow systemRow = dataGridViewRow.Tag as CountryConfig.SystemRow;
                if (systemRow.CurrencyParam != dataGridViewRow.Cells[colCurrencyParameters.Name].Value.ToString())
                {
                    systemRow.CurrencyParam = dataGridViewRow.Cells[colCurrencyParameters.Name].Value.ToString();
                    haveChanges             = true;
                }
                if (systemRow.CurrencyOutput != dataGridViewRow.Cells[colCurrencyOutput.Name].Value.ToString())
                {
                    systemRow.CurrencyOutput = dataGridViewRow.Cells[colCurrencyOutput.Name].Value.ToString();
                    haveChanges = true;
                }
                if (EM_Helpers.SaveConvertToBoolean(dataGridViewRow.Cells[colPrivate.Name].Value) == true)
                {
                    if (systemRow.Private != DefPar.Value.YES)
                    {
                        systemRow.Private = DefPar.Value.YES;
                        haveChanges       = true;
                    }
                }
                else
                {
                    if (systemRow.Private != DefPar.Value.NO)
                    {
                        systemRow.Private = DefPar.Value.NO;
                        haveChanges       = true;
                    }
                }
                if (systemRow.HeadDefInc != dataGridViewRow.Cells[colHeadDefInc.Name].Value.ToString())
                {
                    systemRow.HeadDefInc = dataGridViewRow.Cells[colHeadDefInc.Name].Value.ToString();
                    haveChanges          = true;
                }
                if (systemRow.Year != dataGridViewRow.Cells[colYear.Name].Value.ToString())
                {
                    systemRow.Year = dataGridViewRow.Cells[colYear.Name].Value.ToString();
                    haveChanges    = true;
                }
                string comment = dataGridViewRow.Cells[colComment.Name].Value == null ? string.Empty : dataGridViewRow.Cells[colComment.Name].Value.ToString();
                if (systemRow.Comment != comment)
                {
                    systemRow.Comment = comment;
                    haveChanges       = true;
                }
            }
            DialogResult = haveChanges == true ? DialogResult.OK : DialogResult.Cancel;
            Close();
        }
示例#7
0
        void FillFunctionNodeWithParameters(CountryConfig.SystemRow systemRow, CountryConfig.FunctionRow functionRow, TreeListNode functionNode, bool isFirstSystem)
        {
            //generate the parameters of the function
            int parameterIndex = 0;
            var parameterQuery = (from parameter in functionRow.GetParameterRows() select parameter).OrderBy(parameter => long.Parse(parameter.Order));

            foreach (CountryConfig.ParameterRow parameterRow in parameterQuery.ToList())
            {
                TreeListNode parameterNode = isFirstSystem ? BuildParameterNode(functionNode, parameterRow) : functionNode.Nodes[parameterIndex++];
                (parameterNode.Tag as ParameterTreeListTag).AddParameterRowOfSystem(systemRow.ID, parameterRow);
                parameterNode.SetValue(systemRow.Name, parameterRow.Value);
            }
        }
示例#8
0
        public static string GetSystemYear(string cn, string sn)
        {
            CountryConfigFacade ccf = EM_UI.CountryAdministration.CountryAdministrator.GetCountryConfigFacade(cn);

            if (ccf == null)
            {
                return("");
            }
            CountryConfig.SystemRow sr = ccf.GetSystemRowByName(sn);
            if (sr == null)
            {
                return("");
            }
            return(sr.Year);
        }
示例#9
0
        void FillPolicyNodeWithFunctions(CountryConfig.SystemRow systemRow, CountryConfig.PolicyRow policyRow, TreeListNode policyNode, bool isFirstSystem)
        {
            //generate the functions of the policy
            int functionIndex = 0;
            var functionQuery = (from function in policyRow.GetFunctionRows() select function).OrderBy(function => long.Parse(function.Order));

            foreach (CountryConfig.FunctionRow functionRow in functionQuery.ToList <CountryConfig.FunctionRow>())
            {
                TreeListNode functionNode = isFirstSystem ? BuildFunctionNode(policyNode, functionRow) : policyNode.Nodes[functionIndex++];
                (functionNode.Tag as FunctionTreeListTag).AddFunctionRowOfSystem(systemRow.ID, functionRow);
                functionNode.SetValue(systemRow.Name, ExtensionAndGroupManager.GetExtensionAdaptedSwitch(functionRow));

                //generate the parameters of the function
                FillFunctionNodeWithParameters(systemRow, functionRow, functionNode, isFirstSystem);
            }
        }
        internal List <string> GetSystemsNamesDistinctAndOrdered(string countryShortName)
        {
            CountryConfigFacade ccF = CountryAdministration.CountryAdministrator.GetCountryConfigFacade(countryShortName);
            Dictionary <string, CountryConfig.SystemRow> systemRows = new Dictionary <string, CountryConfig.SystemRow>();

            foreach (DataConfig.DBSystemConfigRow dbSystemConfigRow in _dataConfig.DBSystemConfig.Rows)
            {
                if (systemRows.ContainsKey(dbSystemConfigRow.SystemID))
                {
                    continue;
                }
                CountryConfig.SystemRow systemRow = ccF.GetSystemRowByID(dbSystemConfigRow.SystemID);
                systemRows.Add(systemRow.ID, systemRow);
            }
            return((from s in systemRows.Values orderby long.Parse(s.Order) select s.Name).ToList());
        }
        internal override void PerformAction()
        {
            CountryConfig.SystemRow systemRow = (_senderColumn == null) ? null : (_senderColumn.Tag as SystemTreeListTag).GetSystemRow();
            TreeList countryTreeList          = (_senderColumn != null) ? _senderColumn.TreeList : null;
            string   systemName = systemRow == null ? string.Empty : systemRow.Name;
            string   systemYear = systemRow == null ? string.Empty : systemRow.Year;

            if (!SystemValidation.GetSystemNameAndYear(!_isAddOn, ref systemName, ref systemYear, countryTreeList))
            {
                _actionIsCanceled = true;
                return;
            }

            CountryConfig.SystemRow newSystemRow;
            if (_senderColumn == null) //add very first system
            {
                newSystemRow = _countryConfigFacade.AddFirstSystemRow(systemName);
            }
            else //add system by copying an existing system
            {
                CountryConfig.SystemRow toCopySystemRow = (_senderColumn.Tag as SystemTreeListTag).GetSystemRow();

                //copy system itself
                newSystemRow = CountryConfigFacade.CopySystemRow(systemName, toCopySystemRow);

                //copy all references of the system with datasets (i.e. new system can be used with same datasets as its template)
                if (!_isAddOn)
                {
                    _dataConfigFacade.CopyDBSystemConfigRows(toCopySystemRow, newSystemRow);
                }

                //copy system formats
                _countryConfigFacade.CopySystemFormatting(toCopySystemRow, newSystemRow);

                //rename output filename of default outputs
                RenameOutputFiles(_countryConfigFacade, newSystemRow, toCopySystemRow.Name);

                //adapt exchange-rate in global table
                //note that the exchange-rate-config is not included in the undo-procedure, thus this will not be undone
                AddToExchangeRatesTable(systemName, toCopySystemRow);

                ExtensionAndGroupManager.CopyExtensionAndGroupMemberships(_countryConfigFacade.GetCountryConfig(), newSystemRow.ID, toCopySystemRow.ID);
            }
            newSystemRow.Year = systemYear;
        }
        internal void CopyDBSystemConfigRows(CountryConfig.SystemRow originalSystemRow, CountryConfig.SystemRow copySystemRow)
        {
            foreach (DataConfig.DBSystemConfigRow originalDBSystemConfigRow in
                     (from dbSystemConfig in _dataConfig.DBSystemConfig
                      where dbSystemConfig.SystemID == originalSystemRow.ID
                      select dbSystemConfig).ToList())
            {
                DataConfig.DBSystemConfigRow copyDBSystemConfigRow = _dataConfig.DBSystemConfig.AddDBSystemConfigRow(copySystemRow.ID, copySystemRow.Name, originalDBSystemConfigRow.DataBaseRow,
                                                                                                                     originalDBSystemConfigRow.UseDefault, originalDBSystemConfigRow.UseCommonDefault, originalDBSystemConfigRow.Uprate, //parameter transferred to database-level, can be deleted once not used in any cc_DataConfig.xml anymore
                                                                                                                     originalDBSystemConfigRow.BestMatch);

                foreach (DataConfig.PolicySwitchRow originalExtensionSwitchRow in originalDBSystemConfigRow.GetPolicySwitchRows())
                {
                    _dataConfig.PolicySwitch.AddPolicySwitchRow(originalExtensionSwitchRow.SwitchablePolicyID,
                                                                copySystemRow.ID, originalExtensionSwitchRow.DataBaseID, originalExtensionSwitchRow.Value);
                }
            }
        }
示例#13
0
        internal void InsertFunctionNode(List <CountryConfig.FunctionRow> functionRowsOfAllSystems, TreeListNode policyNode, int nodeIndex = -1)
        {
            TreeListNode functionNode  = null;
            bool         isFirstSystem = true;

            foreach (CountryConfig.FunctionRow functionRow in functionRowsOfAllSystems)
            {
                CountryConfig.SystemRow systemRow = functionRow.PolicyRow.SystemRow;
                functionNode = isFirstSystem ? BuildFunctionNode(policyNode, functionRow) : policyNode.Nodes.LastNode;
                (functionNode.Tag as FunctionTreeListTag).AddFunctionRowOfSystem(systemRow.ID, functionRow);
                functionNode.SetValue(systemRow.Name, ExtensionAndGroupManager.GetExtensionAdaptedSwitch(functionRow));

                FillFunctionNodeWithParameters(systemRow, functionRow, functionNode, isFirstSystem);
                isFirstSystem = false;
            }
            if (nodeIndex != -1)
            {
                _mainForm.treeList.SetNodeIndex(functionNode, nodeIndex);
            }
        }
示例#14
0
        List <SystemAndBase> AssessBases(List <CountryConfig.SystemRow> systems, string country)
        {
            List <SystemAndBase> systemsAndBases = new List <SystemAndBase>();
            CountryConfigFacade  ccf             = CountryAdministrator.GetCountryConfigFacade(country);

            {
                foreach (CountryConfig.SystemRow system in systems)
                {
                    CountryConfig.SystemRow baseSystem = null;
                    foreach (CountryConfig.ConditionalFormatRow conditionalFormatRow in ccf.GetConditionalFormatRowsOfSystem(system))
                    {
                        if (conditionalFormatRow.BaseSystemName != null && conditionalFormatRow.BaseSystemName != string.Empty)
                        {
                            baseSystem = ccf.GetSystemRowByName(conditionalFormatRow.BaseSystemName); break;
                        }
                    }
                    systemsAndBases.Add(new SystemAndBase(system, baseSystem));
                }
            }
            return(systemsAndBases);
        }
        void AddToExchangeRatesTable(string systemName, CountryConfig.SystemRow toCopySystemRow)
        {
            ExchangeRatesConfigFacade excf = EM_AppContext.Instance.GetExchangeRatesConfigFacade(false); if (excf == null)
            {
                return;
            }
            bool found = false;

            foreach (ExchangeRatesConfig.ExchangeRatesRow exchangeRate in excf.GetExchangeRates())
            {
                if (exchangeRate.Country.ToLower() != toCopySystemRow.CountryRow.ShortName.ToLower() ||
                    !ExchangeRate.ValidForToList(exchangeRate.ValidFor).Contains(toCopySystemRow.Name.ToLower()))
                {
                    continue;
                }
                exchangeRate.ValidFor = ExchangeRate.AddToValidFor(exchangeRate.ValidFor, systemName); found = true; break;
            }
            if (found)
            {
                excf.WriteXML();
            }
        }
示例#16
0
        private static void AssessExtensionInfo(CountryConfigFacade ccf, DataConfigFacade dcf,
                                                string extensionId, string offOn, ref Dictionary <string, List <string> > switchInfo)
        {
            Dictionary <string, List <string> > dataSwitches = new Dictionary <string, List <string> >();

            foreach (DataConfig.PolicySwitchRow polSwitch in from e in dcf.GetDataConfig().PolicySwitch where e.SwitchablePolicyID == extensionId select e)
            {
                if (polSwitch.Value != offOn)
                {
                    continue;
                }
                if (!dataSwitches.ContainsKey(polSwitch.DataBaseID))
                {
                    dataSwitches.Add(polSwitch.DataBaseID, new List <string>());
                }
                dataSwitches[polSwitch.DataBaseID].Add(polSwitch.SystemID);
            }
            foreach (var dataSwitch in dataSwitches)
            {
                DataConfig.DataBaseRow dataRow = dcf.GetDataBaseRow(dataSwitch.Key); if (dataRow == null)
                {
                    continue;
                }
                string sumDataSwitches = dataRow.Name + ":";
                foreach (string sysId in dataSwitch.Value)
                {
                    CountryConfig.SystemRow sysRow = ccf.GetSystemRowByID(sysId); if (sysRow == null)
                    {
                        continue;
                    }
                    sumDataSwitches += sysRow.Name + ",";
                }
                if (!switchInfo.ContainsKey(extensionId))
                {
                    switchInfo.Add(extensionId, new List <string>());
                }
                switchInfo[extensionId].Add(RVItem_Base.TrimEnd(sumDataSwitches));
            }
        }
        void FillSystemsList()
        {
            bool firstFill = !_systemRows.Any(); List <string> selIds = new List <string>();

            try { if (!firstFill)
                  {
                      foreach (int index in lstSystems.CheckedIndices)
                      {
                          selIds.Add(_systemRows.ElementAt(index).ID);
                      }
                  }
            } catch { }

            lstSystems.Items.Clear();
            _systemRows.Clear();
            foreach (TreeListColumn systemColumn in _mainForm.GetTreeListBuilder().GetSystemColums())
            {
                CountryConfig.SystemRow systemRow = (systemColumn.Tag as SystemTreeListTag).GetSystemRow();
                int index = lstSystems.Items.Add(systemRow.Name);
                lstSystems.SetItemChecked(index, firstFill || selIds.Contains(systemRow.ID));
                _systemRows.Add(systemRow);
            }
        }
        private Dictionary <string, string> EM3_CreateConfig(string countryShortName, string outputPath,
                                                             DataConfig.DataBaseRow dbr, CountryConfig.SystemRow sr,
                                                             string parModifications = null)
        {
            Dictionary <string, string> config = new Dictionary <string, string>();

            config.Add(TAGS.CONFIG_PATH_OUTPUT, outputPath);
            config.Add(TAGS.CONFIG_PATH_DATA, EM_AppContext.FolderInput);
            config.Add(TAGS.CONFIG_PATH_EUROMODFILES, EM_AppContext.FolderEuromodFiles);
            config.Add(TAGS.CONFIG_COUNTRY, CountryAdministrator.GetCountryFileName(countryShortName).ToLower().Replace(".xml", ""));
            config.Add(TAGS.CONFIG_ID_DATA, dbr.ID);
            config.Add(TAGS.CONFIG_ID_SYSTEM, sr.ID);
            if (textRunFirstNHH.Text != null && !string.IsNullOrEmpty(textRunFirstNHH.Text) && int.TryParse(textRunFirstNHH.Text, out _))
            {
                config.Add(TAGS.CONFIG_FIRST_N_HH_ONLY, textRunFirstNHH.Text);
            }
            if (parModifications != null)
            {
                config.Add(TAGS.CONFIG_STRING_PAR_MODIFICATIONS, parModifications);
            }

            string addOn = GetCheckedAddon();

            if (!string.IsNullOrEmpty(addOn))
            {
                string addOnSys = null;
                foreach (AddOnSystemInfo aos in AddOnInfoHelper.GetAddOnSystemInfo(addOn))
                {
                    foreach (string sysPattern in aos._supportedSystems)
                    {
                        if (EM_Helpers.DoesValueMatchPattern(sysPattern, sr.Name))
                        {
                            addOnSys = aos._addOnSystemName; break;
                        }
                    }
                }
                if (addOnSys == null)
                {
                    throw new Exception($"No matching Addon found for {sr.Name}");
                }
                config.Add(TAGS.CONFIG_ADDON, $"{addOn}|{addOnSys}");
            }
            return(config);
        }
示例#19
0
 internal abstract void StoreChangedValue(string newValue, CountryConfig.SystemRow systemRow); //overtake user changes to data-row (this function is called by the Actions started by HandleValueChanged)
示例#20
0
        void btnOK_Click(object sender, EventArgs e)
        {
            //store information of grid for format settings of conditional formatting
            for (int iRow = 0; iRow < dgvConditionalFormatting.RowCount; ++iRow)
            {
                CountryConfig.ConditionalFormatRow conditionalFormatRow = null;
                if (dgvConditionalFormatting.Rows[iRow].Tag != null)
                {
                    conditionalFormatRow = dgvConditionalFormatting.Rows[iRow].Tag as CountryConfig.ConditionalFormatRow;
                }

                //delete condtional formats
                if (dgvConditionalFormatting.Rows[iRow].Visible == false)
                {
                    _countryConfigFacade.DeleteConditionalFormatRow(conditionalFormatRow);
                    continue;
                }

                // first delete any existing line, then build the new one.
                if (conditionalFormatRow != null)
                {
                    conditionalFormatRow.Delete();
                }
                conditionalFormatRow = _countryConfigFacade.AddConditionalFormatRow(
                    dgvConditionalFormatting.Rows[iRow].Cells[colBackColorConditionalFormatting.Name].Value.ToString(),
                    dgvConditionalFormatting.Rows[iRow].Cells[colForeColorConditionalFormatting.Name].Value.ToString(),
                    dgvConditionalFormatting.Rows[iRow].Cells[colCondition.Name].Value.ToString(),
                    string.Empty);

                //change conditional formats' systems to apply on
                object cellValue = dgvConditionalFormatting.Rows[dgvConditionalFormatting.Rows[iRow].Index].Cells[colSystemsToApply.Name].Value;
                if (cellValue != null)
                {
                    foreach (string systemName in cellValue.ToString().Split(_separator.First()))
                    {
                        CountryConfig.SystemRow systemRow = _countryConfigFacade.GetSystemRowByName(systemName.Trim());
                        if (systemRow != null)
                        {
                            _countryConfigFacade.AddConditionalFormat_SystemsRow(conditionalFormatRow, systemRow);
                        }
                    }
                }
            }

            //store information of grid for format settings of base-derived-system differences
            _systemsToExpand = new List <KeyValuePair <string, string> >();
            for (int iRow = 0; iRow < dgvBaseSystemFormatting.RowCount; ++iRow)
            {
                CountryConfig.SystemRow systemRow = _countryConfigFacade.GetSystemRowByName(dgvBaseSystemFormatting.Rows[iRow].Cells[colSystem.Name].Value.ToString());
                if (systemRow == null)
                {
                    continue;
                }

                CountryConfig.ConditionalFormatRow conditionalFormatRow = null;
                if (dgvBaseSystemFormatting.Rows[iRow].Tag != null)
                {
                    conditionalFormatRow = dgvBaseSystemFormatting.Rows[iRow].Tag as CountryConfig.ConditionalFormatRow;
                }

                string baseSystemName = string.Empty;
                object cellValue      = dgvBaseSystemFormatting.Rows[iRow].Cells[colBaseSystem.Name].Value;
                if (cellValue != null)
                {
                    baseSystemName = cellValue.ToString();
                }

                //expanding of differences between system and its base (if ticked by the user) is handled by the TreeListManager after the CF-action (see TreeListManager.HandleConditionalFormatting)
                //here only gather respective systems and their base
                if (EM_Helpers.SaveConvertToBoolean(dgvBaseSystemFormatting.Rows[iRow].Cells[colExpandDifferences.Name].Value) == true)
                {
                    if (baseSystemName == string.Empty)
                    {
                        continue;
                    }
                    _systemsToExpand.Add(new KeyValuePair <string, string>(systemRow.Name, baseSystemName));
                }

                if (conditionalFormatRow != null)                              // if there was a base system
                {
                    if (conditionalFormatRow.BaseSystemName == baseSystemName) //just format changed, but same base system
                    {
                        conditionalFormatRow.BackColor = dgvBaseSystemFormatting.Rows[iRow].Cells[colBackColorBaseSystemFormatting.Name].Value.ToString();
                        conditionalFormatRow.ForeColor = dgvBaseSystemFormatting.Rows[iRow].Cells[colForeColorBaseSystemFormatting.Name].Value.ToString();
                        continue;
                    }
                    conditionalFormatRow.Delete(); // else delete this and make a new one if required
                }

                if (baseSystemName == string.Empty)
                {
                    continue;
                }

                conditionalFormatRow = _countryConfigFacade.AddConditionalFormatRow(
                    dgvBaseSystemFormatting.Rows[iRow].Cells[colBackColorBaseSystemFormatting.Name].Value.ToString(),
                    dgvBaseSystemFormatting.Rows[iRow].Cells[colForeColorBaseSystemFormatting.Name].Value.ToString(),
                    string.Empty, baseSystemName);

                _countryConfigFacade.AddConditionalFormat_SystemsRow(conditionalFormatRow, systemRow);
            }

            DialogResult = DialogResult.OK;
            Close();
        }
示例#21
0
 internal SystemTreeListTag(CountryConfig.SystemRow systemRow)
 {
     _systemRow = systemRow;
 }
示例#22
0
 internal SystemAndBase(CountryConfig.SystemRow _system, CountryConfig.SystemRow _baseSystem)
 {
     system = _system; baseSystem = _baseSystem;
 }
示例#23
0
        private void EM2_FixUprating(CountryConfig.SystemRow sr1, Dictionary <string, string> upratingFactors, Dictionary <string, string> upratingFactors2, string countryShortName, double alpha, int uprateType, bool treatAsMarket)
        {
            // first get the ils_origy & ils_ben components
            CountryConfig.PolicyRow ilsdef = sr1.GetPolicyRows().FirstOrDefault(p => p.Name.ToLower() == ("ilsdef_" + countryShortName).ToLower());
            if (ilsdef == null)
            {
                ilsdef = sr1.GetPolicyRows().FirstOrDefault(p => p.Name.ToLower() == ("ildef_" + countryShortName).ToLower());
            }
            if (ilsdef == null)
            {
                return;
            }

            CountryConfig.FunctionRow[] il_funcs = ilsdef.GetFunctionRows();
            List <string> ils_origy       = ExpandIncomeList(DefVarName.ILSORIGY, il_funcs).Keys.ToList();
            List <string> ils_ben         = ExpandIncomeList(DefVarName.ILSBEN, il_funcs).Keys.ToList();
            List <string> overrideInclude = ExpandIncomeList("pet_override", il_funcs).Where(x => x.Value).Select(x => x.Key).ToList();
            List <string> overrideExclude = ExpandIncomeList("pet_override", il_funcs).Where(x => !x.Value).Select(x => x.Key).ToList();

            List <string> reservedWords = new List <string> {
                "dataset", "def_factor", "factor_name", "factor_value", "factor_condition", "aggvar_name", "aggvar_part", "aggvar_tolerance", "warnifnofactor", "run_cond"
            };

            // Then apply them to the appropriate variables of s1
            foreach (CountryConfig.FunctionRow fr in sr1.GetPolicyRows().First(p => p.Name.ToLower() == ("Uprate_" + countryShortName).ToLower()).GetFunctionRows())
            {
                if (fr.Name.ToLower() == "uprate")
                {
                    foreach (CountryConfig.ParameterRow pr in fr.GetParameterRows())
                    {
                        string pn = pr.Name.ToLower();

                        if (!reservedWords.Contains(pn))
                        {
                            if (uprateType == 3)    // uprate all
                            {
                                double val;
                                if (upratingFactors.ContainsKey(pr.Value.ToLower()))
                                {
                                    pr.Value = FixDecSep((EM_Helpers.SaveConvertToDouble(upratingFactors2[pr.Value.ToLower()]) * alpha).ToString());
                                }
                                else if (EM_Helpers.TryConvertToDouble(pr.Value.ToLower(), out val))
                                {
                                    pr.Value = FixDecSep((val * alpha).ToString());
                                }
                            }
                            else
                            {
                                bool marketIncome = overrideInclude.Contains(pn);   // if in the override include list
                                if (!overrideExclude.Contains(pn) && !marketIncome) // else if not in the override exlcude list
                                {
                                    VarConfig.VariableRow v = EM_AppContext.Instance.GetVarConfigFacade().GetVariableByName(pn);
                                    if (v == null || v.Monetary != "1")
                                    {
                                        marketIncome = false;
                                    }
                                    else
                                    {
                                        if (treatAsMarket)
                                        {
                                            marketIncome = !pn.EndsWith(DefGeneral.POSTFIX_SIMULATED);
                                        }
                                        else
                                        {
                                            marketIncome = !ils_ben.Contains(pn) && (pn[0] == 'y' || pn[0] == 'a' || pn[0] == 'x' || ils_origy.Contains(pn));
                                        }
                                    }
                                }

                                // if this is a market income
                                if (marketIncome)
                                {
                                    if (uprateType == 1)
                                    {
                                        double val;
                                        if (upratingFactors.ContainsKey(pr.Value.ToLower()))
                                        {
                                            pr.Value = FixDecSep((EM_Helpers.SaveConvertToDouble(upratingFactors[pr.Value.ToLower()]) * alpha).ToString());
                                        }
                                        else if (EM_Helpers.TryConvertToDouble(pr.Value.ToLower(), out val))
                                        {
                                            pr.Value = FixDecSep((val * alpha).ToString());
                                        }
                                    }
                                    else if (uprateType == 2)
                                    {
                                        if (upratingFactors.ContainsKey(pr.Value.ToLower()))
                                        {
                                            pr.Value = FixDecSep((EM_Helpers.SaveConvertToDouble(upratingFactors[pr.Value.ToLower()])).ToString());
                                        }
                                    }
                                }
                                else    // if it is non-market income
                                {
                                    if (uprateType == 2)
                                    {
                                        double val;
                                        if (upratingFactors2.ContainsKey(pr.Value.ToLower()))
                                        {
                                            pr.Value = FixDecSep((EM_Helpers.SaveConvertToDouble(upratingFactors2[pr.Value.ToLower()]) / alpha).ToString());
                                        }
                                        else if (EM_Helpers.TryConvertToDouble(pr.Value.ToLower(), out val))
                                        {
                                            pr.Value = FixDecSep((val / alpha).ToString());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (uprateType > 1)
            {
                string[] monetaryTypes = new string[] { DefPeriod.M, DefPeriod.Y, DefPeriod.Q, DefPeriod.W,
                                                        DefPeriod.D, DefPeriod.L, DefPeriod.S, DefPeriod.C };
                foreach (CountryConfig.FunctionRow fr in sr1.GetPolicyRows().First(p => p.Name.ToLower() == ("Uprate_" + countryShortName).ToLower()).GetFunctionRows())
                {
                    foreach (CountryConfig.ParameterRow pr in fr.GetParameterRows())
                    {
                        string val = pr.Value.ToLower().Trim();
                        if (val.Length < 3)
                        {
                            continue;
                        }
                        string valType = val.Substring(val.Length - 2);

                        if (monetaryTypes.Contains(valType))
                        {
                            val = val.Substring(0, val.Length - 2);
                            if (uprateType == 2)
                            {
                                pr.Value = FixDecSep((EM_Helpers.SaveConvertToDouble(val) / alpha).ToString()) + valType;
                            }
                            else if (uprateType == 3)
                            {
                                pr.Value = FixDecSep((EM_Helpers.SaveConvertToDouble(val) * alpha).ToString()) + valType;
                            }
                        }
                    }
                }
            }
            try
            {
                // Then, fix the output filenames
                sr1.GetPolicyRows().First(p => p.Name.ToLower() == ("output_std_" + countryShortName).ToLower())
                .GetFunctionRows().First(f => f.Name.ToLower() == "defoutput")
                .GetParameterRows().First(p => p.Name.ToLower() == "file")
                .Value = sr1.Name + "_std";
                sr1.GetPolicyRows().First(p => p.Name.ToLower() == ("output_std_hh_" + countryShortName).ToLower())
                .GetFunctionRows().First(f => f.Name.ToLower() == "defoutput")
                .GetParameterRows().First(p => p.Name.ToLower() == "file")
                .Value = sr1.Name + "_std_hh";
                // Finally, if required, do the scaling
                if (checkRadioMarket.Checked)
                {
                    CountryConfig.FunctionRow fr = sr1.GetPolicyRows().First(p => p.Name.ToLower() == ("output_std_" + countryShortName).ToLower())
                                                   .GetFunctionRows().First(f => f.Name.ToLower() == "defoutput");
                    CountryConfig.FunctionRow fr_hh = sr1.GetPolicyRows().First(p => p.Name.ToLower() == ("output_std_hh_" + countryShortName).ToLower())
                                                      .GetFunctionRows().First(f => f.Name.ToLower() == "defoutput");

                    if (fr.GetParameterRows().Count(p => p.Name.ToLower() == DefPar.DefOutput.MultiplyMonetaryBy.ToLower()) == 0)
                    {
                        CountryConfig.ParameterRow fpr = fr.GetParameterRows().First(p => p.Name.ToLower() == "file");
                        CountryConfig.ParameterRow cpr = CountryConfigFacade.AddParameterRow(fpr, false,
                                                                                             DefPar.DefOutput.MultiplyMonetaryBy, DefinitionAdmin.GetParDefinition(DefFun.DefOutput, DefPar.DefOutput.MultiplyMonetaryBy));
                        cpr.Value = FixDecSep((1 / alpha).ToString());
                    }
                    else
                    {
                        CountryConfig.ParameterRow mpr = fr.GetParameterRows().First(p => p.Name.ToLower() == DefPar.DefOutput.MultiplyMonetaryBy.ToLower());
                        double d;
                        if (!EM_Helpers.TryConvertToDouble(mpr.Value, out d))
                        {
                            d = 1;
                        }
                        mpr.Value = FixDecSep((d / alpha).ToString());
                    }

                    if (fr_hh.GetParameterRows().Count(p => p.Name.ToLower() == DefPar.DefOutput.MultiplyMonetaryBy.ToLower()) == 0)
                    {
                        CountryConfig.ParameterRow fpr_hh = fr_hh.GetParameterRows().First(p => p.Name.ToLower() == "file");
                        CountryConfig.ParameterRow cpr    = CountryConfigFacade.AddParameterRow(fpr_hh, false,
                                                                                                DefPar.DefOutput.MultiplyMonetaryBy, DefinitionAdmin.GetParDefinition(DefFun.DefOutput, DefPar.DefOutput.MultiplyMonetaryBy));
                        cpr.Value = FixDecSep((1 / alpha).ToString());
                    }
                    else
                    {
                        CountryConfig.ParameterRow mpr_hh = fr_hh.GetParameterRows().First(p => p.Name.ToLower() == DefPar.DefOutput.MultiplyMonetaryBy.ToLower());
                        double d;
                        if (!EM_Helpers.TryConvertToDouble(mpr_hh.Value, out d))
                        {
                            d = 1;
                        }
                        mpr_hh.Value = FixDecSep((d / alpha).ToString());
                    }
                }
            }
            catch
            {
                throw new Exception("Problem in default output functions.");
            }
        }
示例#24
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();
        }
示例#25
0
        private Dictionary <string, string> EM2_CreateConfig(string countryShortName, string outputPath, DataConfig.DataBaseRow dbr, CountryConfig.SystemRow sr, bool useTempCountry = true)
        {
            Dictionary <string, string> contentEMConfig = new Dictionary <string, string>();

            string emVersion = EM_AppContext.Instance.GetProjectName();

            if (emVersion.Trim() == string.Empty)
            {
                UserInfoHandler.ShowError($"{DefGeneral.BRAND_TITLE} version is not defined. Please define it via the menu 'Configuration'.");
                return(null);
            }
            //fill EMConfig-entry-list
            string dateTimePrefix = string.Format("{0:yyyyMMddHHmm}", DateTime.Now);

            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_ERRLOG_FILE, outputPath + dateTimePrefix + EM_XmlHandler.TAGS.EM2CONFIG_errLogFileName);
            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_LOG_WARNINGS, DefPar.Value.YES);
            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_EMVERSION, emVersion);
            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_UIVERSION, DefGeneral.UI_VERSION);
            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_PARAMPATH, useTempCountry ? EMPath.AddSlash(EMPath.Folder_Temp(EM_AppContext.FolderEuromodFiles)) : EMPath.AddSlash(Path.Combine(EMPath.Folder_Countries(EM_AppContext.FolderEuromodFiles), countryShortName)));
            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_CONFIGPATH, EMPath.Folder_Config(EM_AppContext.FolderEuromodFiles));
            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_OUTPUTPATH, outputPath);
            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_DATAPATH, EM_AppContext.FolderInput);
            string executablePath = EnvironmentInfo.GetEM2ExecutableFile();

            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_EMCONTENTPATH, EM_AppContext.FolderEuromodFiles);
            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_HEADER_DATE, dateTimePrefix);
            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_OUTFILE_DATE, "-");
            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_LOG_RUNTIME, DefPar.Value.NO);
            if (EM_AppContext.Instance.IsPublicVersion())
            {
                contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_ISPUBLICVERSION, DefPar.Value.YES);
            }
            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_DECSIGN_PARAM, EM_Helpers.uiDecimalSeparator);
            string startHH = EM_XmlHandler.TAGS.EM2CONFIG_defaultHHID;
            string lastHH  = EM_XmlHandler.TAGS.EM2CONFIG_defaultHHID;

            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_STARTHH, startHH);
            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_LASTHH, lastHH);
            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_COUNTRY_FILE, CountryAdministrator.GetCountryFileName(countryShortName));
            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_DATACONFIG_FILE, CountryAdministrator.GetDataFileName(countryShortName));
            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_DATASET_ID, dbr.ID);
            contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_SYSTEM_ID, sr.ID);

            //generate for each (available) switchable policy a POLICY_SWITCH-entry
            Dictionary <string, string> extIDAndPattern = new Dictionary <string, string>();

            foreach (GlobLocExtensionRow e in ExtensionAndGroupManager.GetExtensions(countryShortName))
            {
                extIDAndPattern.Add(e.ID, e.ShortName);
            }

            List <string> policySwitchEntries = new List <string>();

            foreach (var e in extIDAndPattern)
            {
                string extID = e.Key, extShortName = e.Value;
                string policySwitchValue = string.Empty;
                if (dbr.GetDBSystemConfigRows().Count(x => x.SystemID == sr.ID) > 0)
                {
                    policySwitchValue = ExtensionAndGroupManager.GetExtensionDefaultSwitch(dbr.GetDBSystemConfigRows().First(x => x.SystemID == sr.ID), extID);
                }

                //generate the POLICY_SWITCH-entry
                //taking into account that there is no need to generate it if the switch is set to n/a (i.e. the switchable policy is not switchable for this db-system-combination or does not even exist)
                if (policySwitchValue != string.Empty && policySwitchValue != DefPar.Value.NA)
                {
                    string policySwitchEntry =                            //the executable needs three pieces of information to overwrite the default value of the policy switch:
                                               extShortName               //which switchable policy (e.g. BTA_??)
                                               + "=" + sr.ID              //which system
                                               + "=" + policySwitchValue; //and the respective value (on or off)
                    policySwitchEntries.Add(policySwitchEntry);
                }
            }

            //for each (available) switchable policy add a POLICY_SWITCH-entry
            foreach (string policySwitchEntry in policySwitchEntries)
            {
                contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_POLICY_SWITCH + Guid.NewGuid().ToString(), policySwitchEntry);
            }


            //now actually write the EMConfigXXX.xml files and hand them over to the run-manager
            string configurationFileNameAndPath = EMPath.Folder_Temp(EM_AppContext.FolderEuromodFiles) + EM_XmlHandler.TAGS.EM2CONFIG_labelEMConfig + Guid.NewGuid().ToString() + ".xml";

            using (XmlTextWriter configurationFileWriter = new XmlTextWriter(configurationFileNameAndPath, null))
            {
                configurationFileWriter.Formatting = System.Xml.Formatting.Indented;
                configurationFileWriter.WriteStartDocument(true);
                configurationFileWriter.WriteStartElement(EM_XmlHandler.TAGS.EM2CONFIG_labelEMConfig);

                string runFormInfoText = string.Empty;
                foreach (string key in contentEMConfig.Keys)
                {
                    if (key.StartsWith(EM_XmlHandler.TAGS.EM2CONFIG_SYSTEM_ID)) //remove Guid, see above
                    {
                        configurationFileWriter.WriteElementString(EM_XmlHandler.TAGS.EM2CONFIG_SYSTEM_ID, contentEMConfig[key]);
                    }
                    else if (key.StartsWith(EM_XmlHandler.TAGS.EM2CONFIG_POLICY_SWITCH)) //remove Guid, see above
                    {
                        configurationFileWriter.WriteElementString(EM_XmlHandler.TAGS.EM2CONFIG_POLICY_SWITCH, contentEMConfig[key]);
                    }
                    else
                    {
                        configurationFileWriter.WriteElementString(key, contentEMConfig[key]);
                    }
                }

                configurationFileWriter.WriteElementString(EM_XmlHandler.TAGS.EM2CONFIG_LAST_RUN, DefPar.Value.NO);
                configurationFileWriter.WriteEndElement();
                configurationFileWriter.WriteEndDocument();
            }
            // EM3 returns the config-dictionary, therefore (mis)use this structure to just store the file-path as the first entry (to avoid extra variables for EM2)
            return(new Dictionary <string, string>()
            {
                { configurationFileNameAndPath, null }
            });
        }
        Dictionary <string, string> GatherComponents()
        {
            Dictionary <string, string> selectedComponents = new Dictionary <string, string>();

            if (chkAllVariables.Checked)
            {
                if (chkCountrySpecific.Checked)
                {
                    string countryShortName = _mainForm.GetCountryShortName();
                    foreach (VarConfig.VariableRow variableRow in EM_AppContext.Instance.GetVarConfigFacade().GetVariablesWithCountrySpecificDescription(countryShortName))
                    {
                        if (IsCheckedVariable(variableRow))
                        {
                            selectedComponents.Add(variableRow.Name, _componentType_Variable);
                        }
                    }
                }
                else if (chkMonetary.Checked || chkNonMonetary.Checked || chkSimulated.Checked || chkNonSimulated.Checked)
                {
                    foreach (VarConfig.VariableRow variableRow in EM_AppContext.Instance.GetVarConfigFacade().GetVariables())
                    {
                        if (IsCheckedVariable(variableRow))
                        {
                            selectedComponents.Add(variableRow.Name, _componentType_Variable);
                        }
                    }
                }
                else
                {
                    foreach (string variableName in EM_AppContext.Instance.GetVarConfigFacade().GetVariables_NamesAndDescriptions().Keys)
                    {
                        if (!selectedComponents.Keys.Contains(variableName.ToLower()))
                        {
                            selectedComponents.Add(variableName.ToLower(), _componentType_Variable);
                        }
                    }
                }
            }

            if (chkAssessmentUnits.Checked)
            {
                List <CountryConfig.ParameterRow> parameterRowsTUs = null;
                foreach (TreeListColumn systemColumn in _mainForm.GetTreeListBuilder().GetSystemColums())
                {
                    CountryConfig.SystemRow systemRow = (systemColumn.Tag as SystemTreeListTag).GetSystemRow();
                    CountryConfigFacade.GetDefFunctionInformation(systemRow, ref parameterRowsTUs, DefFun.DefTu, DefPar.DefTu.Name);
                    foreach (CountryConfig.ParameterRow parameterRowsTU in parameterRowsTUs)
                    {
                        if (!selectedComponents.Keys.Contains(parameterRowsTU.Value.ToLower()))
                        {
                            selectedComponents.Add(parameterRowsTU.Value.ToLower(), _componentType_Taxunit);
                        }
                    }
                }
            }

            if (chkIncomelists.Checked)
            {
                List <CountryConfig.ParameterRow> parameterRowsILs = null;
                foreach (TreeListColumn systemColumn in _mainForm.GetTreeListBuilder().GetSystemColums())
                {
                    CountryConfig.SystemRow systemRow = (systemColumn.Tag as SystemTreeListTag).GetSystemRow();
                    CountryConfigFacade.GetDefFunctionInformation(systemRow, ref parameterRowsILs, DefFun.DefIl, DefPar.DefIl.Name);
                    foreach (CountryConfig.ParameterRow parameterRowsIL in parameterRowsILs)
                    {
                        if (!selectedComponents.Keys.Contains(parameterRowsIL.Value.ToLower()))
                        {
                            selectedComponents.Add(parameterRowsIL.Value.ToLower(), _componentType_Incomelist);
                        }
                    }
                }
            }

            if (chkQueries.Checked)
            {
                foreach (string queryName in DefinitionAdmin.GetQueryNamesAndDesc(false).Keys)
                {
                    if (!selectedComponents.Keys.Contains(queryName.ToLower()))
                    {
                        selectedComponents.Add(queryName.ToLower(), _componentType_Query);
                        DefinitionAdmin.GetQueryDefinition(queryName, out DefinitionAdmin.Query queryDef, out string dummy, false);
                        if (queryDef != null)
                        {
                            foreach (string queryAlias in queryDef.aliases)
                            {
                                selectedComponents.Add(queryAlias.ToLower(), _componentType_Query);
                            }
                        }
                    }
                }
            }

            if (txtComponentName.Text != string.Empty && !IsPatternSearchForSingleComponent()) //pattern-search has to be treated differently
            {
                if (!selectedComponents.Keys.Contains(txtComponentName.Text.ToLower()))
                {
                    selectedComponents.Add(txtComponentName.Text.ToLower(), _componentType_Unknown);
                }
            }

            return(selectedComponents);
        }
 internal override void StoreChangedValue(string newValue, CountryConfig.SystemRow systemRow)
 {
     _policyRows[systemRow.ID].Switch = newValue;
 }
        static internal int GetSystemYear(CountryConfig.SystemRow system)
        {
            int year;

            return(system.Year == null || system.Year == string.Empty || !int.TryParse(system.Year, out year) ? GetSystemYear(system.Name) : year);
        }
示例#29
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();
                    }
                }
            }
        }
示例#30
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}");
            }
        }