Exemple #1
0
        /// <summary>Export the map to PDF</summary>
        /// <param name="folder">The working directory name</param>
        /// <returns>The filename string</returns>
        public string ExportToPNG(string folder)
        {
            string path     = Apsim.FullPath(this.map).Replace(".Simulations.", string.Empty);
            string fileName = Path.Combine(folder, path + ".png");

            Image rawImage = this.view.Export();

            rawImage.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);

            return(fileName);
        }
        /// <summary>Performs the command.</summary>
        /// <param name="commandHistory">The command history.</param>
        public void Do(CommandHistory commandHistory)
        {
            string originalPath = Apsim.FullPath(this.modelToRename);

            // Get original value of property so that we can restore it in Undo if needed.
            originalName = this.modelToRename.Name;

            // Set the new name.
            Structure.Rename(modelToRename, newName);
            explorerView.Tree.Rename(originalPath, this.modelToRename.Name);
        }
Exemple #3
0
        /// <summary>Export the map to PDF</summary>
        /// <param name="workingDirectory"></param>
        /// <returns></returns>
        internal string ExportToPDF(string folder)
        {
            string path     = Apsim.FullPath(map).Replace(".Simulations.", "");
            string fileName = Path.Combine(folder, path + ".png");

            Image rawImage = view.Export();

            rawImage.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);

            return(fileName);
        }
        /// <summary>
        /// Perform the command
        /// </summary>
        public void Do(CommandHistory CommandHistory)
        {
            Simulation clonedSimulation = null;
            IEvent     events           = null;

            try
            {
                clonedSimulation = Apsim.Clone(simulation) as Simulation;
                explorerPresenter.ApsimXFile.MakeSubstitutions(clonedSimulation);

                events = explorerPresenter.ApsimXFile.GetEventService(clonedSimulation);
                events.ConnectEvents();
                explorerPresenter.ApsimXFile.Links.Resolve(clonedSimulation);

                List <ModelDoc> models = new List <ModelDoc>();
                foreach (IModel model in Apsim.ChildrenRecursively(clonedSimulation))
                {
                    ModelDoc newModelDoc = DocumentModel(model);
                    newModelDoc.Name = Apsim.FullPath(model);
                    models.Add(newModelDoc);
                }

                StringWriter  rawXML     = new StringWriter();
                XmlSerializer serialiser = new XmlSerializer(typeof(List <ModelDoc>));
                serialiser.Serialize(rawXML, models);
                rawXML.Close();

                // Load the XSL transform from the resource
                Stream s         = Assembly.GetExecutingAssembly().GetManifestResourceStream("UserInterface.Resources.DebugDoc.xsl");
                var    transform = new XslCompiledTransform();
                using (XmlReader reader = XmlReader.Create(s))
                {
                    transform.Load(reader);
                }

                // Apply the transform to the reader and write it to a temporary file.
                string htmlFileName = Path.GetTempFileName() + ".html";
                using (XmlReader reader = XmlReader.Create(new StringReader(rawXML.ToString())))
                    using (XmlWriter htmlWriter = XmlWriter.Create(htmlFileName))
                    {
                        transform.Transform(reader, htmlWriter);
                    }
                Process.Start(htmlFileName);
            }
            finally
            {
                if (clonedSimulation != null)
                {
                    events.DisconnectEvents();
                    explorerPresenter.ApsimXFile.Links.Unresolve(clonedSimulation);
                }
            }
        }
Exemple #5
0
 /// <summary>
 /// Write a warning message to the summary
 /// </summary>
 /// <param name="model">The model writing the message</param>
 /// <param name="message">The warning message to write</param>
 public void WriteWarning(IModel model, string message)
 {
     if (this.messagesTable != null)
     {
         DataRow newRow = this.messagesTable.NewRow();
         newRow["ComponentName"] = Apsim.FullPath(model);
         newRow["Date"]          = this.clock.Today;
         newRow["Message"]       = message;
         newRow["MessageType"]   = Convert.ToInt32(DataStore.ErrorLevel.Warning);
         this.messagesTable.Rows.Add(newRow);
     }
 }
Exemple #6
0
        /// <summary>Write a message to the summary</summary>
        /// <param name="model">The model writing the message</param>
        /// <param name="message">The message to write</param>
        public void WriteMessage(IModel model, string message)
        {
            if (storage == null)
            {
                throw new ApsimXException(model, "No datastore is available!");
            }
            string modelPath         = Apsim.FullPath(model);
            string relativeModelPath = modelPath.Replace(Apsim.FullPath(simulation) + ".", string.Empty);

            object[] values = new object[] { relativeModelPath, clock.Today, message, Convert.ToInt32(Simulation.ErrorLevel.Information) };
            storage.WriteRow(simulation.Name, "_Messages", summaryTableColumnNames, null, values);
        }
Exemple #7
0
        /// <summary>Perform the command</summary>
        /// <param name="commandHistory">The command history.</param>
        public void Do(CommandHistory commandHistory)
        {
            this.modelToAdd = Apsim.Add(parent, child);

            // The add method above may have renamed the model to avoid a clash with the
            // name of an existing model so just in case, reset the name for the tree.
            nodeDescription.Name = this.modelToAdd.Name;

            this.explorerView.Tree.AddChild(Apsim.FullPath(parent), nodeDescription);

            this.modelAdded = true;
        }
Exemple #8
0
        /// <summary>Performs the command.</summary>
        /// <param name="CommandHistory">The command history.</param>
        public void Do(CommandHistory CommandHistory)
        {
            string originalPath = Apsim.FullPath(modelToRename);

            // Get original value of property so that we can restore it in Undo if needed.
            originalName = modelToRename.Name;

            // Set the new name.
            this.modelToRename.Name = newName;
            Apsim.EnsureNameIsUnique(this.modelToRename);
            explorerView.Rename(originalPath, this.modelToRename.Name);
        }
Exemple #9
0
        /// <summary>
        /// Write a message to the summary
        /// </summary>
        /// <param name="model">The model writing the message</param>
        /// <param name="message">The message to write</param>
        public void WriteMessage(IModel model, string message)
        {
            string modelFullPath     = Apsim.FullPath(model);
            string relativeModelPath = modelFullPath.Replace(Apsim.FullPath(Simulation) + ".", string.Empty);

            DataRow newRow = this.messagesTable.NewRow();

            newRow["ComponentName"] = relativeModelPath;
            newRow["Date"]          = this.clock.Today;
            newRow["Message"]       = message;
            newRow["MessageType"]   = Convert.ToInt32(DataStore.ErrorLevel.Information);
            this.messagesTable.Rows.Add(newRow);
        }
Exemple #10
0
        /// <summary>Undo the command.</summary>
        public void Undo(CommandHistory CommandHistory)
        {
            if (modelMoved)
            {
                presenter.Move(Apsim.FullPath(this.fromModel), fromParent, nodeDescription);
                Structure.Move(fromModel, fromParent);
                fromModel.Name       = originalName;
                nodeDescription.Name = originalName;

                CommandHistory.InvokeModelStructureChanged(fromParent);
                CommandHistory.InvokeModelStructureChanged(toParent);
            }
        }
Exemple #11
0
        /// <summary>
        /// Create an initial conditions table in the DataStore.
        /// </summary>
        private void CreateInitialConditionsTable()
        {
            string simulationPath = Apsim.FullPath(simulation);

            object[] values = new object[] { simulationPath, "Simulation name", "Simulation name", "String", string.Empty, string.Empty, 0, simulation.Name };
            storage.WriteRow(simulation.Name, "_InitialConditions", initialConditionsColumnNames, null, values);

            values = new object[] { simulationPath, "APSIM version", "APSIM version", "String", string.Empty, string.Empty, 0, simulation.ApsimVersion };
            storage.WriteRow(simulation.Name, "_InitialConditions", initialConditionsColumnNames, null, values);

            values = new object[] { simulationPath, "Run on", "Run on", "String", string.Empty, string.Empty, 0, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") };
            storage.WriteRow(simulation.Name, "_InitialConditions", initialConditionsColumnNames, null, values);

            // Get all model properties and store in 'initialConditionsTable'
            foreach (Model model in Apsim.FindAll(simulation))
            {
                string thisRelativeModelPath = Apsim.FullPath(model).Replace(simulationPath + ".", string.Empty);

                List <VariableProperty> properties = new List <VariableProperty>();
                FindAllProperties(model, properties);
                foreach (VariableProperty property in properties)
                {
                    string propertyValue = property.ValueAsString();
                    if (propertyValue != string.Empty)
                    {
                        if (propertyValue != null && property.DataType == typeof(DateTime))
                        {
                            propertyValue = ((DateTime)property.Value).ToString("yyyy-MM-dd HH:mm:ss");
                        }

                        int total;
                        if (double.IsNaN(property.Total))
                        {
                            total = 0;
                        }
                        else
                        {
                            total = 1;
                        }

                        if (property.Units == null)
                        {
                            property.Units = string.Empty;
                        }

                        values = new object[] { thisRelativeModelPath, property.Name, property.Description, property.DataType.Name, property.Units, property.Format, total, propertyValue };
                        storage.WriteRow(simulation.Name, "_InitialConditions", initialConditionsColumnNames, null, values);
                    }
                }
            }
        }
Exemple #12
0
        /// <summary>
        /// Main export code.
        /// </summary>
        //public void DoExportSimulation(Model modelToExport, string folderPath)
        //{
        //    //Load CSS resource

        //    // Make sure the specified folderPath exists because we're going to
        //    // write to it.
        //    Directory.CreateDirectory(folderPath);

        //    //Load CSS resource
        //    Assembly assembly = Assembly.GetExecutingAssembly();
        //    StreamReader reader = new StreamReader(assembly.GetManifestResourceStream("UserInterface.Resources.Export.css"));
        //    string css = reader.ReadToEnd();

        //    // Create index.html
        //    StreamWriter index = new StreamWriter(Path.Combine(folderPath, "Index.html"));
        //    index.WriteLine("<!DOCTYPE html><html lang=\"en-AU\"><head><style type=text/css>" + css + "</style></head>");
        //    index.WriteLine("<body>");

        //    DoExportZone(modelToExport, folderPath, index);

        //    index.WriteLine("</body>");
        //    index.WriteLine("</html>");
        //    index.Close();

        //}

        /// <summary>
        /// Export the specified zone.
        /// </summary>
        /// <param name="modelToExport"></param>
        /// <param name="folderPath"></param>
        /// <param name="index"></param>
        private void DoExportModel(Model modelToExport, string folderPath, StreamWriter index)
        {
            // Select the node in the tree.
            ExplorerPresenter.SelectNode(Apsim.FullPath(modelToExport));

            // If the presenter is exportable then simply export this child.
            // Otherwise, if it is one of a folder, simulation, experiment or zone then
            // recurse down.
            if (ExplorerPresenter.CurrentPresenter is IExportable)
            {
                string html = (ExplorerPresenter.CurrentPresenter as IExportable).ConvertToHtml(folderPath);
                index.WriteLine("<p>" + html + "</p>");
            }
        }
Exemple #13
0
        /// <summary>Export the contents of this graph to the specified file.</summary>
        /// <param name="folder">The folder.</param>
        /// <returns></returns>
        public string ExportToPDF(string folder)
        {
            // The rectange numbers below are optimised for generation of PDF document
            // on a computer that has its display settings at 100%.
            Rectangle r   = new Rectangle(0, 0, 600, 450);
            Bitmap    img = new Bitmap(r.Width, r.Height);

            graphView.Export(img, true);

            string path     = Apsim.FullPath(graph).Replace(".Simulations.", "");
            string fileName = Path.Combine(folder, path + ".png");

            img.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);

            return(fileName);
        }
        /// <summary>
        /// Undo the command
        /// </summary>
        public void Undo(CommandHistory CommandHistory)
        {
            if (ModelMoved)
            {
                ToParent.Children.Remove(FromModel);
                this.explorerView.Tree.Delete(Apsim.FullPath(this.FromModel));
                FromModel.Name       = OriginalName;
                nodeDescription.Name = OriginalName;
                FromParent.Children.Add(FromModel);
                FromModel.Parent = FromParent;
                this.explorerView.Tree.AddChild(Apsim.FullPath(FromParent), nodeDescription);

                CommandHistory.InvokeModelStructureChanged(FromParent);
                CommandHistory.InvokeModelStructureChanged(ToParent);
            }
        }
 /// <summary>
 /// Fill the specified table with columns and rows based on this.Properties
 /// </summary>
 /// <param name="table">The table that needs to be filled</param>
 public void FillTable(DataTable table)
 {
     foreach (IVariable property in properties)
     {
         if (property is VariableObject)
         {
             table.Rows.Add(new object[] { property.Value, null });
         }
         else if (property.Value is IModel)
         {
             table.Rows.Add(new object[] { property.Description, Apsim.FullPath(property.Value as IModel) });
         }
         else
         {
             table.Rows.Add(new object[] { property.Description, property.ValueWithArrayHandling });
         }
     }
 }
Exemple #16
0
        /// <summary>The user has clicked the add button.</summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private void OnAddButtonClicked(object sender, EventArgs e)
        {
            Type selectedModelType = this.allowableChildModels.Find(m => m.FullName == this.view.List.SelectedValue);

            if (selectedModelType != null)
            {
                this.explorerPresenter.MainPresenter.ShowWaitCursor(true);
                try
                {
                    IModel child = (IModel)Activator.CreateInstance(selectedModelType, true);
                    explorerPresenter.Add(child, Apsim.FullPath(this.model));
                }
                finally
                {
                    this.explorerPresenter.MainPresenter.ShowWaitCursor(false);
                }
            }
        }
Exemple #17
0
        /// <summary>
        /// Create and return a new Link object for member
        /// </summary>
        /// <param name="field">The member</param>
        /// <param name="model">Model with the link</param>
        private static ModelDoc.Link DocumentLink(FieldInfo field, IModel model)
        {
            ModelDoc.Link link = new ModelDoc.Link();
            link.Name = field.Name;
            if (field.FieldType.IsGenericType && field.FieldType.GetInterface("IList") != null)
            {
                link.TypeName = "List<" + field.FieldType.GenericTypeArguments[0].Name + ">";
            }
            else
            {
                link.TypeName = field.FieldType.Name;
            }
            UnitsAttribute units = field.GetCustomAttribute <UnitsAttribute>();

            if (units != null)
            {
                link.Units = units.ToString();
            }
            DescriptionAttribute description = field.GetCustomAttribute <DescriptionAttribute>();

            if (description != null)
            {
                link.Description = description.ToString();
            }

            LinkAttribute linkAtt = field.GetCustomAttribute <LinkAttribute>();

            link.IsOptional = linkAtt.IsOptional;

            object linkedObject = field.GetValue(model);

            if (linkedObject != null)
            {
                if (linkedObject is IModel)
                {
                    link.LinkedModelName = Apsim.FullPath(linkedObject as IModel);
                }
                else
                {
                }
            }

            return(link);
        }
Exemple #18
0
        /// <summary>
        /// Select the next node in the view. The next node is defined as the next one
        /// down in the tree view. It will go through child nodes if they exist.
        /// Will return true if next node was successfully selected. Will return
        /// false if no more nodes to select.
        /// </summary>
        /// <returns>True when node is selected</returns>
        /// <exception cref="System.Exception">Cannot find the current selected model in the .apsimx file</exception>
        public bool SelectNextNode()
        {
            this.HideRightHandPanel();

            // Get a complete list of all models in this file.
            List <IModel> allModels = Apsim.ChildrenRecursivelyVisible(this.ApsimXFile);

            allModels.Insert(0, ApsimXFile);

            /* If the current node path is '.Simulations' (the root node) then
             * select the first item in the 'allModels' list. */
            if (this.view.Tree.SelectedNode == string.Empty)
            {
                this.view.Tree.SelectedNode = Apsim.FullPath(allModels[0]);
                return(true);
            }

            // Find the current node in this list.
            int index = -1;

            for (int i = 0; i < allModels.Count; i++)
            {
                if (Apsim.FullPath(allModels[i]) == this.view.Tree.SelectedNode)
                {
                    index = i;
                    break;
                }
            }

            if (index == -1)
            {
                throw new Exception("Cannot find the current selected model in the .apsimx file");
            }

            // If the current model is the last one in the list then return false.
            if (index >= allModels.Count - 1)
            {
                return(false);
            }

            // Select the next node.
            this.view.Tree.SelectedNode = Apsim.FullPath(allModels[index + 1]);
            return(true);
        }
        /// <summary>The user has clicked the add button.</summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private void OnAddButtonClicked(object sender, EventArgs e)
        {
            Type selectedModelType = this.allowableChildFunctions.Find(m => m.FullName == this.view.List.SelectedValue);

            if (selectedModelType != null)
            {
                this.explorerPresenter.MainPresenter.ShowWaitCursor(true);
                try
                {
                    object child       = Activator.CreateInstance(selectedModelType, true);
                    string childString = FileFormat.WriteToString(child as IModel);
                    this.explorerPresenter.Add(childString, Apsim.FullPath(this.model));
                }
                finally
                {
                    this.explorerPresenter.MainPresenter.ShowWaitCursor(false);
                }
            }
        }
Exemple #20
0
 /// <summary>
 /// Adds a property to the DataTable of properties.
 /// </summary>
 /// <param name="table"></param>
 /// <param name="property"></param>
 protected virtual void AddPropertyToTable(DataTable table, IVariable property)
 {
     if (property is VariableObject)
     {
         table.Rows.Add(new object[] { property.Value, null, null });
     }
     else if (property.Value is IModel)
     {
         table.Rows.Add(new object[] { property.Description, Apsim.FullPath(property.Value as IModel), property.Name });
     }
     else if (property is VariableProperty p)
     {
         table.Rows.Add(new object[] { property.Description, property.ValueWithArrayHandling, p.Tooltip });
     }
     else
     {
         table.Rows.Add(new object[] { property.Description, property.ValueWithArrayHandling, property.Description });
     }
 }
Exemple #21
0
        /// <summary>The user has clicked the add button.</summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private void OnAddButtonClicked(object sender, EventArgs e)
        {
            try
            {
                Apsim.ModelDescription selectedModelType = GetModelDescription(tree.SelectedNode);

                if (selectedModelType != null)
                {
                    this.explorerPresenter.MainPresenter.ShowWaitCursor(true);

                    IModel child;
                    if (!(selectedModelType.ModelType == typeof(ModelCollectionFromResource)) &&
                        selectedModelType.ResourceString != null &&
                        selectedModelType.ResourceString.Contains('.'))
                    {
                        List <Exception> exceptions;
                        var contents = ReflectionUtilities.GetResourceAsString(explorerPresenter.ApsimXFile.GetType().Assembly,
                                                                               selectedModelType.ResourceString);
                        child = FileFormat.ReadFromString <Model>(contents, out exceptions);
                        if (child.Children.Count == 1)
                        {
                            child = child.Children[0];
                        }
                    }
                    else
                    {
                        child      = (IModel)Activator.CreateInstance(selectedModelType.ModelType, true);
                        child.Name = selectedModelType.ModelName;
                        if (child is ModelCollectionFromResource resource)
                        {
                            resource.ResourceName = selectedModelType.ResourceString;
                        }
                    }

                    var command = new AddModelCommand(Apsim.FullPath(this.model), child, explorerPresenter);
                    explorerPresenter.CommandHistory.Add(command, true);
                }
            }
            finally
            {
                this.explorerPresenter.MainPresenter.ShowWaitCursor(false);
            }
        }
Exemple #22
0
        /// <summary>The user has clicked the add button.</summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private void OnAddButtonClicked(object sender, EventArgs e)
        {
            Type modelType = typeof(IModel).Assembly.GetType(tree.SelectedNode);

            if (modelType != null)
            {
                this.explorerPresenter.MainPresenter.ShowWaitCursor(true);
                try
                {
                    IModel child = (IModel)Activator.CreateInstance(modelType, true);
                    child.Name = modelType.Name;
                    explorerPresenter.Add(child, Apsim.FullPath(this.model));
                }
                finally
                {
                    this.explorerPresenter.MainPresenter.ShowWaitCursor(false);
                }
            }
        }
Exemple #23
0
        public void OnFindReferences(object sender, EventArgs e)
        {
            try
            {
                IModel model = Apsim.Get(this.explorerPresenter.ApsimXFile, this.explorerPresenter.CurrentNodePath) as IModel;
                if (model != null)
                {
                    string           modelPath  = Apsim.FullPath(model);
                    StringBuilder    message    = new StringBuilder($"Searching for references to model {Apsim.FullPath(model)}...");
                    List <Reference> references = new List <Reference>();
                    message.AppendLine();
                    message.AppendLine();
                    Stopwatch timer = Stopwatch.StartNew();

                    foreach (VariableReference reference in Apsim.FindAll(model, typeof(VariableReference)))
                    {
                        try
                        {
                            if (Apsim.Get(reference, reference.VariableName.Replace(".Value()", "")) == model)
                            {
                                references.Add(new Reference()
                                {
                                    Member = typeof(VariableReference).GetProperty("VariableName"), Model = reference, Target = model
                                });
                            }
                        }
                        catch
                        {
                        }
                    }
                    timer.Stop();
                    message.AppendLine();
                    message.AppendLine($"Finished. Elapsed time: {timer.Elapsed.TotalSeconds.ToString("#.00")} seconds");
                    explorerPresenter.MainPresenter.ShowMessage(message.ToString(), Simulation.MessageType.Information);
                    var dialog = new Utility.FindAllReferencesDialog(model, references, explorerPresenter);
                }
            }
            catch (Exception err)
            {
                explorerPresenter.MainPresenter.ShowError(err);
            }
        }
Exemple #24
0
 /// <summary>
 /// Adds a property to the DataTable of properties.
 /// </summary>
 /// <param name="table"></param>
 /// <param name="property"></param>
 protected virtual void AddPropertyToTable(DataTable table, IVariable property)
 {
     if (property is VariableObject)
     {
         table.Rows.Add(new object[] { property.Value, null });
     }
     else if (property.Value is IModel)
     {
         table.Rows.Add(new object[] { property.Description, Apsim.FullPath(property.Value as IModel) });
     }
     else
     {
         string description = property.Description;
         if (!string.IsNullOrEmpty(property.Units))
         {
             description += " (" + property.Units + ")";
         }
         table.Rows.Add(new object[] { description, property.ValueWithArrayHandling });
     }
 }
Exemple #25
0
 /// <summary>Perform the command</summary>
 /// <param name="commandHistory">The command history.</param>
 public void Do(CommandHistory commandHistory)
 {
     try
     {
         parent = Apsim.Get(presenter.ApsimXFile, parentPath) as IModel;
         if (parent == null)
         {
             throw new Exception("Cannot find model " + parentPath);
         }
         modelToAdd = Structure.Add(childString, parent);
         var nodeDescription = presenter.GetNodeDescription(modelToAdd);
         view.Tree.AddChild(Apsim.FullPath(parent), nodeDescription);
         modelAdded = true;
     }
     catch (Exception err)
     {
         presenter.MainPresenter.ShowError(err);
         modelAdded = false;
     }
 }
Exemple #26
0
        private string[] GetModelNames(Type t)
        {
            List <IModel> models;

            if (t == null)
            {
                models = Apsim.FindAll(model);
            }
            else
            {
                models = Apsim.FindAll(model, t);
            }

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

            foreach (IModel model in models)
            {
                modelNames.Add(Apsim.FullPath(model));
            }
            return(modelNames.ToArray());
        }
Exemple #27
0
        /// <summary>
        /// Adds a property to the DataTable of properties.
        /// </summary>
        /// <param name="table"></param>
        /// <param name="property"></param>
        protected virtual void AddPropertyToTable(DataTable table, IVariable property)
        {
            int row = properties.IndexOf(property);

            if (property is VariableObject)
            {
                table.Rows.Add(new object[] { property.Value, null, null });
            }
            else if (property.Value is IModel)
            {
                table.Rows.Add(new object[] { property.Description, Apsim.FullPath(property.Value as IModel), property.Name });
            }
            else if (property is VariableProperty p)
            {
                table.Rows.Add(new object[] { property.Description, GetCellValue(property, row, 1), p.Tooltip });
            }
            else
            {
                table.Rows.Add(new object[] { property.Description, GetCellValue(property, row, 1), property.Description });
            }
        }
Exemple #28
0
 /// <summary>Undo the command</summary>
 /// <param name="CommandHistory">The command history.</param>
 public void Undo(CommandHistory CommandHistory)
 {
     if (modelWasReplaced)
     {
         Model parent     = modelToInsert.Parent as Model;
         int   modelIndex = parent.Children.IndexOf(modelToInsert as Model);
         try
         {
             this.explorerView.Tree.Delete(Apsim.FullPath(this.modelToInsert));
             parent.Children.Remove(modelToInsert as Model);
             parent.Children.Insert(modelIndex, modelToReplace as Model);
             modelToReplace.Parent = parent;
             var nodeDescription = presenter.GetNodeDescription(modelToReplace);
             this.explorerView.Tree.AddChild(Apsim.FullPath(parent), nodeDescription, modelIndex);
         }
         catch (Exception err)
         {
             presenter.MainPresenter.ShowError(err);
             modelWasReplaced = false;
         }
     }
 }
Exemple #29
0
        /// <summary>Apply fertiliser.</summary>
        /// <param name="Amount">The amount.</param>
        /// <param name="Type">The type.</param>
        /// <param name="Depth">The depth.</param>
        /// <exception cref="ApsimXException">Cannot find fertiliser type ' + Type + '</exception>
        public void Apply(double Amount, Types Type, double Depth = 0.0)
        {
            if (Amount > 0 && NitrogenChanged != null)
            {
                // find the layer that the fertilizer is to be added to.
                int layer = GetLayerDepth(Depth, Soil.Thickness);

                FertiliserType fertiliserType = Definitions.FirstOrDefault(f => f.Name == Type.ToString());
                if (fertiliserType == null)
                {
                    throw new ApsimXException(this, "Cannot find fertiliser type '" + Type + "'");
                }

                NitrogenChangedType NitrogenChanges = new NitrogenChangedType();
                NitrogenChanges.Sender = Apsim.FullPath(this);

                if (fertiliserType.FractionNO3 != 0)
                {
                    NitrogenChanges.DeltaNO3        = new double[Soil.Thickness.Length];
                    NitrogenChanges.DeltaNO3[layer] = Amount * fertiliserType.FractionNO3;
                    NitrogenApplied += Amount * fertiliserType.FractionNO3;
                }
                if (fertiliserType.FractionNH4 != 0)
                {
                    NitrogenChanges.DeltaNH4        = new double[Soil.Thickness.Length];
                    NitrogenChanges.DeltaNH4[layer] = Amount * fertiliserType.FractionNH4;
                    NitrogenApplied += Amount * fertiliserType.FractionNH4;
                }
                if (fertiliserType.FractionUrea != 0)
                {
                    NitrogenChanges.DeltaUrea        = new double[Soil.Thickness.Length];
                    NitrogenChanges.DeltaUrea[layer] = Amount * fertiliserType.FractionUrea;
                    NitrogenApplied += Amount * fertiliserType.FractionUrea;
                }

                NitrogenChanged.Invoke(NitrogenChanges);
                Summary.WriteMessage(this, string.Format("{0} kg/ha of {1} added at depth {2} layer {3}", Amount, Type, Depth, layer + 1));
            }
        }
Exemple #30
0
        /// <summary>
        /// Attach the view to the model.
        /// </summary>
        /// <param name="model">The initial water model</param>
        /// <param name="view">The initial water view</param>
        /// <param name="explorerPresenter">The parent explorer presenter</param>
        public override void Attach(object model, object view, ExplorerPresenter explorerPresenter)
        {
            this.xYPairs     = model as XYPairs;
            this.xYPairsView = view as XYPairsView;
            this.presenter   = explorerPresenter as ExplorerPresenter;
            base.Attach(model, xYPairsView.VariablesGrid, explorerPresenter);
            // Create a list of profile (array) properties. PpoulateView wil create a table from them and
            // hand the table to the variables grid.
            this.FindAllProperties(this.xYPairs);

            this.PopulateView();

            this.presenter.CommandHistory.ModelChanged += OnModelChanged;

            // Populate the graph.
            this.graph = Utility.Graph.CreateGraphFromResource(model.GetType().Name + "Graph");
            this.xYPairs.Children.Add(this.graph);
            this.graph.Parent = this.xYPairs;
            (this.graph.Series[0] as Series).XFieldName = Apsim.FullPath(graph.Parent) + ".X";
            (this.graph.Series[0] as Series).YFieldName = Apsim.FullPath(graph.Parent) + ".Y";
            this.graphPresenter = new GraphPresenter();
            this.presenter.ApsimXFile.Links.Resolve(graphPresenter);
            this.graphPresenter.Attach(this.graph, this.xYPairsView.Graph, this.presenter);
            string xAxisTitle = LookForXAxisTitle();

            if (xAxisTitle != null)
            {
                xYPairsView.Graph.FormatAxis(Axis.AxisType.Bottom, xAxisTitle, false, double.NaN, double.NaN, double.NaN, false);
            }

            string yAxisTitle = LookForYAxisTitle();

            if (yAxisTitle != null)
            {
                xYPairsView.Graph.FormatAxis(Axis.AxisType.Left, yAxisTitle, false, double.NaN, double.NaN, double.NaN, false);
            }

            xYPairsView.Graph.FormatTitle(xYPairs.Parent.Name);
        }