Пример #1
0
        public void AddRepeatField(uint handle, int nRepeat)
        {
            if (!this.m_bIsSet || (int)handle == 0)
            {
                return;
            }
            switch (this.eDataType)
            {
            case CPostItem.DataType.RepeatSTRING:
                this.sValue = StringManip.RemInvalidChar(this.sValue);
                this.GetLink().TablePOST_AddRecurringField_ValueString(handle, this.sLinkName, nRepeat, this.sValue);
                break;

            case CPostItem.DataType.RepeatLONG:
                this.GetLink().TablePOST_AddRecurringField_ValueI32(handle, this.sLinkName, nRepeat, this.nValue);
                break;

            case CPostItem.DataType.RepeatDOUBLE:
                this.GetLink().TablePOST_AddRecurringField_ValueDOUBLE(handle, this.sLinkName, nRepeat, this.dValue);
                break;

            case CPostItem.DataType.RepeatBOOL:
                this.GetLink().TablePOST_AddRecurringField_ValueBOOL(handle, this.sLinkName, nRepeat, this.bValue ? 1 : 0);
                break;
            }
            this.Clear();
        }
Пример #2
0
    public override void Run()
    {
        _IsRunning = true;

        // We need to run ConToSim first. When it has finished then we can
        // let the base class run APSIM.

        SimFileName = Path.Combine(Directory.GetCurrentDirectory(),
                                   Path.GetDirectoryName(_ConFileName),
                                   Path.GetFileNameWithoutExtension(_ConFileName) + "."
                                   + _SimulationName + ".sim");

        _ConFileName     = Path.Combine(Directory.GetCurrentDirectory(), _ConFileName);
        _ConToSimProcess = new ProcessCaller(Application.OpenForms[0]);
        if (Configuration.getArchitecture() == Configuration.architecture.unix)
        {
            _ConToSimProcess.FileName  = "mono";
            _ConToSimProcess.Arguments = StringManip.DQuote(Configuration.RemoveMacros(Path.Combine("%apsim%", "Model", "ConToSim.exe")))
                                         + " " + StringManip.DQuote(_ConFileName) + " " + StringManip.DQuote(_SimulationName);
        }
        else
        {
            _ConToSimProcess.FileName  = Configuration.RemoveMacros(Path.Combine("%apsim%", "Model", "ConToSim.exe"));
            _ConToSimProcess.Arguments = StringManip.DQuote(_ConFileName) + " " + StringManip.DQuote(_SimulationName);
        }
        _ConToSimProcess.AllFinished    += OnConToSimExited;
        _ConToSimProcess.StdOutReceived += OnStdOut;
        _ConToSimProcess.StdErrReceived += OnStdError;
        _ConToSimProcess.Start();
    }
Пример #3
0
        /// <summary>
        /// Create a job for each simulation in the specified .con file.
        /// </summary>
        private void CreateJobsFromCON(string FileName, string[] SimulationPaths, ref List <IJob> jobs)
        {
            // Run ConToSim first.
            string  ConToSimExe = Path.Combine(Configuration.ApsimBinDirectory(), "ConToSim.exe");
            Process ConToSim    = Utility.RunProcess(ConToSimExe,
                                                     StringManip.DQuote(FileName),
                                                     Path.GetDirectoryName(FileName));

            Utility.CheckProcessExitedProperly(ConToSim);

            // If no paths were specified then get a list of all paths.
            if (SimulationPaths == null || SimulationPaths.Length == 0)
            {
                List <String> AllPaths = new List <String> ();
                AllPaths        = ConFile.GetSimsInConFile(FileName);
                SimulationPaths = AllPaths.ToArray();
            }

            // Create a series of jobs for each simulation in the .con file.
            foreach (string SimulationPath in SimulationPaths)
            {
                string SimFileName = Path.Combine(Path.GetDirectoryName(FileName),
                                                  Path.GetFileNameWithoutExtension(FileName) + "." + SimulationPath + ".sim");
                Job J = CreateJob(SimFileName, SimFileName.Replace(".sim", ".sum"));
                jobs.Add(J);
                J = CleanupJob(SimFileName, J.Name);
                jobs.Add(J);
            }
        }
Пример #4
0
 public void OnInitialised()
 {
     co2 = 350;
     inputFile.Open(inputFilename);
     MaxTIndex = StringManip.IndexOfCaseInsensitive(inputFile.Headings, "Maxt");
     MinTIndex = StringManip.IndexOfCaseInsensitive(inputFile.Headings, "Mint");
     RadnIndex = StringManip.IndexOfCaseInsensitive(inputFile.Headings, "Radn");
     RainIndex = StringManip.IndexOfCaseInsensitive(inputFile.Headings, "Rain");
     if (MaxTIndex == -1)
     {
         throw new Exception("Cannot find MaxT in weather file: " + inputFilename);
     }
     if (MinTIndex == -1)
     {
         throw new Exception("Cannot find MinT in weather file: " + inputFilename);
     }
     if (RadnIndex == -1)
     {
         throw new Exception("Cannot find Radn in weather file: " + inputFilename);
     }
     if (RainIndex == -1)
     {
         throw new Exception("Cannot find Rain in weather file: " + inputFilename);
     }
 }
Пример #5
0
        // ------------------------------------------------------------
        // Read in all crop parameters from all crop sections in
        // specified file
        // ------------------------------------------------------------
        static private void ReadCropSections(string SectionBit, string FileName, Soil NewSoil)
        {
            string[] Sections = ApsimFile.IniFile.INIReadAllSections(FileName);
            foreach (string Section in Sections)
            {
                if (ApsimFile.IniFile.INIRead(FileName, Section, "ll") != "")
                {
                    // get the crop name
                    StringCollection SectionBits = StringManip.SplitStringHonouringQuotes(Section, ".");
                    if (SectionBits.Count == 3 && SectionBits[0].ToLower() == SectionBit.ToLower())
                    {
                        string CropName = SectionBits[1];
                        NewSoil.AddCrop(CropName);

                        double[] ll;
                        string   LLValue = GetStringValue(FileName, Section, "ll");
                        if (LLValue.ToLower() == "#ll")
                        {
                            ll = NewSoil.LL15;
                        }
                        else
                        {
                            ll = GetDoubleValues(FileName, Section, "ll");
                        }

                        NewSoil.SetCrop(CropName,
                                        ll,
                                        GetDoubleValues(FileName, Section, "kl"),
                                        GetDoubleValues(FileName, Section, "xf"));
                    }
                }
            }
        }
Пример #6
0
    /// <summary>
    /// A function for reading the filenames in a patch and returning their revision number.
    /// </summary>
    public static string[] FilesInPatch(string PatchFileName, string RootDirectory)
    {
        List <string> FileNames = new List <string>();

        StreamReader Patch = new StreamReader(PatchFileName);

        // Go looking for lines like:
        //    --- Tests/RunAllPlant2Tests.txt	(revision 1790)
        while (!Patch.EndOfStream)
        {
            string Line = Patch.ReadLine();
            if (Line.Contains("--- "))
            {
                Line = Line.Remove(0, 4);
                string   FileName       = Line;
                string   BracketedValue = StringManip.SplitOffBracketedValue(ref FileName, '(', ')');
                string[] RevisionBits   = BracketedValue.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                if (RevisionBits.Length == 2)
                {
                    FileName = Path.Combine(RootDirectory, FileName);
                    FileName = FileName.Replace("/", "\\");  // get rid of yucky unix slashes.
                    FileNames.Add(FileName);
                }
            }
        }
        Patch.Close();
        return(FileNames.ToArray());
    }
Пример #7
0
        public void GetField(uint handle)
        {
            object szValue = new object();

            if ((int)handle == 0)
            {
                return;
            }
            this.m_bIsSet = false;
            switch (this.eDataType)
            {
            case CPostItem.DataType.STRING:
                this.GetLink().TableGET_RecordField_ValueString(handle, this.sLinkName, "", ref szValue);
                this.sValue   = szValue.ToString();
                this.sValue   = StringManip.RemInvalidChar(this.sValue);
                this.m_bIsSet = true;
                break;

            case CPostItem.DataType.LONG:
                this.nValue   = this.GetLink().TableGET_RecordField_ValueI32(handle, this.sLinkName);
                this.m_bIsSet = true;
                break;

            case CPostItem.DataType.DOUBLE:
                this.dValue   = this.GetLink().TableGET_RecordField_ValueDOUBLE(handle, this.sLinkName);
                this.m_bIsSet = true;
                break;

            case CPostItem.DataType.BOOL:
                this.bValue   = this.GetLink().TableGET_RecordField_ValueBOOL(handle, this.sLinkName) != 0;
                this.m_bIsSet = true;
                break;
            }
        }
Пример #8
0
        private void ReadApsimHeaderLines(StreamReaderRandomAccess In,
                                          ref StringCollection ConstantLines,
                                          ref StringCollection HeadingLines)
        {
            string PreviousLine = "";

            string Line = In.ReadLine();

            while (Line != "" || !In.EndOfStream)
            {
                int PosEquals = Line.IndexOf('=');
                if (PosEquals != -1)
                {
                    // constant found.
                    ConstantLines.Add(Line);
                }
                else
                {
                    char[] whitespace           = { ' ', '\t' };
                    int    PosFirstNonBlankChar = StringManip.IndexNotOfAny(Line, whitespace);
                    if (PosFirstNonBlankChar != -1 && Line[PosFirstNonBlankChar] == '(')
                    {
                        HeadingLines.Add(PreviousLine);
                        HeadingLines.Add(Line);
                        break;
                    }
                }
                PreviousLine = Line;
                Line         = In.ReadLine();
            }
        }
Пример #9
0
    /// <summary>
    /// Look for a "kind" attribute on the specified node and return an
    /// equivalent c# type name. Returns blank on error.
    /// </summary>
    private static string GetDotNetType(XmlNode Node)
    {
        if (Node != null)
        {
            string CMPTypeName = XmlHelper.Attribute(Node, "kind");
            switch (CMPTypeName)
            {
            case "boolean": CMPTypeName = "Boolean"; break;

            case "single": CMPTypeName = "Single"; break;

            case "double": CMPTypeName = "Double"; break;

            case "integer4": CMPTypeName = "Int32"; break;

            case "string": CMPTypeName = "String"; break;

            default: return(StringManip.CamelCase(CMPTypeName + "Type"));
            }
            if (XmlHelper.Attribute(Node, "array").ToLower() == "t")
            {
                CMPTypeName += "[]";
            }
            return(CMPTypeName);
        }
        return("");
    }
Пример #10
0
        private void AddFieldNameToAxisTitle(Steema.TeeChart.Axis Axis, string FieldName)
        {
            // Add the specified fieldname to the specified axis.
            Axis.Visible = true;
            if (Axis.Title.Text.Length > 0 && Axis.Title.Text[0] == '[' && FieldName != "")
            {
                string   St         = Axis.Title.Text;
                string   Title      = StringManip.SplitOffBracketedValue(ref St, '[', ']');
                string[] FieldNames = Title.Split(",".ToCharArray());

                if (FieldName != "seriesname")
                {
                    bool Found = false;
                    foreach (string F in FieldNames)
                    {
                        if (F.Trim().ToLower() == FieldName.ToLower())
                        {
                            Found = true;
                        }
                    }
                    if (!Found)
                    {
                        if (Title != "")
                        {
                            Title = Title + ", ";
                        }
                        Title           = Title + FieldName;
                        Axis.Title.Text = "[" + Title + "]";
                    }
                }
            }
        }
Пример #11
0
        /// <summary>
        /// Add our constants to every row in the specified table beginning with the specified StartRow.
        /// </summary>
        public void AddConstantsToData(DataTable Table)
        {
            const string VersionName = "ApsimVersion"; // We want to treat ApsimVersion as a string, not a numeric, to versions like "7.10" display correctly

            foreach (APSIMConstant Constant in Constants)
            {
                Type ColumnType = StringManip.DetermineType(Constant.Value, "");
                if (Constant.Name.Equals(VersionName))
                {
                    ColumnType = typeof(String);
                }
                if (Table.Columns.IndexOf(Constant.Name) == -1)
                {
                    Table.Columns.Add(new DataColumn(Constant.Name, ColumnType));
                }
                for (int Row = 0; Row < Table.Rows.Count; Row++)
                {
                    double Value;
                    if (ColumnType != typeof(String) && Double.TryParse(Constant.Value, NumberStyles.Float, new CultureInfo("en-US"), out Value))
                    {
                        Table.Rows[Row][Constant.Name] = Value;
                    }
                    else
                    {
                        Table.Rows[Row][Constant.Name] = Constant.Value;
                    }
                }
            }
        }
Пример #12
0
    public static void InsertClassCodeIntoDotNetProxyFile(string ClassName, string ClassSourceCode)
    {
        if (ClassSourceCode != "")
        {
            ClassName = StringManip.CamelCase(ClassName);

            // Go open the proxy source file and read it's contents.
            string Contents = "";
            if (File.Exists(WriteableBaseProxyFileName))
            {
                StreamReader In = new StreamReader(WriteableBaseProxyFileName);
                Contents = In.ReadToEnd();
                In.Close();
            }
            if (Contents == "")
            {
                Contents = "using System;\r\n" +
                           "using System.Collections.Generic;\r\n" +
                           "using System.Text;\r\n" +
                           "using System.Runtime.InteropServices;\r\n" +
                           "#pragma warning disable 67 // Suppress warning messages about unused events\r\n" +
                           "namespace ModelFramework {\r\n" +
                           "}\r\n";
            }

            // See if we can find an existing class in the source code.
            int PosStartClass = Contents.IndexOf("public class " + ClassName + " ");
            if (PosStartClass != -1)
            {
                int PosStartAttribute = Contents.LastIndexOf("[ComponentType", PosStartClass);
                int PosOpenBracket    = Contents.IndexOf("{", PosStartClass);
                int PosEndClass       = StringManip.FindMatchingClosingBracket(Contents, PosStartClass, '{', '}');
                if (PosEndClass != -1)
                {
                    if (PosStartAttribute != -1)
                    {
                        PosStartClass = PosStartAttribute;
                    }
                    Contents = Contents.Remove(PosStartClass, PosEndClass - PosStartClass + 5); // also removes 2 x \r\n
                }
            }

            // Remove the last curly bracket - namespace bracket. We'll add it in later.
            int PosLastBracket = Contents.LastIndexOf('}');
            if (PosLastBracket == -1)
            {
                throw new Exception("Cannot find namespace in DotNetProxies.cs");
            }
            Contents = Contents.Remove(PosLastBracket);

            // Now add in our class and closing bracket for namespace.
            Contents = Contents + ClassSourceCode + "\r\n}";

            // Write contents back to proxy file
            StreamWriter Out = new StreamWriter(WriteableBaseProxyFileName);
            Out.Write(Contents);
            Out.Close();
        }
    }
Пример #13
0
        /// <summary>
        /// Transfer a single parameter value (as specified by oldnode and oldpath) to a new
        /// node and path.
        /// </summary>
        private static void TransferParameter(XmlNode OldNode, string OldPath,
                                              XmlNode NewNode, string NewPath)
        {
            string Value = XmlHelper.Value(OldNode, OldPath);

            StringManip.SplitOffBracketedValue(ref Value, '(', ')');
            XmlHelper.SetValue(NewNode, NewPath, Value);
        }
Пример #14
0
    /// <summary>
    /// User has clicked ok - create patch.
    /// </summary>
    private void OnOKButtonClick(object sender, EventArgs e)
    {
        if (SaveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            try
            {
                string DirectoryName = Directory.GetCurrentDirectory();

                bool         SomeAreOutOfDate  = false;
                string       RevisionsFileName = Path.Combine(Directory.GetCurrentDirectory(), "patch.revisions");
                StreamWriter Revisions         = new StreamWriter(RevisionsFileName);

                List <string> FileNames = new List <string>();
                FileNames.Add(Path.GetFileName(RevisionsFileName));
                foreach (ListViewItem Item in ListView.Items)
                {
                    if (Item.Checked)
                    {
                        string Status = Item.SubItems[3].Text;
                        if (Status != "Deleted")
                        {
                            FileNames.Add(Item.Text);
                        }
                        Revisions.WriteLine(StringManip.DQuote(Item.Text) + " " + Status + " " + Item.SubItems[4].Text);
                        if (Item.SubItems[3].Text == "OutOfDate")
                        {
                            SomeAreOutOfDate = true;
                        }
                    }
                }

                Revisions.Close();

                saveSelections();
                if (SomeAreOutOfDate)
                {
                    MessageBox.Show("Some of the selected files are out of date. You need to do an SVN update before submitting a patch to Bob.",
                                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    // Zip all files.
                    Zip.ZipFilesWithDirectories(FileNames, SaveFileDialog.FileName, "");

                    if (MessageBox.Show("Patch file successfully created. Upload to Bob?", "Success", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        Process.Start("http://www.apsim.info/APSIM.Builds.Portal/Upload.aspx");
                    }
                    Close();
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
Пример #15
0
        /// <summary>
        /// Setup the grid as a water grid.
        /// </summary>
        private void AddCropColumns()
        {
            Color[] CropColors          = { Color.FromArgb(173, 221, 142), Color.FromArgb(247, 252, 185) };
            Color[] PredictedCropColors = { Color.FromArgb(233, 191, 255), Color.FromArgb(244, 226, 255) };

            //            DataGridViewColumn SAT = Grid.Columns["SAT\r\n(mm/mm)"];
            //            SAT.Frozen = true;
            Grid.Columns[Grid.ColumnCount - 1].Frozen = true;

            int CropIndex          = 0;
            int PredictedCropIndex = 0;

            foreach (string CropName in Soil.CropNames.Union(Soil.PredictedCropNames, StringComparer.OrdinalIgnoreCase))
            {
                SoilCrop Crop = Soil.Crop(CropName);

                bool  IsReadonly;
                Color CropColour;
                Color ForeColour = Color.Black;
                if (Crop.LLMetadata != null && Crop.LLMetadata.First() == "Estimated")
                {
                    CropColour = PredictedCropColors[PredictedCropIndex];
                    ForeColour = Color.Gray;
                    IsReadonly = true;
                    PredictedCropIndex++;
                    if (PredictedCropIndex >= PredictedCropColors.Length)
                    {
                        PredictedCropIndex = 0;
                    }
                }
                else
                {
                    CropColour = CropColors[CropIndex];
                    IsReadonly = false;
                    CropIndex++;
                    if (CropIndex >= CropColors.Length)
                    {
                        CropIndex = 0;
                    }
                }

                double[] PAWCmm = MathUtility.Multiply(Soil.PAWCCropAtWaterThickness(CropName),
                                                       Soil.Water.Thickness);

                DataGridViewColumn LL   = GridUtility.AddColumn(Grid, CropName + " LL\r\n(mm/mm)", Crop.LL, "f3", CropColour, ForeColour, ToolTips: Crop.LLMetadata, ReadOnly: IsReadonly);
                DataGridViewColumn PAWC = GridUtility.AddColumn(Grid, CropName + " PAWC\r\n", PAWCmm, "f1", CropColour, Color.Gray,
                                                                ReadOnly: true,
                                                                ToolTips: StringManip.CreateStringArray("Calculated from crop LL and DUL", PAWCmm.Length));
                DataGridViewColumn KL = GridUtility.AddColumn(Grid, CropName + " KL\r\n(/day)", Crop.KL, "f2", CropColour, ForeColour, ToolTips: Crop.KLMetadata, ReadOnly: IsReadonly);
                DataGridViewColumn XF = GridUtility.AddColumn(Grid, CropName + " XF\r\n(0-1)", Crop.XF, "f1", CropColour, ForeColour, ToolTips: Crop.XFMetadata, ReadOnly: IsReadonly);

                PAWC.ToolTipText = "Calculated from crop LL and DUL";
                PAWC.ReadOnly    = true;
                UpdateTotal(PAWC);
            }
        }
Пример #16
0
 private static Type DetermineTypeOfColumn(SheetView Grid, int Col)
 {
     for (int Row = 0; Row != Grid.Rows.Count; Row++)
     {
         if (Grid.Cells[Row, Col].Text != "")
         {
             return(StringManip.DetermineType(Grid.Cells[Row, Col].Text, ""));
         }
     }
     return(typeof(string));
 }
Пример #17
0
 private static Type DetermineTypeOfColumn(DataGridView Grid, int Col)
 {
     for (int Row = 0; Row != Grid.Rows.Count; Row++)
     {
         if (Grid.Rows[Row].Cells[Col].Value != null)
         {
             return(StringManip.DetermineType(Grid.Rows[Row].Cells[Col].Value.ToString(), ""));
         }
     }
     return(typeof(string));
 }
Пример #18
0
        private static void Main(string[] args)
        {
            if (args is null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            //string code = "Drysdale Chivhanga";

            Console.WriteLine(StringManip.GetRandomAlphaNumeralString(26));
        }
Пример #19
0
        /// <summary>
        /// Remove comments and units from the specified string.
        /// </summary>
        private static string RemoveComment(string Value)
        {
            int PosComment = Value.IndexOf('!');

            if (PosComment != -1)
            {
                Value = Value.Remove(PosComment);
            }

            StringManip.SplitOffBracketedValue(ref Value, '(', ')');
            return(Value);
        }
Пример #20
0
        /// <summary>
        /// Import from specified par file and returns valid soil XML file.
        /// </summary>
        static public string Import(string FileName)
        {
            if (!File.Exists(FileName))
            {
                throw new Exception("Cannot import file " + FileName + ". File doesn't exist");
            }
            string[] Sections = IniFile.INIReadAllSections(FileName);

            // import all water sections.
            string XmlForAllSoils = "";

            foreach (string Section in Sections)
            {
                if (GetStringValue(FileName, Section, "dlayer") != "")
                {
                    StringCollection SectionBits = StringManip.SplitStringHonouringQuotes(Section, ".");
                    if (SectionBits.Count == 3)
                    {
                        if (SectionBits[1].ToLower() == "soilwat2")
                        {
                            string SoilName = SectionBits[0];
                            Soil   NewSoil  = new Soil();
                            NewSoil.Name = SoilName;

                            // Add in a soil sample node.
                            Sample NewSample = new Sample();
                            NewSample.Thickness = new double[] { 100 };
                            NewSample.SW        = new double[] { 0 };
                            NewSample.NO3       = new double[] { 0 };
                            NewSample.NH4       = new double[] { 0 };
                            NewSoil.Samples.Add(NewSample);

                            // Add in a phosphorus node.
                            NewSoil.Phosphorus           = new Phosphorus();
                            NewSoil.Phosphorus.Thickness = new double[] { 100 };
                            NewSoil.Phosphorus.LabileP   = new double[] { 5 };
                            NewSoil.Phosphorus.Sorption  = new double[] { 50 };
                            NewSoil.Phosphorus.BandedP   = new double[] { 0 };
                            NewSoil.Phosphorus.RockP     = new double[] { 0 };


                            double[] Thickness = ReadWaterSection(SoilName, FileName, NewSoil);
                            NewSoil.Water.Thickness = Thickness;
                            ReadNitrogenSection(SoilName, FileName, NewSoil, Thickness);
                            ReadCropSections(SoilName, FileName, NewSoil, Thickness);
                            ReadPhosphorusSection(SoilName, FileName, NewSoil, Thickness);
                            XmlForAllSoils += NewSoil.ToXml();
                        }
                    }
                }
            }
            return(XmlForAllSoils);
        }
Пример #21
0
        /// <summary>
        /// Convert the specified words to the specified column types and return their values.
        /// </summary>
        private object[] ConvertWordsToObjects(StringCollection Words, Type[] ColumnTypes)
        {
            object[] Values = new object[Words.Count];
            for (int w = 0; w != Words.Count; w++)
            {
                try
                {
                    Words[w] = Words[w].Trim();
                    if (Words[w] == "?" || Words[w] == "*" || Words[w] == "")
                    {
                        Values[w] = DBNull.Value;
                    }

                    else if (ColumnTypes[w] == typeof(DateTime))
                    {
                        // Need to get a sanitised date e.g. d/M/yyyy
                        string DateFormat = Units[w].ToLower();
                        DateFormat = StringManip.SplitOffBracketedValue(ref DateFormat, '(', ')');
                        DateFormat = DateFormat.Replace("mmm", "MMM");
                        DateFormat = DateFormat.Replace("mm", "m");
                        DateFormat = DateFormat.Replace("dd", "d");
                        DateFormat = DateFormat.Replace("m", "M");
                        if (DateFormat == "")
                        {
                            DateFormat = "d/M/yyyy";
                        }
                        DateTime Value = DateTime.ParseExact(Words[w], DateFormat, null);
                        Values[w] = Value;
                    }
                    else if (ColumnTypes[w] == typeof(System.Double))
                    {
                        double Value;
                        if (double.TryParse(Words[w], out Value))
                        {
                            Values[w] = Value;
                        }
                        else
                        {
                            Values[w] = DBNull.Value;
                        }
                    }
                    else
                    {
                        Values[w] = Words[w];
                    }
                }
                catch (Exception)
                {
                    Values[w] = DBNull.Value;
                }
            }
            return(Values);
        }
Пример #22
0
 /// <summary>
 ///  Return the PH units from the specified row on the specified table.
 /// </summary>
 private static Analysis.PHUnitsEnum GetPHUnits(DataTable Table, int Row)
 {
     if (Table.Columns.Contains("PHCode"))
     {
         string Code  = GetStringValue(Table, Row, "PHCode");
         string Units = StringManip.SplitOffBracketedValue(ref Code, '(', ')');
         if (Units == "CaCl2")
         {
             return(Analysis.PHUnitsEnum.CaCl2);
         }
     }
     return(Analysis.PHUnitsEnum.Water);
 }
Пример #23
0
 /// <summary>
 /// Return the OC units from the specified row on the specified table.
 /// </summary>
 private static SoilOrganicMatter.OCUnitsEnum GetOCUnits(DataTable Table, int Row)
 {
     if (Table.Columns.Contains("OCCode"))
     {
         string Code  = GetStringValue(Table, Row, "OCCode");
         string Units = StringManip.SplitOffBracketedValue(ref Code, '(', ')');
         if (Units == "Walkley Black %")
         {
             return(SoilOrganicMatter.OCUnitsEnum.WalkleyBlack);
         }
     }
     return(SoilOrganicMatter.OCUnitsEnum.Total);
 }
Пример #24
0
        public void SetConstant(string ConstantName, string ConstantValue)
        {
            // -------------------------------------
            // Set a given constant's value.
            // -------------------------------------

            foreach (APSIMConstant c in _Constants)
            {
                if (StringManip.StringsAreEqual(c.Name, ConstantName))
                {
                    c.Value = ConstantValue;
                }
            }
        }
Пример #25
0
        // ----------------------------------------------------------
        // Get string value from specified table for specified field.
        // ----------------------------------------------------------
        static private string GetStringValue(string FileName, string SectionName, string Key)
        {
            string Value = ApsimFile.IniFile.INIRead(FileName, SectionName, Key);

            StringManip.SplitOffAfterDelimiter(ref Value, "!");
            StringManip.SplitOffAfterDelimiter(ref Value, "(");
            Value = Value.Replace("\t", "   ");
            if (Value.StartsWith("$"))
            {
                Value = ResolveVariableMacro(FileName, Value);
            }

            return(Value);
        }
Пример #26
0
        /// <summary>
        /// delete a file after a job has finished
        /// </summary>
        private Job CleanupJob(string FileName, string JobName)
        {
            // create job and return it.
            Job J = new Job();

            J.CommandLine     = "%ComSpec% /c del " + StringManip.DQuote(FileName);
            J.CommandLineUnix = "/bin/rm -f " + StringManip.DQuote(FileName);

            J.WorkingDirectory = Path.GetDirectoryName(FileName);
            J.Name             = "Delete " + FileName;
            J.DependsOn        = new List <DependsOn> ();
            J.DependsOn.Add(new DependsOn(JobName));
            return(J);
        }
Пример #27
0
        /// <summary>
        /// Create and return a job to run APSIM.
        /// </summary>
        private Job CreateJob(string FileName, string SumFileName, string SimulationPath = null)
        {
            NumApsimRuns++;

            string Executable = Path.Combine(Configuration.ApsimBinDirectory(), "ApsimModel.exe");

            // Create arguments
            string Arguments = StringManip.DQuote(FileName);

            if (SimulationPath != null)
            {
                Arguments += " " + StringManip.DQuote("Simulation=" + SimulationPath);
            }

            if (MaxLinesInSummaryFile > 0)
            {
                Arguments += " MaxOutputLines=" + MaxLinesInSummaryFile.ToString();
            }

            // create job and return it.
            Job J = new Job();

            J.CommandLine      = StringManip.DQuote(Executable) + " " + Arguments;
            J.WorkingDirectory = Path.GetDirectoryName(FileName);
            // A UNC Path cannot be used as the working directory,
            // so test for this and use the LocalApplicationData folder instead.
            // This folder is reasonably likely to have a non-UNC path, since it is
            // intended to be "local".
            Uri  URI   = null;
            bool isUNC = Uri.TryCreate(J.WorkingDirectory, UriKind.Absolute, out URI) && URI.IsUnc;

            if (isUNC)
            {
                J.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            }
            J.Name = FileName + ":";
            if (SimulationPath == null)
            {
                J.Name += Path.GetFileNameWithoutExtension(SumFileName);
            }
            else
            {
                J.Name += SimulationPath;
            }
            J.IgnoreErrors   = true;
            J.maxLines       = MaxLinesInSummaryFile;
            J.StdOutFilename = SumFileName;
            return(J);
        }
Пример #28
0
        public APSIMConstant Constant(string ConstantName)
        {
            // -------------------------------------
            // Return a given constant to caller
            // -------------------------------------

            foreach (APSIMConstant c in _Constants)
            {
                if (StringManip.StringsAreEqual(c.Name, ConstantName))
                {
                    return(c);
                }
            }
            return(null);
        }
Пример #29
0
 public RunEntireApsimFileJob(string ApsimFileName, JobRunner JobRunner)
     : base(Path.GetFileName(ApsimFileName), JobRunner)
 {
     _ApsimFileName = ApsimFileName;
     if (Configuration.getArchitecture() == Configuration.architecture.unix)
     {
         _Executable = "mono";
         _Arguments  = StringManip.DQuote(_Executable) + " " + StringManip.DQuote(_ApsimFileName);
     }
     else
     {
         _Executable = Configuration.RemoveMacros(Path.Combine("%apsim%", "Model", "ApsimToSim.exe"));
         _Arguments  = StringManip.DQuote(_ApsimFileName);
     }
 }
Пример #30
0
 protected void WriteLogMessage()
 {
     Console.WriteLine("[" + _Status + "] " + Name + " [" + ElapsedTime.ToString() + "sec]");
     if (Status == Status_t.Fail)
     {
         if (StdOut.Length > 0)
         {
             Console.WriteLine(StringManip.IndentText(StdOut.ToString(), 4));
         }
         if (StdErr.Length > 0)
         {
             Console.WriteLine(StringManip.IndentText(StdErr.ToString(), 4));
         }
     }
 }