Esempio n. 1
0
        public bool LoadScheduled(List <Treatments> availableTreatments)
        {
            var select = "SELECT SCHEDULEDID, SCHEDULEDTREATMENTID, SCHEDULEDYEAR FROM SCHEDULED WHERE TREATMENTID='" + this.TreatmentID + "'";

            DataSet ds;

            try
            {
                ds = DBMgr.ExecuteQuery(select);


                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var scheduledId          = int.Parse(row["SCHEDULEDID"].ToString());
                    var scheduledTreatmentId = row["SCHEDULEDTREATMENTID"].ToString();
                    var scheduledYear        = int.Parse(row["SCHEDULEDYEAR"].ToString());
                    var scheduledTreatment   = availableTreatments.Find(t => t.TreatmentID == scheduledTreatmentId);

                    if (scheduledTreatment != null)
                    {
                        _scheduleds.Add(new Scheduled(scheduledId, scheduledTreatment, scheduledYear));
                    }
                }
            }
            catch (Exception exception)
            {
                SimulationMessaging.AddMessage(
                    new SimulationMessage("Fatal Error: Opening SCHEDULED table. SQL Message - " + exception.Message));
                return(false);
            }
            return(true);
        }
Esempio n. 2
0
File: Costs.cs Progetto: jakedw7/iAM
 public double GetCost(Hashtable hashAttributeValue)
 {
     if (this._isCompoundTreatment)
     {
         CompoundTreatment compoundTreatment = Simulation.CompoundTreatments.Find(delegate(CompoundTreatment ct) { return(ct.CompoundTreatmentName == _compoundTreatment); });
         return(compoundTreatment.GetCost(hashAttributeValue));
     }
     else
     {
         int      i     = 0;
         object[] input = new object[_attributesEquation.Count];
         foreach (String str in _attributesEquation)
         {
             if (hashAttributeValue[str] != null)
             {
                 input[i] = hashAttributeValue[str];
             }
             else
             {
                 input[i] = 0;
             }
             i++;
         }
         try
         {
             object result = _calculate.RunMethod(input);
             return((double)result);
         }
         catch (Exception exc)
         {
             SimulationMessaging.AddMessage(new SimulationMessage("Error in RunMethod. " + exc.Message));
             return(0);
         }
     }
 }
Esempio n. 3
0
        public bool IsCriteriaMet(Hashtable hashAttributeValue)
        {
            if (string.IsNullOrWhiteSpace(_criteria))
            {
                return(true);
            }
            object[] input = new object[_attributesCriteria.Count];
            int      i     = 0;

            foreach (String str in _attributesCriteria)
            {
                input[i] = hashAttributeValue[str];
                i++;
            }
            try
            {
                if (_evaluate.m_methodInfo == null)
                {
                    if (_evaluate.m_cr == null)
                    {
                        _evaluate.BuildClass(_evaluate.Expression, false, cgOMS.Prefix + _table + "_" + _column + "_" + _performanceID);
                        _evaluate.CompileAssembly();
                        SimulationMessaging.SaveSerializedCalculateEvaluate(cgOMS.Prefix + _table, _column, _performanceID, _evaluate);
                    }
                }
                bool isMet = (bool)_evaluate.RunMethod(input);
                return(isMet);
            }
            catch (Exception exc)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error in RunMethod.   " + _evaluate.OriginalInput + " " + exc.Message));
                return(false);
            }
        }
Esempio n. 4
0
        private bool GetCalculatedFieldData()
        {
            if (m_listCalculated == null)
            {
                m_listCalculated = new List <Deteriorate>();
            }
            String  strSelect = "SELECT ATTRIBUTE_,EQUATION,CRITERIA FROM " + cgOMS.Prefix + "ATTRIBUTES_CALCULATED";
            DataSet ds;

            try
            {
                ds = DBMgr.ExecuteQuery(strSelect);
            }
            catch (Exception exception)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving Calculated Field data. SQL Message - " + exception.Message));
                return(false);
            }

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                Deteriorate deteriorate = new Deteriorate();

                deteriorate.Attribute = row["ATTRIBUTE_"].ToString();
                deteriorate.Equation  = row["EQUATION"].ToString();
                deteriorate.Criteria  = row["CRITERIA"].ToString();
                m_listCalculated.Add(deteriorate);
            }


            return(true);
        }
Esempio n. 5
0
        public bool LoadSupersedes(object APICall, IMongoCollection <SimulationModel> Simulations, string m_strSimulationID)
        {
            try
            {
                var     select = "SELECT SUPERSEDE_ID, SUPERSEDE_TREATMENT_ID, CRITERIA FROM SUPERSEDES WHERE TREATMENT_ID='" + this.TreatmentID + "'";
                DataSet ds     = DBMgr.ExecuteQuery(select);

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var supersedeId          = int.Parse(row["SUPERSEDE_ID"].ToString());
                    var supersedeTreatmentId = int.Parse(row["SUPERSEDE_TREATMENT_ID"].ToString());
                    var criteria             = "";

                    if (row["CRITERIA"] != DBNull.Value)
                    {
                        criteria = row["CRITERIA"].ToString();
                    }

                    Supersedes.Add(new Supersede(supersedeId, supersedeTreatmentId, criteria));
                }


                foreach (var supersede in Supersedes)
                {
                    foreach (String str in supersede.Criteria.CriteriaAttributes)
                    {
                        if (!SimulationMessaging.IsAttribute(str))
                        {
                            SimulationMessaging.AddMessage(new SimulationMessage("Error: " + str + " which is used by the Supersede criteria is not present in the database."));
                            if (APICall.Equals(true))
                            {
                                var updateStatus = Builders <SimulationModel> .Update
                                                   .Set(s => s.status, "Error: " + str + " which is used by the Supersede criteria is not present in the database");

                                Simulations.UpdateOne(s => s.simulationId == Convert.ToInt32(m_strSimulationID), updateStatus);
                            }
                        }
                        if (!_attributes.Contains(str))
                        {
                            _attributes.Add(str);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                SimulationMessaging.AddMessage(
                    new SimulationMessage("Fatal Error: Opening SUPERSEDE table. SQL Message - " + exception.Message));
                if (APICall.Equals(true))
                {
                    var updateStatus = Builders <SimulationModel> .Update
                                       .Set(s => s.status, "Fatal Error: Opening SUPERSEDE table. SQL Message - " + exception.Message);

                    Simulations.UpdateOne(s => s.simulationId == Convert.ToInt32(m_strSimulationID), updateStatus);
                }
                return(false);
            }
            return(true);
        }
Esempio n. 6
0
        public bool LoadSupersedes()
        {
            try
            {
                var     select = "SELECT SUPERSEDE_ID, SUPERSEDE_TREATMENT_ID, CRITERIA FROM SUPERSEDES WHERE TREATMENT_ID='" + this.TreatmentID + "'";
                DataSet ds     = DBMgr.ExecuteQuery(select);

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var supersedeId          = int.Parse(row["SUPERSEDE_ID"].ToString());
                    var supersedeTreatmentId = int.Parse(row["SUPERSEDE_TREATMENT_ID"].ToString());
                    var criteria             = "";

                    if (row["CRITERIA"] != DBNull.Value)
                    {
                        criteria = row["CRITERIA"].ToString();
                    }

                    Supersedes.Add(new Supersede(supersedeId, supersedeTreatmentId, criteria));
                }


                foreach (var supersede in Supersedes)
                {
                    foreach (String str in supersede.Criteria.CriteriaAttributes)
                    {
                        if (!SimulationMessaging.IsAttribute(str))
                        {
                            SimulationMessaging.AddMessage(new SimulationMessage("Error: " + str + " which is used by the Supersede criteria is not present in the database."));
                        }
                        if (!_attributes.Contains(str))
                        {
                            _attributes.Add(str);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                SimulationMessaging.AddMessage(
                    new SimulationMessage("Fatal Error: Opening SUPERSEDE table. SQL Message - " + exception.Message));
                return(false);
            }
            return(true);
        }
Esempio n. 7
0
        Hashtable m_hashPavmentCoefficient;// Key is pavement type.  Value is list of doubles.



        public CRS()
        {
            if (DBMgr.IsTableInDatabase("CRS_COEFFICIENT"))
            {
                String strSelect = "SELECT PAVEMENT,A,B,C,D FROM CRS_COEFFICIENT";
                try
                {
                    m_hashPavmentCoefficient = new Hashtable();
                    DataSet ds = DBMgr.ExecuteQuery(strSelect);
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        List <double> listCoefficient = new List <double>();

                        double dCoefficient = 0;
                        double.TryParse(dr[1].ToString(), out dCoefficient);
                        listCoefficient.Add(dCoefficient);

                        dCoefficient = 0;
                        double.TryParse(dr[2].ToString(), out dCoefficient);
                        listCoefficient.Add(dCoefficient);

                        dCoefficient = 0;
                        double.TryParse(dr[3].ToString(), out dCoefficient);
                        listCoefficient.Add(dCoefficient);

                        dCoefficient = 0;
                        double.TryParse(dr[4].ToString(), out dCoefficient);
                        listCoefficient.Add(dCoefficient);

                        m_hashPavmentCoefficient.Add(dr[0].ToString(), listCoefficient);
                    }
                }
                catch (Exception exception)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("CRS attribute load error.  Make sure CRS_COEFFICIENT table exists: " + exception.Message));
                }
            }
            else
            {
                m_hashPavmentCoefficient = new Hashtable();
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Get consequence given an input value set.
        /// </summary>
        /// <param name="hashAttributeValue"></param>
        /// <returns></returns>
        public double GetConsequence(Hashtable hashAttributeValue)
        {
            int i = 0;

            object[] input = new object[_attributesEquation.Count];
            foreach (String str in _attributesEquation)
            {
                input[i] = hashAttributeValue[str];
                i++;
            }
            try
            {
                object result = _calculate.RunMethod(input);
                return((double)result);
            }
            catch (Exception exc)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error in RunMethod. " + exc.Message));
                return(0);
            }
        }
Esempio n. 9
0
        public double ApplyDeterioration(Hashtable hashAttributeValue)
        {
            object[] input = new object[_attributesEquation.Count];

            int i = 0;

            foreach (String str in _attributesEquation)
            {
                input[i] = hashAttributeValue[str];
                i++;
            }

            double dReturn = 0;

            try
            {
                dReturn = (double)_calculate.RunMethod(input);
            }
            catch { SimulationMessaging.AddMessage(new SimulationMessage("Error: solving calculated fields for Compound Treatment.")); }
            return(dReturn);
        }
Esempio n. 10
0
        public bool IsCriteriaMet(Hashtable hashAttributeValue)
        {
            if (string.IsNullOrWhiteSpace(m_strCriteria))
            {
                return(true);
            }

            object[] input = new object[this.m_listAttributesCriteria.Count];

            int i = 0;

            foreach (String str in this.m_listAttributesCriteria)
            {
                input[i] = hashAttributeValue[str];
                i++;
            }
            try
            {
                if (evaluate.m_methodInfo == null)
                {
                    if (evaluate.m_cr == null)
                    {
                        evaluate.BuildClass(evaluate.Expression, false, cgOMS.Prefix + _tableName + "_" + _columnName + "_" + _ID);
                        evaluate.CompileAssembly();
                        if (_tableName != null)
                        {
                            SimulationMessaging.SaveSerializedCalculateEvaluate(cgOMS.Prefix + _tableName, _columnName, _ID, evaluate);
                        }
                    }
                }

                Object result = this.Evaluate.RunMethod(input);
                return(bool.Parse(result.ToString()));
            }
            catch (Exception exc)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error in RunMethod.   " + Evaluate.OriginalInput + " " + exc.Message));
                return(false);
            }
        }
Esempio n. 11
0
        public bool LoadScheduled(List <Treatments> availableTreatments, object APICall, IMongoCollection <SimulationModel> Simulations, string m_strSimulationID)
        {
            var select = "SELECT SCHEDULEDID, SCHEDULEDTREATMENTID, SCHEDULEDYEAR FROM SCHEDULED WHERE TREATMENTID='" + this.TreatmentID + "'";

            DataSet ds;

            try
            {
                ds = DBMgr.ExecuteQuery(select);


                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var scheduledId          = int.Parse(row["SCHEDULEDID"].ToString());
                    var scheduledTreatmentId = row["SCHEDULEDTREATMENTID"].ToString();
                    var scheduledYear        = int.Parse(row["SCHEDULEDYEAR"].ToString());
                    var scheduledTreatment   = availableTreatments.Find(t => t.TreatmentID == scheduledTreatmentId);

                    if (scheduledTreatment != null)
                    {
                        _scheduleds.Add(new Scheduled(scheduledId, scheduledTreatment, scheduledYear));
                    }
                }
            }
            catch (Exception exception)
            {
                SimulationMessaging.AddMessage(
                    new SimulationMessage("Fatal Error: Opening SCHEDULED table. SQL Message - " + exception.Message));
                if (APICall.Equals(true))
                {
                    var updateStatus = Builders <SimulationModel> .Update
                                       .Set(s => s.status, "Fatal Error: Opening SCHEDULED table. SQL Message - " + exception.Message);

                    Simulations.UpdateOne(s => s.simulationId == Convert.ToInt32(m_strSimulationID), updateStatus);
                }
                return(false);
            }
            return(true);
        }
Esempio n. 12
0
        public RemainingLife(int remainingLifeId, string attribute, double remainingLifeLimit, string criteria)
        {
            RemainingLifeId    = remainingLifeId;
            Attribute          = attribute;
            RemainingLifeLimit = remainingLifeLimit;

            Criteria = new Criterias("REMAINING_LIFE", "BINARY_CRITERIA", RemainingLifeId.ToString());
            byte[] assemblyCriteria = null;
            string currentCriteria  = "";

            if (!string.IsNullOrWhiteSpace(criteria))
            {
                currentCriteria = Simulation.ConvertOMSAttribute(criteria);
            }
            assemblyCriteria = SimulationMessaging.GetSerializedCalculateEvaluate("REMAINING_LIFE", "BINARY_CRITERIA", RemainingLifeId.ToString(), assemblyCriteria);
            if (assemblyCriteria != null && assemblyCriteria.Length > 0)
            {
                Criteria.Evaluate = (CalculateEvaluate.CalculateEvaluate)AssemblySerialize.DeSerializeObjectFromByteArray(assemblyCriteria);
                if (Criteria.Evaluate.OriginalInput != currentCriteria)
                {
                    Criteria.Evaluate = null;
                }
            }

            if (Criteria.Evaluate != null && Criteria.Evaluate.m_cr != null)
            {
                if (!File.Exists(Criteria.Evaluate.m_cr.PathToAssembly))
                {
                    Criteria.Evaluate = null;
                }
            }

            Criteria.Criteria = criteria;
            foreach (String str in Criteria.Errors)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Supersede criteria for " + criteria + " :" + str));
            }
        }
Esempio n. 13
0
        public BudgetCriteria(int budgetCriteriaId, string budgetName, string criteria)
        {
            BudgetCriteriaId = budgetCriteriaId;
            BudgetName       = budgetName;

            Criteria = new Criterias("BUDGET", "BINARY_CRITERIA", BudgetCriteriaId.ToString());
            byte[] assemblyCriteria = null;
            string currentCriteria  = "";

            if (!string.IsNullOrWhiteSpace(criteria))
            {
                currentCriteria = Simulation.ConvertOMSAttribute(criteria);
            }
            assemblyCriteria = SimulationMessaging.GetSerializedCalculateEvaluate("BUDGET", "BINARY_CRITERIA", BudgetCriteriaId.ToString(), assemblyCriteria);
            if (assemblyCriteria != null && assemblyCriteria.Length > 0)
            {
                Criteria.Evaluate = (CalculateEvaluate.CalculateEvaluate)AssemblySerialize.DeSerializeObjectFromByteArray(assemblyCriteria);
                if (Criteria.Evaluate.OriginalInput != currentCriteria)
                {
                    Criteria.Evaluate = null;
                }
            }

            if (Criteria.Evaluate != null && Criteria.Evaluate.m_cr != null)
            {
                if (!File.Exists(Criteria.Evaluate.m_cr.PathToAssembly))
                {
                    Criteria.Evaluate = null;
                }
            }

            Criteria.Criteria = criteria;
            foreach (String str in Criteria.Errors)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Supersede criteria for " + criteria + " :" + str));
            }
        }
Esempio n. 14
0
        public SplitTreatment(string splitTreamentId, string description, string criteria, List <ISplitTreatmentLimit> limits)
        {
            Id          = splitTreamentId;
            Description = description;
            Limits      = limits;
            Criteria    = new Criterias("SPLIT_TREATMENT", "BINARY_CRITERIA", splitTreamentId);
            byte[] assemblyCriteria = null;
            string currentCriteria  = "";

            if (!string.IsNullOrWhiteSpace(criteria))
            {
                currentCriteria = Simulation.ConvertOMSAttribute(criteria);
            }
            assemblyCriteria = SimulationMessaging.GetSerializedCalculateEvaluate("SPLIT_TREATMENT", "BINARY_CRITERIA", splitTreamentId, assemblyCriteria);
            if (assemblyCriteria != null && assemblyCriteria.Length > 0)
            {
                Criteria.Evaluate = (CalculateEvaluate.CalculateEvaluate)RoadCareGlobalOperations.AssemblySerialize.DeSerializeObjectFromByteArray(assemblyCriteria);
                if (Criteria.Evaluate.OriginalInput != currentCriteria)
                {
                    Criteria.Evaluate = null;
                }
            }

            if (Criteria.Evaluate != null && Criteria.Evaluate.m_cr != null)
            {
                if (!File.Exists(Criteria.Evaluate.m_cr.PathToAssembly))
                {
                    Criteria.Evaluate = null;
                }
            }

            Criteria.Criteria = criteria;
            foreach (String str in Criteria.Errors)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Split treatment criteria for " + criteria + " :" + str));
            }
        }
Esempio n. 15
0
        public void Solve(Hashtable hashAttributeValue)
        {
            double dValue;
            double dMinimum;
            double dMaximum;

            _answer = new double[100];
            if (IsModule)
            {
                if (IsCRS)
                {
                    String strType     = hashAttributeValue[_attributesEquation[0].ToString()].ToString();
                    double dCRS        = Convert.ToDouble(hashAttributeValue[_attributesEquation[1].ToString()]);
                    double dThick      = Convert.ToDouble(hashAttributeValue[_attributesEquation[2].ToString()]);
                    double dESAL       = Convert.ToDouble(hashAttributeValue[_attributesEquation[3].ToString()]);
                    double dESALGrowth = Convert.ToDouble(hashAttributeValue[_attributesEquation[4].ToString()]);

                    double dRSL;
                    double dBenefit;
                    _answer[0] = dCRS;
                    for (int n = 1; n < 100; n++)
                    {
                        double dAge = (double)n;
                        dValue = SimulationMessaging.crs.CalculateCRSBenefit(false, strType, dCRS, dThick, dESAL, dESALGrowth, 1, dAge, SimulationMessaging.Method.BenefitLimit, out dBenefit, out dRSL);
                        try
                        {
                            if (SimulationMessaging.GetAttributeMaximum(this.Attribute, out dMaximum))
                            {
                                if (dValue > dMaximum)
                                {
                                    dValue = dMaximum;
                                }
                            }

                            if (SimulationMessaging.GetAttributeMinimum(this.Attribute, out dMinimum))
                            {
                                if (dValue < dMinimum)
                                {
                                    dValue = dMinimum;
                                }
                            }
                        }
                        catch
                        {
                            String strValue = SimulationMessaging.GetAttributeDefault(this.Attribute);
                            dValue = double.Parse(strValue);
                        }
                        _answer[n] = dValue;
                    }
                    return;
                }
                else if (IsOCI)
                {
                }
            }

            object[] input = new object[_attributesEquation.Count];

            int i    = 0;
            int nAge = -1;

            foreach (String str in _attributesEquation)
            {
                if (str == "AGE")
                {
                    nAge = i;
                }
                input[i] = hashAttributeValue[str];;
                i++;
            }

            for (int n = 0; n < 100; n++)
            {
                double dAge = (double)n;
                if (nAge >= 0)
                {
                    input[nAge] = dAge;
                }
                try
                {
                    object result = _calculate.RunMethod(input);
                    try
                    {
                        dValue = (double)result;
                        if (SimulationMessaging.GetAttributeMaximum(this.Attribute, out dMaximum))
                        {
                            if (dValue > dMaximum)
                            {
                                dValue = dMaximum;
                            }
                        }

                        if (SimulationMessaging.GetAttributeMinimum(this.Attribute, out dMinimum))
                        {
                            if (dValue < dMinimum)
                            {
                                dValue = dMinimum;
                            }
                        }
                    }
                    catch
                    {
                        String strValue = SimulationMessaging.GetAttributeDefault(this.Attribute);
                        dValue = double.Parse(strValue);
                    }
                    _answer[n] = dValue;
                }
                catch (Exception exc)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error in RunMethod.   " + _calculate.OriginalInput + " " + exc.Message));
                }
            }
            return;
        }
Esempio n. 16
0
        /// <summary>
        /// Check if budget can support treatment.  Checks for each priority.
        /// </summary>
        /// <param name="fAmount"></param>
        /// <param name="strBudget"></param>
        /// <param name="strYear"></param>
        /// <param name="hashAttributeValue"></param>
        /// <param name="priority"></param>
        /// <returns></returns>
        public string IsBudgetAvailable(float fAmount, String strBudget, String strYear, Hashtable hashAttributeValue, Priorities priority)
        {
            string[] budgets;
            try
            {
                budgets = strBudget.Split('|');
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Budget is null." + e.Message));
                throw e;
            }

            foreach (string budget in budgets)
            {
                string    budgetCheck = budget.Trim();
                Hashtable hashYearAmount;
                Hashtable hashYearAmountOriginal;
                float     fAvailable;
                float     fOriginal;
                float     fAfterSpending;
                float     fPercent;

                //Budget not defined
                try
                {
                    if (!BudgetYear.Contains(budgetCheck))
                    {
                        continue;
                    }
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking budget year. " + e.Message));
                    throw e;
                }


                try
                {
                    hashYearAmount = (Hashtable)BudgetYear[budgetCheck];
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving budget year. " + e.Message));
                    throw e;
                }
                try
                {
                    if (!hashYearAmount.Contains(strYear))
                    {
                        continue;
                    }
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking year amount. " + e.Message));
                    throw e;
                }

                try
                {
                    fAvailable = (float)hashYearAmount[strYear];
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving year amount. " + e.Message));
                    throw e;
                }

                try
                {
                    if (!BudgetYearOriginal.Contains(budgetCheck))
                    {
                        continue;
                    }
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking budget year original. " + e.Message));
                    throw e;
                }

                try
                {
                    hashYearAmountOriginal = (Hashtable)BudgetYearOriginal[budgetCheck];
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving budget year original. " + e.Message));
                    throw e;
                }


                try
                {
                    if (!hashYearAmountOriginal.Contains(strYear))
                    {
                        continue;
                    }
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking year amount original. " + e.Message));
                    throw e;
                }

                try
                {
                    fOriginal = (float)hashYearAmountOriginal[strYear];
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving year amount original. " + e.Message));
                    throw e;
                }

                fAfterSpending = fAvailable - fAmount;
                if (fOriginal <= 0)
                {
                    continue;
                }
                fPercent = (1 - fAfterSpending / fOriginal) * 100;

                try
                {
                    if (priority.IsAllSections)
                    {
                        float fPercentLimit = (float)priority.BudgetPercent[budgetCheck];
                        if (fPercent < fPercentLimit)
                        {
                            return(budgetCheck);
                        }
                    }
                    else
                    {
                        if (priority.Criteria.IsCriteriaMet(hashAttributeValue))
                        {
                            float fPercentLimit = (float)priority.BudgetPercent[budgetCheck];
                            if (fPercent < fPercentLimit)
                            {
                                return(budgetCheck);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving budget year original. " + e.Message));
                    throw e;
                }
            }

            return(null);
        }
Esempio n. 17
0
        /// <summary>
        /// Loads all feasibility criteria for this treatment in for this treatment ID.
        /// </summary>
        public bool LoadFeasibility(object APICall, IMongoCollection <SimulationModel> Simulations, string m_strSimulationID)
        {
            String strSelect = "SELECT CRITERIA,BINARY_CRITERIA,FEASIBILITYID FROM " + cgOMS.Prefix + "FEASIBILITY WHERE TREATMENTID='" + this.TreatmentID + "'";

            _table  = cgOMS.Prefix + "FEASIBILITY";
            _column = "BINARY_CRITERIA";

            DataSet ds;

            try
            {
                ds = DBMgr.ExecuteQuery(strSelect);
            }
            catch (Exception exception)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Fatal Error: Opening Treatment FEASIBILITY table.  SQL Message - " + exception.Message));
                if (APICall.Equals(true))
                {
                    var updateStatus = Builders <SimulationModel> .Update
                                       .Set(s => s.status, "Fatal Error: Opening Treatment FEASIBILITY table.");

                    Simulations.UpdateOne(s => s.simulationId == Convert.ToInt32(m_strSimulationID), updateStatus);
                }
                return(false);
            }


            foreach (DataRow row in ds.Tables[0].Rows)
            {
                _id = row["FEASIBILITYID"].ToString();
                Criterias criteria         = new Criterias(_table, _column, _id);
                byte[]    assemblyCriteria = null;
                string    currentCriteria  = "";
                if (row["CRITERIA"] != DBNull.Value)
                {
                    currentCriteria = Simulation.ConvertOMSAttribute(row["CRITERIA"].ToString());
                }
                assemblyCriteria = SimulationMessaging.GetSerializedCalculateEvaluate(_table, _column, _id, assemblyCriteria);
                if (assemblyCriteria != null && assemblyCriteria.Length > 0)
                {
                    criteria.Evaluate = (CalculateEvaluate.CalculateEvaluate)AssemblySerialize.DeSerializeObjectFromByteArray(assemblyCriteria);
                    if (criteria.Evaluate.OriginalInput != currentCriteria)
                    {
                        criteria.Evaluate = null;
                    }
                }

                if (criteria.Evaluate != null && criteria.Evaluate.m_cr != null)
                {
                    if (!File.Exists(criteria.Evaluate.m_cr.PathToAssembly))
                    {
                        criteria.Evaluate = null;
                    }
                }

                criteria.Criteria = Simulation.ConvertOMSAttribute(row["CRITERIA"].ToString());

                foreach (String str in criteria.Errors)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Treatment feasibility criteria for Treatment " + _treatment + ":" + str));
                    if (APICall.Equals(true))
                    {
                        var updateStatus = Builders <SimulationModel> .Update
                                           .Set(s => s.status, "Error: Treatment feasibility criteria for Treatment " + _treatment + ":" + str);

                        Simulations.UpdateOne(s => s.simulationId == Convert.ToInt32(m_strSimulationID), updateStatus);
                    }
                }

                this.CriteriaList.Add(criteria);
                foreach (String str in criteria.CriteriaAttributes)
                {
                    if (!SimulationMessaging.IsAttribute(str))
                    {
                        SimulationMessaging.AddMessage(new SimulationMessage("Error: " + str + " which is used by the Feasibility criteria is not present in the database."));
                        if (APICall.Equals(true))
                        {
                            var updateStatus = Builders <SimulationModel> .Update
                                               .Set(s => s.status, "Error: " + str + " which is used by the Feasibility criteria is not present in the database");

                            Simulations.UpdateOne(s => s.simulationId == Convert.ToInt32(m_strSimulationID), updateStatus);
                        }
                    }
                    if (!_attributes.Contains(str))
                    {
                        _attributes.Add(str);
                    }
                }
            }
            return(true);
        }
Esempio n. 18
0
        public void MoveBudgetAcross(string budget, string year, Priorities priority)
        {
            //Get next budget.
            var nextBudget = GetNextBudget(budget);

            //Add what is left from current budget (and priority) to the the next budget.

            string    budgetCheck = budget.Trim();
            Hashtable hashYearAmount;
            Hashtable hashYearAmountOriginal;
            float     available = 0;
            float     original  = 0;

            //Budget not defined
            try
            {
                if (!BudgetYear.Contains(budgetCheck))
                {
                    return;
                }
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking budget year. " + e.Message));
                throw e;
            }


            try
            {
                hashYearAmount = (Hashtable)BudgetYear[budgetCheck];
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving budget year. " + e.Message));
                throw e;
            }
            try
            {
                if (!hashYearAmount.Contains(year))
                {
                    return;
                }
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking year amount. " + e.Message));
                throw e;
            }

            try
            {
                available = (float)hashYearAmount[year];
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving year amount. " + e.Message));
                throw e;
            }

            try
            {
                if (!BudgetYearOriginal.Contains(budgetCheck))
                {
                    return;
                }
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking budget year original. " + e.Message));
                throw e;
            }

            try
            {
                hashYearAmountOriginal = (Hashtable)BudgetYearOriginal[budgetCheck];
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving budget year original. " + e.Message));
                throw e;
            }


            try
            {
                if (!hashYearAmountOriginal.Contains(year))
                {
                    return;
                }
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking year amount original. " + e.Message));
                throw e;
            }

            try
            {
                original = (float)hashYearAmountOriginal[year];
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving year amount original. " + e.Message));
                throw e;
            }


            if (original <= 0)
            {
                return;
            }
            var percent = (1 - available / original) * 100;

            try
            {
                var percentLimit = (float)priority.BudgetPercent[budgetCheck];
                if (percent < percentLimit)
                {
                    var difference   = percentLimit - percent;
                    var budgetToMove = original * difference / 100;
                    hashYearAmount[year] = (float)hashYearAmount[year] - budgetToMove;

                    hashYearAmount       = (Hashtable)BudgetYear[nextBudget];
                    hashYearAmount[year] = (float)hashYearAmount[year] + budgetToMove;
                }
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving budget year original. " + e.Message));
                throw e;
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Check if budget can support treatment.  Checks for each priority.
        /// </summary>
        /// <param name="fAmount"></param>
        /// <param name="strBudget"></param>
        /// <param name="strYear"></param>
        /// <param name="hashAttributeValue"></param>
        /// <param name="priority"></param>
        /// <param name="limits">Limits where treatments are split over multiple years</param>
        /// <returns></returns>
        public string IsBudgetAvailable(float fAmount, string strBudget, String strYear, Hashtable hashAttributeValue, Priorities priority, List <ISplitTreatmentLimit> limits, string budgetLimitType, out string budgetHash, out ISplitTreatmentLimit splitTreatmentLimit, out string reasonNoBudget)
        {
            reasonNoBudget = "";
            string noBudgetAvailable = "";

            splitTreatmentLimit = limits[0];

            //Check priority.  If not possible just return null.
            if (!(priority.IsAllSections || priority.Criteria.IsCriteriaMet(hashAttributeValue)))
            {
                budgetHash     = "";
                reasonNoBudget = "Priority (" + priority.PriorityLevel + ") criteria not met for year " + strYear;
                return(noBudgetAvailable);
            }

            string[] possibleBudgets;


            foreach (var limit in limits)
            {
                if (limit.Amount > fAmount)
                {
                    splitTreatmentLimit = limit;
                    break;
                }
            }



            budgetHash = "";
            try
            {
                possibleBudgets = strBudget.Split('|');

                for (int i = 0; i < possibleBudgets.Length; i++)
                {
                    possibleBudgets[i] = possibleBudgets[i].Trim();
                }
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Budget is null." + e.Message));
                throw e;
            }

            //If there are no budget criteria, then ignore.  The list is enforced.

            var budgets = new List <string>();

            if (SimulationMessaging.BudgetCriterias.Count > 0)
            {
                var listAvailableBudget = new List <BudgetCriteria>();
                foreach (var budgetCriteria in SimulationMessaging.BudgetCriterias)
                {
                    if (budgetCriteria.Criteria.IsCriteriaMet(hashAttributeValue))
                    {
                        listAvailableBudget.Add(budgetCriteria);
                    }
                }


                foreach (var budget in possibleBudgets)
                {
                    var available = listAvailableBudget.Find(b => b.BudgetName == budget);
                    if (available != null && !budgets.Contains(available.BudgetName))
                    {
                        budgets.Add(available.BudgetName);
                    }
                }
            }
            else
            {
                foreach (var budget in possibleBudgets)
                {
                    budgets.Add(budget);
                }
            }

            if (budgets.Count == 0)
            {
                reasonNoBudget = "Budget (" + strBudget + ") did not meet budget criteria.";
            }

            foreach (string budget in budgets)
            {
                string    budgetCheck = budget.Trim();
                Hashtable hashYearAmount;
                Hashtable hashYearAmountOriginal;
                float     fAvailable;
                float     fOriginal;
                float     fAfterSpending;
                float     fPercent;

                //Budget not defined
                try
                {
                    if (!BudgetYear.Contains(budgetCheck))
                    {
                        continue;
                    }
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking budget year. " + e.Message));
                    throw e;
                }


                try
                {
                    hashYearAmount = (Hashtable)BudgetYear[budgetCheck];
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving budget year. " + e.Message));
                    throw e;
                }

                try
                {
                    if (!BudgetYearOriginal.Contains(budgetCheck))
                    {
                        continue;
                    }
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking budget year original. " + e.Message));
                    throw e;
                }

                bool currentBudgetAvailable = true;

                if (budgetLimitType.ToLower() == "unlimited")//If the budget is available (possible budget) and is unlimited... we are good.
                {
                    return(budgetCheck);
                }


                //Starting here need to loop through year amounts.
                var year = Convert.ToInt32(strYear);
                for (int i = 0; i < splitTreatmentLimit.Percentages.Count; i++)
                {
                    var currentYearAmount = fAmount * splitTreatmentLimit.Percentages[i] / 100;
                    var currentYear       = year + i;

                    //Priority must be all years, match the current year or the current year must be greater than maximum year and the Maximum year must be a priority.
                    if (!(priority.IsAllYears || priority.Years == currentYear || (currentYear > MaximumYear && priority.Years == MaximumYear)))
                    {
                        reasonNoBudget = "Priority is not set for year " + currentYear;
                        return(null);
                    }

                    try
                    {
                        //This occurs when a split treament goes past then end.
                        if (!hashYearAmount.Contains(currentYear.ToString()))
                        {
                            continue;
                        }
                        //Not past end of analysis.
                        fAvailable = (float)hashYearAmount[currentYear.ToString()];
                    }
                    catch (Exception e)
                    {
                        SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving year amount. " + e.Message));
                        throw e;
                    }


                    //This gets a hash of all years and the amount of budgets originally available.
                    try
                    {
                        hashYearAmountOriginal = (Hashtable)BudgetYearOriginal[budgetCheck];
                        //This occurs when a split treament goes pas then end.
                        if (!hashYearAmountOriginal.ContainsKey(currentYear.ToString()))
                        {
                            continue;
                        }
                    }
                    catch (Exception e)
                    {
                        SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving budget year original. " + e.Message));
                        throw e;
                    }


                    try
                    {
                        if (!hashYearAmountOriginal.Contains(currentYear.ToString()))
                        {
                            continue;
                        }
                        fOriginal = (float)hashYearAmountOriginal[currentYear.ToString()];
                    }
                    catch (Exception e)
                    {
                        SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving year amount original. " + e.Message));
                        throw e;
                    }

                    fAfterSpending = fAvailable - currentYearAmount;
                    if (fOriginal <= 0)
                    {
                        continue;
                    }
                    fPercent = (1 - fAfterSpending / fOriginal) * 100;


                    try
                    {
                        float fPercentLimit = (float)priority.BudgetPercent[budgetCheck];
                        var   original      = (float)priority.BudgetPercent[budgetCheck] * fOriginal / 100;
                        budgetHash = currentYearAmount.ToString("#,##0.##") + "/" + fAmount.ToString("#,##0.##") + "/" + fAvailable.ToString("#,##0.##") + "/" + original.ToString("#,##0.##");
                        //if (fPercent < fPercentLimit) return budgetCheck;
                        if (fPercent > fPercentLimit)
                        {
                            currentBudgetAvailable = false;
                            reasonNoBudget         = "Percent after spending greater than priority limit " + fPercent.ToString("f2") + "/" + fPercentLimit.ToString("f2") + " for year(" + currentYear + ")";
                            return(noBudgetAvailable);
                        }
                    }
                    catch (Exception e)
                    {
                        SimulationMessaging.AddMessage(new SimulationMessage("Error: Evaluating priority. " + e.Message));
                        throw e;
                    }
                }
                //To be true here, there must be money available for each year.
                if (currentBudgetAvailable)
                {
                    return(budgetCheck);
                }
            }
            return(noBudgetAvailable);
        }
Esempio n. 20
0
        public void LoadBudgets()
        {
            string[] budgets = BudgetOrderString.Split(',');
            String   strBudget;

            for (int i = 0; i < budgets.Length; i++)
            {
                strBudget = budgets[i];
                m_listBudgetOrder.Add(strBudget);
            }

            String  strSelect = "SELECT YEAR_,BUDGETNAME,AMOUNT FROM " + cgOMS.Prefix + "YEARLYINVESTMENT WHERE SIMULATIONID='" + this.InvestmentID + "' ORDER BY YEAR_";
            DataSet ds        = null;

            try
            {
                ds = DBMgr.ExecuteQuery(strSelect);
            }
            catch (Exception ex)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Loading YEARLYINVESTMENT table." + ex.Message));
                return;
            }

            String strYear;

            String strAmount;

            MaximumYear = Int32.MinValue;

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                strYear = row[0].ToString();
                var year = Convert.ToInt32(strYear);
                if (year > MaximumYear)
                {
                    MaximumYear = year;
                }
                strBudget = row[1].ToString();
                strAmount = row[2].ToString();

                if (BudgetYear.Contains(strBudget))
                {
                    Hashtable hashYearAmount         = (Hashtable)BudgetYear[strBudget];
                    Hashtable hashYearAmountOriginal = (Hashtable)BudgetYearOriginal[strBudget];

                    m_hashBudgetYear.Remove(strBudget);
                    m_hashBudgetYearOriginal.Remove(strBudget);

                    if (strAmount == "")
                    {
                        hashYearAmount.Add(strYear, 0.0);
                        hashYearAmountOriginal.Add(strYear, 0.0);
                    }
                    else
                    {
                        hashYearAmount.Add(strYear, float.Parse(strAmount));
                        hashYearAmountOriginal.Add(strYear, float.Parse(strAmount));
                    }

                    BudgetYear.Add(strBudget, hashYearAmount);
                    BudgetYearOriginal.Add(strBudget, hashYearAmountOriginal);
                }
                else
                {
                    Hashtable hashYearAmount         = new Hashtable();
                    Hashtable hashYearAmountOriginal = new Hashtable();

                    if (strAmount == "")
                    {
                        hashYearAmount.Add(strYear, 0.0);
                        hashYearAmountOriginal.Add(strYear, 0.0);
                    }
                    else
                    {
                        hashYearAmount.Add(strYear, float.Parse(strAmount));
                        hashYearAmountOriginal.Add(strYear, float.Parse(strAmount));
                    }



                    BudgetYear.Add(strBudget, hashYearAmount);
                    BudgetYearOriginal.Add(strBudget, hashYearAmountOriginal);
                }
            }

            foreach (var budget in BudgetYear.Keys)
            {
                var hashYearAmount         = (Hashtable)BudgetYear[budget];
                var hashYearAmountOriginal = (Hashtable)BudgetYearOriginal[budget];

                for (int year = MaximumYear + 1; year < MaximumYear + 101; year++)
                {
                    hashYearAmount.Add(year.ToString(), hashYearAmount[MaximumYear.ToString()]);
                    hashYearAmountOriginal.Add(year.ToString(), hashYearAmountOriginal[MaximumYear.ToString()]);
                }
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Load all cost information associated with this treatment.
        /// </summary>
        public bool LoadCost(object APICall, IMongoCollection <SimulationModel> Simulations, string m_strSimulationID)
        {
            Costs  cost;
            String select = "SELECT COST_,UNIT,CRITERIA,BINARY_CRITERIA,ISFUNCTION, COSTID FROM " + cgOMS.Prefix + "COSTS WHERE TREATMENTID='" + this.TreatmentID + "'";

            if (SimulationMessaging.IsOMS)
            {
                select = "SELECT COST_,UNIT,CRITERIA,BINARY_CRITERIA,NULL AS ISFUNCTION, COSTID FROM " + cgOMS.Prefix + "COSTS WHERE TREATMENTID='" + this.TreatmentID + "'";
            }
            DataSet ds;

            try
            {
                //SimulationMessaging.AddMessage("DEBUGGING: Attempting cost select...");
                ds = DBMgr.ExecuteQuery(select);
                //SimulationMessaging.AddMessage("DEBUGGING: Cost select successful.");
            }
            catch (Exception exception)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Fatal Error: Opening COSTS table.  SQL message - " + exception.Message));
                if (APICall.Equals(true))
                {
                    var updateStatus = Builders <SimulationModel> .Update
                                       .Set(s => s.status, "Fatal Error: Opening COSTS table.  SQL message - " + exception.Message);

                    Simulations.UpdateOne(s => s.simulationId == Convert.ToInt32(m_strSimulationID), updateStatus);
                }
                return(false);
            }


            foreach (DataRow row in ds.Tables[0].Rows)
            {
                string id = row["COSTID"].ToString();
                cost = new Costs(id);

                if (row["CRITERIA"].ToString().Trim().Length == 0)
                {
                    cost.Default = true;
                }
                else
                {
                    cost.Default = false;
                    string criteria         = row["CRITERIA"].ToString();
                    byte[] assemblyCriteria = null;
                    assemblyCriteria = SimulationMessaging.GetSerializedCalculateEvaluate(cgOMS.Prefix + "COSTS", "BINARY_CRITERIA", cost.CostID, assemblyCriteria);
                    if (assemblyCriteria != null && assemblyCriteria.Length > 0)
                    {
                        cost.Criteria.Evaluate = (CalculateEvaluate.CalculateEvaluate)AssemblySerialize.DeSerializeObjectFromByteArray(assemblyCriteria);
                        if (cost.Criteria.Evaluate.OriginalInput != criteria)
                        {
                            cost.Criteria.Evaluate = null;
                        }
                    }

                    cost.Criteria.Criteria = criteria;
                    foreach (String str in cost.Criteria.CriteriaAttributes)
                    {
                        if (!SimulationMessaging.IsAttribute(str))
                        {
                            SimulationMessaging.AddMessage(new SimulationMessage("Error: " + str + " which is used by the Cost criteria is not present in the database."));
                            if (APICall.Equals(true))
                            {
                                var updateStatus = Builders <SimulationModel> .Update
                                                   .Set(s => s.status, "Error: " + str + " which is used by the Cost criteria is not present in the database");

                                Simulations.UpdateOne(s => s.simulationId == Convert.ToInt32(m_strSimulationID), updateStatus);
                            }
                        }
                        if (!_attributes.Contains(str))
                        {
                            _attributes.Add(str);
                        }
                    }
                }


                byte[] assemblyCost = null;
                //objectValue = row["BINARY_COST"];
                //if (objectValue != System.DBNull.Value)
                //{
                //    assemblyCost = (byte[])row["BINARY_COST"];
                //}
                String strCost = row["COST_"].ToString();
                assemblyCost = SimulationMessaging.GetSerializedCalculateEvaluate(cgOMS.Prefix + "COSTS", "BINARY_EQUATION", cost.CostID, assemblyCost);
                if (assemblyCost != null && assemblyCost.Length > 0)
                {
                    cost.Calculate = (CalculateEvaluate.CalculateEvaluate)AssemblySerialize.DeSerializeObjectFromByteArray(assemblyCost);
                    if (cost.Calculate.OriginalInput != strCost)
                    {
                        cost.Calculate = null;
                    }
                }

                if (strCost.Trim() == "")
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Fatal Error: Cost equation is blank for treatment - " + _treatment));
                    if (APICall.Equals(true))
                    {
                        var updateStatus = Builders <SimulationModel> .Update
                                           .Set(s => s.status, "Fatal Error: Cost equation is blank for treatment - " + _treatment);

                        Simulations.UpdateOne(s => s.simulationId == Convert.ToInt32(m_strSimulationID), updateStatus);
                    }
                    return(false);
                }

                bool   isFunction = false;
                object function   = row["ISFUNCTION"];
                if (row["ISFUNCTION"] != DBNull.Value)
                {
                    isFunction = Convert.ToBoolean(row["ISFUNCTION"]);
                }
                if (isFunction)
                {
                    cost.SetFunction(row["COST_"].ToString());
                }
                else
                {
                    cost.Equation = row["COST_"].ToString();
                }

                foreach (String str in cost._attributesEquation)
                {
                    if (str != "AREA" && str != "LENGTH")
                    {
                        if (!SimulationMessaging.IsAttribute(str))
                        {
                            SimulationMessaging.AddMessage(new SimulationMessage("Error: " + str + " which is used by the Cost equation is not present in the database."));
                            if (APICall.Equals(true))
                            {
                                var updateStatus = Builders <SimulationModel> .Update
                                                   .Set(s => s.status, "Error: " + str + " which is used by the Cost equation is not present in the database");

                                Simulations.UpdateOne(s => s.simulationId == Convert.ToInt32(m_strSimulationID), updateStatus);
                            }
                        }
                        if (!_attributes.Contains(str))
                        {
                            _attributes.Add(str);
                        }
                    }
                }
                if (!cost.IsCompoundTreatment)
                {
                    if (cost._calculate.m_listError.Count > 0)
                    {
                        foreach (String str in cost.Calculate.m_listError)
                        {
                            SimulationMessaging.AddMessage(new SimulationMessage("Fatal Error: Cost equation:" + str));
                            if (APICall.Equals(true))
                            {
                                var updateStatus = Builders <SimulationModel> .Update
                                                   .Set(s => s.status, "Fatal Error: Cost equation:" + str);

                                Simulations.UpdateOne(s => s.simulationId == Convert.ToInt32(m_strSimulationID), updateStatus);
                            }
                            return(false);
                        }
                    }
                }
                _costs.Add(cost);
            }
            return(true);
        }
Esempio n. 22
0
        /// <summary>
        /// Load all consequence information associated with treat.
        /// </summary>
        public bool LoadConsequences(object APICall, IMongoCollection <SimulationModel> Simulations, string m_strSimulationID)
        {
            Consequences consequence;
            String       select = "SELECT ATTRIBUTE_,CHANGE_,CRITERIA,EQUATION,ISFUNCTION, CONSEQUENCEID FROM " + cgOMS.Prefix + "CONSEQUENCES WHERE TREATMENTID='" + _treatmentID + "'";

            if (SimulationMessaging.IsOMS)
            {
                select = "SELECT ATTRIBUTE_,CHANGE_,CRITERIA,EQUATION,NULL AS ISFUNCTION, CONSEQUENCEID FROM " + cgOMS.Prefix + "CONSEQUENCES WHERE TREATMENTID='" + _treatmentID + "'";
            }

            DataSet ds;

            try
            {
                ds = DBMgr.ExecuteQuery(select);
            }
            catch (Exception exception)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Fatal Error: Opening CONSEQUENCES table. SQL Message - " + exception.Message));
                if (APICall.Equals(true))
                {
                    var updateStatus = Builders <SimulationModel> .Update
                                       .Set(s => s.status, "Fatal Error: Opening CONSEQUENCES table. SQL Message - " + exception.Message);

                    Simulations.UpdateOne(s => s.simulationId == Convert.ToInt32(m_strSimulationID), updateStatus);
                }
                return(false);
            }

            var consequenceCount = 0;

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                string id = row["CONSEQUENCEID"].ToString();
                consequence = new Consequences(id);
                String strAttribute = row["ATTRIBUTE_"].ToString();
                String strChange    = row["CHANGE_"].ToString();
                String strCriteria  = row["CRITERIA"].ToString();
                String strEquation  = row["EQUATION"].ToString();
                consequence.TreatmentID = this.TreatmentID;
                consequence.Treatment   = this.Treatment;

                SimulationMessaging.AddMessage(new SimulationMessage("Compiling treatment consequence " + consequenceCount));
                if (APICall.Equals(true))
                {
                    var updateStatus = Builders <SimulationModel> .Update
                                       .Set(s => s.status, "Compiling treatment consequence " + consequenceCount);

                    Simulations.UpdateOne(s => s.simulationId == Convert.ToInt32(m_strSimulationID), updateStatus);
                }
                consequenceCount++;


                if (strCriteria.Trim().Length == 0)
                {
                    consequence.Default = true;
                }
                else
                {
                    consequence.Default = false;

                    byte[] assemblyCriteria = null;
                    assemblyCriteria = SimulationMessaging.GetSerializedCalculateEvaluate(cgOMS.Prefix + "CONSEQUENCES", "BINARY_CRITERIA", id, assemblyCriteria);
                    if (assemblyCriteria != null && assemblyCriteria.Length > 0)
                    {
                        consequence.Criteria.Evaluate = (CalculateEvaluate.CalculateEvaluate)AssemblySerialize.DeSerializeObjectFromByteArray(assemblyCriteria);
                        if (consequence.Criteria.Evaluate.OriginalInput != strCriteria)
                        {
                            consequence.Criteria.Evaluate = null;
                        }
                    }

                    consequence.Criteria.Criteria = strCriteria;
                    //Get attributes from consequence criteria
                    foreach (String str in consequence.Criteria.CriteriaAttributes)
                    {
                        if (!SimulationMessaging.IsAttribute(str))
                        {
                            SimulationMessaging.AddMessage(new SimulationMessage("Error: " + str + " which is used by the Consequence criteria is not present in the database."));
                            if (APICall.Equals(true))
                            {
                                var updateStatus = Builders <SimulationModel> .Update
                                                   .Set(s => s.status, "Error: " + str + " which is used by the Consequence criteria is not present in the database");

                                Simulations.UpdateOne(s => s.simulationId == Convert.ToInt32(m_strSimulationID), updateStatus);
                            }
                        }
                        if (!_attributes.Contains(str))
                        {
                            _attributes.Add(str);
                        }
                    }
                }


                if (string.IsNullOrWhiteSpace(strEquation.Trim()))
                {
                    consequence.IsEquation = false;;
                }
                else
                {
                    byte[] assembly = SimulationMessaging.GetSerializedCalculateEvaluate(cgOMS.Prefix + "CONSEQUENCES", "BINARY_EQUATION", id, null);
                    if (assembly != null && assembly.Length > 0)
                    {
                        consequence._calculate = (CalculateEvaluate.CalculateEvaluate)AssemblySerialize.DeSerializeObjectFromByteArray(assembly);
                        if (consequence._calculate.OriginalInput != strEquation)
                        {
                            consequence._calculate = null;
                        }
                    }

                    bool isFunction = false;
                    if (row["ISFUNCTION"] != DBNull.Value)
                    {
                        isFunction = Convert.ToBoolean(row["ISFUNCTION"]);
                    }

                    if (isFunction)
                    {
                        consequence.SetFunction(strEquation);
                    }
                    else
                    {
                        consequence.Equation = strEquation;
                    }
                    //Get attributes from consequence criteria
                    foreach (string attribute in consequence._attributesEquation)
                    {
                        if (!SimulationMessaging.IsAttribute(attribute))
                        {
                            SimulationMessaging.AddMessage(new SimulationMessage("Error: " + attribute + " which is used by the Consequence criteria is not present in the database."));
                            if (APICall.Equals(true))
                            {
                                var updateStatus = Builders <SimulationModel> .Update
                                                   .Set(s => s.status, "Error: " + attribute + " which is used by the Consequence criteria is not present in the database");

                                Simulations.UpdateOne(s => s.simulationId == Convert.ToInt32(m_strSimulationID), updateStatus);
                            }
                        }
                        if (!_attributes.Contains(attribute))
                        {
                            _attributes.Add(attribute);
                        }
                    }
                }

                consequence.LoadAttributeChange(strAttribute, strChange);
                ConsequenceList.Add(consequence);

                // Get attributes from Attribute change
                foreach (String str in consequence.Attributes)
                {
                    if (!_attributes.Contains(str))
                    {
                        _attributes.Add(str);
                    }
                }
            }
            return(true);
        }
Esempio n. 23
0
        private List <CompoundTreatmentElement> LoadCompoundTreatmentElements(string strCompoundTreatmentName)
        {
            List <CompoundTreatmentElement> listCompoundTreatment = new List <CompoundTreatmentElement>();
            string  strSelect = "SELECT ct.COMPOUND_TREATMENT_ID, AFFECTED_ATTRIBUTE, COMPOUND_TREATMENT_NAME ,ATTRIBUTE_FROM, ATTRIBUTE_TO,EXTENT_,QUANTITY_,COST_,CRITERIA_ FROM COMPOUND_TREATMENT_ELEMENTS cte RIGHT JOIN COMPOUND_TREATMENTS ct ON cte.COMPOUND_TREATMENT_ID = ct.COMPOUND_TREATMENT_ID WHERE COMPOUND_TREATMENT_NAME='" + strCompoundTreatmentName + "'";
            DataSet ds        = DBMgr.ExecuteQuery(strSelect);

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                try
                {
                    string compoundTreatmentID = row["COMPOUND_TREATMENT_ID"].ToString();
                    string affectedAttribute   = row["AFFECTED_ATTRIBUTE"].ToString();

                    // These two properties could probably be moved out of this loop, they are assigned the same value each time through.
                    _affectedAttribute   = affectedAttribute;
                    _compoundTreatmentID = compoundTreatmentID;

                    string strTreatmentName = row["COMPOUND_TREATMENT_NAME"].ToString();
                    string strAttributeFrom = "";
                    string strAttributeTo   = "";
                    string strExtent        = "";
                    string strQuantity      = "";
                    string strCriteria      = "";
                    string costEquation     = "";

                    if (!String.IsNullOrEmpty(row["ATTRIBUTE_FROM"].ToString()))
                    {
                        strAttributeFrom = row["ATTRIBUTE_FROM"].ToString();
                    }
                    if (!String.IsNullOrEmpty(row["ATTRIBUTE_TO"].ToString()))
                    {
                        strAttributeTo = row["ATTRIBUTE_TO"].ToString();
                    }
                    if (!String.IsNullOrEmpty(row["EXTENT_"].ToString()))
                    {
                        strExtent = row["EXTENT_"].ToString();
                    }
                    if (!String.IsNullOrEmpty(row["QUANTITY_"].ToString()))
                    {
                        strQuantity = row["QUANTITY_"].ToString();
                    }
                    if (!String.IsNullOrEmpty(row["CRITERIA_"].ToString()))
                    {
                        strCriteria = row["CRITERIA_"].ToString();
                    }
                    if (!String.IsNullOrEmpty(row["COST_"].ToString()))
                    {
                        costEquation = row["COST_"].ToString();
                    }
                    if (strTreatmentName != "" && strAttributeFrom != "" && strAttributeTo != "" && strExtent != "" && strQuantity != "")
                    {
                        listCompoundTreatment.Add(new CompoundTreatmentElement(compoundTreatmentID, strTreatmentName, strAttributeFrom, strAttributeTo, costEquation, strExtent, strQuantity, strCriteria));
                    }
                }
                catch (Exception ex)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error parsing compound treatment." + ex.Message));
                }
            }
            return(listCompoundTreatment);
        }
Esempio n. 24
0
        public bool LoadBudgetPercentages(List <String> listBudgets)
        {
            //Cleanup unused Budgets
            String strDelete = "DELETE FROM " + cgOMS.Prefix + "PRIORITYFUND WHERE PRIORITYID='" + this.PriorityID + "'";

            if (listBudgets.Count > 0)
            {
                strDelete += " AND (";
            }
            int nBudget = 0;

            foreach (String sBudget in listBudgets)
            {
                if (nBudget > 0)
                {
                    strDelete += " AND ";
                }
                strDelete += "BUDGET<>'" + sBudget + "'";
                nBudget++;
            }
            if (listBudgets.Count > 0)
            {
                strDelete += ")";
            }

            try
            {
                DBMgr.ExecuteNonQuery(strDelete);
            }
            catch (Exception except)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Fatal Error: Error removing non-used budget priorities. " + except.Message));
                return(false);
            }

            if (SimulationMessaging.IsOMS)
            {
                foreach (string budget in listBudgets)
                {
                    m_hashBudgetPercent.Add(budget, 100f);
                }
            }
            else
            {
                String  strSelect = "SELECT BUDGET, FUNDING FROM " + cgOMS.Prefix + "PRIORITYFUND WHERE PRIORITYID='" + this.PriorityID + "'";
                DataSet ds;
                try
                {
                    ds = DBMgr.ExecuteQuery(strSelect);
                    if (ds.Tables[0].Rows.Count != listBudgets.Count)
                    {
                        SimulationMessaging.AddMessage(new SimulationMessage("Fatal Error: Each budget must have a funding level for each priority level."));
                        return(false);
                    }
                }
                catch
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Filling Priority budgets and funding"));
                    return(false);
                }

                String strBudget;
                String strFunding;
                float  fFunding;

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    strBudget  = row[0].ToString();
                    fFunding   = 100;
                    strFunding = row[1].ToString();
                    float.TryParse(strFunding, out fFunding);
                    m_hashBudgetPercent.Add(strBudget, fFunding);
                }
            }
            return(true);
        }
Esempio n. 25
0
        /// <summary>
        /// Check if budget can support treatment.  Checks for each priority.
        /// </summary>
        /// <param name="fAmount"></param>
        /// <param name="strBudget"></param>
        /// <param name="strYear"></param>
        /// <param name="hashAttributeValue"></param>
        /// <param name="priority"></param>
        /// <returns></returns>
        public string IsBudgetAvailable(float fAmount, String strBudget, String strYear, Hashtable hashAttributeValue, Priorities priority)
        {
            string[] possibleBudgets;
            try
            {
                possibleBudgets = strBudget.Split('|');
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Budget is null." + e.Message));
                throw e;
            }

            //If there are no budget criteria, then ignore.  The list is enforced.

            var budgets = new List <string>();

            if (SimulationMessaging.BudgetCriterias.Count > 0)
            {
                var listAvailableBudget = new List <BudgetCriteria>();
                foreach (var budgetCriteria in SimulationMessaging.BudgetCriterias)
                {
                    if (budgetCriteria.Criteria.IsCriteriaMet(hashAttributeValue))
                    {
                        listAvailableBudget.Add(budgetCriteria);
                    }
                }


                foreach (var budget in possibleBudgets)
                {
                    var available = listAvailableBudget.Find(b => b.BudgetName == budget);
                    if (available != null && !budgets.Contains(available.BudgetName))
                    {
                        budgets.Add(available.BudgetName);
                    }
                }
            }
            else
            {
                foreach (var budget in possibleBudgets)
                {
                    budgets.Add(budget);
                }
            }



            foreach (string budget in budgets)
            {
                string    budgetCheck = budget.Trim();
                Hashtable hashYearAmount;
                Hashtable hashYearAmountOriginal;
                float     fAvailable;
                float     fOriginal;
                float     fAfterSpending;
                float     fPercent;

                //Budget not defined
                try
                {
                    if (!BudgetYear.Contains(budgetCheck))
                    {
                        continue;
                    }
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking budget year. " + e.Message));
                    throw e;
                }


                try
                {
                    hashYearAmount = (Hashtable)BudgetYear[budgetCheck];
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving budget year. " + e.Message));
                    throw e;
                }
                try
                {
                    if (!hashYearAmount.Contains(strYear))
                    {
                        continue;
                    }
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking year amount. " + e.Message));
                    throw e;
                }

                try
                {
                    fAvailable = (float)hashYearAmount[strYear];
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving year amount. " + e.Message));
                    throw e;
                }

                try
                {
                    if (!BudgetYearOriginal.Contains(budgetCheck))
                    {
                        continue;
                    }
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking budget year original. " + e.Message));
                    throw e;
                }

                try
                {
                    hashYearAmountOriginal = (Hashtable)BudgetYearOriginal[budgetCheck];
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving budget year original. " + e.Message));
                    throw e;
                }


                try
                {
                    if (!hashYearAmountOriginal.Contains(strYear))
                    {
                        continue;
                    }
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking year amount original. " + e.Message));
                    throw e;
                }

                try
                {
                    fOriginal = (float)hashYearAmountOriginal[strYear];
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving year amount original. " + e.Message));
                    throw e;
                }

                fAfterSpending = fAvailable - fAmount;
                if (fOriginal <= 0)
                {
                    continue;
                }
                fPercent = (1 - fAfterSpending / fOriginal) * 100;

                try
                {
                    if (priority.IsAllSections)
                    {
                        float fPercentLimit = (float)priority.BudgetPercent[budgetCheck];
                        if (fPercent < fPercentLimit)
                        {
                            return(budgetCheck);
                        }
                    }
                    else
                    {
                        if (priority.Criteria.IsCriteriaMet(hashAttributeValue))
                        {
                            float fPercentLimit = (float)priority.BudgetPercent[budgetCheck];
                            if (fPercent < fPercentLimit)
                            {
                                return(budgetCheck);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving budget year original. " + e.Message));
                    throw e;
                }
            }

            return(null);
        }