/// <summary>Adds a new model (as specified by the string argument) to the specified parent.</summary> /// <param name="parent">The parent to add the model to</param> /// <param name="st">The string representing the new model</param> /// <returns>The newly created model.</returns> public static IModel Add(string st, IModel parent) { // The strategy here is to try and add the string as if it was a APSIM Next Gen. // string (json or xml). If that throws an exception then try adding it as if // it was an APSIM 7.10 string (xml). If that doesn't work throw 'invalid format' exception. List <Exception> creationExceptions; IModel modelToAdd = null; try { modelToAdd = FileFormat.ReadFromString <IModel>(st, out creationExceptions); } catch (Exception err) { if (err.Message.StartsWith("Unknown string encountered")) { throw; } } if (modelToAdd == null) { // Try the string as if it was an APSIM 7.10 xml string. var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<Simulation>" + st + "</Simulation>"); var importer = new Importer(); var rootNode = xmlDocument.DocumentElement as XmlNode; var convertedNode = importer.AddComponent(rootNode.ChildNodes[0], ref rootNode); rootNode.RemoveAll(); rootNode.AppendChild(convertedNode); var newSimulationModel = FileFormat.ReadFromString <IModel>(rootNode.OuterXml, out creationExceptions); if (newSimulationModel == null || newSimulationModel.Children.Count == 0) { throw new Exception("Cannot add model. Invalid model being added."); } modelToAdd = newSimulationModel.Children[0]; } // Correctly parent all models. modelToAdd = Add(modelToAdd, parent); // Ensure the model name is valid. EnsureNameIsUnique(modelToAdd); // Call OnCreated foreach (IModel model in modelToAdd.FindAllDescendants().ToList()) { model.OnCreated(); } return(modelToAdd); }
/// <summary>Adds a new model (as specified by the string argument) to the specified parent.</summary> /// <param name="parent">The parent to add the model to</param> /// <param name="st">The string representing the new model</param> /// <returns>The newly created model.</returns> public static IModel Add(string st, IModel parent) { List <Exception> creationExceptions; IModel modelToAdd = FileFormat.ReadFromString <IModel>(st, out creationExceptions); // Correctly parent all models. Add(modelToAdd, parent); // Ensure the model name is valid. EnsureNameIsUnique(modelToAdd); // Call OnCreated Apsim.ChildrenRecursively(modelToAdd).ForEach(m => m.OnCreated()); return(modelToAdd); }