public static object ParseAs(this string value, Type t) { if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable <>)) { if (string.IsNullOrWhiteSpace(value)) { return(null); } else { return(ParseAs(value, t.GetGenericArguments()[0])); } } if (t.GetInterface(nameof(IParsable)) != null) { IParsable o = (IParsable)Activator.CreateInstance(t); o.ReadFromString(value); return(o); } if (string.Equals(t.BaseType.Name, nameof(Enum), StringComparison.InvariantCulture)) { return(Enum.Parse(t, value)); } switch (t.Name) { case nameof(Boolean): return(bool.Parse(value)); case nameof(SByte): return(sbyte.Parse(value)); case nameof(Byte): return(byte.Parse(value)); case nameof(Char): return(char.Parse(value)); case nameof(Int16): return(short.Parse(value)); case nameof(UInt16): return(ushort.Parse(value)); case nameof(Int32): return(int.Parse(value)); case nameof(UInt32): return(uint.Parse(value)); case nameof(Int64): return(long.Parse(value)); case nameof(UInt64): return(ulong.Parse(value)); case nameof(Single): return(float.Parse(value)); case nameof(Double): return(double.Parse(value)); case nameof(Decimal): return(decimal.Parse(value)); case nameof(String): return(value); } throw new InvalidOperationException($"{t.GetFriendlyName()} is not parsable"); }
public Analyzer(IParsable parser) { if (null == parser) { throw new ArgumentNullException("parser"); } this.parser = parser; reportItems = new ReportCollection(); }
public ConfigManager(string path, Type mainType) { if (path.EndsWith(".xml")) { parser = new XmlParser(path, mainType); } else if (path.EndsWith(".json")) { parser = new JsonParser(path, mainType); } else { throw new ArgumentNullException($"invalid extension"); } }
public ConfigProvider(string filePath) { if (!File.Exists(filePath)) { throw new ArgumentException("File doesnt exist"); } if (Path.GetExtension(filePath) == ".json") { parser = new ParserJson(filePath); } if (Path.GetExtension(filePath) == ".xml") { parser = new ParserXml(filePath); } }
/// <summary> /// Sets the value of a parsertarget using a string /// </summary> public static void SetValueFromString(MemberInfo member, Object reference, String value) { // Get the current value Object current = GetValue(member, reference); Object backup = current; try { // Get the type of the member Type memberType = MemberType(member); // Is the member a string member? if (memberType == typeof(String)) { // Simply assign the new value SetValue(member, reference, value); return; } // Is the member a parsable type? if (typeof(IParsable).IsAssignableFrom(memberType)) { // Is the member null? if (current == null) { SetValue(member, reference, current = Activator.CreateInstance(memberType)); } // Now we can parse the value IParsable parser = (IParsable)current; parser.SetFromString(value); // Reapply SetValue(member, reference, parser); return; } } catch (Exception e) { Debug.LogException(e); SetValue(member, reference, backup); return; } // The member wasn't parsable throw new InvalidOperationException("The member wasn't parsable"); }
/// <summary> /// Processes a value from a config /// </summary> /// <returns></returns> private static Object ProcessValue(Type targetType, String nodeValue) { // If the target is a String, it works natively if (targetType == typeof(String)) { return(nodeValue); } // Figure out if this object is a parsable type if (!typeof(IParsable).IsAssignableFrom(targetType)) { return(null); } // Create a new object IParsable targetParsable = (IParsable)Activator.CreateInstance(targetType); targetParsable.SetFromString(nodeValue); return(targetParsable); }
public static bool Draw(ILoadable loadable, ICopyable copyable, IParsable compilable) { try { EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("File", EditorStyles.toolbarButton, GUILayout.Width(35))) { GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("New "), false, OnNew, loadable); menu.AddItem(new GUIContent("Load"), false, OnLoad, loadable); menu.AddItem(new GUIContent("Save"), false, OnSave, loadable); menu.AddItem(new GUIContent("Export as constellation file"), false, OnExportAsCL, loadable); menu.ShowAsContext(); return(true); } if (GUILayout.Button("Edit", EditorStyles.toolbarButton, GUILayout.Width(35))) { GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("Copy"), false, Copy, copyable); menu.AddItem(new GUIContent("Past"), false, Paste, copyable); menu.ShowAsContext(); return(true); } if (GUILayout.Button("Refresh", EditorStyles.toolbarButton, GUILayout.Width(70))) { compilable.ParseScript(true); return(true); } GUILayout.Label("", EditorStyles.toolbarButton); EditorGUILayout.EndHorizontal(); }catch { } return(false); }
protected override void BuildDialog() { // Skin Skin = KittopiaTech.Skin; // Get the enum type Object value = GetValue(); Type enumParser = value.GetType(); Type enumType = enumParser.GetGenericArguments()[0]; Int32 count = Enum.GetNames(enumType).Length; GUIScrollList(new Vector2(390, Math.Min(count * 25f + 20f, 400)), false, true, () => { GUIVerticalLayout(true, false, 2f, new RectOffset(8, 26, 8, 8), TextAnchor.UpperLeft, () => { GUIContentSizer(ContentSizeFitter.FitMode.Unconstrained, ContentSizeFitter.FitMode.PreferredSize, true); String[] names = Enum.GetNames(enumType); for (Int32 i = 0; i < names.Length; i++) { Int32 index = i; GUIToggleButton(() => (GetValue() as IWritable)?.ValueToString() == names[index], names[index], s => { if (s) { IParsable parsable = GetValue() as IParsable; parsable?.SetFromString(names[index]); SetValue(parsable); } }, -1, 25f); } }); }); }
/** * Load data for ParserTarget field or property from a configuration node * * @param member Member to load data for * @param o Instance of the object which owns member * @param node Configuration node from which to load data **/ public static void LoadObjectMemberFromConfigurationNode(MemberInfo member, object o, ConfigNode node, bool getChilds = true) { // Get the parser target, only one is allowed so it will be first ParserTarget target = (member.GetCustomAttributes(typeof(ParserTarget), true) as ParserTarget[]) [0]; // Figure out if this field exists and if we care bool isNode = node.HasNode(target.fieldName); bool isValue = node.HasValue(target.fieldName); // Obtain the type the member is (can only be field or property) Type targetType = null; object targetValue = null; if (member.MemberType == MemberTypes.Field) { targetType = (member as FieldInfo).FieldType; if (getChilds) { targetValue = (member as FieldInfo).GetValue(o); } else { targetValue = null; } } else { targetType = (member as PropertyInfo).PropertyType; try { if ((member as PropertyInfo).CanRead && getChilds) { targetValue = (member as PropertyInfo).GetValue(o, null); } else { targetValue = null; } } catch (Exception) { } } // If there was no data found for this node if (!isNode && !isValue) { if (!target.optional && !(target.allowMerge && targetValue != null)) { // Error - non optional field is missing throw new ParserTargetMissingException("Missing non-optional field: " + o.GetType() + "." + target.fieldName); } // Nothing to do, so DONT return! return; } // If this object is a value (attempt no merge here) if (isValue) { // The node value string nodeValue = node.GetValue(target.fieldName); // Merge all values of the node if (target.getAll != null) { nodeValue = String.Join(target.getAll, node.GetValues(target.fieldName)); } // If the target is a string, it works natively if (targetType.Equals(typeof(string))) { targetValue = nodeValue; } // Figure out if this object is a parsable type else if (typeof(IParsable).IsAssignableFrom(targetType)) { // Create a new object IParsable targetParsable = (IParsable)Activator.CreateInstance(targetType); targetParsable.SetFromString(nodeValue); targetValue = targetParsable; } // Throw exception or print error else { return; } } // If this object is a node (potentially merge) else { // If the target type is a ConfigNode, this works natively if (targetType == typeof(ConfigNode)) { targetValue = node.GetNode(target.fieldName); } // Check for Ranges else if (targetType == typeof(NumericParser <Double>)) { targetValue = new NumericParser <Double>((Double)CreateObjectFromConfigNode <Range>(node.GetNode(target.fieldName))); } // We need to get an instance of the object we are trying to populate // If we are not allowed to merge, or the object does not exist, make a new instance else if (targetValue == null || !target.allowMerge) { targetValue = CreateObjectFromConfigNode(targetType, node.GetNode(target.fieldName), target.getChild); } // Otherwise we can merge this value else { LoadObjectFromConfigurationNode(targetValue, node.GetNode(target.fieldName), target.getChild); } } // If the member type is a field, set the value if (member.MemberType == MemberTypes.Field) { (member as FieldInfo).SetValue(o, targetValue); } // If the member wasn't a field, it must be a property. If the property is writable, set it. else if ((member as PropertyInfo).CanWrite) { (member as PropertyInfo).SetValue(o, targetValue, null); } }
/** * Load data for ParserTarget field or property from a configuration node * * @param member Member to load data for * @param o Instance of the object which owns member * @param node Configuration node from which to load data **/ public static void LoadObjectMemberFromConfigurationNode(MemberInfo member, object o, ConfigNode node, bool getChilds = true) { // Get the parser target, only one is allowed so it will be first ParserTarget target = (member.GetCustomAttributes((typeof(ParserTarget)), true) as ParserTarget[]) [0]; // Figure out if this field exists and if we care bool isNode = node.HasNode(target.fieldName); bool isValue = node.HasValue(target.fieldName); // Obtain the type the member is (can only be field or property) Type targetType = null; object targetValue = null; if (member.MemberType == MemberTypes.Field) { targetType = (member as FieldInfo).FieldType; if (getChilds) { targetValue = (member as FieldInfo).GetValue(o); } else { targetValue = null; } } else { targetType = (member as PropertyInfo).PropertyType; try { if ((member as PropertyInfo).CanRead && getChilds) { targetValue = (member as PropertyInfo).GetValue(o, null); } else { targetValue = null; } } catch (Exception e) { // Ignore runtime getters if (!e.StackTrace.Contains(".get_")) { Debug.LogException(e); } } } Logger.Active.Log("Parsing Target " + target.fieldName + " in (" + o.GetType() + ") as (" + targetType + ")"); // If there was no data found for this node if (!isNode && !isValue) { if (!target.optional && !(target.allowMerge && targetValue != null)) { // Error - non optional field is missing throw new ParserTargetMissingException("Missing non-optional field: " + o.GetType() + "." + target.fieldName); } // Nothing to do, so DONT return! return; } // Does this node have a required config source type (and if so, check if valid) RequireConfigType[] attributes = member.GetCustomAttributes(typeof(RequireConfigType), true) as RequireConfigType[]; if (attributes.Length > 0) { if ((attributes[0].type == ConfigType.Node && !isNode) || (attributes[0].type == ConfigType.Value && !isValue)) { throw new ParserTargetTypeMismatchException(target.fieldName + " requires config value of " + attributes[0].type); } } // If this object is a value (attempt no merge here) if (isValue) { // The node value string nodeValue = node.GetValue(target.fieldName); // Merge all values of the node if (target.getAll != null) { nodeValue = String.Join(target.getAll, node.GetValues(target.fieldName)); } // If the target is a string, it works natively if (targetType.Equals(typeof(string))) { targetValue = nodeValue; } // Figure out if this object is a parsable type else if ((typeof(IParsable)).IsAssignableFrom(targetType)) { // Create a new object IParsable targetParsable = (IParsable)Activator.CreateInstance(targetType); targetParsable.SetFromString(nodeValue); targetValue = targetParsable; } // Throw exception or print error else { Logger.Active.Log("[Kopernicus]: Configuration.Parser: ParserTarget \"" + target.fieldName + "\" is a non parsable type: " + targetType); return; } } // If this object is a node (potentially merge) else if (isNode) { // If the target type is a ConfigNode, this works natively if (targetType.Equals(typeof(ConfigNode))) { targetValue = node.GetNode(target.fieldName); } // We need to get an instance of the object we are trying to populate // If we are not allowed to merge, or the object does not exist, make a new instance else if (targetValue == null || !target.allowMerge) { targetValue = CreateObjectFromConfigNode(targetType, node.GetNode(target.fieldName), target.getChild); } // Otherwise we can merge this value else { LoadObjectFromConfigurationNode(targetValue, node.GetNode(target.fieldName), target.getChild); } } // If the member type is a field, set the value if (member.MemberType == MemberTypes.Field) { (member as FieldInfo).SetValue(o, targetValue); } // If the member wasn't a field, it must be a property. If the property is writable, set it. else if ((member as PropertyInfo).CanWrite) { (member as PropertyInfo).SetValue(o, targetValue, null); } }
public FakeAnalyzer(IParsable parser, UInt32 actualReportItemCount) : base(parser) { this.actualReportItemCount = actualReportItemCount; }
public FakeAnalyzer(IParsable parser, UInt32 actualReportItemCount) : base(parser) { this.actualReportItemCount = actualReportItemCount; }
public BasicWithoutMetaData() { dummyClient = new DummyClient(); argumentParser = BuildParser(dummyClient); }