示例#1
0
        private void InitSourcesActions()
        {
            AddSourceCommand = new AddModelCommand <SourceItemViewModel>(SelectedMod.Sources, new SourceItemViewModel(SelectedMod.Mod, this), ActionsManager);
            AddSourceCommand.CommandExecuted += ((cmd, param) => SelectedSource = param);

            DeleteSourceCommand = new DeleteModelCommand <SourceItemViewModel>(SelectedMod.Sources, ActionsManager);
        }
示例#2
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 = (IModel)Activator.CreateInstance(selectedModelType.ModelType, true);
                    child.Name = selectedModelType.ModelName;
                    if (child is ModelCollectionFromResource resource)
                    {
                        resource.ResourceName = selectedModelType.ModelName;
                    }

                    var command = new AddModelCommand(Apsim.FullPath(this.model), child, explorerPresenter);
                    explorerPresenter.CommandHistory.Add(command, true);
                }
            }
            finally
            {
                this.explorerPresenter.MainPresenter.ShowWaitCursor(false);
            }
        }
示例#3
0
 private void RefreshCommands()
 {
     AddMakeCommand.RaiseCanExecuteChanged();
     RemoveMakeCommand.RaiseCanExecuteChanged();
     AddModelCommand.RaiseCanExecuteChanged();
     RemoveModelCommand.RaiseCanExecuteChanged();
 }
示例#4
0
 public IActionResult AddModel([FromBody] ModelDTO modelDTO)
 {
     _logger?.LogInformation($"Inicio del servicio: [Post] https://localhost:5001/api/models ");
     try {
         ModelMapper modelMapper = MapperFactory.CreateModelMapper();
         Entity      model       = modelMapper.CreateEntity(modelDTO);
         _logger?.LogInformation($" Se transformó de DTO a Entity ");
         AddModelCommand command = CommandFactory.CreateAddModelCommand((Model)model);
         _logger?.LogInformation($" Ejecución del comando ");
         command.Execute();
         return(Ok("ok " + command.GetResult()));
     } catch (RequiredAttributeException ex) {
         _logger?.LogWarning("Atributo requerido: " + ex.Message);
         return(StatusCode(400, ex.Message));
     } catch (BrandNotFoundException ex) {
         _logger?.LogWarning("La marca con Id : " + ex.BrandId + "no encontrado");
         return(StatusCode(404, ex.Message + ex.BrandId));
     } catch (UniqueAttributeException ex) {
         _logger?.LogWarning(ex.Message);
         return(StatusCode(500, ex.Message));
     } catch (InternalServerErrorException ex) {
         _logger?.LogError("Error: " + ex.Ex.Message);
         return(StatusCode(500, ex.Message));
     } catch (Exception) {
         _logger?.LogError("Error inesperado");
         return(StatusCode(400));
     }
 }
示例#5
0
        /// <summary>
        /// Adds a model to a parent model.
        /// </summary>
        /// <param name="st">The string representation (JSON or XML) of a model.</param>
        /// <param name="parentPath">Path to the parent</param>
        public void Add(string st, string parentPath)
        {
            IModel model = FileFormat.ReadFromString <IModel>(st, out List <Exception> errors);

            if (errors != null && errors.Count > 0)
            {
                throw errors[0];
            }
            AddModelCommand command = new AddModelCommand(parentPath, model, view, this);

            CommandHistory.Add(command, true);
        }
示例#6
0
        private void InitActions()
        {
            AddModCommand = new AddModelCommand <ModItemViewModel>(Mods, new ModItemViewModel(new Mod(), this), ActionsManager);
            AddModCommand.CommandExecuted += ((cmd, param) =>
            {
                SelectedMod = param;
                Status.IsProgressVisible = false;
                Status.Status = string.Format("Added mod with ID = {0}", SelectedMod.Mod.ID);
            });

            DeleteModCommand    = new DeleteModelCommand <ModItemViewModel>(Mods, ActionsManager);
            CheckAllModsCommand = new CheckAllModsCommand(this);
            SaveChangesCommand  = new SaveChangesCommand();
        }
示例#7
0
        /// <summary>A node has been dropped.</summary>
        /// <param name="sender">Sending object</param>
        /// <param name="e">Drop arguments</param>
        private void OnDrop(object sender, DropArgs e)
        {
            try
            {
                string toParentPath = e.NodePath;
                Model  toParent     = this.ApsimXFile.FindByPath(toParentPath)?.Value as Model;

                DragObject dragObject = e.DragObject as DragObject;
                if (dragObject != null && toParent != null)
                {
                    string modelString    = dragObject.ModelString;
                    string fromParentPath = StringUtilities.ParentName(dragObject.NodePath);

                    ICommand cmd = null;
                    if (e.Moved)
                    {
                        if (fromParentPath != toParentPath)
                        {
                            Model fromModel = this.ApsimXFile.FindByPath(dragObject.NodePath)?.Value as Model;
                            if (fromModel != null)
                            {
                                cmd = new MoveModelCommand(fromModel, toParent, GetNodeDescription);
                                CommandHistory.Add(cmd);
                            }
                        }
                    }
                    else if (e.Copied)
                    {
                        var command = new AddModelCommand(toParent, modelString, GetNodeDescription);
                        CommandHistory.Add(command, true);
                    }
                    else if (e.Linked)
                    {
                        // tbi
                        MainPresenter.ShowMessage("Linked models TBI", Simulation.MessageType.Information);
                    }
                    view.Tree.ExpandChildren(toParent.FullPath, false);
                }
            }
            catch (Exception err)
            {
                MainPresenter.ShowError(err);
            }
        }
示例#8
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(this.model, child);
                    explorerPresenter.CommandHistory.Add(command, true);
                    explorerPresenter.Refresh();
                }
            }
            finally
            {
                this.explorerPresenter.MainPresenter.ShowWaitCursor(false);
            }
        }
示例#9
0
        public void OnPasteClick(object sender, EventArgs e)
        {
            try
            {
                string internalCBText = this.explorerPresenter.GetClipboardText("_APSIM_MODEL");
                string externalCBText = this.explorerPresenter.GetClipboardText("CLIPBOARD");

                string text = string.IsNullOrEmpty(externalCBText) ? internalCBText : externalCBText;

                IModel   currentNode = explorerPresenter.ApsimXFile.FindByPath(explorerPresenter.CurrentNodePath)?.Value as IModel;
                ICommand command     = new AddModelCommand(currentNode, text);
                explorerPresenter.CommandHistory.Add(command, true);
                explorerPresenter.Refresh();
            }
            catch (Exception err)
            {
                explorerPresenter.MainPresenter.ShowError(err);
            }
        }
示例#10
0
        public void OnPasteClick(object sender, EventArgs e)
        {
            try
            {
                string internalCBText = this.explorerPresenter.GetClipboardText("_APSIM_MODEL");
                string externalCBText = this.explorerPresenter.GetClipboardText("CLIPBOARD");

                string text = string.IsNullOrEmpty(externalCBText) ? internalCBText : externalCBText;

                var command = new AddModelCommand(explorerPresenter.CurrentNodePath,
                                                  text,
                                                  explorerPresenter);
                explorerPresenter.CommandHistory.Add(command, true);
            }
            catch (Exception err)
            {
                explorerPresenter.MainPresenter.ShowError(err);
            }
        }
示例#11
0
        /// <summary>
        /// User has clicked the add soil button.
        /// </summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event arguments.</param>
        private void OnAddSoilButtonClicked(object sender, EventArgs e)
        {
            foreach (int selectedIndex in dataView.SelectedIndicies)
            {
                var  values       = dataView.GetRow(selectedIndex);
                var  soilName     = (string)values[0];
                Soil matchingSoil = Apsim.Clone <Soil>(allSoils.First(s => s.Soil.Name == soilName).Soil);

                if (!matchingSoil.Children.Any(c => c is INutrient))
                {
                    matchingSoil.Children.Add(new Nutrient()
                    {
                        ResourceName = "Nutrient"
                    });
                }
                ICommand addSoil = new AddModelCommand(model, matchingSoil, explorerPresenter.GetNodeDescription);
                explorerPresenter.CommandHistory.Add(addSoil);
            }
            explorerPresenter.Populate();
        }
示例#12
0
        public IActionResult AddModel(AddModelCommand command)
        {
            try
            {
                using var repository = _repositoryFactory.Create();
                repository.Add(new DeviceModel
                {
                    ModelName = command.ModelName,
                    ModelId   = command.ModelId,
                    ImageUrl  = command.ImageUrl
                });
                repository.Commit();

                return(Ok(null));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex));
            }
        }
示例#13
0
        /// <summary>A node has been dropped.</summary>
        /// <param name="sender">Sending object</param>
        /// <param name="e">Drop arguments</param>
        private void OnDrop(object sender, DropArgs e)
        {
            try
            {
                string toParentPath = e.NodePath;
                Model  toParent     = Apsim.Get(this.ApsimXFile, toParentPath) as Model;

                DragObject dragObject = e.DragObject as DragObject;
                if (dragObject != null && toParent != null)
                {
                    string modelString    = dragObject.ModelString;
                    string fromParentPath = StringUtilities.ParentName(dragObject.NodePath);

                    ICommand cmd = null;
                    if (e.Copied)
                    {
                        var command = new AddModelCommand(toParentPath,
                                                          modelString,
                                                          this);
                        CommandHistory.Add(command, true);
                    }
                    else if (e.Moved)
                    {
                        if (fromParentPath != toParentPath)
                        {
                            Model fromModel = Apsim.Get(this.ApsimXFile, dragObject.NodePath) as Model;
                            if (fromModel != null)
                            {
                                cmd = new MoveModelCommand(fromModel, toParent, this.GetNodeDescription(fromModel), this);
                                CommandHistory.Add(cmd);
                            }
                        }
                    }
                }
            }
            catch (Exception err)
            {
                MainPresenter.ShowError(err);
            }
        }
示例#14
0
        private static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Not enough arguments !");
                return;
            }

            Config.Model = args[0].ToLower().UppercaseFirst();
            var command = "";

            if (args.Length > 1)
            {
                command = args[1].ToLower();
            }

            if (args.Length > 2)
            {
                Config.Area = args[2].ToLower().UppercaseFirst();
            }

            Config.ModelsPath     = Environment.CurrentDirectory + "\\";
            Config.ViewModelsPath = new System.IO.DirectoryInfo(Config.ModelsPath).Parent.FullName + "\\ViewModels\\";
            Config.RepositoryPath = new System.IO.DirectoryInfo(Config.ModelsPath).Parent.Parent.FullName + "\\Repository\\";
            Config.ServicePath    = new System.IO.DirectoryInfo(Config.ModelsPath).Parent.Parent.FullName + "\\Service\\";

            if (string.IsNullOrEmpty(Config.Area))
            {
                Config.ControllerPath = new System.IO.DirectoryInfo(Config.ModelsPath).Parent.Parent.Parent.FullName + "\\Portal.Web\\Controllers\\";
                Config.ViewsPath      = new System.IO.DirectoryInfo(Config.ModelsPath).Parent.Parent.Parent.FullName + "\\Portal.Web\\Views\\" + Config.Model + "\\";
            }
            else
            {
                Config.ControllerPath = new System.IO.DirectoryInfo(Config.ModelsPath).Parent.Parent.Parent.FullName + "\\Portal.Web\\Areas\\" + Config.Area + "\\Controllers\\";
                Config.ViewsPath      = new System.IO.DirectoryInfo(Config.ModelsPath).Parent.Parent.Parent.FullName + "\\Portal.Web\\Areas\\" + Config.Area + "\\Views\\" + Config.Model + "\\";
            }

            var viewsDir = new System.IO.DirectoryInfo(Config.ViewsPath);

            if (!viewsDir.Exists)
            {
                viewsDir.Create();
            }

            Config.PropertyNames        = ClassHelper.GetPropertyNames(Config.ModelsPath + Config.Model + ".cs");
            Config.PropertyTypes        = ClassHelper.GetPropertyTypes(Config.ModelsPath + Config.Model + ".cs");
            Config.PropertyDeclarations = ClassHelper.GetPropertyDeclarations(Config.ModelsPath + Config.Model + ".cs");

            switch (command)
            {
            case "sr":
            case "service":
                var iserviceCommand = new IServiceCommand();
                var serviceCommand  = new ServiceCommand();
                iserviceCommand.Execute();
                serviceCommand.Execute();
                break;

            case "rp":
            case "repository":
                var irepositoryCommand = new IRepositoryCommand();
                var repositoryCommand  = new RepositoryCommand();
                irepositoryCommand.Execute();
                repositoryCommand.Execute();
                break;

            case "vm":
            case "viewmodel":
                var viewModelCommand = new ViewModelCommand();
                viewModelCommand.Execute();
                break;

            case "ad":
            case "addmodel":
                var addModel = new AddModelCommand();
                addModel.Execute();
                break;

            case "vi":
            case "views":
                var indexCommand   = new IndexCommand();
                var createCommand  = new CreateCommand();
                var editCommand    = new EditCommand();
                var deleteCommand  = new DeleteCommand();
                var detailsCommand = new DetailsCommand();

                indexCommand.Execute();
                createCommand.Execute();
                editCommand.Execute();
                deleteCommand.Execute();
                detailsCommand.Execute();

                break;

            case "cr":
            case "controller":
                var controllerCommand = new ControllerCommand();
                controllerCommand.Execute();
                break;

            case "go":
            default:
                var goCommand = new GoCommand();
                goCommand.Execute();


                break;
            }
        }
示例#15
0
        /// <summary>
        /// Pastes the contents of the clipboard.
        /// </summary>
        /// <param name="xml">The XML document text</param>
        /// <param name="parentPath">Path to the parent</param>
        public void Add(string xml, string parentPath)
        {
            try
            {
                XmlDocument document = new XmlDocument();
                try
                {
                    document.LoadXml(xml);
                }
                catch (XmlException)
                {
                    MainPresenter.ShowMessage("Invalid XML. Are you sure you're trying to paste an APSIM model?", Simulation.ErrorLevel.Error);
                }

                object newModel = XmlUtilities.Deserialise(document.DocumentElement, this.ApsimXFile.GetType().Assembly);

                // See if the presenter is happy with this model being added.
                Model         parentModel   = Apsim.Get(this.ApsimXFile, parentPath) as Model;
                AllowDropArgs allowDropArgs = new AllowDropArgs();
                allowDropArgs.NodePath   = parentPath;
                allowDropArgs.DragObject = new DragObject()
                {
                    NodePath  = null,
                    ModelType = newModel.GetType(),
                    Xml       = this.GetClipboardText()
                };

                this.OnAllowDrop(null, allowDropArgs);

                // If it is happy then issue an AddModelCommand.
                if (allowDropArgs.Allow)
                {
                    // If the model xml is a soil object then try and convert from old
                    // APSIM format to new.
                    if (document.DocumentElement.Name == "Soil" && XmlUtilities.Attribute(document.DocumentElement, "Name") != string.Empty)
                    {
                        XmlDocument newDoc = new XmlDocument();
                        newDoc.AppendChild(newDoc.CreateElement("D"));
                        APSIMImporter importer = new APSIMImporter();
                        importer.ImportSoil(document.DocumentElement, newDoc.DocumentElement, newDoc.DocumentElement);
                        XmlNode soilNode = XmlUtilities.FindByType(newDoc.DocumentElement, "Soil");
                        if (soilNode != null &&
                            XmlUtilities.FindByType(soilNode, "Sample") == null &&
                            XmlUtilities.FindByType(soilNode, "InitialWater") == null)
                        {
                            // Add in an initial water and initial conditions models.
                            XmlNode initialWater = soilNode.AppendChild(soilNode.OwnerDocument.CreateElement("InitialWater"));
                            XmlUtilities.SetValue(initialWater, "Name", "Initial water");
                            XmlUtilities.SetValue(initialWater, "PercentMethod", "FilledFromTop");
                            XmlUtilities.SetValue(initialWater, "FractionFull", "1");
                            XmlUtilities.SetValue(initialWater, "DepthWetSoil", "NaN");
                            XmlNode initialConditions = soilNode.AppendChild(soilNode.OwnerDocument.CreateElement("Sample"));
                            XmlUtilities.SetValue(initialConditions, "Name", "Initial conditions");
                            XmlUtilities.SetValue(initialConditions, "Thickness/double", "1800");
                            XmlUtilities.SetValue(initialConditions, "NO3/double", "10");
                            XmlUtilities.SetValue(initialConditions, "NH4/double", "1");
                            XmlUtilities.SetValue(initialConditions, "NO3Units", "kgha");
                            XmlUtilities.SetValue(initialConditions, "NH4Units", "kgha");
                            XmlUtilities.SetValue(initialConditions, "SWUnits", "Volumetric");
                        }

                        document.LoadXml(newDoc.DocumentElement.InnerXml);
                    }

                    IModel child = XmlUtilities.Deserialise(document.DocumentElement, this.ApsimXFile.GetType().Assembly) as IModel;

                    AddModelCommand command = new AddModelCommand(parentModel, document.DocumentElement, this.GetNodeDescription(child), this.view);
                    this.CommandHistory.Add(command, true);
                }
            }
            catch (Exception exception)
            {
                this.MainPresenter.ShowMessage(exception.Message, Simulation.ErrorLevel.Error);
            }
        }
示例#16
0
        public void CreateGraphs()
        {
            Simulations sims = CreateTemplate();

            sims.FileName = Path.ChangeExtension(Path.GetTempFileName(), ".apsimx");

            DataStore storage = sims.FindInScope <DataStore>();

            storage.FileName = Path.ChangeExtension(sims.FileName, ".db");

            // Run the file to populate the datastore.
            Runner           runner = new Runner(sims);
            List <Exception> errors = runner.Run();

            if (errors != null && errors.Count > 0)
            {
                throw errors[0];
            }

            // Open the .apsimx file in the GUI.
            sims.Write(sims.FileName);
            ExplorerPresenter explorer = UITestsMain.MasterPresenter.OpenApsimXFileInTab(sims.FileName, true);

            GtkUtilities.WaitForGtkEvents();
            sims = explorer.ApsimXFile;

            // Create a graphs folder under the zone.
            IModel paddock = sims.FindInScope <Zone>();
            Folder graphs  = new Folder();

            graphs.Name = "Graphs";

            var command = new AddModelCommand(paddock, graphs);

            explorer.CommandHistory.Add(command, true);

            // Add an empty graph to the folder.
            Models.Graph graph = new Models.Graph();
            graph.Name = "Graph";
            command    = new AddModelCommand(graphs, graph);
            explorer.CommandHistory.Add(command, true);

            // Add an empty series to the graph.
            Models.Series series = new Models.Series();
            series.Name = "Series";
            command     = new AddModelCommand(graph, series);
            explorer.CommandHistory.Add(command, true);
            explorer.Refresh();

            // click on the series node.
            explorer.SelectNode(series.FullPath);
            GtkUtilities.WaitForGtkEvents();

            // Get a reference to the OxyPlot PlotView via reflection.
            SeriesView seriesView = explorer.CurrentRightHandView as SeriesView;
            GraphView  view       = seriesView?.GraphView as GraphView;

            Assert.NotNull(view);

            PlotView plot = ReflectionUtilities.GetValueOfFieldOrProperty("plot1", view) as PlotView;

            Assert.NotNull(plot);

            // Series has no table name or x/y series names yet, so there should
            // be nothing shown on the graph.
            Assert.AreEqual(0, plot.Model.Series.Count);

            // Now draw some data on the graph.
            seriesView.DataSource.SelectedValue = "Report";
            seriesView.X.SelectedValue          = "n";
            seriesView.Y.SelectedValue          = "n2";
            seriesView.SeriesType.SelectedValue = "Scatter";

            GtkUtilities.WaitForGtkEvents();

            // There should now be one series showing.
            Assert.AreEqual(1, plot.Model.Series.Count);

            // It should be a line series.
            Assert.True(plot.Model.Series[0] is LineSeries, "Graph series type is set to scatter, but the series object is not a LineSeries.");

            // Series colour should not be white, and should not be the same as the background colour.
            LineSeries line = plot.Model.Series[0] as LineSeries;

            OxyPlot.OxyColor empty = OxyPlot.OxyColor.FromArgb(0, 0, 0, 0);
            OxyPlot.OxyColor white = OxyPlot.OxyColor.FromArgb(0, 255, 255, 255);
            Assert.AreNotEqual(empty, line.Color, "Graph line series default colour is white on white.");
            Assert.AreNotEqual(white, line.Color, "Graph line series default colour is white on white.");

            // Legend should be visible but empty by default.
            Assert.True(plot.Model.IsLegendVisible);
            // todo - ensure legend is empty

            // Next, we want to change the legend position and ensure that the legend actually moves.

            // Click on the 'show in legend' checkbox.
            seriesView.ShowInLegend.Checked = true;
            GtkUtilities.WaitForGtkEvents();

            // Double click on the middle of the legend.
            Cairo.Rectangle legendRect = plot.Model.LegendArea.ToRect(true);
            double          x          = (legendRect.X + (legendRect.X + legendRect.Width)) / 2;
            double          y          = (legendRect.Y + (legendRect.Y + legendRect.Height)) / 2;

            GtkUtilities.DoubleClick(plot, x, y, wait: true);

            // Default legend position should be top-left.
            Assert.AreEqual(plot.Model.LegendPosition, OxyPlot.LegendPosition.TopLeft);

            // Now we want to change the legend position. First, get a reference to the legend view
            // via the legend presenter, via the graph presenter, via the series presenter, via the explorer presenter.
            Assert.True(explorer.CurrentPresenter is SeriesPresenter);
            SeriesPresenter seriesPresenter = explorer.CurrentPresenter as SeriesPresenter;
            LegendPresenter legendPresenter = seriesPresenter.GraphPresenter.CurrentPresenter as LegendPresenter;

            // todo: should we add something like a GetView() method to the IPresenter interface?
            // It might be a bit of work to set up but would save us having to use reflection
            LegendView legendView = ReflectionUtilities.GetValueOfFieldOrProperty("view", legendPresenter) as LegendView;

            // The legend options are inside a Gtk expander.
            Assert.IsTrue(legendView.MainWidget.Parent is Expander);
            Expander expander = legendView.MainWidget.Parent as Expander;

            // The expander should be expanded and the options visible.
            Assert.IsTrue(expander.Expanded);
            Assert.IsTrue(legendView.MainWidget.Visible);

            // The legend view contains a combo box with the legend position options (top-right, bottom-left, etc).
            // This should really be refactored to use a public IDropDownView, which is much more convenient to use.
            // First, get a reference to the combo box via reflection.
            ComboBox combo = ReflectionUtilities.GetValueOfFieldOrProperty("combobox1", legendView) as ComboBox;

            // fixme - we should support all valid OxyPlot legend position types.
            foreach (Models.Graph.LegendPositionType legendPosition in Enum.GetValues(typeof(Models.Graph.LegendPositionType)))
            {
                string name = legendPosition.ToString();
                GtkUtilities.SelectComboBoxItem(combo, name, wait: true);

                OxyPlot.LegendPosition oxyPlotEquivalent = (OxyPlot.LegendPosition)Enum.Parse(typeof(OxyPlot.LegendPosition), name);
                Assert.AreEqual(plot.Model.LegendPosition, oxyPlotEquivalent);
            }

            // If we change the graph to a box plot then the several unused properties should be disabled.
            // These are x variable dropdown, x cumulative, x on top, marker size/type checkboxes.

            // First, make sure that these options are sensitive to input and can be changed.
            Assert.IsTrue(seriesView.X.IsSensitive);
            Assert.IsTrue(seriesView.XCumulative.IsSensitive);
            Assert.IsTrue(seriesView.XOnTop.IsSensitive);
            Assert.IsTrue(seriesView.MarkerSize.IsSensitive);
            Assert.IsTrue(seriesView.MarkerType.IsSensitive);

            // Now change series type to box plot.
            GtkUtilities.SelectComboBoxItem(seriesView.SeriesType, "Box", wait: true);
            Assert.AreEqual(SeriesType.Box, series.Type);

            // Ensure the box plot is not white in light theme.
            plot = ReflectionUtilities.GetValueOfFieldOrProperty("plot1", view) as PlotView;
            Assert.NotNull(plot);
            BoxPlotSeries boxPlot = plot.Model.Series.OfType <BoxPlotSeries>().FirstOrDefault();

            Assert.NotNull(boxPlot);

            Assert.AreNotEqual(empty, boxPlot.Fill);
            Assert.AreNotEqual(white, boxPlot.Fill);
            Assert.AreNotEqual(empty, boxPlot.Stroke);
            Assert.AreNotEqual(white, boxPlot.Stroke);

            // The controls should no longer be sensitive.
            Assert.IsFalse(seriesView.XCumulative.IsSensitive);
            Assert.IsFalse(seriesView.XOnTop.IsSensitive);
            Assert.IsFalse(seriesView.MarkerSize.IsSensitive);
            Assert.IsFalse(seriesView.MarkerType.IsSensitive);

            // Change the series type back to scatter.
            GtkUtilities.SelectComboBoxItem(seriesView.SeriesType, "Scatter", wait: true);

            // The controls should be sensitive once more.
            Assert.IsTrue(seriesView.X.IsSensitive);
            Assert.IsTrue(seriesView.XCumulative.IsSensitive);
            Assert.IsTrue(seriesView.XOnTop.IsSensitive);
            Assert.IsTrue(seriesView.MarkerSize.IsSensitive);
            Assert.IsTrue(seriesView.MarkerType.IsSensitive);
        }
示例#17
0
        /// <summary>
        /// Adds a model to a parent model.
        /// </summary>
        /// <param name="child">The string representation (JSON or XML) of a model.</param>
        /// <param name="parentPath">Path to the parent</param>
        public void Add(IModel child, string parentPath)
        {
            AddModelCommand command = new AddModelCommand(parentPath, child, view, this);

            CommandHistory.Add(command, true);
        }
示例#18
0
        /// <summary>Pastes the contents of the clipboard.</summary>
        public void Add(string xml, string parentPath)
        {
            try
            {
                XmlDocument document = new XmlDocument();
                try
                {
                    document.LoadXml(xml);
                }
                catch(XmlException)
                {
                    MainPresenter.ShowMessage("Invalid XML. Are you sure you're trying to paste an APSIM model?", DataStore.ErrorLevel.Error);
                }
                object newModel = XmlUtilities.Deserialise(document.DocumentElement, ApsimXFile.GetType().Assembly);

                // See if the presenter is happy with this model being added.
                Model parentModel = Apsim.Get(this.ApsimXFile, parentPath) as Model;
                AllowDropArgs allowDropArgs = new AllowDropArgs();
                allowDropArgs.NodePath = parentPath;
                allowDropArgs.DragObject = new DragObject()
                {
                    NodePath = null,
                    ModelType = newModel.GetType(),
                    Xml = GetClipboardText()
                };
                this.OnAllowDrop(null, allowDropArgs);

                // If it is happy then issue an AddModelCommand.
                if (allowDropArgs.Allow)
                {
                    // If the model xml is a soil object then try and convert from old
                    // APSIM format to new.
                    if (document.DocumentElement.Name == "Soil" && XmlUtilities.Attribute(document.DocumentElement, "Name") != "")
                    {
                        XmlDocument newDoc = new XmlDocument();
                        newDoc.AppendChild(newDoc.CreateElement("D"));
                        APSIMImporter importer = new APSIMImporter();
                        importer.ImportSoil(document.DocumentElement, newDoc.DocumentElement, newDoc.DocumentElement);
                        XmlNode soilNode = XmlUtilities.FindByType(newDoc.DocumentElement, "Soil");
                        if (soilNode != null &&
                            XmlUtilities.FindByType(soilNode, "Sample") == null &&
                            XmlUtilities.FindByType(soilNode, "InitialWater") == null)
                        {
                            // Add in an initial water and initial conditions models.
                            XmlNode initialWater = soilNode.AppendChild(soilNode.OwnerDocument.CreateElement("InitialWater"));
                            XmlUtilities.SetValue(initialWater, "Name", "Initial water");
                            XmlUtilities.SetValue(initialWater, "PercentMethod", "FilledFromTop");
                            XmlUtilities.SetValue(initialWater, "FractionFull", "1");
                            XmlUtilities.SetValue(initialWater, "DepthWetSoil", "NaN");
                            XmlNode initialConditions = soilNode.AppendChild(soilNode.OwnerDocument.CreateElement("Sample"));
                            XmlUtilities.SetValue(initialConditions, "Name", "Initial conditions");
                            XmlUtilities.SetValue(initialConditions, "Thickness/double", "1800");
                            XmlUtilities.SetValue(initialConditions, "NO3/double", "10");
                            XmlUtilities.SetValue(initialConditions, "NH4/double", "1");
                            XmlUtilities.SetValue(initialConditions, "NO3Units", "kgha");
                            XmlUtilities.SetValue(initialConditions, "NH4Units", "kgha");
                            XmlUtilities.SetValue(initialConditions, "SWUnits", "Volumetric");
                        }
                        document.LoadXml(newDoc.DocumentElement.InnerXml);
                    }

                    IModel child = XmlUtilities.Deserialise(document.DocumentElement, ApsimXFile.GetType().Assembly) as IModel;

                    AddModelCommand command = new AddModelCommand(parentModel, document.DocumentElement,
                                                                  GetNodeDescription(child), view);
                    this.CommandHistory.Add(command, true);
                }
            }
            catch (Exception exception)
            {
                this.MainPresenter.ShowMessage(exception.Message, DataStore.ErrorLevel.Error);
            }
        }
示例#19
0
        /// <summary>
        /// Handles presses of the "ok" button
        /// Attempts to retrieve the indicated soil description and put it in place of the original soil.
        /// Closes the dialog if successful
        /// </summary>
        /// <param name="sender">Sender of the event</param>
        /// <param name="e">Event arguments</param>
        private void BtnOk_Clicked(object sender, EventArgs e)
        {
            if (!CheckValue(entryLatitude) || !CheckValue(entryLatitude))
            {
                return;
            }
            if (String.IsNullOrWhiteSpace(entryFilePath.Text))
            {
                ShowMessage(MessageType.Warning, "You must provide a file name for saving the weather data", "No file path");
                BtnBrowse_Clicked(this, null);
                return;
            }
            string newWeatherPath = null;

            WaitCursor = true;
            try
            {
                if (radioSiloDataDrill.Active)
                {
                    newWeatherPath = GetDataDrill();
                }
                else if (radioSiloPatchPoint.Active)
                {
                    newWeatherPath = GetPatchPoint();
                }
                else if (radioNASA.Active)
                {
                    newWeatherPath = GetNasaChirps();
                }
            }
            finally
            {
                WaitCursor = false;
            }
            if (string.IsNullOrWhiteSpace(newWeatherPath))
            {
                ShowMessage(MessageType.Error, "Unable to obtain data for this site", "Error");
            }
            else
            {
                if (dest is Weather)
                {
                    // If there is an existing Weather model (and there usually will be), is it better to replace
                    // the model, or modify the FullFileName of the original?
                    IPresenter currentPresenter = explorerPresenter.CurrentPresenter;
                    if (currentPresenter is MetDataPresenter)
                    {
                        (currentPresenter as MetDataPresenter).OnBrowse(newWeatherPath);
                    }
                    else
                    {
                        explorerPresenter.CommandHistory.Add(new UserInterface.Commands.ChangeProperty(dest, "FullFileName", newWeatherPath));
                    }
                }
                else if (dest is Simulation)
                {
                    Weather newWeather = new Weather();
                    newWeather.FullFileName = newWeatherPath;
                    string          modelStr = FileFormat.WriteToString(newWeather);
                    AddModelCommand command  = new AddModelCommand(replaceNode, modelStr, owningView, explorerPresenter);
                    explorerPresenter.CommandHistory.Add(command, true);
                }
                dialog1.Destroy();
            }
        }
示例#20
0
        public async Task <ActionResult <int> > CreateMake([FromBody] AddModelCommand command)
        {
            int id = await this.Mediator.Send(command);

            return(Ok(id));
        }