Esempio n. 1
0
        public static void LoadPerformanceCurvesToDecisionEngine(int simulationID, string asset, Boolean addAssetClause)
        {
            string assetTypesOID = OMS.GetAssetTypeOID(asset);

            if (assetTypesOID != null)
            {
                OMSAssetConditionIndexStore assetOCI = OMS.GetAssetConditionIndex(asset);
                string predictionGroupTable          = assetOCI.ConditionCategoryTable.Replace("ConditionCategories", "PredictionGroups");
                string predictionPointsTable         = predictionGroupTable.Replace("PredictionGroups", "PredictionPoints");
                using (SqlConnection connection = new SqlConnection(DB.OMSConnectionString))
                {
                    connection.Open();
                    string        select = "SELECT " + predictionGroupTable + "OID, PredictionGroup, Filter FROM " + predictionGroupTable + " WHERE Inactive = '0'";
                    SqlCommand    cmd    = new SqlCommand(select, connection);
                    SqlDataReader dr     = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        string predictionGroupOID = dr[predictionGroupTable + "OID"].ToString();
                        string predictionGroup    = "";
                        if (dr["PredictionGroup"] != DBNull.Value)
                        {
                            predictionGroup = dr["PredictionGroup"].ToString();
                        }
                        //OMS doesn't use .amount - the parser definitely does not.
                        string criteria = dr["Filter"].ToString().Replace(".amount", "").Replace("[Type]", "[Type1]");
                        if (addAssetClause)
                        {
                            criteria += " && ([AssetType] is equal to \"" + asset + "\")";
                        }
                        InsertPredictionPoints(simulationID, predictionGroupOID, predictionGroup, criteria, predictionGroupTable, predictionPointsTable);
                    }
                }
            }
        }
Esempio n. 2
0
        public static void Run([TimerTrigger("* * * * *")] TimerInfo myTimer, TraceWriter log) //Every min
        {
            log.Info($"Function executed at: {DateTime.Now}");


            var HOSTIP    = "137.117.83.184";
            var WORKSPACE = "621c5c67-acd6-42b9-9e5f-f1a2c9c602a0";
            var KEY       = "8vlY3QiRTPVzVrXqZsH3VZsCMN7sKlXVfQPF60GooMtd9AlXXsBzvtSef9hEkd/rw3cy+rz0/wz6r0MdGfkFsw==";

            var oms = new OMS()
            {
                Workspace = WORKSPACE,
                SharedKey = KEY,
                LogName   = "Minecraft"
            };


            var ms = new MineStat(HOSTIP, 25565);

            var json = $"{{\"numplayers\":\"{ms.CurrentPlayers}\",\"maxPlayers\":\"{ms.MaximumPlayers}\"}}";

            log.Info(json);

            oms.Log(json);
        }
Esempio n. 3
0
    public CogwheelFact(int i, Vector3 P, Vector3 N, float R, float iR, float oR)
    {
        this.Id            = i;
        this.Point         = P;
        this.Normal        = N;
        this.Radius        = R;
        this.InsideRadius  = iR;
        this.OutsideRadius = oR;

        List <MMTTerm> tupleArguments = new List <MMTTerm>
        {
            new OMF(P.x),
            new OMF(P.y),
            new OMF(P.z)
        };

        List <MMTTerm> wheelOfArguments = new List <MMTTerm>
        {
            new OMF(this.Radius),
            new OMF(this.InsideRadius),
            new OMF(this.OutsideRadius),
            new OMA(new OMS(MMTURIs.Tuple), tupleArguments)
        };

        MMTTerm tp = new OMS(MMTURIs.Cogwheel);
        MMTTerm df = new OMA(new OMS(MMTURIs.CogwheelOf), wheelOfArguments);

        MMTSymbolDeclaration mmtDecl = new MMTSymbolDeclaration(this.Label, tp, df);
        string body = MMTSymbolDeclaration.ToJson(mmtDecl);

        AddFactResponse res = AddFactResponse.sendAdd(GameSettings.ServerAdress + "/fact/add", body);

        this.backendURI = res.uri;
        Debug.Log(this.backendURI);
    }
Esempio n. 4
0
    private void init(string pid1, string pid2)
    {
        SetDistance();

        PointFact pf1 = _Facts[pid1] as PointFact;
        PointFact pf2 = _Facts[pid2] as PointFact;

        string p1URI = pf1.Id;
        string p2URI = pf2.Id;
        float  v     = (pf1.Point - pf2.Point).magnitude;

        MMTTerm lhs =
            new OMA(
                new OMS(MMTURIs.Metric),
                new List <MMTTerm> {
            new OMS(p1URI),
            new OMS(p2URI)
        }
                );

        MMTTerm valueTp = new OMS(MMTURIs.RealLit);
        MMTTerm value   = new OMF(v);

        //see point label
        MMTValueDeclaration mmtDecl = new MMTValueDeclaration(this.Label, lhs, valueTp, value);

        AddFactResponse.sendAdd(mmtDecl, out this._URI);
    }
Esempio n. 5
0
        /// <summary>
        /// Retrieves a list of all Attributes available in treatments.  Extend this to include Cost and Consequence criteria (and consquence attributes)
        /// </summary>
        /// <param name="simulationID"></param>
        /// <returns></returns>
        public static List <AttributeStore> GetTreatmentAttributes(string assetName, string simulationID)
        {
            List <AttributeStore> attributes = new List <AttributeStore>();

            using (SqlConnection connection = new SqlConnection(DB.ConnectionString))//DecisionEngine connection string
            {
                try
                {
                    connection.Open();

                    string        query = "SELECT CRITERIA FROM " + DB.TablePrefix + "FEASIBILITY F INNER JOIN " + DB.TablePrefix + "TREATMENTS T ON F.TREATMENTID=T.TREATMENTID WHERE T.SIMULATIONID='" + simulationID + "'";
                    SqlCommand    cmd   = new SqlCommand(query, connection);
                    SqlDataReader dr    = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        string criteria = null;
                        if (dr["CRITERIA"] != DBNull.Value)
                        {
                            criteria = dr["CRITERIA"].ToString();
                            List <AttributeStore> criteriaAttributes = OMS.ParseAttributes(assetName, criteria);
                            foreach (AttributeStore attribute in criteriaAttributes)
                            {
                                if (!attributes.Contains(attribute))
                                {
                                    attributes.Add(attribute);
                                }
                            }
                        }
                    }

                    dr.Close();
                    //Get COSTS
                    query = "SELECT COST_ FROM " + DB.TablePrefix + "COSTS C INNER JOIN " + DB.TablePrefix + "TREATMENTS T on C.TREATMENTID = T.TREATMENTID WHERE T.SIMULATIONID =@simulationID";
                    cmd   = new SqlCommand(query, connection);
                    cmd.Parameters.Add(new SqlParameter("simulationID", simulationID));
                    dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        if (dr["COST_"] != DBNull.Value)
                        {
                            string cost = dr["COST_"].ToString();
                            List <AttributeStore> costAttributes = OMS.ParseAttributes(assetName, cost);
                            foreach (AttributeStore attribute in costAttributes)
                            {
                                if (!attributes.Contains(attribute))
                                {
                                    attributes.Add(attribute);
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    DataAccessExceptionHandler.HandleException(e, false);
                }
            }
            return(attributes);
        }
Esempio n. 6
0
        //Retreives OMS default files and adds them to the RoadCare database.
        private static void InsertOMSActivities(SimulationStore simulation)
        {
            List <OMSActivityStore> activities = OMS.GetActivities(simulation.Asset);

            foreach (OMSActivityStore activity in activities)
            {
                AddActivity(activity, simulation);
            }
            AddNoTreatment(simulation);
        }
Esempio n. 7
0
        public override bool Equals(object obj)
        {
            if (!(obj is OMS))
            {
                return(false);
            }

            OMS oms = (OMS)obj;

            return(kind.Equals(oms.kind) &&
                   uri.Equals(oms.uri));
        }
Esempio n. 8
0
 public static void InsertOMSActivities(String simulationID, List <String> assets)
 {
     foreach (String asset in assets)
     {
         List <OMSActivityStore> activities = OMS.GetActivities(asset);
         foreach (OMSActivityStore activity in activities)
         {
             AddActivity(activity, simulationID, asset);
         }
     }
     AddNoTreatment(simulationID);
 }
Esempio n. 9
0
        public IApplication GetApplicationFactory(OMS oms)
        {
            switch (oms)
            {
            case OMS.connexx:
                return(new Connexx());

            case OMS.noah:
                return(new Noah());
            }

            return(null);
        }
Esempio n. 10
0
        /// <summary>
        /// Retrieves a list of all Attributes available in Performance.  Extend if Equation based performance.
        /// </summary>
        /// <param name="simulationID"></param>
        /// <returns></returns>
        public static List <AttributeStore> GetPerformanceAttributes(string assetName, string simulationID)
        {
            List <AttributeStore> attributes = new List <AttributeStore>();

            using (SqlConnection connection = new SqlConnection(DB.ConnectionString))//DecisionEngine connection string
            {
                try
                {
                    connection.Open();

                    string        query = "SELECT CRITERIA FROM " + DB.TablePrefix + "PERFORMANCE WHERE SIMULATIONID='" + simulationID + "'";
                    SqlCommand    cmd   = new SqlCommand(query, connection);
                    SqlDataReader dr    = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        string criteria = null;
                        if (dr["CRITERIA"] != DBNull.Value)
                        {
                            criteria = dr["CRITERIA"].ToString();
                            List <AttributeStore> criteriaAttributes = OMS.ParseAttributes(assetName, criteria);
                            foreach (AttributeStore attribute in criteriaAttributes)
                            {
                                if (!attributes.Contains(attribute))
                                {
                                    attributes.Add(attribute);
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    DataAccessExceptionHandler.HandleException(e, false);
                }
            }


            AttributeStore ageAttribute = new AttributeStore();

            ageAttribute.AttributeField           = "AGE";
            ageAttribute.DisplayName              = "AGE";
            ageAttribute.OmsObjectUserIDHierarchy = "AGE";
            ageAttribute.FieldType    = "NUMBER";
            ageAttribute.Minimum      = 0;
            ageAttribute.Maximum      = 100;
            ageAttribute.InitialValue = "0";
            attributes.Add(ageAttribute);


            return(attributes);
        }
Esempio n. 11
0
 /// <summary>
 /// This function for testing purposes.   This should be filled by the interface.
 /// </summary>
 /// <param name="simulation"></param>
 private static void ActivityFeasibilityCostConsequences(SimulationStore simulation)
 {
     if (!IsTreamentsDefined(simulation.SimulationID))
     {
         List <OMSActivityStore> activities = OMS.GetActivities(simulation.Asset);
         if (activities != null)
         {
             foreach (OMSActivityStore activity in activities)
             {
                 CreateScenario.AddActivity(activity, simulation);
             }
         }
     }
 }
Esempio n. 12
0
        public static string ConvertDisplayCostToOMS(string activityID, string criteria)
        {
            string simulationID     = GetSimulationIDFromActivityID(activityID);
            string assetName        = SelectScenario.GetAssetType(simulationID);
            string displayAttribute = SimulationComponents.FindAttribute(criteria, 0);

            if (displayAttribute != null)
            {
                List <AttributeStore> attributes = OMS.GetAssetAttributes(assetName);
                AttributeStore        attribute  = attributes.Find(delegate(AttributeStore a) { return(a.OmsHierarchy == displayAttribute); });
                criteria = criteria.Replace("[" + displayAttribute + "]", "[" + attribute.OmsObjectUserIDHierarchy + "]");
            }
            return(criteria);
        }
Esempio n. 13
0
        /// <summary>
        /// Gets the OCI weightings from the OMS database and inserts the result into the DecisionEngine OCI_WEIGHTS table
        /// </summary>
        /// <param name="simulation">SimlulationID for which to insert OCI weights</param>
        public static void ConditionCategoryWeights(String simulationID, List <String> assets)
        {
            DeleteScenario.DeleteConditionCategoryWeight(simulationID);
            foreach (String asset in assets)
            {
                OMSAssetConditionIndexStore oci = OMS.GetAssetConditionIndex(asset);

                for (int i = 0; i < oci.ConditionIndexes.Count; i++)
                {
                    string conditionIndex = oci.ConditionIndexes[i].AttributeDE;
                    string weight         = oci.Weights[i].Weight.ToString();
                    string criteria       = oci.Weights[i].Criteria;

                    if (assets.Count > 1 && criteria != null)
                    {
                        criteria += "[AssetType]=|" + asset + "|";
                    }
                    else if (assets.Count > 1)
                    {
                        criteria = "[AssetType]=|" + asset + "|";
                    }

                    try
                    {
                        using (SqlConnection connection = new SqlConnection(DB.ConnectionString))
                        {
                            connection.Open();
                            string     insert = "INSERT INTO " + DB.TablePrefix + "OCI_WEIGHTS (SIMULATIONID,CONDITION_CATEGORY,WEIGHT,CRITERIA) VALUES(@simulationID,@conditionIndex,@weight,@criteria)";
                            SqlCommand cmd    = new SqlCommand(insert, connection);
                            cmd.Parameters.Add(new SqlParameter("simulationID", simulationID));
                            cmd.Parameters.Add(new SqlParameter("conditionIndex", "__" + conditionIndex.Replace(" ", "").Replace("/", "")));
                            cmd.Parameters.Add(new SqlParameter("weight", weight));
                            if (criteria == null)
                            {
                                cmd.Parameters.Add(new SqlParameter("criteria", DBNull.Value));
                            }
                            else
                            {
                                cmd.Parameters.Add(new SqlParameter("criteria", criteria));
                            }
                            cmd.ExecuteNonQuery();
                        }
                    }
                    catch (Exception ex)
                    {
                        Utility.ExceptionHandling.DataAccessExceptionHandler.HandleException(ex, false);
                    }
                }
            }
        }
Esempio n. 14
0
        private static void UpdateImpact(string assetType, string activityID, string conditionIndex, string value)
        {
            OMSAssetConditionIndexStore oci = OMS.GetAssetConditionIndex(assetType);
            OMSConditionIndexStore      omsConditionIndex = oci.ConditionIndexes.Find(delegate(OMSConditionIndexStore ci) { return(ci.ConditionCategory == conditionIndex); });

            if (omsConditionIndex != null)
            {
                string attribute = omsConditionIndex.AttributeDE;
                if (string.IsNullOrWhiteSpace(value))//The user has deleted an impact.
                {
                    DeleteScenario.DeleteImpact(activityID, attribute);
                }
                else
                {
                    bool isExists = false;
                    using (SqlConnection connection = new SqlConnection(DB.ConnectionString))
                    {
                        try
                        {
                            connection.Open();
                            string        query = "SELECT CONSEQUENCEID FROM " + DB.TablePrefix + "CONSEQUENCES WHERE TREATMENTID='" + activityID + "' AND ATTRIBUTE_='" + attribute + "'";
                            SqlCommand    cmd   = new SqlCommand(query, connection);
                            SqlDataReader dr    = cmd.ExecuteReader();
                            if (dr.Read())
                            {
                                isExists = true;
                            }
                        }
                        catch (Exception e)
                        {
                            DataAccessExceptionHandler.HandleException(e, false);
                            return;
                        }
                    }

                    if (isExists)
                    {
                        //Update impact
                        UpdateImpact(activityID, attribute, value);
                    }
                    else //Insert impact
                    {
                        InsertImpact(activityID, attribute, value);
                    }
                }
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Fills the Targets and Deficients tables with values from SimulationStore
        /// </summary>
        /// <param name="simulation">SimulationStore for this scenario</param>
        public static void TargetAndDeficients(SimulationStore simulation)
        {
            string simulationID = simulation.SimulationID;

            //Delete previous Targets and deficient.  Recalculate from SimulationStore
            DeleteScenario.DeleteTargets(simulationID);
            //This function will only perform useful work if Deficients are added below.
            DeleteScenario.DeleteDeficients(simulationID);

            try
            {
                //If USE_TARGET then set analysis type to Until Targets and Deficients Met
                using (SqlConnection connection = new SqlConnection(DB.ConnectionString))
                {
                    connection.Open();
                    string insert = "INSERT INTO " + DB.TablePrefix + "TARGETS " +
                                    "(SIMULATIONID,ATTRIBUTE_,TARGETMEAN,TARGETNAME)" +
                                    "VALUES('" + simulationID + "','OverallConditionIndex','" + simulation.TargetOCI + "','OMS')";

                    SqlCommand cmd = new SqlCommand(insert, connection);
                    cmd.ExecuteNonQuery();

                    //Allow determination of OCI limit and possible separate OCI Remaining Life
                    insert = "INSERT INTO " + DB.TablePrefix + "DEFICIENTS " +
                             "(SIMULATIONID,ATTRIBUTE_,DEFICIENTNAME,DEFICIENT,PERCENTDEFICIENT)" +
                             "VALUES('" + simulationID + "','OverallConditionIndex','OCI Deficient','0','0')";
                    cmd = new SqlCommand(insert, connection);
                    cmd.ExecuteNonQuery();

                    //This is so remaining life can be calculated for each individiual condition index
                    OMSAssetConditionIndexStore oci = OMS.GetAssetConditionIndex(simulation.Asset);
                    foreach (OMSConditionIndexStore ci in oci.ConditionIndexes)
                    {
                        insert = "INSERT INTO " + DB.TablePrefix + "DEFICIENTS " +
                                 "(SIMULATIONID,ATTRIBUTE_,DEFICIENTNAME,DEFICIENT,PERCENTDEFICIENT)" +
                                 "VALUES('" + simulationID + "','" + ci.AttributeDE + "','" + ci.AttributeDE + " Deficient','0','0')";
                        cmd = new SqlCommand(insert, connection);
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                Utility.ExceptionHandling.DataAccessExceptionHandler.HandleException(ex, false);
            }
        }
Esempio n. 16
0
    private MMTDeclaration generateNot90DegreeAngleDeclaration(float val, string p1URI, string p2URI, string p3URI)
    {
        MMTTerm lhs =
            new OMA(
                new OMS(MMTURIs.Angle),
                new List <MMTTerm> {
            new OMS(p1URI),
            new OMS(p2URI),
            new OMS(p3URI)
        }
                );

        MMTTerm valueTp = new OMS(MMTURIs.RealLit);
        MMTTerm value   = new OMF(val);

        return(new MMTValueDeclaration(this.Label, lhs, valueTp, value));
    }
        private LaboratoryViewModel GetLaboratoryModelForCarnumber(string carNumber)
        {
            var model = new LaboratoryViewModel();

            using (var dl = new OMS())
            {
                var order = DatabaseHelper.GetOrderByCarNumber(carNumber);
                if (order != null)
                {
                    Product product = dl.Products.FirstOrDefault(p => p.Id == order.ProductId);

                    model.OrderId          = order.Id;
                    model.OrderTypeId      = order.OrderTypeId;
                    model.Barcode          = order.Barcode;
                    model.CarNumber        = carNumber;
                    model.TruckNumber      = order.TrailerNumber;
                    model.ProductId        = order.ProductId;
                    model.ClassificationId = order.ClassificationId;
                    model.Placards         = order.Placards;
                    switch (order.OrderTypeId)
                    {
                    case 2:
                    case 3:
                        model.Silage = order.TankNumber.HasValue ?order.TankNumber.Value:0;
                        break;

                    case 4:
                    case 6:
                        model.Tank = order.TankNumber.HasValue ? order.TankNumber.Value : 0;
                        break;

                    default:
                        break;
                    }
                    model.Comment = order.Comment;
                    if (product != null)
                    {
                        model.ProductName = product.Name;
                    }
                    model.ClassificationName = dl.Classifications.Single(c => c.Id == order.ClassificationId).Name;
                }
            }
            return(model);
        }
Esempio n. 18
0
        /// <summary>
        /// Convert SimulationStore into necessary tables entries for RoadCare
        /// </summary>
        /// <param name="simulationID"></param>
        public static void Simulation(string simulationID)
        {
            SimulationStore             simulation = SelectScenario.GetSimulationStore(simulationID);
            OMSAssetConditionIndexStore oci        = OMS.GetAssetConditionIndex(simulation.Asset);

            PrepareAnalysis.Priorities(simulation);
            //PrepareAnalysis.TargetAndDeficients(simulation);
            PrepareAnalysis.ConditionCategoryWeights(simulation);
            //PrepareAnalysis.Performance(simulation);
            //PrepareAnalysis.RepeatedActivities(simulation);
            //PrepareAnalysis.ActivityFeasibilityCostConsequences(simulation);
            List <AttributeStore>    attributes   = PrepareAnalysis.Attributes(simulation);
            AssetRequestOMSDataStore assetRequest = new AssetRequestOMSDataStore(DateTime.Now, attributes, oci);
            Dictionary <string, AssetReplyOMSLookupTable> assetLookups = OMS.GetAssetLookupData(assetRequest);
            List <AssetReplyOMSDataStore> assets = OMS.GetAssetData(assetRequest);
            List <AssetReplyOMSDataStore> assetsWithCondition = assets.FindAll(delegate(AssetReplyOMSDataStore arods) { return(arods.ConditionIndices != null); });

            PrepareAnalysis.Assets(simulation, assetsWithCondition, attributes, assetRequest, assetLookups);
        }
Esempio n. 19
0
    private void init(Vector3 P, Vector3 N)
    {
        this.Point  = P;
        this.Normal = N;

        List <MMTTerm> arguments = new List <MMTTerm>
        {
            new OMF(P.x),
            new OMF(P.y),
            new OMF(P.z)
        };

        //OMS constructor generates full URI
        MMTTerm tp = new OMS(MMTURIs.Point);
        MMTTerm df = new OMA(new OMS(MMTURIs.Tuple), arguments);

        MMTSymbolDeclaration mmtDecl = new MMTSymbolDeclaration(this.Label, tp, df);

        AddFactResponse.sendAdd(mmtDecl, out this._URI);
    }
Esempio n. 20
0
    private void init(string pid1, string pid2)
    {
        PointFact pf1 = _Facts[pid1] as PointFact;
        PointFact pf2 = _Facts[pid2] as PointFact;

        string p1URI = pf1.Id;
        string p2URI = pf2.Id;

        List <MMTTerm> arguments = new List <MMTTerm>
        {
            new OMS(p1URI),
            new OMS(p2URI)
        };

        //OMS constructor generates full URI
        MMTTerm tp = new OMS(MMTURIs.LineType);
        MMTTerm df = new OMA(new OMS(MMTURIs.LineOf), arguments);

        MMTSymbolDeclaration mmtDecl = new MMTSymbolDeclaration(this.Label, tp, df);

        AddFactResponse.sendAdd(mmtDecl, out this._URI);
    }
Esempio n. 21
0
        /// <summary>
        /// Insert the Prediction curve from PrectionGroups and PredictionPoints into PERFORMANCE
        /// </summary>
        /// <param name="simulation">Simulation for which to build performance curves for.</param>
        public static void Performance(String simulationID, List <String> assets)
        {
            DeleteScenario.DeletePerformance(simulationID);

            foreach (String asset in assets)
            {
                List <OMSPrediction> predictions = OMS.GetPredictionsCurves(asset);

                foreach (OMSPrediction prediction in predictions)
                {
                    foreach (OMSCategoryPrediction conditionIndex in prediction.CategoryPredictions)
                    {
                        string attribute    = "__" + conditionIndex.ConditionCategory.Replace(" ", "").Replace("/", "");
                        string equationName = prediction.PredictionGroupName;
                        string equation     = conditionIndex.GetPiecewiseCurve();
                        string criteria     = prediction.PredictionFilter;
                        bool   piecewise    = true;
                        try
                        {
                            using (SqlConnection connection = new SqlConnection(DB.ConnectionString))
                            {
                                connection.Open();
                                string insert = "INSERT INTO " + DB.TablePrefix + "PERFORMANCE " +
                                                "(SIMULATIONID,ATTRIBUTE_,EQUATIONNAME,CRITERIA,EQUATION,PIECEWISE)" +
                                                "VALUES('" + simulationID + "','" + attribute + "','" + equationName + "','" + criteria + "','" + equation + "','" + piecewise.ToString() + "')";

                                SqlCommand cmd = new SqlCommand(insert, connection);
                                cmd.ExecuteNonQuery();
                            }
                        }
                        catch (Exception ex)
                        {
                            Utility.ExceptionHandling.DataAccessExceptionHandler.HandleException(ex, false);
                        }
                    }
                }
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Returns a list of all attributes used in Priority Critera.
        /// </summary>
        /// <param name="assetName">Asset type for which simulation is performed</param>
        /// <param name="simulationID">SimulationID of anlaysis</param>
        /// <returns></returns>
        public static List <AttributeStore> GetPriorityAttributes(string assetName, string simulationID)
        {
            List <AttributeStore> attributes = new List <AttributeStore>();

            using (SqlConnection connection = new SqlConnection(DB.ConnectionString))//DecisionEngine connection string
            {
                try
                {
                    connection.Open();

                    string        query = "SELECT CRITERIA FROM " + DB.TablePrefix + "PRIORITY WHERE SIMULATIONID='" + simulationID + "'";
                    SqlCommand    cmd   = new SqlCommand(query, connection);
                    SqlDataReader dr    = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        string criteria = null;
                        if (dr["CRITERIA"] != DBNull.Value)
                        {
                            criteria = dr["CRITERIA"].ToString();
                            List <AttributeStore> criteriaAttributes = OMS.ParseAttributes(assetName, criteria);
                            foreach (AttributeStore attribute in criteriaAttributes)
                            {
                                if (!attributes.Contains(attribute))
                                {
                                    attributes.Add(attribute);
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    DataAccessExceptionHandler.HandleException(e, false);
                }
            }
            return(attributes);
        }
Esempio n. 23
0
        /// <summary>
        /// This object is passed to the OMS class to request data for the contained tables.
        /// </summary>
        /// <param name="beforeDate">The date on of before which the data is desired.</param>
        /// <param name="attributes">A unique list of Attribute Stores required to perform the simulation</param>
        public AssetRequestOMSDataStore(DateTime beforeDate, List <AttributeStore> attributes, OMSAssetConditionIndexStore conditionIndex)

        {
            _beforeDate     = beforeDate;
            _conditionIndex = conditionIndex;
            _tables         = new List <AssetRequestOMSTableStore>();
            if (attributes != null && attributes.Count > 0)
            {
                _assetTypeName = attributes[0].AssetType;

                foreach (AttributeStore attribute in attributes)
                {
                    if (!attribute.IsConditionCategory && attribute.AttributeField != "AGE")//Ignore AGE which is calculated in DecisionEngine and ConditionIndices which are got with different.
                    {
                        int index = Tables.FindIndex(delegate(AssetRequestOMSTableStore art) { return(art.TableName == attribute.OmsTable); });
                        if (index < 0)
                        {
                            string foreignKey               = null;
                            string primaryKey               = null;
                            string foreignKeyTable          = null;
                            AssetRequestOMSTableStore table = new AssetRequestOMSTableStore(attribute.OmsTable);
                            table.Columns.Add(new AssetRequestOMSColumnStore(attribute.AttributeField.ToString(), attribute.OmsObjectUserIDHierarchy.ToString(), attribute.AttributeField));
                            OMS.GetPrimaryKeyForLookups(attribute.OmsOIDHierarchy, out primaryKey, out foreignKey, out foreignKeyTable);
                            table.PrimaryKeyColumn = primaryKey;
                            table.ForeignKeyColumn = foreignKey;
                            table.ForeignKeyTable  = foreignKeyTable;
                            _tables.Add(table);
                        }
                        else
                        {
                            Tables[index].Columns.Add(new AssetRequestOMSColumnStore(attribute.AttributeField.ToString(), attribute.OmsObjectUserIDHierarchy.ToString(), attribute.AttributeField));
                        }
                    }
                }
            }
        }
Esempio n. 24
0
        public static string GetDecisionEngineCritera(string omsCriteria, string asset)
        {
            omsCriteria = omsCriteria.Replace("[]", "cgde_timeperiodof"); // Square brackets denote variables.  [] messes this up.
            string        deCriteria  = "";
            List <string> expressions = new List <string>();              //List of omsExpressions

            int lastOpen = -1;
            int i        = 0;

            while (i < omsCriteria.Length)//Find all expressions
            {
                if (omsCriteria[i] == '(')
                {
                    lastOpen = i;
                }
                if (omsCriteria[i] == ')' && lastOpen >= 0)
                {
                    string expression = omsCriteria.Substring(lastOpen, i - lastOpen + 1);
                    if (expression.Contains("["))
                    {
                        byte   numberExpressions = (byte)expressions.Count;
                        string placeHolder       = numberExpressions.ToString("x2");
                        expressions.Add(expression);
                        omsCriteria = omsCriteria.Replace(expression, placeHolder);
                        i           = 0;
                    }
                    lastOpen = -1;
                }
                else
                {
                    i++;
                }
            }

            omsCriteria = omsCriteria.Replace("AND", "&&").Replace("OR", "||").Replace("NOT", "!");

            if (CheckMatchingParentheses(omsCriteria))
            {
                byte index = 0;
                deCriteria = omsCriteria;
                foreach (string expression in expressions)
                {
                    string         variable  = GetVariable(expression);
                    AttributeStore attribute = OMS.GetAssetAttributes(asset).Find(delegate(AttributeStore a) { return(a.OmsObjectUserIDHierarchy == variable); });
                    if (attribute != null)
                    {
                        string placeholder  = index.ToString("x2");
                        string deExpression = ConvertToDecisionEngine(expression, attribute.FieldType);
                        deCriteria = deCriteria.Replace(placeholder, deExpression);
                    }
                    else
                    {
                        deCriteria = "Variable = " + variable + " not found for " + asset + ".";
                        break;
                    }
                    index++;
                }
            }
            else
            {
                deCriteria = "Parentheses in input criteria do not match.";
            }
            return(deCriteria);
        }
        public ActionResult ReportProductMovementForm(ReportProductMovementViewModel model)
        {
            List <Silage> siloses = new List <Silage>();
            ReportProductMovementViewModel newModel = new ReportProductMovementViewModel();

            var d  = DateTime.Now.Date;
            var bd = d.AddDays(-1).Date;

            if (model.DateBegin == DateTime.MinValue)
            {
                newModel.DateBegin = new DateTime(bd.Year, bd.Month, bd.Day, 7, 0, 0);
            }
            else
            {
                newModel.DateBegin = new DateTime(model.DateBegin.Year,
                                                  model.DateBegin.Month, model.DateBegin.Day, 7, 0, 0);
            }

            if (model.TimeBegin == DateTime.MinValue)
            {
                newModel.TimeBegin = new DateTime(bd.Year, bd.Month, bd.Day, 7, 0, 0);
            }
            else
            {
                newModel.TimeBegin = model.TimeBegin;
            }


            if (model.DateFinish == DateTime.MinValue)
            {
                newModel.DateFinish = new DateTime(d.Year, d.Month, d.Day, 19, 00, 00);
            }
            else
            {
                newModel.DateFinish = new DateTime(model.DateFinish.Year,
                                                   model.DateFinish.Month, model.DateFinish.Day, 7, 0, 0);
            }

            if (model.TimeFinish == DateTime.MinValue)
            {
                newModel.TimeFinish = new DateTime(d.Year, d.Month, d.Day, 19, 00, 00);
            }
            else
            {
                newModel.TimeFinish = model.TimeFinish;
            }


            using (var dl = new OMS())
            {
                newModel.IsPrint = true;

                var elevatorMovingView = dl.vwStorageMovingOperations.
                                         Where(m => m.OperationDate >= model.DateBegin &&
                                               m.OperationDate <= model.DateFinish && m.Weight > 5 &&
                                               ((m.SilageToId >= 28 &&
                                                 m.SilageToId <= 105 ||
                                                 m.SilageToId == 115)
                                                &&
                                                (m.SilageFromId != 24 && m.SilageFromId != 25 && m.SilageFromId != 26 &&
                                                 m.SilageToId != 24 && m.SilageToId != 25 && m.SilageToId != 26)

                                               ))
                                         .Select(m => new ElevatorMovingItemViewModel
                {
                    ProductName            = m.ProductName,
                    ClassificationFromName = m.ClassificationFromName,
                    ClassificationToName   = m.ClassificationToName,
                    Date           = m.OperationDate,
                    SilageFromName = m.SilageFrom,
                    SilageToName   = m.SilageTo,
                    Weight         = m.Weight,
                    OperatorLogin  = m.UserLogin
                });

                newModel.ElevatorMovingItems.AddRange(elevatorMovingView);
            }
            return(View(newModel));
        }
Esempio n. 26
0
 public IAPIProfile CreateAPIProfile(OMS.Core.DoMain.PaypalAccountType entity)
 {
     IAPIProfile payPalAPI = CreateAPIProfile(entity.APIKEY, entity.APIPWD, entity.ApiToken); ;
     return payPalAPI;
 }
Esempio n. 27
0
        private void GetPaypalAddress(OMS.Core.DoMain.OrderType order)
        {
            if (string.IsNullOrEmpty(order.TxnId))
                return;
            foreach (IAPIProfile item in paypals)
            {
                //获得paypal地址
                com.paypal.soap.api.GetTransactionDetailsResponseType transactionDetails = AppSettingHelper.GetTransactionDetails(order.TxnId, item);
                if (transactionDetails.Ack == com.paypal.soap.api.AckCodeType.Success || transactionDetails.Ack == com.paypal.soap.api.AckCodeType.SuccessWithWarning)
                {
                    OMS.Core.DoMain.BuyerAddressType bat = new Core.DoMain.BuyerAddressType();
                    bat.Street = transactionDetails.PaymentTransactionDetails.PayerInfo.Address.Street1 + " " + transactionDetails.PaymentTransactionDetails.PayerInfo.Address.Street2;
                    bat.City = transactionDetails.PaymentTransactionDetails.PayerInfo.Address.CityName;
                    bat.StateOrProvince = transactionDetails.PaymentTransactionDetails.PayerInfo.Address.StateOrProvince;
                    bat.CountryCode = transactionDetails.PaymentTransactionDetails.PayerInfo.Address.Country.ToString();
                    bat.Country = transactionDetails.PaymentTransactionDetails.PayerInfo.Address.CountryName;
                    bat.PostCode = transactionDetails.PaymentTransactionDetails.PayerInfo.Address.PostalCode;
                    bat.ContactMan = transactionDetails.PaymentTransactionDetails.PayerInfo.Address.Name;
                    bat.Email = transactionDetails.PaymentTransactionDetails.PayerInfo.Payer;
                    bat.Phone = transactionDetails.PaymentTransactionDetails.PayerInfo.ContactPhone;
                    order.PayEmail = transactionDetails.PaymentTransactionDetails.ReceiverInfo.Business;
                    order.OrderPayTax = Convert.ToDouble(transactionDetails.PaymentTransactionDetails.PaymentInfo.FeeAmount.Value);
                    order.PayCurrencyCode = transactionDetails.PaymentTransactionDetails.PaymentInfo.FeeAmount.currencyID.ToString();
                    bat.BuyerCode = order.BuyerCode;
                    bat.BuyerId = order.BuyerId;
                    order.Description = transactionDetails.PaymentTransactionDetails.PayerInfo.Address.CountryName;
                    //判断该地址是否保存在数据库中.
                    OMS.Core.DoMain.BuyerAddressType bat2 = OMS.Core.DoMain.BuyerAddressType.find("ContactMan=:p1 and Street=:p2").set("p1", bat.ContactMan).set("p2", bat.Street).first();
                    if (bat2 != null)
                    {
                        order.AddressId = bat2.Id.ToString();
                    }
                    else
                    {
                        bat.insert();
                        order.AddressId = bat.Id.ToString();
                    }

                    break;
                }
            }
        }
Esempio n. 28
0
        public static void AddActivity(OMSActivityStore activity, String simulationID, String asset)
        {
            //Insert activity in treatments
            //Get Identity
            string treatmentID = null;
            int    year        = DateTime.Now.Year + 1;

            using (SqlConnection connection = new SqlConnection(DB.ConnectionString))
            {
                connection.Open();
                string insert = "INSERT INTO " + DB.TablePrefix + "TREATMENTS (SIMULATIONID,TREATMENT,BEFOREANY,BEFORESAME,OMS_REPEAT_START, OMS_REPEAT_INTERVAL, OMS_OID, OMS_IS_SELECTED,OMS_IS_EXCLUSIVE, OMS_IS_REPEAT)"
                                + " VALUES ('" + simulationID + "','" + activity.ActivityName + "','1','1','" + year + "','1','" + activity.ActivityOID + "','0','0','0')";
                try
                {
                    SqlCommand cmd = new SqlCommand(insert, connection);
                    cmd.ExecuteNonQuery();
                    string selectIdentity = "SELECT IDENT_CURRENT ('" + DB.TablePrefix + "TREATMENTS') FROM " + DB.TablePrefix + "TREATMENTS";
                    cmd         = new SqlCommand(selectIdentity, connection);
                    treatmentID = cmd.ExecuteScalar().ToString();
                }
                catch (Exception e)
                {
                    Utility.ExceptionHandling.DataAccessExceptionHandler.HandleException(e, false);
                }

                try
                {
                    double cost = 0;
                    if (activity.OmsCost.CostPerUnit != double.NaN)
                    {
                        cost = activity.OmsCost.CostPerUnit;
                        if (cost <= 0)
                        {
                            cost = 1;
                        }
                    }
                    else
                    {
                        cost = 1;
                    }
                    insert = "INSERT INTO " + DB.TablePrefix + "COSTS (TREATMENTID,COST_) VALUES ('" + treatmentID + "','" + cost.ToString() + "')";
                    SqlCommand cmd = new SqlCommand(insert, connection);
                    cmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    Utility.ExceptionHandling.DataAccessExceptionHandler.HandleException(e, false);
                }

                OMSAssetConditionIndexStore oci = OMS.GetAssetConditionIndex(asset);

                foreach (OMSConsequenceStore consequence in activity.ConsequenceList)
                {
                    try
                    {
                        OMSConditionIndexStore condition = oci.ConditionIndexes.Find(delegate(OMSConditionIndexStore ci) { return(ci.ConditionCategory == consequence.ConditionCategory); });

                        if (condition != null)
                        {
                            insert = "INSERT INTO " + DB.TablePrefix + "CONSEQUENCES (TREATMENTID,ATTRIBUTE_,CHANGE_) VALUES ('" + treatmentID + "','__" + condition.AttributeDE.Replace(" ", "").Replace("/", "") + "','" + consequence.GetDecisionEngineConsequence() + "')";
                            SqlCommand cmd = new SqlCommand(insert, connection);
                            cmd.ExecuteNonQuery();
                        }
                    }
                    catch (Exception e)
                    {
                        Utility.ExceptionHandling.DataAccessExceptionHandler.HandleException(e, false);
                    }
                }

                try
                {
                    string conditionIndexCriteria = GetConditionIndexCriteria(activity.ConsequenceList);

                    if (String.IsNullOrWhiteSpace(conditionIndexCriteria))
                    {
                        conditionIndexCriteria = "[AssetType]=|" + asset + "|";
                    }
                    else
                    {
                        conditionIndexCriteria = " AND [AssetType]=|" + asset + "|";
                    }


                    insert = "INSERT INTO " + DB.TablePrefix + "FEASIBILITY (TREATMENTID,CRITERIA) VALUES ('" + treatmentID + "','" + conditionIndexCriteria + "')";
                    SqlCommand cmd = new SqlCommand(insert, connection);
                    cmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    Utility.ExceptionHandling.DataAccessExceptionHandler.HandleException(e, false);
                }
            }
        }
Esempio n. 29
0
        private static void GetItems(OrderType ot, OMS.Core.DoMain.OrderType order)
        {
            foreach (TransactionType tran in ot.TransactionArray)
            {
                OMS.Core.DoMain.OrderGoodsType ogt = new Core.DoMain.OrderGoodsType();

                ogt.ItemAttr = tran.OrderLineItemID;
                ogt.OrderNo = order.Id.ToString();
                ogt.Sku = tran.Item.ItemID;
                ogt.ItemName = tran.Item.Title;
                ogt.ItemNum = tran.QuantityPurchased;
                ogt.ItemPrice = tran.TransactionPrice.Value;
                OMS.Core.DoMain.GoodsCoefficientType cf = OMS.Core.DoMain.GoodsCoefficientType.find("SaleSku='" + ogt.Sku + "'").first();
                if (cf != null && cf.Id != 0)
                {
                    ogt.ItemNo = cf.ItemSku;
                    ogt.ItemNum = cf.GoodsNum * ogt.ItemNum;
                }
                else
                {
                    string sku = ogt.ItemName.Substring(ogt.ItemName.LastIndexOf('#') + 1).Trim();
                    if (sku.Length == 4)
                    {
                        cf = new Core.DoMain.GoodsCoefficientType();
                        cf.GoodsNum = 1;
                        cf.ItemSku = sku;
                        cf.SaleSku = ogt.Sku;
                        cf.insert();
                        ogt.ItemNo = cf.ItemSku;
                        ogt.ItemNum = cf.GoodsNum * ogt.ItemNum;
                    }

                }
                ogt.insert();
            }
        }
Esempio n. 30
0
        private static void GetOrderBasic(Core.DoMain.SaleAccountType account, OrderType ot, OMS.Core.DoMain.OrderType order)
        {
            order.OrderExNo = ot.OrderID;
            order.OrderForm = PlatformType.Ebay.ToString();
            order.UserNameForm = account.UserName;

            order.PayStatus = ot.PaidTime == DateTime.MinValue ? PayStatusType.未付款.ToString() : PayStatusType.已付款.ToString();
            order.PayTime = ot.PaidTime;
            order.Payment = ot.CheckoutStatus.PaymentMethod.ToString();
            order.ShippedStatus = ot.ShippedTime == DateTime.MinValue ? "未发货" : "已发货";
            order.OrderNote = ot.BuyerCheckoutMessage;
            order.OrderCurrencyCode = ot.AmountPaid.currencyID.ToString();
            order.OrderAmount = ot.AmountPaid.Value;
            order.BuyerCode = ot.BuyerUserID;
            if (ot.ExternalTransaction.Count > 0)
            {
                order.TxnId = ot.ExternalTransaction[0].ExternalTransactionID;
            }
            order.NowOrderType = NowOrderType.普通.ToString();
            order.ModifiedOn = ot.CheckoutStatus.LastModifiedTime;
            order.CreateOn = ot.CreatedTime;
            order.CreateBy = "OMS_Auto";
            order.ModifiedBy = "OMS_Auto";
        }
Esempio n. 31
0
        private static void GetBuyer(OMS.Core.DoMain.OrderType order)
        {
            OMS.Core.DoMain.BuyerType bt = OMS.Core.DoMain.BuyerType.find("BuyerCode='" + order.BuyerCode + "' and  PlatformCode ='" + PlatformType.Ebay.ToString() + "'").first();
            if (bt == null)
            {
                bt = new Core.DoMain.BuyerType();
                //不存在是的操作
                bt.BuyerCode = order.BuyerCode;
                bt.PlatformCode = PlatformType.Ebay.ToString();

                bt.BuyCount++;
                bt.insert();
            }
            else
            {
                bt.BuyCount++;
                bt.update();
            }
            order.BuyerId = bt.Id.ToString();
        }
Esempio n. 32
0
 public List <AttributeStore> GetAttributes()
 {
     return(OMS.ParseAttributes(_assetName, _predictionFilter));
 }
Esempio n. 33
0
        /// <summary>
        /// Parses a DecisionEngine WHERE clause into a display element.
        /// </summary>
        public void ParseCriteria(string criteria, List <ConsequenceStore> consequences)
        {
            if (criteria != null)
            {
                criteria     = RemoveDoubleWhiteSpace(criteria);
                _whereClause = criteria;

                List <string> listCriteria = new List <string>();//List of omsExpressions
                int           lastOpen     = -1;
                int           i            = 0;
                while (i < _whereClause.Length)//Find all expressions
                {
                    if (_whereClause[i] == '(')
                    {
                        lastOpen = i;
                    }
                    if (_whereClause[i] == ')' && lastOpen >= 0)
                    {
                        string expression = _whereClause.Substring(lastOpen, i - lastOpen + 1);
                        if (expression.Contains("["))
                        {
                            byte   numberExpressions = (byte)listCriteria.Count;
                            string placeHolder       = numberExpressions.ToString("x2");
                            listCriteria.Add(expression);
                            _whereClause = _whereClause.Replace(expression, placeHolder);
                            i            = 0;
                        }
                        lastOpen = -1;
                    }
                    else
                    {
                        i++;
                    }
                }

                OMSAssetConditionIndexStore oci = OMS.GetAssetConditionIndex(_assetName);
                _conditionIndexes = new List <ActivityConditionIndex>();
                foreach (OMSConditionIndexStore ci in oci.ConditionIndexes)
                {
                    List <string> conditionExpressions = new List <string>();
                    for (int j = 0; j < listCriteria.Count; j++)
                    {
                        string expression = listCriteria[j];
                        if (expression != null)
                        {
                            string attribute = "[__" + ci.AttributeDE + "]";
                            if (expression.Contains(attribute))
                            {
                                conditionExpressions.Add(expression);

                                //Remove expression from criteria to get non-condition index criteria
                                criteria = criteria.Replace("AND " + expression, "");
                                criteria = criteria.Replace(expression, "");

                                listCriteria[j] = null;
                            }
                        }
                    }
                    ActivityConditionIndex activityConditionIndex = new ActivityConditionIndex(ci, conditionExpressions, consequences);
                    _conditionIndexes.Add(activityConditionIndex);
                }

                //Pickup OverallConditionIndex
                List <string> OCIExpressions = new List <string>();
                for (int j = 0; j < listCriteria.Count; j++)
                {
                    string expression = listCriteria[j];
                    if (expression != null)
                    {
                        string attribute = "[OverallConditionIndex]";
                        if (expression.Contains(attribute))
                        {
                            OCIExpressions.Add(expression);

                            //Remove expression from criteria to get non-condition index criteria
                            criteria = criteria.Replace("AND " + expression, "");
                            criteria = criteria.Replace(expression, "");

                            listCriteria[j] = null;
                        }
                    }
                }
                ActivityConditionIndex activityOCI = new ActivityConditionIndex(OCIExpressions, consequences);
                _conditionIndexes.Add(activityOCI);


                _criteria = criteria.Trim();
                if (_criteria.Length > 3 && _criteria.Substring(0, 3) == "AND")
                {
                    _criteria = _criteria.Substring(3);
                }
            }
        }
Esempio n. 34
0
        private static List <AttributeStore> Attributes(SimulationStore simulation)
        {
            DeleteScenario.DeleteAttributes(simulation.SimulationID);

            List <AttributeStore> attributes = DecisionEngine.GetTreatmentAttributes(simulation.Asset, simulation.SimulationID);


            List <AttributeStore> attributePriority = DecisionEngine.GetPriorityAttributes(simulation.Asset, simulation.SimulationID);

            foreach (AttributeStore attribute in attributePriority)
            {
                if (!attributes.Contains(attribute))
                {
                    attributes.Add(attribute);
                }
            }

            List <AttributeStore> attributePerformance = DecisionEngine.GetPerformanceAttributes(simulation.Asset, simulation.SimulationID);

            foreach (AttributeStore attribute in attributePerformance)
            {
                if (!attributes.Contains(attribute))
                {
                    attributes.Add(attribute);
                }
            }

            List <AttributeStore> attributeArea = OMS.ParseAttributes(simulation.Asset, simulation.SimulationArea);

            foreach (AttributeStore attribute in attributeArea)
            {
                if (!attributes.Contains(attribute))
                {
                    attributes.Add(attribute);
                }
            }

            //Retrieve a list of attributes that are marked as condition categories.
            List <AttributeStore> conditionCategoryAttributes = OMS.GetAssetAttributes(simulation.Asset).FindAll(delegate(AttributeStore a) { return(a.IsConditionCategory == true); });

            foreach (AttributeStore attribute in conditionCategoryAttributes)
            {
                if (!attributes.Contains(attribute))
                {
                    attributes.Add(attribute);
                }
            }


            OMSAssetConditionIndexStore oci = OMS.GetAssetConditionIndex(simulation.Asset);

            for (int i = 0; i < oci.ConditionIndexes.Count; i++)
            {
                string criteria = oci.Weights[i].Criteria;
                if (criteria != null)
                {
                    List <AttributeStore> ociCriteriaAttributes = OMS.ParseAttributes(simulation.Asset, criteria);
                    foreach (AttributeStore attribute in ociCriteriaAttributes)
                    {
                        if (!attributes.Contains(attribute))
                        {
                            attributes.Add(attribute);
                        }
                    }
                }
            }


            //Adds attributes for JurisdictionFilter
            List <AttributeStore> jurisdictionAttributes = OMS.ParseAttributes(simulation.Asset, simulation.Jurisdiction);

            foreach (AttributeStore attribute in jurisdictionAttributes)
            {
                if (!attributes.Contains(attribute))
                {
                    attributes.Add(attribute);
                }
            }


            //Add street for output display
            AttributeStore attributeStreet = OMS.GetAssetAttributes(simulation.Asset).Find(delegate(AttributeStore a) { return(a.OmsObjectUserIDHierarchy == "Street"); });

            if (attributeStreet != null && !attributes.Contains(attributeStreet))
            {
                attributes.Add(attributeStreet);
            }

            //Add ID for output display
            AttributeStore attributeID = OMS.GetAssetAttributes(simulation.Asset).Find(delegate(AttributeStore a) { return(a.OmsObjectUserIDHierarchy == "ID"); });

            if (attributeID != null && !attributes.Contains(attributeID))
            {
                attributes.Add(attributeID);
            }

            //Add Installed for calculation of AGE
            AttributeStore attributeInstalled = OMS.GetAssetAttributes(simulation.Asset).Find(delegate(AttributeStore a) { return(a.OmsObjectUserIDHierarchy == "Installed"); });

            if (attributeInstalled != null && !attributes.Contains(attributeInstalled))
            {
                attributes.Add(attributeInstalled);
            }

            //Add Replaced for calculation of AGE
            AttributeStore attributeReplaced = OMS.GetAssetAttributes(simulation.Asset).Find(delegate(AttributeStore a) { return(a.OmsObjectUserIDHierarchy == "Replaced"); });

            if (attributeReplaced != null && !attributes.Contains(attributeReplaced))
            {
                attributes.Add(attributeReplaced);
            }

            //Add gis shape for output display
            AttributeStore attributecgShape = OMS.GetAssetAttributes(simulation.Asset).Find(delegate(AttributeStore a) { return(a.OmsObjectUserIDHierarchy == "cgShape"); });

            if (attributecgShape != null && !attributes.Contains(attributecgShape))
            {
                attributes.Add(attributecgShape);
            }


            foreach (AttributeStore attribute in attributes)
            {
                string simulationID = simulation.SimulationID;
                string attribute_   = attribute.OmsObjectUserIDHierarchy;
                if (attribute.IsConditionCategory && attribute_ != "OverallConditionIndex")
                {
                    attribute_ = "__" + attribute_.Replace(" ", "").Replace("/", "");
                }
                string type_               = attribute.FieldType;
                string default_value       = "";
                string maximum             = "";
                string minimum             = "";
                bool   ascending           = attribute.Ascending;
                string format              = "";
                string isConditionCategory = attribute.IsConditionCategory.ToString();;

                if (attribute.InitialValue != null)
                {
                    default_value = attribute.InitialValue;
                }
                if (!float.IsNaN(attribute.Minimum))
                {
                    minimum = attribute.Minimum.ToString();
                }
                if (!float.IsNaN(attribute.Maximum))
                {
                    maximum = attribute.Maximum.ToString();
                }
                if (attribute.Format != null)
                {
                    format = attribute.Format;
                }


                switch (type_)
                {
                case "Time":
                case "Date":
                case "DateTime":
                    type_ = "DATETIME";
                    break;

                case "YesNo":
                case "Text":
                case "Lookup":
                case "Quantity.unit":
                    type_ = "STRING";
                    break;

                case "Number":
                case "Integer":
                case "Quantity":
                case "Currency":
                    type_ = "NUMBER";
                    break;

                default:
                    break;
                }

                try
                {
                    using (SqlConnection connection = new SqlConnection(DB.ConnectionString))
                    {
                        connection.Open();
                        string insert = "INSERT INTO " + DB.TablePrefix + "OMS_ATTRIBUTES " +
                                        "(SIMULATIONID,ATTRIBUTE_,TYPE_,DEFAULT_VALUE,MINIMUM_,MAXIMUM,ASCENDING,FORMAT,IS_CONDITION_INDEX,ATTRIBUTE_OMS)" +
                                        "VALUES('" + simulationID + "','" + attribute_ + "','" + type_ + "','" + default_value + "','" + minimum + "','" + maximum + "','" + ascending.ToString() + "','" + format + "','" + isConditionCategory + "','" + attribute.OmsHierarchy + "')";

                        SqlCommand cmd = new SqlCommand(insert, connection);
                        cmd.ExecuteNonQuery();
                    }
                }
                catch (Exception ex)
                {
                    Utility.ExceptionHandling.DataAccessExceptionHandler.HandleException(ex, false);
                }
            }
            return(attributes);
        }
Esempio n. 35
0
        public static List <AttributeStore> InitializeRoadCareAttributes(List <String> assets, List <String> additionalAttributes)
        {
            DeleteScenario.DeleteAssets("0");
            List <AttributeStore> crossAssets = new List <AttributeStore>();

            foreach (String asset in assets)
            {
                List <AttributeStore>       attributes = new List <AttributeStore>();
                OMSAssetConditionIndexStore oci        = OMS.GetAssetConditionIndex(asset);
                for (int i = 0; i < oci.ConditionIndexes.Count; i++)
                {
                    string criteria = oci.Weights[i].Criteria;
                    if (criteria != null)
                    {
                        List <AttributeStore> ociCriteriaAttributes = OMS.ParseAttributes(asset, criteria);
                        foreach (AttributeStore attribute in ociCriteriaAttributes)
                        {
                            if (!attributes.Contains(attribute))
                            {
                                attributes.Add(attribute);
                            }
                        }
                    }
                }



                //Get additional data requested.
                List <AttributeStore> attributeAsset = OMS.GetAssetAttributes(asset);
                foreach (String additionalAttribute in additionalAttributes)
                {
                    AttributeStore additional = attributeAsset.Find(delegate(AttributeStore a) { return(a.AttributeField == additionalAttribute); });
                    if (!attributes.Contains(additional))
                    {
                        if (additional != null)
                        {
                            attributes.Add(additional);
                        }
                    }

                    AttributeStore crossAsset = crossAssets.Find(delegate(AttributeStore a) { return(a.AttributeField == additionalAttribute); });
                    if (crossAsset == null)
                    {
                        if (additional != null)
                        {
                            crossAssets.Add(additional);
                        }
                    }
                }


                AssetRequestOMSDataStore assetRequest = new AssetRequestOMSDataStore(DateTime.Now, attributes, oci);
                Dictionary <string, AssetReplyOMSLookupTable> assetLookups = OMS.GetAssetLookupData(assetRequest);
                List <AssetReplyOMSDataStore> assetsFromRequest            = OMS.GetAssetData(assetRequest);
                List <AssetReplyOMSDataStore> assetsWithCondition          = assetsFromRequest.FindAll(delegate(AssetReplyOMSDataStore arods) { return(arods.ConditionIndices != null); });

                PrepareAnalysis.Assets("0", assetsWithCondition, attributes, assetRequest, assetLookups, false);
            }

            //Do something with cross attributes.
            AttributeStore assetType = new AttributeStore(null, "AssetType", "AssetType", null);

            assetType.FieldType = "Text";
            crossAssets.Add(assetType);

            AttributeStore overallConditionIndex = new AttributeStore(null, "OverallConditionIndex", "OverallConditionIndex", null);

            overallConditionIndex.FieldType    = "Number";
            overallConditionIndex.Minimum      = 0;
            overallConditionIndex.Maximum      = 100;
            overallConditionIndex.Format       = "f1";
            overallConditionIndex.InitialValue = "100";
            overallConditionIndex.Ascending    = true;
            crossAssets.Add(overallConditionIndex);


            foreach (String asset in assets)
            {
                OMSAssetConditionIndexStore oci = OMS.GetAssetConditionIndex(asset);

                foreach (OMSConditionIndexStore ci  in oci.ConditionIndexes)
                {
                    String         conditionIndex          = "__" + ci.ConditionCategory.Replace(" ", "").Replace("/", "");
                    AttributeStore attributeConditionIndex = crossAssets.Find(delegate(AttributeStore a) { return(a.OmsObjectUserIDHierarchy == conditionIndex); });
                    if (attributeConditionIndex == null)
                    {
                        attributeConditionIndex           = new AttributeStore(null, conditionIndex, conditionIndex, null);
                        attributeConditionIndex.FieldType = "Number";
                        crossAssets.Add(attributeConditionIndex);
                    }
                }
            }
            return(crossAssets);
        }