public object GetValue(object target) { if (target is ModelCollectionFromResource m && Apsim.Ancestor <Replacements>(m) == null) { return(m.ChildrenToSerialize); } return(new DynamicValueProvider(memberInfo).GetValue(target)); }
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { JsonProperty property = base.CreateProperty(member, memberSerialization); if (property.PropertyName == "Children") { property.ShouldSerialize = instance => { if (instance is IOptionallySerialiseChildren) { // If resource model is under replacements, // always serialize children. if (Apsim.Ancestor <Replacements>(instance as IModel) != null) { return(true); } return((instance as IOptionallySerialiseChildren).DoSerialiseChildren); } return(true); }; } else if (typeof(ModelCollectionFromResource).IsAssignableFrom(member.DeclaringType)) { property.ShouldSerialize = instance => { var xmlIgnore = member.GetCustomAttribute <XmlIgnoreAttribute>(); var jsonIgnore = member.GetCustomAttribute <JsonIgnoreAttribute>(); if (xmlIgnore != null || jsonIgnore != null) { return(false); } // If this property has a description attribute, then it's settable // from the UI, in which case it should always be serialized. var description = member.GetCustomAttribute <DescriptionAttribute>(); if (description != null) { return(true); } // If the model is under a replacements node, then serialize everything. ModelCollectionFromResource resource = instance as ModelCollectionFromResource; if (Apsim.Ancestor <Replacements>(resource) != null) { return(true); } // Otherwise, only serialize if the property is inherited from // Model or ModelCollectionFromResource. return(member.DeclaringType.IsAssignableFrom(typeof(ModelCollectionFromResource))); }; } return(property); }
public void AncestorTest() { // Passing in null should return null. Assert.Null(Apsim.Ancestor <IModel>(null)); // Passing in the top-level simulations object should return null. Assert.Null(Apsim.Ancestor <IModel>(simulations)); // Passing in an object should never return that object Assert.AreNotEqual(simulation, Apsim.Ancestor <Simulation>(simulation)); // Searching for any IModel ancestor should return the node's parent. Assert.AreEqual(simulation.Parent, Apsim.Ancestor <IModel>(simulation)); }
private static void ChangeVariableValue(IVariable variable, string value) { variable.Value = ReflectionUtilities.StringToObject(variable.DataType, value); if (variable is VariableComposite composite) { IModel model = composite.Variables.FirstOrDefault(v => v is VariableObject obj && obj.Value is IModel)?.Value as IModel; if (model != null) { ModelCollectionFromResource resourceModel = Apsim.Ancestor <ModelCollectionFromResource>(model); if (resourceModel != null) { resourceModel.ResourceName = null; } if (model.Parent is Manager manager) { manager.RebuildScriptModel(); } } } }