Apply R# clean-up for reliability (#877)
* Apply R# clean-up for reliability - Migrate to NUnit4 Assert.That - Update dependencise versions - Fix LangVersion to 9.0 (until net core migration) - Reformat code - Apply 'var' style (easier for refactoring) - Remove redundant parentheses - Add braces on every condition blocks (1 line) - Uses new null checking patterns - Uses AutoProperties when possible - Uses string scalar type instead of class - Clean usings - Add .orig files in git ignore - Rename some properties to respect defined conventions and US format definition - ID -> Id - BPM -> Bpm - Finish -> End * Update R# settings according to the clean-up made
This commit is contained in:
1 parent
b9b0f7c8df
commit
6ffa63b923
236 files changed
+14194
-7278
No files matched your search
@@ -46,7 +46,7 @@ namespace VocaluxeLib.Xml
|
||||
[AttributeUsage(AttributeTargets.Field)]
|
||||
public class XmlNormalizedAttribute : XmlRangedAttribute
|
||||
{
|
||||
public XmlNormalizedAttribute() : base(0, 1) {}
|
||||
public XmlNormalizedAttribute() : base(0, 1) { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -67,11 +67,20 @@ namespace VocaluxeLib.Xml
|
||||
public bool IsValid(Type type, object value)
|
||||
{
|
||||
if (type == typeof(int))
|
||||
{
|
||||
return ((int)value).IsInRange(Min, Max);
|
||||
}
|
||||
|
||||
if (type == typeof(float))
|
||||
{
|
||||
return ((float)value).IsInRange(Min, Max);
|
||||
}
|
||||
|
||||
if (type == typeof(double))
|
||||
{
|
||||
return ((double)value).IsInRange(Min, Max);
|
||||
}
|
||||
|
||||
Debug.Assert(false, "Ranged attribute has invalid type");
|
||||
return false;
|
||||
}
|
||||
@@ -99,11 +108,18 @@ namespace VocaluxeLib.Xml
|
||||
{
|
||||
Type subType;
|
||||
if (type.IsGenericType)
|
||||
{
|
||||
subType = type.GetGenericArguments().Last();
|
||||
}
|
||||
else if (type.IsArray)
|
||||
{
|
||||
subType = type.GetElementType();
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return subType.GetTypeName();
|
||||
}
|
||||
|
||||
@@ -114,7 +130,7 @@ namespace VocaluxeLib.Xml
|
||||
/// <param name="field">Field descrived by the struct</param>
|
||||
private static void _FillInfo(ref SFieldInfo info, MemberInfo field)
|
||||
{
|
||||
XmlAttributeAttribute attribute = field.GetAttribute<XmlAttributeAttribute>();
|
||||
var attribute = field.GetAttribute<XmlAttributeAttribute>();
|
||||
if (attribute != null)
|
||||
{
|
||||
info.IsAttribute = true;
|
||||
@@ -122,12 +138,14 @@ namespace VocaluxeLib.Xml
|
||||
}
|
||||
else
|
||||
{
|
||||
XmlElementAttribute element = field.GetAttribute<XmlElementAttribute>();
|
||||
var element = field.GetAttribute<XmlElementAttribute>();
|
||||
if (element != null)
|
||||
{
|
||||
info.Name = element.ElementName;
|
||||
}
|
||||
else
|
||||
{
|
||||
XmlArrayAttribute array = field.GetAttribute<XmlArrayAttribute>();
|
||||
var array = field.GetAttribute<XmlArrayAttribute>();
|
||||
if (array != null)
|
||||
{
|
||||
Debug.Assert(info.Type.IsList() || info.Type.IsArray, "Only lists and arrays can have the array attribute");
|
||||
@@ -137,35 +155,54 @@ namespace VocaluxeLib.Xml
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(info.Name))
|
||||
{
|
||||
info.Name = field.Name;
|
||||
XmlAltNameAttribute altName = field.GetAttribute<XmlAltNameAttribute>();
|
||||
}
|
||||
|
||||
var altName = field.GetAttribute<XmlAltNameAttribute>();
|
||||
if (altName != null)
|
||||
{
|
||||
info.AltName = altName.AltName;
|
||||
}
|
||||
|
||||
if (info.Type.IsGenericType)
|
||||
{
|
||||
info.SubType = info.Type.GetGenericArguments().Last();
|
||||
}
|
||||
else if (info.Type.IsArray)
|
||||
{
|
||||
info.SubType = info.Type.GetElementType();
|
||||
}
|
||||
|
||||
if (info.Type.IsList() || info.Type.IsArray)
|
||||
{
|
||||
if (!info.IsList)
|
||||
{
|
||||
Debug.Assert(!field.HasAttribute<XmlArrayAttribute>(), "A field cannot have an XmlElement- and XmlArray-Attribute");
|
||||
if (info.Type.IsArray && info.SubType == typeof(byte))
|
||||
{
|
||||
info.IsByteArray = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
info.IsEmbeddedList = true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
XmlArrayItemAttribute arrayItem = field.GetAttribute<XmlArrayItemAttribute>();
|
||||
var arrayItem = field.GetAttribute<XmlArrayItemAttribute>();
|
||||
if (arrayItem != null && !string.IsNullOrEmpty(arrayItem.ElementName))
|
||||
{
|
||||
info.ArrayItemName = arrayItem.ElementName;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (info.Type.IsNullable())
|
||||
{
|
||||
info.IsNullable = true;
|
||||
}
|
||||
else if (info.Type.IsDictionary())
|
||||
{
|
||||
Debug.Assert(info.Type.GetGenericArguments()[0] == typeof(string), "Keys of dictionaries must be strings");
|
||||
@@ -173,13 +210,16 @@ namespace VocaluxeLib.Xml
|
||||
}
|
||||
|
||||
if (field.HasAttribute<XmlNormalizedAttribute>())
|
||||
{
|
||||
Debug.Assert(info.Type == typeof(float) || (info.IsNullable && info.SubType == typeof(float)), "Only floats can be normalized");
|
||||
info.Ranged = field.GetAttribute<XmlRangedAttribute>();
|
||||
Type tmpType = info.IsNullable ? info.SubType : info.Type;
|
||||
Debug.Assert(info.Ranged == null || tmpType == typeof(int) || tmpType == typeof(float) || tmpType == typeof(double),
|
||||
"Only ints,floats and double can be ranged");
|
||||
}
|
||||
|
||||
DefaultValueAttribute defAttr = field.GetAttribute<DefaultValueAttribute>();
|
||||
info.Ranged = field.GetAttribute<XmlRangedAttribute>();
|
||||
var tmpType = info.IsNullable ? info.SubType : info.Type;
|
||||
Debug.Assert(info.Ranged == null || tmpType == typeof(int) || tmpType == typeof(float) || tmpType == typeof(double),
|
||||
"Only ints,floats and double can be ranged");
|
||||
|
||||
var defAttr = field.GetAttribute<DefaultValueAttribute>();
|
||||
if (defAttr != null)
|
||||
{
|
||||
Debug.Assert(!info.Type.IsList(), "Lists cannot have a default value");
|
||||
@@ -202,26 +242,37 @@ namespace VocaluxeLib.Xml
|
||||
{
|
||||
List<SFieldInfo> result;
|
||||
if (_CacheFields.TryGetValue(type, out result))
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
result = new List<SFieldInfo>();
|
||||
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
|
||||
foreach (FieldInfo field in fields)
|
||||
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
|
||||
foreach (var field in fields)
|
||||
{
|
||||
if (field.HasAttribute<XmlIgnoreAttribute>() || field.Name.EndsWith("Specified"))
|
||||
{
|
||||
continue;
|
||||
SFieldInfo info = new SFieldInfo(field);
|
||||
}
|
||||
|
||||
var info = new SFieldInfo(field);
|
||||
_FillInfo(ref info, field);
|
||||
result.Add(info);
|
||||
}
|
||||
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
|
||||
foreach (PropertyInfo property in properties)
|
||||
|
||||
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
|
||||
foreach (var property in properties)
|
||||
{
|
||||
if (property.HasAttribute<XmlIgnoreAttribute>() || property.Name.EndsWith("Specified") || !property.CanRead || !property.CanWrite)
|
||||
{
|
||||
continue;
|
||||
SFieldInfo info = new SFieldInfo(property);
|
||||
}
|
||||
|
||||
var info = new SFieldInfo(property);
|
||||
_FillInfo(ref info, property);
|
||||
result.Add(info);
|
||||
}
|
||||
|
||||
_CacheFields.Add(type, result);
|
||||
return result;
|
||||
}
|
||||
@@ -246,16 +297,24 @@ namespace VocaluxeLib.Xml
|
||||
{
|
||||
string name;
|
||||
if (_CacheTypeName.TryGetValue(type, out name))
|
||||
{
|
||||
return name;
|
||||
XmlTypeAttribute att = type.GetAttribute<XmlTypeAttribute>();
|
||||
}
|
||||
|
||||
var att = type.GetAttribute<XmlTypeAttribute>();
|
||||
if (att != null)
|
||||
{
|
||||
name = att.TypeName;
|
||||
if (string.IsNullOrEmpty(name))
|
||||
{
|
||||
name = type.Name;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
name = type.Name;
|
||||
}
|
||||
|
||||
_CacheTypeName.Add(type, name);
|
||||
return name;
|
||||
}
|
||||
@@ -279,7 +338,7 @@ namespace VocaluxeLib.Xml
|
||||
/// <returns></returns>
|
||||
public static T GetAttribute<T>(this ICustomAttributeProvider field) where T : class
|
||||
{
|
||||
object[] attributes = field.GetCustomAttributes(typeof(T), false);
|
||||
var attributes = field.GetCustomAttributes(typeof(T), false);
|
||||
return attributes.Length == 0 ? null : (T)attributes[0];
|
||||
}
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ namespace VocaluxeLib.Xml
|
||||
/// <returns></returns>
|
||||
private string _GetXPath(XmlNode node)
|
||||
{
|
||||
StringBuilder builder = new StringBuilder();
|
||||
var builder = new StringBuilder();
|
||||
while (node != null)
|
||||
{
|
||||
switch (node.NodeType)
|
||||
@@ -49,7 +49,7 @@ namespace VocaluxeLib.Xml
|
||||
node = ((XmlAttribute)node).OwnerElement;
|
||||
break;
|
||||
case XmlNodeType.Element:
|
||||
string index = _FindElementIndex(node);
|
||||
var index = _FindElementIndex(node);
|
||||
builder.Insert(0, "/" + node.Name + index);
|
||||
node = node.ParentNode;
|
||||
break;
|
||||
@@ -59,6 +59,7 @@ namespace VocaluxeLib.Xml
|
||||
throw new ArgumentException("Only elements and attributes are supported");
|
||||
}
|
||||
}
|
||||
|
||||
throw new ArgumentException("Node was not in a document");
|
||||
}
|
||||
|
||||
@@ -69,21 +70,28 @@ namespace VocaluxeLib.Xml
|
||||
/// <returns></returns>
|
||||
private string _FindElementIndex(XmlNode element)
|
||||
{
|
||||
XmlNode parentNode = element.ParentNode;
|
||||
var parentNode = element.ParentNode;
|
||||
if (parentNode is XmlDocument)
|
||||
{
|
||||
return "";
|
||||
XmlElement parent = (XmlElement)parentNode;
|
||||
int index = 1;
|
||||
}
|
||||
|
||||
var parent = (XmlElement)parentNode;
|
||||
var index = 1;
|
||||
if (parent != null)
|
||||
{
|
||||
XmlNode[] siblings = parent.ChildNodes.Cast<XmlNode>().Where(candidate => candidate is XmlElement && candidate.Name == element.Name).ToArray();
|
||||
foreach (XmlNode candidate in siblings)
|
||||
var siblings = parent.ChildNodes.Cast<XmlNode>().Where(candidate => candidate is XmlElement && candidate.Name == element.Name).ToArray();
|
||||
foreach (var candidate in siblings)
|
||||
{
|
||||
if (candidate == element)
|
||||
{
|
||||
return siblings.Length > 1 ? "[" + index + "]" : "";
|
||||
}
|
||||
|
||||
index++;
|
||||
}
|
||||
}
|
||||
|
||||
throw new ArgumentException("Couldn't find element within parent");
|
||||
}
|
||||
#endregion Debug Helpers
|
||||
@@ -105,8 +113,8 @@ namespace VocaluxeLib.Xml
|
||||
|
||||
public override String ToString()
|
||||
{
|
||||
string xPath = Node == null ? "" : _GetXPath(Node);
|
||||
string type = IsError ? "Error" : "Warning";
|
||||
var xPath = Node == null ? "" : _GetXPath(Node);
|
||||
var type = IsError ? "Error" : "Warning";
|
||||
return type + ": " + base.Message.Replace("%n", xPath);
|
||||
}
|
||||
}
|
||||
@@ -174,7 +182,10 @@ namespace VocaluxeLib.Xml
|
||||
public virtual void HandleError(CXmlException e)
|
||||
{
|
||||
if (e.IsError)
|
||||
{
|
||||
throw e;
|
||||
}
|
||||
|
||||
CLog.Error(e.ToString());
|
||||
}
|
||||
}
|
||||
@@ -192,7 +203,6 @@ namespace VocaluxeLib.Xml
|
||||
_UnescapeStringValues = unescapeStringValues;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new XmlDeserializer
|
||||
/// </summary>
|
||||
@@ -217,8 +227,11 @@ namespace VocaluxeLib.Xml
|
||||
if (type.IsEnum)
|
||||
{
|
||||
if (node == null)
|
||||
{
|
||||
return null;
|
||||
string stringValue = node.InnerText;
|
||||
}
|
||||
|
||||
var stringValue = node.InnerText;
|
||||
try
|
||||
{
|
||||
return Enum.Parse(type, stringValue);
|
||||
@@ -229,84 +242,134 @@ namespace VocaluxeLib.Xml
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
if (type == typeof(Guid))
|
||||
{
|
||||
return Guid.Parse(node.InnerText);
|
||||
if (type == typeof(string)) {
|
||||
if(node == null) {
|
||||
}
|
||||
|
||||
if (type == typeof(string))
|
||||
{
|
||||
if (node == null)
|
||||
{
|
||||
return null;
|
||||
} else if(_UnescapeStringValues) {
|
||||
}
|
||||
else if (_UnescapeStringValues)
|
||||
{
|
||||
return Regex.Unescape(node.InnerText);
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
return node.InnerText;
|
||||
}
|
||||
}
|
||||
|
||||
if (type.IsPrimitive)
|
||||
{
|
||||
return _GetPrimitiveValue(node, type) ?? value;
|
||||
}
|
||||
|
||||
if (type.IsNullable())
|
||||
{
|
||||
if (node == null || !node.HasChildNodes)
|
||||
{
|
||||
return null;
|
||||
Type subType = type.GetGenericArguments()[0];
|
||||
}
|
||||
|
||||
var subType = type.GetGenericArguments()[0];
|
||||
return _GetValue(node, subType, subName, value);
|
||||
}
|
||||
|
||||
if (type.IsList() || type.IsArray)
|
||||
{
|
||||
Type subType = type.IsArray ? type.GetElementType() : type.GetGenericArguments()[0];
|
||||
var subType = type.IsArray ? type.GetElementType() : type.GetGenericArguments()[0];
|
||||
if (subName == null)
|
||||
{
|
||||
subName = subType.GetTypeName();
|
||||
}
|
||||
|
||||
subName = subName.ToLowerInvariant();
|
||||
List<object> subValues = new List<object>();
|
||||
var subValues = new List<object>();
|
||||
if (node != null)
|
||||
{
|
||||
foreach (XmlNode subNode in node.ChildNodes)
|
||||
{
|
||||
if (subNode is XmlComment)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (subName == subNode.Name.ToLowerInvariant() && !subNode.Name.ToLowerInvariant().StartsWith(subName))
|
||||
{
|
||||
_ErrorHandler.HandleError(new CXmlException("Invalid list entry '" + subNode.Name + "' in %n; Expected: " + subName, node));
|
||||
object subValue = _GetValue(subNode, subType);
|
||||
}
|
||||
|
||||
var subValue = _GetValue(subNode, subType);
|
||||
if (subValue != null)
|
||||
{
|
||||
subValues.Add(subValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (value == null)
|
||||
{
|
||||
return _CreateList(type, subValues);
|
||||
}
|
||||
|
||||
_FillList(value, type, subValues);
|
||||
return value;
|
||||
}
|
||||
|
||||
if (type.IsDictionary())
|
||||
{
|
||||
Type subType = type.GetGenericArguments()[1];
|
||||
object dict = value ?? Activator.CreateInstance(type);
|
||||
MethodInfo add = type.GetMethod("Add");
|
||||
var subType = type.GetGenericArguments()[1];
|
||||
var dict = value ?? Activator.CreateInstance(type);
|
||||
var add = type.GetMethod("Add");
|
||||
if (subName != null)
|
||||
{
|
||||
subName = subName.ToLowerInvariant();
|
||||
}
|
||||
|
||||
if (node != null)
|
||||
{
|
||||
foreach (XmlNode subNode in node.ChildNodes)
|
||||
{
|
||||
if (subNode is XmlComment)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
string key;
|
||||
if (subName != null)
|
||||
{
|
||||
if (subName != subNode.Name.ToLowerInvariant() && !subNode.Name.ToLowerInvariant().StartsWith(subName))
|
||||
{
|
||||
_ErrorHandler.HandleError(new CXmlException("Invalid dictionary entry '" + subNode.Name + "' in %n; Expected: " + subName, node));
|
||||
XmlNode nameAtt = (subNode.Attributes == null) ? null : subNode.Attributes.GetNamedItem("name");
|
||||
}
|
||||
|
||||
var nameAtt = subNode.Attributes == null ? null : subNode.Attributes.GetNamedItem("name");
|
||||
if (nameAtt == null)
|
||||
{
|
||||
_ErrorHandler.HandleError(new CXmlException("'name' attribute is missing in %n", subNode));
|
||||
continue;
|
||||
}
|
||||
|
||||
key = nameAtt.Value;
|
||||
}
|
||||
else
|
||||
{
|
||||
key = subNode.Name;
|
||||
object subValue = _GetValue(subNode, subType);
|
||||
}
|
||||
|
||||
var subValue = _GetValue(subNode, subType);
|
||||
if (subValue != null)
|
||||
add.Invoke(dict, new object[] {key, subValue});
|
||||
{
|
||||
add.Invoke(dict, new object[] { key, subValue });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dict;
|
||||
}
|
||||
|
||||
@@ -322,6 +385,7 @@ namespace VocaluxeLib.Xml
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
_ReadChildNodes(node, value, true);
|
||||
_ReadChildNodes(node, value, false);
|
||||
return value;
|
||||
@@ -336,19 +400,23 @@ namespace VocaluxeLib.Xml
|
||||
private object _GetPrimitiveValue(XmlNode node, Type type)
|
||||
{
|
||||
if (node == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
object value;
|
||||
string nodeVal = node.InnerText;
|
||||
var nodeVal = node.InnerText;
|
||||
try
|
||||
{
|
||||
int p = nodeVal.IndexOf(',');
|
||||
var p = nodeVal.IndexOf(',');
|
||||
if (p > 0 && p >= nodeVal.Length - 3)
|
||||
{
|
||||
_ErrorHandler.HandleError(new CXmlInvalidValueException("German number format converted to English in %n", node, nodeVal, false));
|
||||
char[] tmp = nodeVal.ToCharArray();
|
||||
var tmp = nodeVal.ToCharArray();
|
||||
tmp[p] = '.';
|
||||
nodeVal = new string(tmp);
|
||||
}
|
||||
|
||||
value = Convert.ChangeType(nodeVal, type, CultureInfo.InvariantCulture);
|
||||
}
|
||||
catch (FormatException e)
|
||||
@@ -361,6 +429,7 @@ namespace VocaluxeLib.Xml
|
||||
_ErrorHandler.HandleError(new CXmlInvalidValueException(e.Message + " in %n: '%v'", node, nodeVal));
|
||||
return null;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
@@ -377,8 +446,12 @@ namespace VocaluxeLib.Xml
|
||||
_AddList(result, field, new List<object>());
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!field.HasDefaultValue)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
field.SetValue(result, field.DefaultValue);
|
||||
return true;
|
||||
}
|
||||
@@ -392,19 +465,26 @@ namespace VocaluxeLib.Xml
|
||||
private static void _FillList(object list, Type type, ICollection values)
|
||||
{
|
||||
if (values.Count <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (type.IsArray)
|
||||
{
|
||||
Array array = (Array)list;
|
||||
int i = 0;
|
||||
foreach (object value in values)
|
||||
var array = (Array)list;
|
||||
var i = 0;
|
||||
foreach (var value in values)
|
||||
{
|
||||
array.SetValue(value, i++);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
MethodInfo addMethod = type.GetMethod("Add");
|
||||
foreach (object value in values)
|
||||
addMethod.Invoke(list, new object[] {value});
|
||||
var addMethod = type.GetMethod("Add");
|
||||
foreach (var value in values)
|
||||
{
|
||||
addMethod.Invoke(list, new object[] { value });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -416,7 +496,7 @@ namespace VocaluxeLib.Xml
|
||||
/// <returns>Newly created collection</returns>
|
||||
private static object _CreateList(Type type, ICollection values)
|
||||
{
|
||||
object list = type.IsArray ? Array.CreateInstance(type.GetElementType(), values.Count) : Activator.CreateInstance(type, new object[] {values.Count});
|
||||
var list = type.IsArray ? Array.CreateInstance(type.GetElementType(), values.Count) : Activator.CreateInstance(type, new object[] { values.Count });
|
||||
_FillList(list, type, values);
|
||||
return list;
|
||||
}
|
||||
@@ -442,36 +522,50 @@ namespace VocaluxeLib.Xml
|
||||
{
|
||||
IEnumerable nodes;
|
||||
if (parent == null)
|
||||
{
|
||||
nodes = null;
|
||||
}
|
||||
else if (attributes)
|
||||
{
|
||||
nodes = parent.Attributes;
|
||||
}
|
||||
else
|
||||
{
|
||||
nodes = parent.ChildNodes;
|
||||
}
|
||||
|
||||
List<SFieldInfo> fields = o.GetType().GetFields(attributes);
|
||||
var fields = o.GetType().GetFields(attributes);
|
||||
|
||||
if (nodes != null)
|
||||
{
|
||||
//Dictionary of all embedded lists to allow interleaved/mixed elements
|
||||
Dictionary<string, Tuple<SFieldInfo, List<object>>> embLists = new Dictionary<string, Tuple<SFieldInfo, List<object>>>();
|
||||
var embLists = new Dictionary<string, Tuple<SFieldInfo, List<object>>>();
|
||||
foreach (XmlNode node in nodes)
|
||||
{
|
||||
if (node is XmlComment || node.LocalName == "xsd" || node.LocalName == "xsi")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
SFieldInfo field = new SFieldInfo();
|
||||
var field = new SFieldInfo();
|
||||
int curField;
|
||||
for (curField = 0; curField < fields.Count; curField++)
|
||||
{
|
||||
field = fields[curField];
|
||||
if (field.Name == node.Name || field.AltName == node.Name || (field.IsEmbeddedList && node.Name.StartsWith(field.Name)))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (curField >= fields.Count)
|
||||
{
|
||||
string msg = "Unexpected element: %n";
|
||||
var msg = "Unexpected element: %n";
|
||||
if (fields.Count > 0)
|
||||
{
|
||||
msg += " Expected: " + string.Join(", ", fields.Select(f => f.Name));
|
||||
}
|
||||
|
||||
_ErrorHandler.HandleError(new CXmlException(msg, node));
|
||||
continue;
|
||||
}
|
||||
@@ -488,9 +582,13 @@ namespace VocaluxeLib.Xml
|
||||
{
|
||||
_ErrorHandler.HandleError(new CXmlInvalidValueException("Invalid value in %n: %v", node, node.InnerText));
|
||||
if (!_CheckAndSetDefaultValue(o, field))
|
||||
{
|
||||
_ErrorHandler.HandleError(new CXmlException("No default value for %n", node));
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
field.SetValue(o, value);
|
||||
}
|
||||
else if (field.IsEmbeddedList)
|
||||
@@ -501,24 +599,31 @@ namespace VocaluxeLib.Xml
|
||||
entry = new Tuple<SFieldInfo, List<object>>(field, new List<object>());
|
||||
embLists.Add(field.Name, entry);
|
||||
}
|
||||
object subValue = _GetValue(node, field.SubType);
|
||||
|
||||
var subValue = _GetValue(node, field.SubType);
|
||||
if (subValue != null)
|
||||
{
|
||||
entry.Item2.Add(subValue);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
fields.RemoveAt(curField); //Do this also on error
|
||||
object value = _GetValue(node, field.Type, field.ArrayItemName);
|
||||
var value = _GetValue(node, field.Type, field.ArrayItemName);
|
||||
if (value == null)
|
||||
{
|
||||
if (_CheckAndSetDefaultValue(o, field))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!field.IsNullable)
|
||||
{
|
||||
_ErrorHandler.HandleError(new CXmlException("No default value for unset field at %n", node));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (field.Ranged != null && value != null && !field.Ranged.IsValid(field.IsNullable ? field.SubType : field.Type, value))
|
||||
{
|
||||
_ErrorHandler.HandleError(new CXmlInvalidValueException("Value in %n is not in the range " + field.Ranged +
|
||||
@@ -528,22 +633,29 @@ namespace VocaluxeLib.Xml
|
||||
field.SetValue(o, value);
|
||||
}
|
||||
}
|
||||
|
||||
//Add embedded lists
|
||||
foreach (Tuple<SFieldInfo, List<object>> entry in embLists.Values)
|
||||
foreach (var entry in embLists.Values)
|
||||
{
|
||||
_AddList(o, entry.Item1, entry.Item2);
|
||||
fields.Remove(entry.Item1);
|
||||
}
|
||||
}
|
||||
foreach (SFieldInfo field in fields)
|
||||
|
||||
foreach (var field in fields)
|
||||
{
|
||||
if (!_CheckAndSetDefaultValue(o, field))
|
||||
{
|
||||
if (parent != null)
|
||||
{
|
||||
_ErrorHandler.HandleError(new CXmlMissingElementException(parent, field));
|
||||
object value = _GetValue(null, field.Type, field.ArrayItemName, field.GetValue(o));
|
||||
}
|
||||
|
||||
var value = _GetValue(null, field.Type, field.ArrayItemName, field.GetValue(o));
|
||||
if (value != null)
|
||||
{
|
||||
field.SetValue(o, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -563,13 +675,14 @@ namespace VocaluxeLib.Xml
|
||||
return (T)o;
|
||||
}
|
||||
|
||||
XmlDocument xDoc = new XmlDocument();
|
||||
var xDoc = new XmlDocument();
|
||||
xDoc.Load(reader);
|
||||
if (xDoc.DocumentElement == null)
|
||||
{
|
||||
_ErrorHandler.HandleError(new CXmlException("Root element not found!", null));
|
||||
return (T)o;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
o = _GetValue(xDoc.DocumentElement, o.GetType(), o.GetType().GetSubTypeName(), o);
|
||||
@@ -578,6 +691,7 @@ namespace VocaluxeLib.Xml
|
||||
{
|
||||
throw e.InnerException ?? e;
|
||||
}
|
||||
|
||||
return (T)o;
|
||||
}
|
||||
|
||||
@@ -603,11 +717,11 @@ namespace VocaluxeLib.Xml
|
||||
public T DeserializeString<T>(string xml, T o) where T : new()
|
||||
{
|
||||
var reader = new XmlTextReader(new StringReader(xml))
|
||||
{
|
||||
WhitespaceHandling = WhitespaceHandling.Significant,
|
||||
Normalization = true,
|
||||
XmlResolver = null
|
||||
};
|
||||
{
|
||||
WhitespaceHandling = WhitespaceHandling.Significant,
|
||||
Normalization = true,
|
||||
XmlResolver = null
|
||||
};
|
||||
try
|
||||
{
|
||||
return _Deserialize<T>(reader, o);
|
||||
@@ -640,13 +754,16 @@ namespace VocaluxeLib.Xml
|
||||
public T Deserialize<T>(string filePath, T o) where T : new()
|
||||
{
|
||||
if (!File.Exists(filePath))
|
||||
{
|
||||
throw new FileNotFoundException(filePath);
|
||||
}
|
||||
|
||||
var reader = new XmlTextReader(filePath)
|
||||
{
|
||||
WhitespaceHandling = WhitespaceHandling.Significant,
|
||||
Normalization = true,
|
||||
XmlResolver = null
|
||||
};
|
||||
{
|
||||
WhitespaceHandling = WhitespaceHandling.Significant,
|
||||
Normalization = true,
|
||||
XmlResolver = null
|
||||
};
|
||||
try
|
||||
{
|
||||
return _Deserialize<T>(reader, o);
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
@@ -49,11 +48,11 @@ namespace VocaluxeLib.Xml
|
||||
/// Uniform settings for writing XML files. ALWAYS use this!
|
||||
/// </summary>
|
||||
private readonly XmlWriterSettings _XmlSettings = new XmlWriterSettings
|
||||
{
|
||||
Indent = true,
|
||||
Encoding = Encoding.UTF8,
|
||||
ConformanceLevel = ConformanceLevel.Document
|
||||
};
|
||||
{
|
||||
Indent = true,
|
||||
Encoding = Encoding.UTF8,
|
||||
ConformanceLevel = ConformanceLevel.Document
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Writes a value as a node or attribute
|
||||
@@ -69,10 +68,13 @@ namespace VocaluxeLib.Xml
|
||||
{
|
||||
if (!isAttribute && _GetCommentCallback != null)
|
||||
{
|
||||
string comment = _GetCommentCallback(name);
|
||||
var comment = _GetCommentCallback(name);
|
||||
if (!string.IsNullOrEmpty(comment))
|
||||
{
|
||||
writer.WriteComment(comment);
|
||||
}
|
||||
}
|
||||
|
||||
if (type.IsEnum || type == typeof(string) || type.IsPrimitive)
|
||||
{
|
||||
string strVal;
|
||||
@@ -84,15 +86,24 @@ namespace VocaluxeLib.Xml
|
||||
{
|
||||
throw new XmlException("Cannot convert value of type " + type.Name + " to string in node " + name + " (" + e.Message + ")");
|
||||
}
|
||||
|
||||
if (isAttribute)
|
||||
{
|
||||
writer.WriteAttributeString(name, strVal);
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteStartElement(name);
|
||||
if (nameAttribute != null)
|
||||
{
|
||||
writer.WriteAttributeString("name", nameAttribute);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(strVal))
|
||||
{
|
||||
writer.WriteValue(strVal);
|
||||
}
|
||||
|
||||
writer.WriteEndElement();
|
||||
}
|
||||
}
|
||||
@@ -101,18 +112,26 @@ namespace VocaluxeLib.Xml
|
||||
writer.WriteElementString(name, value.ToString());
|
||||
}
|
||||
else if (type.IsNullable())
|
||||
{
|
||||
_WriteValue(writer, name, type.GetGenericArguments()[0], value, isAttribute, arrayItemName, nameAttribute);
|
||||
}
|
||||
else if (type.IsList() || type.IsArray)
|
||||
{
|
||||
Debug.Assert(!isAttribute, "Lists cannot be attributes");
|
||||
writer.WriteStartElement(name);
|
||||
if (nameAttribute != null)
|
||||
{
|
||||
writer.WriteAttributeString("name", nameAttribute);
|
||||
Type subType = type.IsArray ? type.GetElementType() : type.GetGenericArguments()[0];
|
||||
String subName = arrayItemName ?? subType.GetTypeName();
|
||||
IEnumerable list = (IEnumerable)value;
|
||||
foreach (object subValue in list)
|
||||
}
|
||||
|
||||
var subType = type.IsArray ? type.GetElementType() : type.GetGenericArguments()[0];
|
||||
var subName = arrayItemName ?? subType.GetTypeName();
|
||||
var list = (IEnumerable)value;
|
||||
foreach (var subValue in list)
|
||||
{
|
||||
_WriteValue(writer, subName, subType, subValue, false);
|
||||
}
|
||||
|
||||
writer.WriteEndElement();
|
||||
}
|
||||
else if (type.IsDictionary())
|
||||
@@ -120,9 +139,12 @@ namespace VocaluxeLib.Xml
|
||||
Debug.Assert(!isAttribute, "Dictionaries cannot be attributes");
|
||||
writer.WriteStartElement(name);
|
||||
if (nameAttribute != null)
|
||||
{
|
||||
writer.WriteAttributeString("name", nameAttribute);
|
||||
Type subType = type.GetGenericArguments()[1];
|
||||
IDictionary dict = (IDictionary)value;
|
||||
}
|
||||
|
||||
var subType = type.GetGenericArguments()[1];
|
||||
var dict = (IDictionary)value;
|
||||
foreach (DictionaryEntry entry in dict)
|
||||
{
|
||||
string subName;
|
||||
@@ -137,8 +159,10 @@ namespace VocaluxeLib.Xml
|
||||
subName = arrayItemName;
|
||||
subNameAttribute = (string)entry.Key;
|
||||
}
|
||||
|
||||
_WriteValue(writer, subName, subType, entry.Value, false, null, subNameAttribute);
|
||||
}
|
||||
|
||||
writer.WriteEndElement();
|
||||
}
|
||||
else
|
||||
@@ -146,9 +170,15 @@ namespace VocaluxeLib.Xml
|
||||
Debug.Assert(!isAttribute, "Complex types cannot be attributes");
|
||||
writer.WriteStartElement(name);
|
||||
if (nameAttribute != null)
|
||||
{
|
||||
writer.WriteAttributeString("name", nameAttribute);
|
||||
}
|
||||
|
||||
if (value != null)
|
||||
{
|
||||
_WriteFields(writer, value);
|
||||
}
|
||||
|
||||
writer.WriteEndElement();
|
||||
}
|
||||
}
|
||||
@@ -160,28 +190,38 @@ namespace VocaluxeLib.Xml
|
||||
/// <param name="o">Object to process</param>
|
||||
private void _WriteFields(XmlWriter writer, object o)
|
||||
{
|
||||
IEnumerable<SFieldInfo> fields = o.GetType().GetFieldInfos();
|
||||
foreach (SFieldInfo field in fields)
|
||||
var fields = o.GetType().GetFieldInfos();
|
||||
foreach (var field in fields)
|
||||
{
|
||||
object value = field.GetValue(o);
|
||||
var value = field.GetValue(o);
|
||||
if (!_WriteDefaults && field.HasDefaultValue && Equals(value, field.DefaultValue))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (field.IsEmbeddedList)
|
||||
{
|
||||
IEnumerable values = (IEnumerable)value;
|
||||
bool empty = true;
|
||||
foreach (object subValue in values)
|
||||
var values = (IEnumerable)value;
|
||||
var empty = true;
|
||||
foreach (var subValue in values)
|
||||
{
|
||||
_WriteValue(writer, field.Name, field.SubType, subValue, field.IsAttribute);
|
||||
empty = false;
|
||||
}
|
||||
|
||||
if (empty && _WriteDefaults)
|
||||
{
|
||||
writer.WriteElementString(field.Name, "");
|
||||
}
|
||||
}
|
||||
else if (field.IsByteArray)
|
||||
{
|
||||
writer.WriteElementString(field.Name, Convert.ToBase64String((byte[])value));
|
||||
}
|
||||
else
|
||||
{
|
||||
_WriteValue(writer, field.Name, field.Type, value, field.IsAttribute, field.ArrayItemName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,18 +235,25 @@ namespace VocaluxeLib.Xml
|
||||
{
|
||||
if (string.IsNullOrEmpty(rootNodeName))
|
||||
{
|
||||
XmlRootAttribute root = o.GetType().GetAttribute<XmlRootAttribute>();
|
||||
var root = o.GetType().GetAttribute<XmlRootAttribute>();
|
||||
if (root != null && !string.IsNullOrEmpty(root.ElementName))
|
||||
{
|
||||
rootNodeName = root.ElementName;
|
||||
}
|
||||
else
|
||||
{
|
||||
XmlTypeAttribute typeAtt = o.GetType().GetAttribute<XmlTypeAttribute>();
|
||||
var typeAtt = o.GetType().GetAttribute<XmlTypeAttribute>();
|
||||
if (typeAtt != null && !string.IsNullOrEmpty(typeAtt.TypeName))
|
||||
{
|
||||
rootNodeName = typeAtt.TypeName;
|
||||
}
|
||||
else
|
||||
{
|
||||
rootNodeName = "root";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
writer.WriteStartDocument();
|
||||
@@ -227,8 +274,10 @@ namespace VocaluxeLib.Xml
|
||||
/// <param name="rootNodeName">Name of the root node (overwrites default value specified by XmlRoot/XmlTypeAttributes which defaults to "root")</param>
|
||||
public void Serialize(string filePath, object o, string rootNodeName = null)
|
||||
{
|
||||
using (XmlWriter writer = XmlWriter.Create(filePath, _XmlSettings))
|
||||
using (var writer = XmlWriter.Create(filePath, _XmlSettings))
|
||||
{
|
||||
_Serialize(writer, o, rootNodeName);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -239,9 +288,12 @@ namespace VocaluxeLib.Xml
|
||||
/// <returns>Serialized object</returns>
|
||||
public string Serialize(object o, string rootNodeName = null)
|
||||
{
|
||||
MemoryStream result = new MemoryStream();
|
||||
using (XmlWriter writer = XmlWriter.Create(result, _XmlSettings))
|
||||
var result = new MemoryStream();
|
||||
using (var writer = XmlWriter.Create(result, _XmlSettings))
|
||||
{
|
||||
_Serialize(writer, o, rootNodeName);
|
||||
}
|
||||
|
||||
result.Position = 0;
|
||||
return new StreamReader(result).ReadToEnd();
|
||||
}
|
||||
|
||||
@@ -80,14 +80,18 @@ namespace VocaluxeLib.Xml
|
||||
public void SetValue(object o, object value)
|
||||
{
|
||||
if (_Field != null)
|
||||
{
|
||||
_Field.SetValue(o, value);
|
||||
}
|
||||
else
|
||||
_Property.SetValue(o, value, new object[] {});
|
||||
{
|
||||
_Property.SetValue(o, value, new object[] { });
|
||||
}
|
||||
}
|
||||
|
||||
public object GetValue(object o)
|
||||
{
|
||||
return (_Field != null) ? _Field.GetValue(o) : _Property.GetValue(o, new object[] {});
|
||||
return _Field != null ? _Field.GetValue(o) : _Property.GetValue(o, new object[] { });
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user