コード例 #1
0
        /// <summary>
        /// Run tests
        /// </summary>
        /// <param name="accept">If true, the stats from this run will be written to file as the accepted stats.</param>
        /// <param name="GUIrun">If true, do not raise an exception on test failure.</param>
        public void Test(bool accept = false, bool GUIrun = false)
        {
            PredictedObserved PO = Parent as PredictedObserved;

            if (PO == null)
            {
                return;
            }
            IStorageReader DS = PO.Parent as IStorageReader;

            MathUtilities.RegrStats[] stats;
            List <string>             statNames = (new MathUtilities.RegrStats()).GetType().GetFields().Select(f => f.Name).ToList(); // use reflection, get names of stats available
            DataTable     POtable = DS.GetData(PO.Name);
            List <string> columnNames;
            string        sigIdent = "X";

            if (POtable == null)
            {
                object sim = PO.Parent;
                while (sim as Simulations == null)
                {
                    sim = ((Model)sim).Parent;
                }

                throw new ApsimXException(this, "Could not find PO table in " + (sim != null ? ((Simulations)sim).FileName : "<unknown>") + ". Has the simulation been run?");
            }
            columnNames = POtable.Columns.Cast <DataColumn>().Select(c => c.ColumnName).ToList(); //get list of column names
            columnNames = columnNames.Where(c => c.Contains("Observed")).ToList();                //filter names that are not pred/obs pairs
            for (int i = 0; i < columnNames.Count; i++)
            {
                columnNames[i] = columnNames[i].Replace("Observed.", "");
            }
            columnNames.Sort(); //ensure column names are always in the same order
            columnNames.Remove("CheckpointID");
            stats = new MathUtilities.RegrStats[columnNames.Count];
            List <double> x = new List <double>();
            List <double> y = new List <double>();
            string        xstr, ystr;
            double        xres;
            double        yres;

            for (int c = 0; c < columnNames.Count; c++) //on each P/O column pair
            {
                string observedFieldName  = "Observed." + columnNames[c];
                string predictedFieldName = "Predicted." + columnNames[c];
                if (POtable.Columns.Contains(observedFieldName) &&
                    POtable.Columns.Contains(predictedFieldName))
                {
                    x.Clear();
                    y.Clear();
                    foreach (DataRow row in POtable.Rows)
                    {
                        xstr = row[observedFieldName].ToString();
                        ystr = row[predictedFieldName].ToString();
                        if (Double.TryParse(xstr, out xres) && Double.TryParse(ystr, out yres))
                        {
                            x.Add(xres);
                            y.Add(yres);
                        }
                    }
                    if (x.Count == 0 || y.Count == 0)
                    {
                        continue;
                    }

                    stats[c] = MathUtilities.CalcRegressionStats(columnNames[c], y, x);
                }
            }

            //remove any null stats which can occur from non-numeric columns such as dates
            List <MathUtilities.RegrStats> list = new List <MathUtilities.RegrStats>(stats);

            list.RemoveAll(l => l == null);
            stats = list.ToArray();

            //remove entries from column names
            for (int i = columnNames.Count() - 1; i >= 0; i--)
            {
                bool found = false;
                for (int j = 0; j < stats.Count(); j++)
                {
                    if (columnNames[i] == stats[j].Name)
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    columnNames.RemoveAt(i);
                }
            }

            //turn stats array into a DataTable
            //first, check if there is already an AcceptedStats array, create if not.
            //If the names don't match, then use current stats as user has dragged
            //an already existing Test to a new node.
            if (AcceptedStats == null || POName != PO.Name)
            {
                POName            = PO.Name;
                AcceptedStats     = stats;
                AcceptedStatsName = StringUtilities.Build(statNames, " ");
            }

            //then make sure the names and order of the accepted stats are the same as the new ones.
            if (StringUtilities.Build(statNames, " ") != AcceptedStatsName)
            {
                throw new ApsimXException(this, "Names, number or order of accepted stats do not match class MathUtilities.RegrStats. The class has probably changed.");
            }

            Table = new DataTable("StatTests");
            Table.Columns.Add("Name", typeof(string));
            Table.Columns.Add("Variable", typeof(string));
            Table.Columns.Add("Test", typeof(string));
            Table.Columns.Add("Accepted", typeof(double));
            Table.Columns.Add("Current", typeof(double));
            Table.Columns.Add("Difference", typeof(double));
            Table.Columns.Add("Fail?", typeof(string));

            double    accepted;
            double    current;
            DataTable AcceptedTable             = Table.Copy();
            DataTable CurrentTable              = Table.Copy();

            //accepted table
            for (int i = 0; i < AcceptedStats.Count(); i++)
            {
                for (int j = 1; j < statNames.Count; j++) //start at 1; we don't want Name field.
                {
                    accepted = Convert.ToDouble(AcceptedStats[i].GetType().GetField(statNames[j]).GetValue(AcceptedStats[i]),
                                                System.Globalization.CultureInfo.InvariantCulture);
                    AcceptedTable.Rows.Add(PO.Name,
                                           AcceptedStats[i].Name,
                                           statNames[j],
                                           accepted,
                                           null,
                                           null,
                                           null);
                }
            }

            //current table
            Table = AcceptedTable.Copy();
            int rowIndex = 0;

            for (int i = 0; i < stats.Count(); i++)
            {
                for (int j = 1; j < statNames.Count; j++) //start at 1; we don't want Name field.
                {
                    current = Convert.ToDouble(stats[i].GetType().GetField(statNames[j]).GetValue(stats[i]),
                                               System.Globalization.CultureInfo.InvariantCulture);
                    CurrentTable.Rows.Add(PO.Name,
                                          stats[i].Name,
                                          statNames[j],
                                          null,
                                          current,
                                          null,
                                          null);
                    Table.Rows[rowIndex]["Current"] = current;
                    rowIndex++;
                }
            }

            //Merge overwrites rows, so add the correct data back in
            foreach (DataRow row in Table.Rows)
            {
                DataRow[] rowAccepted = AcceptedTable.Select("Name = '" + row["Name"] + "' AND Variable = '" + row["Variable"] + "' AND Test = '" + row["Test"] + "'");
                DataRow[] rowCurrent  = CurrentTable.Select("Name = '" + row["Name"] + "' AND Variable = '" + row["Variable"] + "' AND Test = '" + row["Test"] + "'");

                if (rowAccepted.Count() == 0)
                {
                    row["Accepted"] = DBNull.Value;
                }
                else
                {
                    row["Accepted"] = rowAccepted[0]["Accepted"];
                }

                if (rowCurrent.Count() == 0)
                {
                    row["Current"] = DBNull.Value;
                }
                else
                {
                    row["Current"] = rowCurrent[0]["Current"];
                }

                if (row["Accepted"] != DBNull.Value && row["Current"] != DBNull.Value)
                {
                    row["Difference"] = Convert.ToDouble(row["Current"],
                                                         System.Globalization.CultureInfo.InvariantCulture) -
                                        Convert.ToDouble(row["Accepted"], System.Globalization.CultureInfo.InvariantCulture);
                    row["Fail?"] = Math.Abs(Convert.ToDouble(row["Difference"], System.Globalization.CultureInfo.InvariantCulture))
                                   > Math.Abs(Convert.ToDouble(row["Accepted"], System.Globalization.CultureInfo.InvariantCulture)) * 0.01 ? sigIdent : " ";
                }
                else
                {
                    row["Difference"] = DBNull.Value;
                    row["Fail?"]      = sigIdent;
                }
            }
            //Tables could be large so free the memory.
            AcceptedTable = null;
            CurrentTable  = null;

            if (accept)
            {
                AcceptedStats = stats;
            }
            else
            {
                foreach (DataRow row in Table.Rows)
                {
                    if (row["Fail?"].ToString().Equals(sigIdent))
                    {
                        if (!GUIrun)
                        {
                            object sim = PO.Parent;
                            while (sim as Simulations == null)
                            {
                                sim = ((Model)sim).Parent;
                            }

                            throw new ApsimXException(this, "Significant differences found during regression testing of " + PO.Name + " in " + (sim != null ? ((Simulations)sim).FileName : "<unknown>"));
                        }
                    }
                }
            }
        }
コード例 #2
0
        /// <summary>
        /// Open the forage data file.
        /// </summary>
        /// <returns>True if the file was successfully opened</returns>
        public bool OpenDataFile()
        {
            if (System.IO.File.Exists(this.FullFileName))
            {
                if (this.reader == null)
                {
                    this.reader = new ApsimTextFile();
                    this.reader.Open(this.FullFileName, this.ExcelWorkSheetName);

                    if (this.reader.Headings == null)
                    {
                        throw new Exception("@error:Invalid format of datafile [x=" + this.FullFileName.Replace("\\", "\\&shy;") + "]\nExpecting Header row followed by units row in brackets.\nHeading1      Heading2      Heading3\n( )         ( )        ( )");
                    }

                    this.soilNumIndex         = StringUtilities.IndexOfCaseInsensitive(this.reader.Headings, "SoilNum");
                    this.cropNameIndex        = StringUtilities.IndexOfCaseInsensitive(this.reader.Headings, "CropName");
                    this.yearIndex            = StringUtilities.IndexOfCaseInsensitive(this.reader.Headings, "Year");
                    this.monthIndex           = StringUtilities.IndexOfCaseInsensitive(this.reader.Headings, "Month");
                    this.amountKgIndex        = StringUtilities.IndexOfCaseInsensitive(this.reader.Headings, "AmtKg");
                    this.nitrogenPercentIndex = StringUtilities.IndexOfCaseInsensitive(this.reader.Headings, "Npct");

                    if (this.soilNumIndex == -1)
                    {
                        if (this.reader == null || this.reader.Constant("SoilNum") == null)
                        {
                            throw new Exception("@error:Cannot find [o=SoilNum] column in crop file [x=" + this.FullFileName.Replace("\\", "\\&shy;") + "]");
                        }
                    }

                    if (this.cropNameIndex == -1)
                    {
                        if (this.reader == null || this.reader.Constant("CropName") == null)
                        {
                            throw new Exception("@error:Cannot find [o=CropName] column in crop file [x=" + this.FullFileName.Replace("\\", "\\&shy;") + "]");
                        }
                    }

                    if (this.yearIndex == -1)
                    {
                        if (this.reader == null || this.reader.Constant("Year") == null)
                        {
                            throw new Exception("@error:Cannot find [o=Year] column in crop file [x=" + this.FullFileName.Replace("\\", "\\&shy;") + "]");
                        }
                    }

                    if (this.monthIndex == -1)
                    {
                        if (this.reader == null || this.reader.Constant("Month") == null)
                        {
                            throw new Exception("@error:Cannot find [o=Month] column in crop file [x=" + this.FullFileName.Replace("\\", "\\&shy;") + "]");
                        }
                    }

                    if (this.amountKgIndex == -1)
                    {
                        if (this.reader == null || this.reader.Constant("AmtKg") == null)
                        {
                            throw new Exception("@error:Cannot find [o=AmtKg] column in crop file [x=" + this.FullFileName.Replace("\\", "\\&shy;") + "]");
                        }
                    }
                }
                else
                {
                    if (this.reader.IsExcelFile != true)
                    {
                        this.reader.SeekToDate(this.reader.FirstDate);
                    }
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #3
0
ファイル: FileCrop.cs プロジェクト: JulianneLilley/ApsimX
        /// <summary>
        /// Open the forage data file.
        /// </summary>
        /// <returns>True if the file was successfully opened</returns>
        public bool OpenDataFile()
        {
            if (System.IO.File.Exists(this.FullFileName))
            {
                if (this.reader == null)
                {
                    this.reader = new ApsimTextFile();
                    this.reader.Open(this.FullFileName, this.ExcelWorkSheetName);

                    if (this.reader.Headings == null)
                    {
                        string fileType = "Text file";
                        string extra    = "\nExpecting Header row followed by units row in brackets.\nHeading1      Heading2      Heading3\n( )         ( )        ( )";
                        if (reader.IsCSVFile)
                        {
                            fileType = "Comma delimited text file (csv)";
                        }
                        if (reader.IsExcelFile)
                        {
                            fileType = "Excel file";
                            extra    = "";
                        }
                        throw new Exception($"@error:Invalid {fileType} format of datafile [x={this.FullFileName.Replace("\\", "\\&shy;")}]{extra}");
                    }

                    this.soilNumIndex         = StringUtilities.IndexOfCaseInsensitive(this.reader.Headings, SoilTypeColumnName);
                    this.cropNameIndex        = StringUtilities.IndexOfCaseInsensitive(this.reader.Headings, CropNameColumnName);
                    this.yearIndex            = StringUtilities.IndexOfCaseInsensitive(this.reader.Headings, YearColumnName);
                    this.monthIndex           = StringUtilities.IndexOfCaseInsensitive(this.reader.Headings, MonthColumnName);
                    this.amountKgIndex        = StringUtilities.IndexOfCaseInsensitive(this.reader.Headings, AmountColumnName);
                    this.nitrogenPercentIndex = StringUtilities.IndexOfCaseInsensitive(this.reader.Headings, PercentNitrogenColumnName);

                    if (this.soilNumIndex == -1)
                    {
                        if (this.reader == null || this.reader.Constant(SoilTypeColumnName) == null)
                        {
                            throw new Exception($"@error:Cannot find Land Id column [o={SoilTypeColumnName??"Empty"}] in crop file [x={this.FullFileName.Replace("\\", "\\&shy;")}] for [x={this.Name}]");
                        }
                    }

                    if (this.cropNameIndex == -1)
                    {
                        if (this.reader == null || this.reader.Constant(CropNameColumnName) == null)
                        {
                            throw new Exception($"@error:Cannot find CropName column [o={CropNameColumnName ?? "Empty"}] in crop file [x=" + this.FullFileName.Replace("\\", "\\&shy;") + "]" + $" for [x={this.Name}]");
                        }
                    }

                    if (this.yearIndex == -1)
                    {
                        if (this.reader == null || this.reader.Constant(YearColumnName) == null)
                        {
                            throw new Exception($"@error:Cannot find Year column [o={YearColumnName ?? "Empty"}] in crop file [x=" + this.FullFileName.Replace("\\", "\\&shy;") + "]" + $" for [x={this.Name}]");
                        }
                    }

                    if (this.monthIndex == -1)
                    {
                        if (this.reader == null || this.reader.Constant(MonthColumnName) == null)
                        {
                            throw new Exception($"@error:Cannot find Month column [o={MonthColumnName ?? "Empty"}] in crop file [x=" + this.FullFileName.Replace("\\", "\\&shy;") + "]" + $" for [x={this.Name}]");
                        }
                    }

                    if (this.amountKgIndex == -1)
                    {
                        if (this.reader == null || this.reader.Constant(AmountColumnName) == null)
                        {
                            throw new Exception($"@error:Cannot find Amount column [o={AmountColumnName}] in crop file [x=" + this.FullFileName.Replace("\\", "\\&shy;") + "]" + $" for [x={this.Name}]");
                        }
                    }
                }
                else
                {
                    if (this.reader.IsExcelFile != true)
                    {
                        this.reader.SeekToDate(this.reader.FirstDate);
                    }
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #4
0
        void OnLoadRequestedPath(HandleFlag handled)
        {
            if (SprocketPath.Sections.Length == 0)
            {
                return;
            }
            if (SprocketPath.Sections[0] != "admin")
            {
                return;
            }
            bool   processed = false;
            string lastchunk = SprocketPath.Sections[SprocketPath.Sections.Length - 1];

            switch (lastchunk)
            {
            case "admin.css":
                HttpContext.Current.Response.TransmitFile("~/resources/admin/admin.css");
                HttpContext.Current.Response.ContentType = "text/css";
                processed = true;
                break;

            default:
                WebAuthentication auth     = WebAuthentication.Instance;
                HttpResponse      Response = HttpContext.Current.Response;
                HttpServerUtility Server   = HttpContext.Current.Server;
                switch (SprocketPath.Value)
                {
                case "admin/login":
                    ShowLoginScreen();
                    processed = true;
                    break;

                case "admin/logout":
                    auth.ClearAuthenticationCookie();
                    Response.Redirect(WebUtility.MakeFullPath("admin/login"));
                    processed = true;
                    break;

                case "admin/login/process":
                    if (auth.ProcessLoginForm("SprocketUsername", "SprocketPassword", "SprocketPreserveLogin"))
                    {
                        Response.Redirect(WebUtility.MakeFullPath("admin"));
                    }
                    else
                    {
                        ShowLoginScreen("Invalid Username and/or Password.");
                    }
                    processed = true;
                    break;

                default:
                    if (!WebAuthentication.IsLoggedIn)
                    {
                        GotoLoginScreen();
                        processed = true;
                    }
                    else if (OnCMSAdminAuthenticationSuccess != null)
                    {
                        Result result = new Result();
                        OnCMSAdminAuthenticationSuccess(auth.CurrentUsername, result);
                        if (!result.Succeeded)
                        {
                            ShowLoginScreen(result.Message);
                            processed = true;
                        }
                    }
                    break;
                }
                break;
            }
            if (processed)
            {
                handled.Set();
                return;
            }

            if (OnAdminRequest != null)
            {
                AdminInterface admin = new AdminInterface();
                OnAdminRequest(admin, handled);
                if (handled.Handled)
                {
                    WebClientScripts scripts = WebClientScripts.Instance;
                    admin.AddMainMenuLink(new AdminMenuLink("Administrative Tasks", WebUtility.MakeFullPath("admin"), -100));
                    admin.AddMainMenuLink(new AdminMenuLink("Log Out", WebUtility.MakeFullPath("admin/logout"), 100));
                    admin.AddFooterLink(new AdminMenuLink("&copy; 2005-" + SprocketDate.Now.Year + " " + SprocketSettings.GetValue("WebsiteName"), "", 100));
                    string powered = SprocketSettings.GetValue("ShowPoweredBySprocket");
                    if (powered != null)
                    {
                        if (StringUtilities.MatchesAny(powered.ToLower(), "true", "yes"))
                        {
                            admin.AddFooterLink(new AdminMenuLink("Powered by Sprocket", "http://www.sprocketcms.com", 1000));
                        }
                    }
                    admin.AddHeadSection(new RankedString(scripts.BuildStandardScriptsBlock(), 1));
                    HttpContext.Current.Response.Write(admin.Render());
                }
            }
        }
コード例 #5
0
ファイル: SyntaxEditor.cs プロジェクト: PenguinF/sandra-three
 public void UpdateText()
 {
     DockProperties.CaptionText = StringUtilities.ConditionalFormat(titleString.DisplayText.Value, new[] { OwnerEditor.CodeFilePathDisplayString });
     DockPropertiesChanged?.Invoke();
 }
コード例 #6
0
        /// <summary>
        /// Format the grid based on the data in the specified table.
        /// </summary>
        /// <param name="table">The table to use to format the grid.</param>
        private void FormatGrid(DataTable table)
        {
            Color[] cropColors          = { Color.FromArgb(173, 221, 142), Color.FromArgb(247, 252, 185) };
            Color[] predictedCropColors = { Color.FromArgb(233, 191, 255), Color.FromArgb(244, 226, 255) };

            int cropIndex          = 0;
            int predictedCropIndex = 0;

            Color foregroundColour = Color.Black;
            Color backgroundColour = Color.White;

            for (int col = 0; col < this.propertiesInGrid.Count; col++)
            {
                VariableProperty property = this.propertiesInGrid[col];

                string columnName = property.Description;

                // crop colours
                if (property.CropName != null)
                {
                    if (property.Metadata.Contains("Estimated"))
                    {
                        backgroundColour = predictedCropColors[predictedCropIndex];
                        foregroundColour = Color.Gray;
                        if (columnName.Contains("XF"))
                        {
                            predictedCropIndex++;
                        }

                        if (predictedCropIndex >= predictedCropColors.Length)
                        {
                            predictedCropIndex = 0;
                        }
                    }
                    else
                    {
                        backgroundColour = cropColors[cropIndex];
                        if (columnName.Contains("XF"))
                        {
                            cropIndex++;
                        }

                        if (cropIndex >= cropColors.Length)
                        {
                            cropIndex = 0;
                        }
                    }
                }

                // tool tips
                string[] toolTips = null;
                if (property.IsReadOnly)
                {
                    foregroundColour = Color.Gray;
                    toolTips         = StringUtilities.CreateStringArray("Calculated", this.view.ProfileGrid.RowCount);
                }
                else
                {
                    foregroundColour = Color.Black;
                    toolTips         = property.Metadata;
                }

                string format = property.Format;
                if (format == null)
                {
                    format = "N3";
                }

                IGridColumn gridColumn = this.view.ProfileGrid.GetColumn(col);
                gridColumn.Format           = format;
                gridColumn.BackgroundColour = backgroundColour;
                gridColumn.ForegroundColour = foregroundColour;
                gridColumn.ReadOnly         = property.IsReadOnly;
                for (int rowIndex = 0; rowIndex < toolTips.Length; rowIndex++)
                {
                    IGridCell cell = this.view.ProfileGrid.GetCell(col, rowIndex);
                    cell.ToolTip = toolTips[rowIndex];
                }

                // colour the column headers of total columns.
                if (!double.IsNaN(property.Total))
                {
                    gridColumn.HeaderForegroundColour = Color.Red;
                }
            }

            this.view.ProfileGrid.RowCount = 100;
        }
コード例 #7
0
 private void TxtExpediente_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
 {
     e.Handled = StringUtilities.IsTextAllowed(e.Text);
 }
コード例 #8
0
        /// <summary>
        /// Diagnostic event handler method for 'Microsoft.AspNetCore.Hosting.HttpRequestIn.Start' event.
        /// </summary>
        public void OnHttpRequestInStart(HttpContext httpContext)
        {
            if (this.client.IsEnabled())
            {
                // It's possible to host multiple apps (ASP.NET Core or generic hosts) in the same process
                // Each of this apps has it's own HostingDiagnosticListener and corresponding Http listener.
                // We should ignore events for all of them except one
                if (!SubscriptionManager.IsActive(this))
                {
                    AspNetCoreEventSource.Instance.NotActiveListenerNoTracking("Microsoft.AspNetCore.Hosting.HttpRequestIn.Start", Activity.Current?.Id);
                    return;
                }

                if (Activity.Current == null)
                {
                    AspNetCoreEventSource.Instance.LogHostingDiagnosticListenerOnHttpRequestInStartActivityNull();
                    return;
                }

                var    currentActivity = Activity.Current;
                var    isActivityCreatedFromRequestIdHeader = true;
                string sourceAppId      = null;
                string originalParentId = currentActivity.ParentId;

                Activity newActivity = null;
                // W3C
                if (this.enableW3CHeaders)
                {
                    isActivityCreatedFromRequestIdHeader = false;
                    SetW3CContext(httpContext.Request.Headers, currentActivity, out sourceAppId);

                    var parentSpanId = currentActivity.GetParentSpanId();
                    if (parentSpanId != null)
                    {
                        originalParentId = $"|{currentActivity.GetTraceId()}.{parentSpanId}.";
                    }
                }

                // x-ms-*
                if (originalParentId == null &&
                    httpContext.Request.Headers.TryGetValue(RequestResponseHeaders.StandardRootIdHeader, out StringValues alternativeRootIdValues) &&
                    alternativeRootIdValues != StringValues.Empty)
                {
                    isActivityCreatedFromRequestIdHeader = false;
                    newActivity = new Activity(ActivityCreatedByHostingDiagnosticListener)
                                  .SetParentId(StringUtilities.EnforceMaxLength(alternativeRootIdValues.First(),
                                                                                InjectionGuardConstants.RequestHeaderMaxLength));

                    if (httpContext.Request.Headers.TryGetValue(RequestResponseHeaders.StandardParentIdHeader, out StringValues parentId))
                    {
                        originalParentId = StringUtilities.EnforceMaxLength(parentId.First(),
                                                                            InjectionGuardConstants.RequestHeaderMaxLength);
                    }
                }

                // no headers
                else if (originalParentId == null)
                {
                    // As a first step in supporting W3C protocol in ApplicationInsights,
                    // we want to generate Activity Ids in the W3C compatible format.
                    // While .NET changes to Activity are pending, we want to ensure trace starts with W3C compatible Id
                    // as early as possible, so that everyone has a chance to upgrade and have compatibility with W3C systems once they arrive.
                    // So if there is no current Activity (i.e. there were no Request-Id header in the incoming request), we'll override ParentId on
                    // the current Activity by the properly formatted one. This workaround should go away
                    // with W3C support on .NET https://github.com/dotnet/corefx/issues/30331

                    newActivity = new Activity(ActivityCreatedByHostingDiagnosticListener);
                    if (this.enableW3CHeaders)
                    {
                        newActivity.GenerateW3CContext();
                        newActivity.SetParentId(newActivity.GetTraceId());
                    }
                    else
                    {
                        newActivity.SetParentId(W3CUtilities.GenerateTraceId());
                    }
                    // end of workaround
                }

                if (newActivity != null)
                {
                    newActivity.Start();
                    currentActivity = newActivity;
                }

                var requestTelemetry = InitializeRequestTelemetry(httpContext, currentActivity, isActivityCreatedFromRequestIdHeader, Stopwatch.GetTimestamp());
                if (this.enableW3CHeaders && sourceAppId != null)
                {
                    requestTelemetry.Source = sourceAppId;
                }

                requestTelemetry.Context.Operation.ParentId = originalParentId;
                SetAppIdInResponseHeader(httpContext, requestTelemetry);
            }
        }
コード例 #9
0
        public async Task <ActionResult> NewRegister(RegisterViewModel model, HttpPostedFileBase AvatarImage)
        {
            if (ModelState.IsValid)
            {
                //registering the user with inputs
                var user = new ApplicationUser
                {
                    FirstName   = model.FName,
                    LastName    = model.LName,
                    DisplayName = model.DisplayName,
                    UserName    = model.Email,
                    Email       = model.Email,
                    AvatarPath  = ""
                };

                //validating the image that they chose as avatar
                if (AvatarImage != null)
                {
                    if (ImageUploadValidator.IsWebFriendlyImage(AvatarImage))
                    {
                        var fileName     = Path.GetFileName(AvatarImage.FileName);
                        var justFileName = Path.GetFileNameWithoutExtension(fileName);
                        justFileName = StringUtilities.URLFriendly(justFileName);
                        fileName     = $"{justFileName}_{DateTime.Now.Ticks}{Path.GetExtension(fileName)}";

                        AvatarImage.SaveAs(Path.Combine(Server.MapPath("~/Avatars/"), fileName));
                        user.AvatarPath = "/Avatars/" + fileName;
                    }
                }

                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    //Assign to guest role by
                    await UserManager.AddToRoleAsync(user.Id, "Guest");

                    //roleHelper.AddUserToRole(user.Id, "Guest");

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    //await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    //send confirmation email
                    try
                    {
                        var from  = $"Financial Admin<{WebConfigurationManager.AppSettings["emailfrom"]}>";
                        var email = new MailMessage(from, model.Email)
                        {
                            Subject    = "Confirm your account",
                            Body       = $"Please confirm your account by clicking <a href=\"{callbackUrl}\">here</a>",
                            IsBodyHtml = true
                        };
                        var svc = new PersonalEmail();
                        await svc.SendAsync(email);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        await Task.FromResult(0);
                    }

                    return(RedirectToAction("ForgotPasswordConfirmation", "Account"));
                }
                AddErrors(result);
            }
            // If we got this far, something failed, redisplay form
            return(RedirectToAction("Register"));
        }
コード例 #10
0
ファイル: APSIMFiles.cs プロジェクト: zur003/APSIM.Cloud
        /// <summary>Do all soil related settings.</summary>
        /// <param name="simulation">The specification to use</param>
        /// <param name="workingFolder">The folder where files shoud be created.</param>
        private static void DoSoil(APSIMSpecification simulation, string workingFolder)
        {
            Soil soil;

            if (simulation.Soil == null)
            {
                if (simulation.SoilPath.StartsWith("http"))
                {
                    // Soil and Landscape grid
                    string xml;
                    using (var client = new WebClient())
                    {
                        xml = client.DownloadString(simulation.SoilPath);
                    }
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(xml);
                    List <XmlNode> soils = XmlUtilities.ChildNodes(doc.DocumentElement, "Soil");
                    if (soils.Count == 0)
                    {
                        throw new Exception("Cannot find soil in Soil and Landscape Grid");
                    }
                    soil = XmlUtilities.Deserialise(soils[0], typeof(Soil)) as Soil;
                }
                else
                {
                    // Apsoil web service.
                    APSOIL.Service apsoilService = new APSOIL.Service();
                    string         soilXml       = apsoilService.SoilXML(simulation.SoilPath);
                    if (soilXml == string.Empty)
                    {
                        throw new Exception("Cannot find soil: " + simulation.SoilPath);
                    }
                    soil = SoilUtilities.FromXML(soilXml);
                }
            }
            else
            {
                // Just use the soil we already have
                soil = simulation.Soil;
            }

            // Make sure we have a soil crop parameterisation. If not then try creating one
            // based on wheat.
            Sow sowing = YieldProphetUtility.GetCropBeingSown(simulation.Management);

            string[] cropNames = soil.Water.Crops.Select(c => c.Name).ToArray();
            if (cropNames.Length == 0)
            {
                throw new Exception("Cannot find any crop parameterisations in soil: " + simulation.SoilPath);
            }

            if (sowing != null && !StringUtilities.Contains(cropNames, sowing.Crop))
            {
                SoilCrop wheat = soil.Water.Crops.Find(c => c.Name.Equals("wheat", StringComparison.InvariantCultureIgnoreCase));
                if (wheat == null)
                {
                    // Use the first crop instead.
                    wheat = soil.Water.Crops[0];
                }

                SoilCrop newSoilCrop = new SoilCrop();
                newSoilCrop.Name      = sowing.Crop;
                newSoilCrop.Thickness = wheat.Thickness;
                newSoilCrop.LL        = wheat.LL;
                newSoilCrop.KL        = wheat.KL;
                newSoilCrop.XF        = wheat.XF;
                soil.Water.Crops.Add(newSoilCrop);
            }

            // Remove any initwater nodes.
            soil.InitialWater = null;

            // Transfer the simulation samples to the soil
            if (simulation.Samples != null)
            {
                soil.Samples = simulation.Samples;
            }

            if (simulation.InitTotalWater != 0)
            {
                soil.InitialWater = new InitialWater();
                soil.InitialWater.PercentMethod = InitialWater.PercentMethodEnum.FilledFromTop;

                double pawc;
                if (sowing == null || sowing.Crop == null)
                {
                    pawc = MathUtilities.Sum(PAWC.OfSoilmm(soil));
                    soil.InitialWater.RelativeTo = "LL15";
                }
                else
                {
                    SoilCrop crop = soil.Water.Crops.Find(c => c.Name.Equals(sowing.Crop, StringComparison.InvariantCultureIgnoreCase));
                    pawc = MathUtilities.Sum(PAWC.OfCropmm(soil, crop));
                    soil.InitialWater.RelativeTo = crop.Name;
                }

                soil.InitialWater.FractionFull = Convert.ToDouble(simulation.InitTotalWater) / pawc;
            }

            if (simulation.InitTotalNitrogen != 0)
            {
                // Add in a sample.
                Sample nitrogenSample = new Sample();
                nitrogenSample.Name = "NitrogenSample";
                soil.Samples.Add(nitrogenSample);
                nitrogenSample.Thickness = new double[] { 150, 150, 3000 };
                nitrogenSample.NO3Units  = Nitrogen.NUnitsEnum.kgha;
                nitrogenSample.NH4Units  = Nitrogen.NUnitsEnum.kgha;
                nitrogenSample.NO3       = new double[] { 6.0, 2.1, 0.1 };
                nitrogenSample.NH4       = new double[] { 0.5, 0.1, 0.1 };
                nitrogenSample.OC        = new double[] { double.NaN, double.NaN, double.NaN };
                nitrogenSample.EC        = new double[] { double.NaN, double.NaN, double.NaN };
                nitrogenSample.PH        = new double[] { double.NaN, double.NaN, double.NaN };

                double Scale = Convert.ToDouble(simulation.InitTotalNitrogen) / MathUtilities.Sum(nitrogenSample.NO3);
                nitrogenSample.NO3 = MathUtilities.Multiply_Value(nitrogenSample.NO3, Scale);
            }

            // Add in soil temperature. Needed for Aflatoxin risk.
            soil.SoilTemperature = new SoilTemperature();
            soil.SoilTemperature.BoundaryLayerConductance = 15;
            soil.SoilTemperature.Thickness = new double[] { 2000 };
            soil.SoilTemperature.InitialSoilTemperature = new double[] { 22 };
            if (soil.Analysis.ParticleSizeClay == null)
            {
                soil.Analysis.ParticleSizeClay = MathUtilities.CreateArrayOfValues(60, soil.Analysis.Thickness.Length);
            }
            InFillMissingValues(soil.Analysis.ParticleSizeClay);

            foreach (Sample sample in soil.Samples)
            {
                CheckSample(soil, sample, sowing);
            }

            Defaults.FillInMissingValues(soil);

            // Correct the CONA / U parameters depending on LAT/LONG
            CorrectCONAU(simulation, soil, workingFolder);

            // get rid of <soiltype> from the soil
            // this is necessary because NPD uses this field and puts in really long
            // descriptive classifications. Soiln2 bombs with an FString internal error.
            soil.SoilType = null;

            // Set the soil name to 'soil'
            soil.Name = "Soil";

            simulation.Soil = soil;
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: gsemac/OurFoodChain.Bot
        private static string GeneratePictureFilenameFromSpecies(ISpecies species, string pictureUrl)
        {
            string pictureFilename = GetPictureFilenameFromPictureUrl(pictureUrl);

            return(string.Format("{0}-{1}{2}", species.GetFullName().ToLower().Replace(' ', '_'), StringUtilities.GetMD5(pictureUrl), System.IO.Path.GetExtension(pictureFilename).ToLower()));
        }
コード例 #12
0
        // -----------------------------------------------------
        //   Error Listfile Reporting Method
        // -----------------------------------------------------

        internal void MakeListing(ScanBuff buff, StreamWriter sWrtr, string name, string version)
        {
            int line = 1;
            int eNum = 0;
            int eLin = 0;

            int nxtC = (int)'\n';
            int groupFirst;
            int currentCol;
            int currentLine;

            //
            //  Errors are sorted by line number
            //
            errors = SortedErrorList();
            //
            //  Reset the source file buffer to the start
            //
            buff.Pos = 0;
            sWrtr.WriteLine();
            ListDivider(sWrtr);
            sWrtr.WriteLine("//  GPPG error listing for yacc source file <"
                            + name + ">");
            ListDivider(sWrtr);
            sWrtr.WriteLine("//  Version:  " + version);
            sWrtr.WriteLine("//  Machine:  " + Environment.MachineName);
            sWrtr.WriteLine("//  DateTime: " + DateTime.Now.ToString());
            sWrtr.WriteLine("//  UserName: "******"// Warning: " : "// Error: ");
                        string msg    = StringUtilities.MakeComment(3, prefix + err.message);
                        if (StringUtilities.MaxWidth(msg) > maxGroupWidth)
                        {
                            maxGroupWidth = StringUtilities.MaxWidth(msg);
                        }
                        sWrtr.Write(msg);
                        sWrtr.WriteLine();
                    }
                    if (groupFirst < eNum)
                    {
                        sWrtr.Write("// ");
                        Spaces(sWrtr, maxGroupWidth - 3);
                        sWrtr.WriteLine();
                    }
                    currentLine = eLin;
                    groupFirst  = eNum;
                }
                //
                //  Emit lines up to *and including* the error line
                //
                while (line <= eLin)
                {
                    nxtC = buff.Read();
                    if (nxtC == (int)'\n')
                    {
                        line++;
                    }
                    else if (nxtC == ScanBuff.EndOfFile)
                    {
                        break;
                    }
                    sWrtr.Write((char)nxtC);
                }
                //
                //  Now emit the error message(s)
                //
                if (errN.span.endColumn > 3 && errN.span.startColumn < 80)
                {
                    if (currentCol == 0)
                    {
                        sWrtr.Write("//");
                        currentCol = 2;
                    }
                    if (errN.span.startColumn > currentCol)
                    {
                        Spaces(sWrtr, errN.span.startColumn - currentCol - 1);
                        currentCol = errN.span.startColumn - 1;
                    }
                    for (; currentCol < errN.span.endColumn && currentCol < 80; currentCol++)
                    {
                        sWrtr.Write('^');
                    }
                }
            }
            //
            //  Clean up after last message listing
            //  Spill all the waiting messages
            //
            int maxEpilogWidth = 0;

            if (currentCol > 0)
            {
                sWrtr.WriteLine();
            }
            for (int i = groupFirst; i < errors.Count; i++)
            {
                Error  err    = errors[i];
                string prefix = (err.isWarn ? "// Warning: " : "// Error: ");
                string msg    = StringUtilities.MakeComment(3, prefix + err.message);
                if (StringUtilities.MaxWidth(msg) > maxEpilogWidth)
                {
                    maxEpilogWidth = StringUtilities.MaxWidth(msg);
                }
                sWrtr.Write(msg);
                sWrtr.WriteLine();
            }
            if (groupFirst < errors.Count)
            {
                sWrtr.Write("// ");
                Spaces(sWrtr, maxEpilogWidth - 3);
                sWrtr.WriteLine();
            }
            //
            //  And dump the tail of the file
            //
            nxtC = buff.Read();
            while (nxtC != ScanBuff.EndOfFile)
            {
                sWrtr.Write((char)nxtC);
                nxtC = buff.Read();
            }
            ListDivider(sWrtr); sWrtr.WriteLine();
            sWrtr.Flush();
            // sWrtr.Close();
        }
コード例 #13
0
 private static string ToAssertString(IEnumerable <HighlightedSegment <Token> > segments) => StringUtilities.JoinLines(segments.Select(s => $"({s.Start}:{s.End}:{s.Value})"));
コード例 #14
0
 private string GetTagPathDescription()
 {
     return(StringUtilities.Combine(_currentTagPath, "/", GetTagName));
 }
コード例 #15
0
        public static WaypointGenerator Create(ConfigNode configNode, WaypointGeneratorFactory factory)
        {
            WaypointGenerator wpGenerator = new WaypointGenerator();

            // Waypoint Manager integration
            EventData <string> onWaypointIconAdded = GameEvents.FindEvent <EventData <string> >("OnWaypointIconAdded");

            bool valid = true;
            int  index = 0;

            foreach (ConfigNode child in ConfigNodeUtil.GetChildNodes(configNode))
            {
                DataNode dataNode = new DataNode("WAYPOINT_" + index, factory.dataNode, factory);
                try
                {
                    ConfigNodeUtil.SetCurrentDataNode(dataNode);
                    dataNode["type"] = child.name;

                    double?      altitude = null;
                    WaypointData wpData   = new WaypointData(child.name);

                    // Use an expression to default - then it'll work for dynamic contracts
                    if (!child.HasValue("targetBody"))
                    {
                        child.AddValue("targetBody", "@/targetBody");
                    }
                    valid &= ConfigNodeUtil.ParseValue <CelestialBody>(child, "targetBody", x => wpData.waypoint.celestialName = x != null ? x.name : "", factory);

                    valid &= ConfigNodeUtil.ParseValue <List <string> >(child, "name", x => wpData.names = x, factory, new List <string>());
                    valid &= ConfigNodeUtil.ParseValue <double?>(child, "altitude", x => altitude = x, factory, (double?)null);
                    valid &= ConfigNodeUtil.ParseValue <List <string> >(child, "parameter", x => wpData.parameter = x, factory, new List <string>());
                    valid &= ConfigNodeUtil.ParseValue <bool>(child, "hidden", x => wpData.waypoint.visible = !x, factory, false);

                    Action <string> assignWaypoint = (x) =>
                    {
                        wpData.waypoint.id = x;
                        if (onWaypointIconAdded != null)
                        {
                            onWaypointIconAdded.Fire(x);
                        }
                    };
                    if (!wpData.waypoint.visible)
                    {
                        valid &= ConfigNodeUtil.ParseValue <string>(child, "icon", assignWaypoint, factory, "");
                    }
                    else
                    {
                        valid &= ConfigNodeUtil.ParseValue <string>(child, "icon", assignWaypoint, factory);
                    }

                    valid &= ConfigNodeUtil.ParseValue <bool>(child, "underwater", x => wpData.underwater = x, factory, false);
                    valid &= ConfigNodeUtil.ParseValue <bool>(child, "clustered", x => wpData.waypoint.isClustered = x, factory, false);

                    // Track the index
                    wpData.waypoint.index = index++;

                    // Get altitude
                    if (altitude == null)
                    {
                        wpData.waypoint.altitude = 0.0;
                        wpData.randomAltitude    = true;
                    }
                    else
                    {
                        wpData.waypoint.altitude = altitude.Value;
                    }

                    // Get settings that differ by type
                    if (child.name == "WAYPOINT")
                    {
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "latitude", x => wpData.waypoint.latitude = x, factory);
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "longitude", x => wpData.waypoint.longitude = x, factory);
                    }
                    else if (child.name == "RANDOM_WAYPOINT")
                    {
                        // Get settings for randomization
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "waterAllowed", x => wpData.waterAllowed = x, factory, true);
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "forceEquatorial", x => wpData.forceEquatorial = x, factory, false);
                        valid &= ConfigNodeUtil.ParseValue <int>(child, "count", x => wpData.count = x, factory, 1, x => Validation.GE(x, 1));
                    }
                    else if (child.name == "RANDOM_WAYPOINT_NEAR")
                    {
                        // Get settings for randomization
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "waterAllowed", x => wpData.waterAllowed = x, factory, true);

                        // Get near waypoint details
                        valid &= ConfigNodeUtil.ParseValue <int>(child, "nearIndex", x => wpData.nearIndex = x, factory,
                                                                 x => Validation.GE(x, 0) && Validation.LT(x, wpGenerator.waypoints.Count));
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "chained", x => wpData.chained = x, factory, false);
                        valid &= ConfigNodeUtil.ParseValue <int>(child, "count", x => wpData.count = x, factory, 1, x => Validation.GE(x, 1));

                        // Get distances
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "minDistance", x => wpData.minDistance = x, factory, 0.0, x => Validation.GE(x, 0.0));
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "maxDistance", x => wpData.maxDistance = x, factory, x => Validation.GT(x, 0.0));
                    }
                    else if (child.name == "PQS_CITY")
                    {
                        wpData.randomAltitude = false;
                        valid &= ConfigNodeUtil.ParseValue <string>(child, "pqsCity", x => {}, factory, x =>
                        {
                            bool v = true;
                            if (!string.IsNullOrEmpty(wpData.waypoint.celestialName))
                            {
                                try
                                {
                                    CelestialBody body = FlightGlobals.Bodies.Where(b => b.name == wpData.waypoint.celestialName).First();
                                    wpData.pqsCity     = body.GetComponentsInChildren <PQSCity>(true).Where(pqs => pqs.name == x).First();
                                }
                                catch (Exception e)
                                {
                                    LoggingUtil.LogError(typeof(WaypointGenerator), "Couldn't load PQSCity with name '" + x + "'");
                                    LoggingUtil.LogException(e);
                                    v = false;
                                }
                            }
                            else
                            {
                                // Force this to get re-run when the targetBody is loaded
                                throw new DataNode.ValueNotInitialized("/targetBody");
                            }
                            return(v);
                        });
                        valid &= ConfigNodeUtil.ParseValue <Vector3d>(child, "pqsOffset", x => wpData.pqsOffset = x, factory, new Vector3d());
                    }
                    else
                    {
                        LoggingUtil.LogError(factory, "Unrecognized waypoint node: '" + child.name + "'");
                        valid = false;
                    }

                    // Check for unexpected values
                    valid &= ConfigNodeUtil.ValidateUnexpectedValues(child, factory);

                    // Copy waypoint data
                    WaypointData old = wpData;
                    for (int i = 0; i < old.count; i++)
                    {
                        wpData = new WaypointData(old, null);
                        wpGenerator.waypoints.Add(wpData);

                        if (old.parameter.Any())
                        {
                            wpData.parameter = new List <string>();
                            wpData.parameter.Add(old.parameter.Count() == 1 ? old.parameter.First() : old.parameter.ElementAtOrDefault(i));
                        }

                        // Set the name
                        if (old.names.Any())
                        {
                            wpData.waypoint.name = (old.names.Count() == 1 ? old.names.First() : old.names.ElementAtOrDefault(i));
                        }
                        if (string.IsNullOrEmpty(wpData.waypoint.name) || wpData.waypoint.name.ToLower() == "site")
                        {
                            wpData.waypoint.name = StringUtilities.GenerateSiteName(random.Next(), wpData.waypoint.celestialBody, !wpData.waterAllowed);
                        }

                        // Handle waypoint chaining
                        if (wpData.chained && i != 0)
                        {
                            wpData.nearIndex = wpGenerator.waypoints.Count - 2;
                        }
                    }
                }
                finally
                {
                    ConfigNodeUtil.SetCurrentDataNode(factory.dataNode);
                }
            }

            return(valid ? wpGenerator : null);
        }
コード例 #16
0
 /// <summary>
 /// Returns the <see cref="PersonName.FormattedName"/> property of each input value, separated by ",\n".
 /// </summary>
 public static string PersonNameListFormatter(IEnumerable <PersonName> personNames)
 {
     return(StringUtilities.Combine <PersonName>(personNames, ",\n", PersonNameFormatter));
 }
コード例 #17
0
        /// <summary>
        /// Return a predicted SoilCrop for the specified crop name or null if not found.
        /// </summary>
        /// <param name="soil">The soil.</param>
        /// <param name="CropName">Name of the crop.</param>
        /// <returns></returns>
        private static SoilCrop PredictedCrop(Soil soil, string CropName)
        {
            double[] A = null;
            double   B = double.NaN;

            double[] KL = null;

            if (soil.SoilType == null)
            {
                return(null);
            }

            if (soil.SoilType.Equals("Black Vertosol", StringComparison.CurrentCultureIgnoreCase))
            {
                if (CropName.Equals("Cotton", StringComparison.CurrentCultureIgnoreCase))
                {
                    A  = BlackVertosol.CottonA;
                    B  = BlackVertosol.CottonB;
                    KL = CottonKL;
                }
                else if (CropName.Equals("Sorghum", StringComparison.CurrentCultureIgnoreCase))
                {
                    A  = BlackVertosol.SorghumA;
                    B  = BlackVertosol.SorghumB;
                    KL = SorghumKL;
                }
                else if (CropName.Equals("Wheat", StringComparison.CurrentCultureIgnoreCase))
                {
                    A  = BlackVertosol.WheatA;
                    B  = BlackVertosol.WheatB;
                    KL = WheatKL;
                }
            }
            else if (soil.SoilType.Equals("Grey Vertosol", StringComparison.CurrentCultureIgnoreCase))
            {
                if (CropName.Equals("Cotton", StringComparison.CurrentCultureIgnoreCase))
                {
                    A  = GreyVertosol.CottonA;
                    B  = GreyVertosol.CottonB;
                    KL = CottonKL;
                }
                else if (CropName.Equals("Sorghum", StringComparison.CurrentCultureIgnoreCase))
                {
                    A  = GreyVertosol.SorghumA;
                    B  = GreyVertosol.SorghumB;
                    KL = SorghumKL;
                }
                else if (CropName.Equals("Wheat", StringComparison.CurrentCultureIgnoreCase))
                {
                    A  = GreyVertosol.WheatA;
                    B  = GreyVertosol.WheatB;
                    KL = WheatKL;
                }
                else if (CropName.Equals("Barley", StringComparison.CurrentCultureIgnoreCase))
                {
                    A  = GreyVertosol.BarleyA;
                    B  = GreyVertosol.BarleyB;
                    KL = BarleyKL;
                }
                else if (CropName.Equals("Chickpea", StringComparison.CurrentCultureIgnoreCase))
                {
                    A  = GreyVertosol.ChickpeaA;
                    B  = GreyVertosol.ChickpeaB;
                    KL = ChickpeaKL;
                }
                else if (CropName.Equals("Fababean", StringComparison.CurrentCultureIgnoreCase))
                {
                    A  = GreyVertosol.FababeanA;
                    B  = GreyVertosol.FababeanB;
                    KL = FababeanKL;
                }
                else if (CropName.Equals("Mungbean", StringComparison.CurrentCultureIgnoreCase))
                {
                    A  = GreyVertosol.MungbeanA;
                    B  = GreyVertosol.MungbeanB;
                    KL = MungbeanKL;
                }
            }


            if (A == null)
            {
                return(null);
            }

            double[] LL = PredictedLL(soil, A, B);
            LL = Layers.MapConcentration(LL, PredictedThickness, soil.Thickness, LL.Last());
            KL = Layers.MapConcentration(KL, PredictedThickness, soil.Thickness, KL.Last());
            double[] XF       = Layers.MapConcentration(PredictedXF, PredictedThickness, soil.Thickness, PredictedXF.Last());
            string[] Metadata = StringUtilities.CreateStringArray("Estimated", soil.Thickness.Length);

            return(new SoilCrop()
            {
                Name = CropName,
                LL = LL,
                LLMetadata = Metadata,
                KL = KL,
                KLMetadata = Metadata,
                XF = XF,
                XFMetadata = Metadata
            });
        }
コード例 #18
0
 /// <summary>
 /// Returns the input values combined into a single string, separated by ",\n".
 /// </summary>
 public static string StringListFormat(string[] input)
 {
     return(StringUtilities.Combine <string>(input, ",\n"));
 }
コード例 #19
0
        private List <udtScansDataType> LoadScansFile(string scansFilePath)
        {
            const string FILTERED_SCANS_SUFFIX = "_filtered_scans.csv";

            var dctColumnInfo = new Dictionary <string, int>
            {
                { "type", -1 },
                { "bpi", -1 },
                { "bpi_mz", -1 },
                { "tic", -1 },
                { "num_peaks", -1 },
                { "num_deisotoped", -1 }
            };

            var colIndexScanOrFrameNum  = -1;
            var colIndexScanOrFrameTime = -1;

            var scanData         = new List <udtScansDataType>();
            var rowNumber        = 0;
            var colIndexScanInfo = -1;

            if (!File.Exists(scansFilePath) && scansFilePath.ToLower().EndsWith(FILTERED_SCANS_SUFFIX.ToLower()))
            {
                scansFilePath = scansFilePath.Substring(0, scansFilePath.Length - FILTERED_SCANS_SUFFIX.Length) + "_scans.csv";
            }

            if (!File.Exists(scansFilePath))
            {
                OnWarningEvent("Warning: _scans.csv file is missing; will plot vs. scan number instead of vs. elution time");
                return(scanData);
            }

            Console.WriteLine("  Reading the _scans.csv file");

            using (var reader = new StreamReader(new FileStream(scansFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
            {
                while (!reader.EndOfStream)
                {
                    rowNumber += 1;
                    var dataLine = reader.ReadLine();

                    if (string.IsNullOrWhiteSpace(dataLine))
                    {
                        continue;
                    }

                    var dataColumns = dataLine.Split(',').ToList();

                    if (rowNumber == 1)
                    {
                        // Parse the header row
                        ParseColumnHeaders(dctColumnInfo, dataColumns, "_scans.csv");

                        colIndexScanOrFrameNum = GetScanOrFrameColIndex(dataColumns, "_scans.csv");

                        colIndexScanOrFrameTime = dataColumns.IndexOf("frame_time");
                        if (colIndexScanOrFrameTime < 0)
                        {
                            colIndexScanOrFrameTime = dataColumns.IndexOf("scan_time");
                        }

                        // The info column will have data of the form "FTMS + p NSI Full ms [400.00-2000.00]" for Thermo datasets
                        // For .mzXML files, this fill will simply have an integer (and thus isn't useful)
                        // It may not be present in older _scans.csv files and is thus optional
                        colIndexScanInfo = dataColumns.IndexOf("info");

                        continue;
                    }

                    try
                    {
                        var udtScanData = new udtScansDataType();

                        int.TryParse(dataColumns[colIndexScanOrFrameNum], out udtScanData.Scan);
                        float.TryParse(dataColumns[colIndexScanOrFrameTime], out udtScanData.ElutionTime);
                        int.TryParse(dataColumns[dctColumnInfo["type"]], out udtScanData.MSLevel);
                        double.TryParse(dataColumns[dctColumnInfo["bpi"]], out udtScanData.BasePeakIntensity);
                        double.TryParse(dataColumns[dctColumnInfo["bpi_mz"]], out udtScanData.BasePeakMZ);
                        double.TryParse(dataColumns[dctColumnInfo["tic"]], out udtScanData.TotalIonCurrent);
                        int.TryParse(dataColumns[dctColumnInfo["num_peaks"]], out udtScanData.NumPeaks);
                        int.TryParse(dataColumns[dctColumnInfo["num_deisotoped"]], out udtScanData.NumDeisotoped);

                        if (colIndexScanInfo > 0)
                        {
                            var infoText = dataColumns[colIndexScanInfo];

                            // Only store infoText in .FilterText if infoText is not simply an integer
                            if (!int.TryParse(infoText, out _))
                            {
                                udtScanData.FilterText = infoText;
                            }
                        }

                        scanData.Add(udtScanData);

                        if (mSaveTICAndBPI)
                        {
                            mTICAndBPIPlot.AddData(udtScanData.Scan, udtScanData.MSLevel, udtScanData.ElutionTime, udtScanData.BasePeakIntensity, udtScanData.TotalIonCurrent);
                        }

                        string scanTypeName;
                        if (string.IsNullOrWhiteSpace(udtScanData.FilterText))
                        {
                            udtScanData.FilterText = udtScanData.MSLevel > 1 ? "HMSn" : "HMS";
                            scanTypeName           = udtScanData.FilterText;
                        }
                        else
                        {
                            scanTypeName = XRawFileIO.GetScanTypeNameFromThermoScanFilterText(udtScanData.FilterText);
                        }

                        var scanStatsEntry = new ScanStatsEntry
                        {
                            ScanNumber                 = udtScanData.Scan,
                            ScanType                   = udtScanData.MSLevel,
                            ScanTypeName               = scanTypeName,
                            ScanFilterText             = XRawFileIO.MakeGenericThermoScanFilter(udtScanData.FilterText),
                            ElutionTime                = udtScanData.ElutionTime.ToString("0.0###"),
                            TotalIonIntensity          = StringUtilities.ValueToString(udtScanData.TotalIonCurrent, 5),
                            BasePeakIntensity          = StringUtilities.ValueToString(udtScanData.BasePeakIntensity, 5),
                            BasePeakMZ                 = udtScanData.BasePeakMZ.ToString("0.0###"),
                            BasePeakSignalToNoiseRatio = "0",
                            IonCount                   = udtScanData.NumDeisotoped,
                            IonCountRaw                = udtScanData.NumPeaks,
                            ExtendedScanInfo           =
                            {
                                CollisionMode  = string.Empty,
                                ScanFilterText = udtScanData.FilterText
                            }
                        };

                        mDatasetStatsSummarizer.AddDatasetScan(scanStatsEntry);
                    }
                    catch (Exception ex)
                    {
                        OnWarningEvent("Warning: Ignoring scan " + dataColumns[dctColumnInfo["scan_num"]] + " since data conversion error: " + ex.Message);
                    }
                }
            }

            return(scanData);
        }
コード例 #20
0
ファイル: PropertyPresenter.cs プロジェクト: oseledets/ApsimX
        /// <summary>
        /// Format the grid.
        /// </summary>
        private void FormatGrid()
        {
            for (int i = 0; i < this.properties.Count; i++)
            {
                IGridCell cell = this.grid.GetCell(1, i);

                if (this.properties[i].DisplayType == DisplayAttribute.DisplayTypeEnum.TableName)
                {
                    DataStore dataStore = new DataStore(this.model);
                    cell.EditorType      = EditorTypeEnum.DropDown;
                    cell.DropDownStrings = dataStore.TableNames;
                    dataStore.Disconnect();
                }
                else if (this.properties[i].DisplayType == DisplayAttribute.DisplayTypeEnum.CultivarName)
                {
                    cell.EditorType = EditorTypeEnum.DropDown;
                    ICrop crop = GetCrop(properties);
                    if (crop != null)
                    {
                        cell.DropDownStrings = GetCultivarNames(crop);
                    }
                }
                else if (this.properties[i].DisplayType == DisplayAttribute.DisplayTypeEnum.FileName)
                {
                    cell.EditorType = EditorTypeEnum.Button;
                }
                else if (this.properties[i].DisplayType == DisplayAttribute.DisplayTypeEnum.FieldName)
                {
                    cell.EditorType = EditorTypeEnum.DropDown;
                    string[] fieldNames = GetFieldNames();
                    if (fieldNames != null)
                    {
                        cell.DropDownStrings = fieldNames;
                    }
                }
                else
                {
                    object cellValue = this.properties[i].ValueWithArrayHandling;
                    if (cellValue is DateTime)
                    {
                        cell.EditorType = EditorTypeEnum.DateTime;
                    }
                    else if (cellValue is bool)
                    {
                        cell.EditorType = EditorTypeEnum.Boolean;
                    }
                    else if (cellValue.GetType().IsEnum)
                    {
                        cell.EditorType      = EditorTypeEnum.DropDown;
                        cell.DropDownStrings = StringUtilities.EnumToStrings(cellValue);
                    }
                    else if (cellValue.GetType() == typeof(ICrop))
                    {
                        cell.EditorType = EditorTypeEnum.DropDown;
                        List <string> cropNames = new List <string>();
                        foreach (Model crop in Apsim.FindAll(this.model, typeof(ICrop)))
                        {
                            cropNames.Add(crop.Name);
                        }
                        cell.DropDownStrings = cropNames.ToArray();
                    }
                    else if (this.properties[i].DataType == typeof(ICrop))
                    {
                        List <string> plantNames = Apsim.FindAll(this.model, typeof(ICrop)).Select(m => m.Name).ToList();
                        cell.EditorType      = EditorTypeEnum.DropDown;
                        cell.DropDownStrings = plantNames.ToArray();
                    }
                    else
                    {
                        cell.EditorType = EditorTypeEnum.TextBox;
                    }
                }
            }

            IGridColumn descriptionColumn = this.grid.GetColumn(0);

            descriptionColumn.Width    = -1;
            descriptionColumn.ReadOnly = true;

            IGridColumn valueColumn = this.grid.GetColumn(1);

            valueColumn.Width = -1;
        }
コード例 #21
0
ファイル: Utilities.cs プロジェクト: lie112/ApsimX
 public static string RunModels(string arguments)
 {
     return(RunModels(StringUtilities.SplitStringHonouringQuotes(arguments, " ").Cast <string>().ToArray()));
 }
コード例 #22
0
        /// <summary>
        /// Publishes information about linked models/images/object styles in the model.
        /// </summary>
        public void PublishData()
        {
            try
            {
                if (!MonitorUtilities.IsUpdaterOn(Project, Config, UpdaterGuid))
                {
                    return;
                }
                if (string.IsNullOrEmpty(FamiliesId))
                {
                    return;
                }

                var unusedFamilies    = 0;
                var oversizedFamilies = 0;
                var inPlaceFamilies   = 0;
                var families          = new FilteredElementCollector(Doc)
                                        .OfClass(typeof(Family))
                                        .Cast <Family>()
                                        .ToList();

                var config = MissionControlSetup.Configurations.ContainsKey(CentralPath)
                    ? MissionControlSetup.Configurations[CentralPath]
                    : null;

                var familyNameCheck = new List <string> {
                    "HOK_I", "HOK_M"
                };                                                           //defaults
                if (config != null)
                {
                    familyNameCheck = config.Updaters.First(x => string.Equals(x.UpdaterId,
                                                                               Properties.Resources.HealthReportTrackerGuid, StringComparison.OrdinalIgnoreCase)).UserOverrides.FamilyNameCheck.Values;
                }

                //var count = 0;
                var famOutput = new List <FamilyItem>();
                StatusBarManager.InitializeProgress("Exporting Family Info:", families.Count);
                foreach (var family in families)
                {
                    // (Konrad) Uncomment for Debug.
                    //count++;
                    //if (count > 5) continue;
                    if (StatusBarManager.Cancel)
                    {
                        StatusBarManager.CancelProgress();
                        return;
                    }
                    StatusBarManager.StepForward();

                    var sizeCheck     = false;
                    var instanceCheck = false;
                    var nameCheck     = false;

                    var instances = CountFamilyInstances(family);
                    if (instances == 0)
                    {
                        unusedFamilies++;
                        instanceCheck = true;
                    }
                    if (family.IsInPlace)
                    {
                        inPlaceFamilies++;
                    }

                    long size           = 0;
                    var  refPlanes      = 0;
                    var  arrays         = 0;
                    var  voids          = 0;
                    var  nestedFamilies = 0;
                    var  parameters     = 0;
                    var  sizeStr        = "0Kb";
                    var  images         = 0;
                    try
                    {
                        var famDoc = Doc.EditFamily(family);

                        var storedPath = famDoc.PathName;
                        if (File.Exists(storedPath))
                        {
                            size = new FileInfo(storedPath).Length;
                        }
                        else
                        {
                            if (string.IsNullOrWhiteSpace(famDoc.Title))
                            {
                                continue;                                          // could cause an exception
                            }
                            var myDocPath = IsCitrixMachine()
                                ? AppSettings.Instance.TempLocation.TempPath
                                : Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                            var path = myDocPath + "\\temp_" + famDoc.Title;
                            if (path.IndexOfAny(Path.GetInvalidPathChars()) != -1)
                            {
                                continue;                                                    // could cause an exception
                            }
                            if (File.Exists(path))
                            {
                                TryToDelete(path);
                            }
                            famDoc.SaveAs(path);
                            size = new FileInfo(path).Length;
                            TryToDelete(path);
                        }

                        refPlanes = new FilteredElementCollector(famDoc)
                                    .OfClass(typeof(ReferencePlane))
                                    .GetElementCount();

                        var filter = new LogicalOrFilter(new List <ElementFilter>
                        {
                            new ElementClassFilter(typeof(LinearArray)),
                            new ElementClassFilter(typeof(RadialArray))
                        });

                        arrays = new FilteredElementCollector(famDoc)
                                 .WherePasses(filter)
                                 .GetElementCount();

                        images = new FilteredElementCollector(famDoc)
                                 .OfClass(typeof(ImageType))
                                 .WhereElementIsElementType()
                                 .GetElementCount();

                        voids = new FilteredElementCollector(famDoc)
                                .OfClass(typeof(Extrusion))
                                .Cast <Extrusion>()
                                .Count(x => !x.IsSolid);

                        nestedFamilies = new FilteredElementCollector(famDoc)
                                         .OfClass(typeof(Family))
                                         .GetElementCount();
#if RELEASE2015
                        //(Konrad) Since Revit 2015 API doesn't support this we will just skip it.
                        parameters = 0;
#else
                        parameters = new FilteredElementCollector(famDoc)
                                     .OfClass(typeof(ParameterElement))
                                     .GetElementCount();
#endif
                        famDoc.Close(false);

                        sizeStr = StringUtilities.BytesToString(size);
                        if (size > 1000000)
                        {
                            oversizedFamilies++; // >1MB
                            sizeCheck = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
                        Log.AppendLog(LogMessageType.ERROR, "Failed to retrieve size, refPlanes, arrays, voids...");
                    }

                    if (!familyNameCheck.Any(family.Name.Contains))
                    {
                        nameCheck = true;
                    }

                    var famItem = new FamilyItem
                    {
                        Name              = family.Name,
                        ElementId         = family.Id.IntegerValue,
                        Size              = sizeStr,
                        SizeValue         = size,
                        Instances         = instances,
                        ArrayCount        = arrays,
                        RefPlaneCount     = refPlanes,
                        VoidCount         = voids,
                        NestedFamilyCount = nestedFamilies,
                        ParametersCount   = parameters,
                        ImageCount        = images,
                        Tasks             = new List <FamilyTask>()
                    };

                    if (nameCheck || sizeCheck || instanceCheck)
                    {
                        famItem.IsFailingChecks = true;
                    }
                    else
                    {
                        famItem.IsFailingChecks = false;
                    }

                    famOutput.Add(famItem);
                }

                if (!ServerUtilities.GetByCentralPath(CentralPath, "families/centralpath", out FamilyData famStat))
                {
                    Log.AppendLog(LogMessageType.ERROR, "Failed to retrieve Families data.");
                    return;
                }

                var famDict = new Dictionary <string, FamilyItem>();
                if (famStat != null)
                {
                    famDict = famStat.Families.ToDictionary(x => x.Name, x => x);
                }

                // (Konrad) I know it's not efficient to iterate this list yet again, but
                // I want to minimize the amount of time between publishing families and
                // retrieving them from database to avoid someone adding tasks to DB while
                // we are exporting and hence losing them after the export.
                foreach (var family in famOutput)
                {
                    if (famDict.ContainsKey(family.Name))
                    {
                        family.Tasks.AddRange(famDict[family.Name].Tasks);
                        famDict.Remove(family.Name);
                    }
                }

                foreach (var item in famDict.Values.ToList())
                {
                    item.IsDeleted = true;
                    famOutput.Add(item);
                }

                var familyStats = new FamilyData
                {
                    CentralPath       = CentralPath.ToLower(),
                    TotalFamilies     = famOutput.Count,
                    UnusedFamilies    = unusedFamilies,
                    InPlaceFamilies   = inPlaceFamilies,
                    OversizedFamilies = oversizedFamilies,
                    CreatedBy         = Environment.UserName.ToLower(),
                    CreatedOn         = DateTime.UtcNow,
                    Families          = famOutput
                };

                if (!ServerUtilities.Put(familyStats, "families/" + famStat.Id))
                {
                    Log.AppendLog(LogMessageType.ERROR, "Failed to publish Families data.");
                }
                StatusBarManager.FinalizeProgress();
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
            }
        }
コード例 #23
0
ファイル: JsGlobal.cs プロジェクト: mikelgusev/Gsemac.Common
        public static string Unescape(string str)
        {
            str = StringUtilities.Unescape(str, UnescapeOptions.UnescapeEscapeSequences | UnescapeOptions.UnescapeUriEncoding);

            return(str);
        }
コード例 #24
0
        public void BasicNameWithList(string title, string minorWords, string expected)
        {
            var actual = StringUtilities.TitleCase(title, minorWords);

            Assert.Matches(expected, actual);
        }
コード例 #25
0
ファイル: Locater.cs プロジェクト: peter-devoil/ApsimX
        /// <summary>
        /// Get the value of a variable or model.
        /// </summary>
        /// <param name="namePath">The name of the object to return</param>
        /// <param name="relativeTo">The model calling this method</param>
        /// <param name="ignoreCase">If true, ignore case when searching for the object or property</param>
        /// <returns>The found object or null if not found</returns>
        public IVariable GetInternal(string namePath, Model relativeTo, bool ignoreCase = false)
        {
            Model            relativeToModel = relativeTo;
            string           cacheKey        = namePath;
            StringComparison compareType     = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;

            // Look in cache first.
            object value = GetFromCache(cacheKey, relativeToModel);

            if (value != null)
            {
                return(value as IVariable);
            }

            IVariable returnVariable = null;

            if (namePath == null || namePath.Length == 0)
            {
                return(null);
            }
            else if (namePath[0] != '.' &&
                     namePath.Replace("()", "").IndexOfAny("(+*/".ToCharArray()) != -1)
            {
                // expression - need a better way of detecting an expression
                returnVariable = new VariableExpression(namePath, relativeToModel);
            }
            else
            {
                // Remove a square bracketed model name and change our relativeTo model to
                // the referenced model.
                if (namePath.StartsWith("["))
                {
                    int posCloseBracket = namePath.IndexOf(']');
                    if (posCloseBracket == -1)
                    {
                        return(null);
                    }
                    string modelName = namePath.Substring(1, posCloseBracket - 1);
                    namePath = namePath.Remove(0, posCloseBracket + 1);
                    Model foundModel = relativeToModel.FindInScope(modelName) as Model;
                    if (foundModel == null)
                    {
                        // Didn't find a model with a name matching the square bracketed string so
                        // now try and look for a model with a type matching the square bracketed string.
                        Type[] modelTypes = GetTypeWithoutNameSpace(modelName);
                        if (modelTypes.Length == 1)
                        {
                            foundModel = relativeToModel.FindAllInScope().FirstOrDefault(m => modelTypes[0].IsAssignableFrom(m.GetType())) as Model;
                        }
                    }
                    if (foundModel == null)
                    {
                        return(null);
                    }
                    else
                    {
                        relativeToModel = foundModel;
                    }
                }
                else if (namePath.StartsWith("."))
                {
                    // Absolute path
                    Model root = relativeToModel;
                    while (root.Parent != null)
                    {
                        root = root.Parent as Model;
                    }
                    relativeToModel = root;

                    int posPeriod = namePath.IndexOf('.', 1);
                    if (posPeriod == -1)
                    {
                        // Path starts with a . and only contains a single period.
                        // If name matches then no problem. Otherwise we need to return null.
                        posPeriod = namePath.IndexOf('.');
                        if (namePath.Remove(0, posPeriod) == relativeToModel.Name)
                        {
                            posPeriod = namePath.Length;
                        }
                    }

                    namePath = namePath.Remove(0, posPeriod);
                    if (namePath.StartsWith("."))
                    {
                        namePath = namePath.Remove(0, 1);
                    }
                }
                else
                {
                    // Try a report column.
                    foreach (Report report in relativeTo.FindAllInScope <Report>())
                    {
                        IReportColumn column = report.Columns?.Find(c => c.Name == namePath);
                        if (column != null)
                        {
                            return(new VariableObject(column.GetValue(0)));
                        }
                    }
                }

                // Now walk the series of '.' separated path bits, assuming the path bits
                // are child models. Stop when we can't find the child model.
                string[] namePathBits = namePath.Split(".".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                int      i;
                for (i = 0; i < namePathBits.Length; i++)
                {
                    IModel localModel = relativeToModel.Children.FirstOrDefault(m => m.Name.Equals(namePathBits[i], compareType));
                    if (localModel == null)
                    {
                        // Allow for the possibility that the first path element may point to
                        // the starting parent model, rather than to a child within that model
                        if ((i == 0) && relativeToModel.Name.Equals(namePathBits[i], compareType))
                        {
                            continue;
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        relativeToModel = localModel as Model;
                    }
                }

                // At this point there are only 2 possibilities. We have encountered a
                // PropertyInfo or the path is invalid.
                // We now need to loop through the remaining path bits and keep track of each
                // section of the path as each section will have to be evaulated everytime a
                // a get is done for this path.
                // The variable 'i' will point to the name path that cannot be found as a model.
                object           relativeToObject = relativeToModel;
                List <IVariable> properties       = new List <IVariable>();
                properties.Add(new VariableObject(relativeToModel));
                for (int j = i; j < namePathBits.Length; j++)
                {
                    // look for an array specifier e.g. sw[2]
                    string arraySpecifier = null;
                    if (namePathBits[j].Contains("["))
                    {
                        arraySpecifier = StringUtilities.SplitOffBracketedValue(ref namePathBits[j], '[', ']');
                    }

                    // Look for either a property or a child model.
                    IModel localModel = null;
                    if (relativeToObject == null)
                    {
                        return(null);
                    }
                    PropertyInfo propertyInfo = relativeToObject.GetType().GetProperty(namePathBits[j]);
                    if (propertyInfo == null && ignoreCase) // If not found, try using a case-insensitive search
                    {
                        propertyInfo = relativeToObject.GetType().GetProperty(namePathBits[j], BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase);
                    }
                    if (relativeToObject is IFunction && namePathBits[j] == "Value()")
                    {
                        MethodInfo method = relativeToModel.GetType().GetMethod("Value");
                        properties.Add(new VariableMethod(relativeToModel, method));
                    }
                    else if (propertyInfo == null && relativeToObject is Model)
                    {
                        // Not a property, may be a child model.
                        localModel = (relativeToObject as IModel).Children.FirstOrDefault(m => m.Name.Equals(namePathBits[i], compareType));
                        if (localModel == null)
                        {
                            return(null);
                        }

                        properties.Add(new VariableObject(localModel));
                        relativeToObject = localModel;
                    }
                    else if (propertyInfo != null)
                    {
                        VariableProperty property = new VariableProperty(relativeToObject, propertyInfo, arraySpecifier);
                        properties.Add(property);
                        relativeToObject = property.Value;
                    }
                    else if (relativeToObject is IList)
                    {
                        // Special case: we are trying to get a property of an array(IList). In this case
                        // we want to return the property value for all items in the array.
                        VariableProperty property = new VariableProperty(relativeToObject, namePathBits[j], arraySpecifier);
                        properties.Add(property);
                        relativeToObject = property.Value;
                    }
                    else
                    {
                        return(null);
                    }
                }

                // We now have a list of IVariable instances that can be evaluated to
                // produce a return value for the given path. Wrap the list into an IVariable.
                returnVariable = new VariableComposite(namePath, properties);
            }

            // Add variable to cache.
            AddToCache(cacheKey, relativeTo, returnVariable);

            return(returnVariable);
        }
コード例 #26
0
        public void NoMinorWords(string title, string minorWords, string expected)
        {
            var actual = StringUtilities.TitleCase(title, minorWords);

            Assert.Equal(expected, actual);
        }
コード例 #27
0
        /// <summary>
        /// Get the value of a variable or model.
        /// </summary>
        /// <param name="namePath">The name of the object to return</param>
        /// <param name="ignoreCase">If true, ignore case when searching for the object or property</param>
        /// <returns>The found object or null if not found</returns>
        private IVariable GetInternal(string namePath, bool ignoreCase = true)
        {
            IModel           relativeTo  = relativeToModel;
            string           cacheKey    = namePath;
            StringComparison compareType = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;

            // Look in cache first.
            object value = null;

            if (cache.ContainsKey(cacheKey))
            {
                value = cache[cacheKey];
            }
            if (value != null)
            {
                return(value as IVariable);
            }

            IVariable returnVariable = null;

            if (namePath == null || namePath.Length == 0)
            {
                return(null);
            }
            else if (namePath[0] != '.' &&
                     (namePath.Replace("()", "").IndexOfAny("+*/".ToCharArray()) != -1
                      | (namePath.IndexOfAny("(".ToCharArray()) >= 0 && namePath.Substring(0, (namePath.IndexOf('(') >= 0? namePath.IndexOf('(') : 0)).IndexOfAny("[.".ToCharArray()) == -1)))
            {
                // expression - need a better way of detecting an expression
                returnVariable = new VariableExpression(namePath, relativeTo as Model);
            }
            else
            {
                namePath = namePath.Replace("Value()", "Value().");
                // Remove a square bracketed model name and change our relativeTo model to
                // the referenced model.
                if (namePath.StartsWith("["))
                {
                    int posCloseBracket = namePath.IndexOf(']');
                    if (posCloseBracket == -1)
                    {
                        return(null);
                    }
                    string modelName = namePath.Substring(1, posCloseBracket - 1);
                    namePath = namePath.Remove(0, posCloseBracket + 1);
                    Model foundModel = Apsim.Find(relativeTo, modelName) as Model;
                    if (foundModel == null)
                    {
                        // Didn't find a model with a name matching the square bracketed string so
                        // now try and look for a model with a type matching the square bracketed string.
                        Type[] modelTypes = GetTypeWithoutNameSpace(modelName);
                        if (modelTypes.Length == 1)
                        {
                            foundModel = Apsim.Find(relativeTo, modelTypes[0]) as Model;
                        }
                    }
                    if (foundModel == null)
                    {
                        return(null);
                    }
                    else
                    {
                        relativeTo = foundModel;
                    }
                }
                else if (namePath.StartsWith("."))
                {
                    // Absolute path
                    IModel root = relativeTo;
                    while (root.Parent != null)
                    {
                        root = root.Parent as Model;
                    }
                    relativeTo = root;

                    int posPeriod = namePath.IndexOf('.', 1);
                    if (posPeriod == -1)
                    {
                        posPeriod = namePath.Length;
                    }

                    namePath = namePath.Remove(0, posPeriod);
                    if (namePath.StartsWith("."))
                    {
                        namePath.Remove(1);
                    }
                }

                // Now walk the series of '.' separated path bits, assuming the path bits
                // are child models. Stop when we can't find the child model.
                string[] namePathBits = namePath.Split(".".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                int      i;
                for (i = 0; i < namePathBits.Length; i++)
                {
                    IModel localModel = relativeTo.Children.FirstOrDefault(m => m.Name.Equals(namePathBits[i], compareType));
                    if (localModel == null)
                    {
                        break;
                    }
                    else
                    {
                        relativeTo = localModel as Model;
                    }
                }

                // At this point there are only 2 possibilities. We have encountered a
                // PropertyInfo/MethodInfo or the path is invalid.
                // We now need to loop through the remaining path bits and keep track of each
                // section of the path as each section will have to be evaulated everytime a
                // a get is done for this path.
                // The variable 'i' will point to the name path that cannot be found as a model.
                object           relativeToObject = relativeTo;
                List <IVariable> properties       = new List <IVariable>();
                properties.Add(new VariableObject(relativeTo));
                for (int j = i; j < namePathBits.Length; j++)
                {
                    // look for an array specifier e.g. sw[2]
                    string arraySpecifier = null;
                    if (namePathBits[j].Contains("["))
                    {
                        arraySpecifier = StringUtilities.SplitOffBracketedValue(ref namePathBits[j], '[', ']');
                    }

                    // Look for either a property or a child model.
                    IModel localModel = null;
                    if (relativeToObject == null)
                    {
                        return(null);
                    }

                    // Check property info
                    PropertyInfo propertyInfo = relativeToObject.GetType().GetProperty(namePathBits[j]);
                    if (propertyInfo == null && ignoreCase) // If not found, try using a case-insensitive search
                    {
                        propertyInfo = relativeToObject.GetType().GetProperty(namePathBits[j], BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase);
                    }

                    // If not property info
                    // Check method info
                    MethodInfo    methodInfo    = null;
                    List <object> argumentsList = null;
                    if (propertyInfo == null)
                    {
                        if (namePathBits[j].IndexOf('(') > 0)
                        {
                            relativeToObject.GetType().GetMethod(namePathBits[j].Substring(0, namePathBits[j].IndexOf('(')));
                            if (methodInfo == null && ignoreCase) // If not found, try using a case-insensitive search
                            {
                                methodInfo = relativeToObject.GetType().GetMethod(namePathBits[j].Substring(0, namePathBits[j].IndexOf('(')), BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase);
                            }
                        }
                        if (methodInfo != null)
                        {
                            // get arguments and store in VariableMethod
                            string args = namePathBits[j].Substring(namePathBits[j].IndexOf('('));
                            args = args.Substring(0, args.IndexOf(')'));
                            args = args.Replace("(", "").Replace(")", "");
                            if (args.Length > 0)
                            {
                                argumentsList = new List <object>();
                                args          = args.Trim('(').Trim(')');
                                var argList = args.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                                // get arguments
                                ParameterInfo[] pars = methodInfo.GetParameters();

                                for (int argid = 0; argid < argList.Length; argid++)
                                {
                                    var cleanArg = argList[argid].Trim(' ').Trim(new char[] { '(', ')' }).Trim(' ').Trim('"');
                                    switch (Type.GetTypeCode(pars[argid].ParameterType))
                                    {
                                    case TypeCode.Double:
                                        argumentsList.Add(Convert.ToDouble(cleanArg, CultureInfo.InvariantCulture));
                                        break;

                                    case TypeCode.Int32:
                                        argumentsList.Add(Convert.ToInt32(cleanArg, CultureInfo.InvariantCulture));
                                        break;

                                    case TypeCode.String:
                                        argumentsList.Add(cleanArg);
                                        break;

                                    default:
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    //if (relativeToObject is IFunction && namePathBits[j] == "Value()")
                    //{
                    //    MethodInfo method = relativeTo.GetType().GetMethod("Value");
                    //    properties.Add(new VariableMethod(relativeTo, method));
                    //}
                    //                    else if (propertyInfo == null && methodInfo == null && relativeToObject is Model)

                    if (propertyInfo == null && methodInfo == null && relativeToObject is Model)
                    {
                        // Not a property, may be an unchecked method or a child model.
                        localModel = (relativeToObject as IModel).Children.FirstOrDefault(m => m.Name.Equals(namePathBits[j], compareType));
                        if (localModel == null)
                        {
                            // Not a model
                            return(null);
                        }
                        else
                        {
                            properties.Add(new VariableObject(localModel));
                            relativeToObject = localModel;
                        }
                    }
                    else if (propertyInfo != null)
                    {
                        VariableProperty property = new VariableProperty(relativeToObject, propertyInfo, arraySpecifier);
                        properties.Add(property);
                        relativeToObject = property.Value;
                    }
                    else if (methodInfo != null)
                    {
                        VariableMethod method = null;
                        if (argumentsList != null)
                        {
                            method = new VariableMethod(relativeToObject, methodInfo, argumentsList.ToArray <object>());
                        }
                        else
                        {
                            method = new VariableMethod(relativeToObject, methodInfo, null);
                        }
                        //                        VariableProperty property = new VariableProperty(relativeToObject, propertyInfo, arraySpecifier);
                        properties.Add(method);
                        relativeToObject = method.Value;
                    }
                    else if (relativeToObject is IList)
                    {
                        // Special case: we are trying to get a property of an array(IList). In this case
                        // we want to return the property value for all items in the array.
                        VariableProperty property = new VariableProperty(relativeToObject, namePathBits[j]);
                        properties.Add(property);
                        relativeToObject = property.Value;
                    }
                    else
                    {
                        return(null);
                    }
                }

                // We now have a list of IVariable instances that can be evaluated to
                // produce a return value for the given path. Wrap the list into an IVariable.
                returnVariable = new VariableComposite(namePath, properties);
            }

            // Add variable to cache.
            cache.Add(cacheKey, returnVariable);

            return(returnVariable);
        }
コード例 #28
0
        public static void ToXml(TextWriter writer, TraceProcess stats, TraceLoadedDotNetRuntime runtime, string indent)
        {
            JITStatsEx statsEx = JITStatsEx.Create(runtime);

            // TODO pay attention to indent;
            writer.Write(" <JitProcess Process=\"{0}\" ProcessID=\"{1}\" JitTimeMSec=\"{2:n3}\" Count=\"{3}\" ILSize=\"{4}\" NativeSize=\"{5}\"",
                         stats.Name, stats.ProcessID, runtime.JIT.Stats().TotalCpuTimeMSec, runtime.JIT.Stats().Count, runtime.JIT.Stats().TotalILSize, runtime.JIT.Stats().TotalNativeSize);
            if (stats.CPUMSec != 0)
            {
                writer.Write(" ProcessCpuTimeMsec=\"{0}\"", stats.CPUMSec);
            }

            if (!string.IsNullOrEmpty(stats.CommandLine))
            {
                writer.Write(" CommandLine=\"{0}\"", XmlUtilities.XmlEscape(stats.CommandLine, false));
            }

            writer.WriteLine(">");
            writer.WriteLine("  <JitEvents>");
            foreach (TraceJittedMethod _event in runtime.JIT.Methods)
            {
                ToXml(writer, _event);
            }

            writer.WriteLine("  </JitEvents>");

            writer.WriteLine(" <ModuleStats Count=\"{0}\" TotalCount=\"{1}\" TotalJitTimeMSec=\"{2:n3}\" TotalILSize=\"{3}\" TotalNativeSize=\"{4}\">",
                             statsEx.TotalModuleStats.Count, runtime.JIT.Stats().Count, runtime.JIT.Stats().TotalCpuTimeMSec, runtime.JIT.Stats().TotalILSize, runtime.JIT.Stats().TotalNativeSize);

            // Sort the module list by Jit Time;
            List <string> moduleNames = new List <string>(statsEx.TotalModuleStats.Keys);

            moduleNames.Sort(delegate(string x, string y)
            {
                double diff = statsEx.TotalModuleStats[y].TotalCpuTimeMSec - statsEx.TotalModuleStats[x].TotalCpuTimeMSec;
                if (diff > 0)
                {
                    return(1);
                }
                else if (diff < 0)
                {
                    return(-1);
                }

                return(0);
            });

            foreach (string moduleName in moduleNames)
            {
                JITStats info = statsEx.TotalModuleStats[moduleName];
                writer.Write("<Module");
                writer.Write(" JitTimeMSec={0}", StringUtilities.QuotePadLeft(info.TotalCpuTimeMSec.ToString("n3"), 11));
                writer.Write(" Count={0}", StringUtilities.QuotePadLeft(info.Count.ToString(), 7));
                writer.Write(" ILSize={0}", StringUtilities.QuotePadLeft(info.TotalILSize.ToString(), 9));
                writer.Write(" NativeSize={0}", StringUtilities.QuotePadLeft(info.TotalNativeSize.ToString(), 9));
                writer.Write(" Name=\"{0}\"", moduleName);
                writer.WriteLine("/>");
            }
            writer.WriteLine("  </ModuleStats>");

            writer.WriteLine(" </JitProcess>");
        }
コード例 #29
0
        private string AddFileNameListItem(string fileName, ref Gdk.Pixbuf image)
        {
            image = null;
            Listview.ItemPadding = 6; // Restore padding if we have images to display

            List <string> resourceNames = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames().ToList();

            List <string> images = resourceNames.FindAll(r => r.EndsWith(".svg"));

            images.AddRange(resourceNames.FindAll(r => r.Contains(".LargeImages.")));

            string result     = $"<span>{Path.GetFileName(fileName)}</span>\n<small><i><span>{Path.GetDirectoryName(fileName)}</span></i></small>";
            string searchName = Path.GetFileNameWithoutExtension(fileName);

            (bool exists, string resourceName) = ExplorerPresenter.CheckIfIconExists(searchName);
            if (exists)
            {
                image = new Gdk.Pixbuf(null, resourceName);
            }
            else
            {
                // Add an image index.
                foreach (string imageName in images)
                {
                    string[] parts          = imageName.Split('.');
                    string   shortImageName = parts.Length > 1 ? parts[parts.Length - 2] : StringUtilities.GetAfter(imageName, ".LargeImages.").Replace(".png", "");
                    if (result.ToLower().Contains(shortImageName.ToLower()))
                    {
                        image = new Gdk.Pixbuf(null, imageName);
                        break;
                    }
                }
            }
            if (image == null)
            {
                image = new Gdk.Pixbuf(null, "ApsimNG.Resources.apsim logo32.png");
            }

            return(result);
        }
コード例 #30
0
 /// <summary>
 /// Gets a text description of this object.
 /// </summary>
 public override string ToString()
 {
     return(StringUtilities.Combine(new string[] { Name, Uid }, " | ", true));
 }