Пример #1
0
        public static IEnumerable <T> AllGameItemsFromAsset <T>(LoadableXmlAsset asset) where T : new()
        {
            if (asset.xmlDoc == null)
            {
                yield break;
            }
            XmlNodeList assetNodes = asset.xmlDoc.DocumentElement.SelectNodes(typeof(T).Name);
            bool        gotData    = false;
            IEnumerator enumerator = assetNodes.GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    object       obj         = enumerator.Current;
                    XmlNode      node        = (XmlNode)obj;
                    XmlAttribute abstractAtt = node.Attributes["Abstract"];
                    if (abstractAtt == null || !(abstractAtt.Value.ToLower() == "true"))
                    {
                        T item;
                        try
                        {
                            item    = DirectXmlToObject.ObjectFromXml <T>(node, true);
                            gotData = true;
                        }
                        catch (Exception ex)
                        {
                            Log.Error(string.Concat(new object[]
                            {
                                "Exception loading data from file ",
                                asset.name,
                                ": ",
                                ex
                            }), false);
                            continue;
                        }
                        yield return(item);
                    }
                }
            }
            finally
            {
                IDisposable disposable;
                if ((disposable = (enumerator as IDisposable)) != null)
                {
                    disposable.Dispose();
                }
            }
            if (!gotData)
            {
                Log.Error(string.Concat(new object[]
                {
                    "Found no usable data when trying to get ",
                    typeof(T),
                    "s from file ",
                    asset.name
                }), false);
            }
            yield break;
        }
            public override bool TryResolve(FailMode failReportMode)
            {
                failReportMode = FailMode.LogErrors;
                bool flag  = typeof(Def).IsAssignableFrom(typeof(K));
                bool flag2 = typeof(Def).IsAssignableFrom(typeof(V));
                List <Pair <K, V> > list = new List <Pair <K, V> >();

                foreach (XmlNode wantedDictRef in this.wantedDictRefs)
                {
                    XmlNode xmlNode  = wantedDictRef["key"];
                    XmlNode xmlNode2 = wantedDictRef["value"];
                    K       first    = (!flag) ? DirectXmlToObject.ObjectFromXml <K>(xmlNode, true) : DirectXmlCrossRefLoader.TryResolveDef <K>(xmlNode.InnerText, failReportMode);
                    V       second   = (!flag2) ? DirectXmlToObject.ObjectFromXml <V>(xmlNode2, true) : DirectXmlCrossRefLoader.TryResolveDef <V>(xmlNode2.InnerText, failReportMode);
                    list.Add(new Pair <K, V>(first, second));
                }
                Dictionary <K, V> dictionary = (Dictionary <K, V>)base.wanter;

                dictionary.Clear();
                foreach (Pair <K, V> item in list)
                {
                    try
                    {
                        dictionary.Add(item.First, item.Second);
                    }
                    catch
                    {
                        Log.Error("Failed to load key/value pair: " + item.First + ", " + item.Second);
                    }
                }
                return(true);
            }
Пример #3
0
 public static IEnumerable <T> AllGameItemsFromAsset <T>(LoadableXmlAsset asset) where T : new()
 {
     if (asset.xmlDoc != null)
     {
         XmlNodeList xmlNodeList = asset.xmlDoc.DocumentElement.SelectNodes(typeof(T).Name);
         bool        gotData     = false;
         foreach (XmlNode item in xmlNodeList)
         {
             XmlAttribute xmlAttribute = item.Attributes["Abstract"];
             if (xmlAttribute == null || !(xmlAttribute.Value.ToLower() == "true"))
             {
                 T val;
                 try
                 {
                     val     = DirectXmlToObject.ObjectFromXml <T>(item, doPostLoad: true);
                     gotData = true;
                 }
                 catch (Exception ex)
                 {
                     Log.Error("Exception loading data from file " + asset.name + ": " + ex);
                     continue;
                 }
                 yield return(val);
             }
         }
         if (!gotData)
         {
             Log.Error("Found no usable data when trying to get " + typeof(T) + "s from file " + asset.name);
         }
     }
 }
Пример #4
0
        public static T ItemFromXmlFile <T>(string filePath, bool resolveCrossRefs = true) where T : new()
        {
            if (resolveCrossRefs && DirectXmlCrossRefLoader.LoadingInProgress)
            {
                Log.Error("Cannot call ItemFromXmlFile with resolveCrossRefs=true while loading is already in progress.");
            }
            FileInfo fileInfo = new FileInfo(filePath);

            if (!fileInfo.Exists)
            {
                return(Activator.CreateInstance <T>());
            }
            T result;

            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(File.ReadAllText(fileInfo.FullName));
                T t = DirectXmlToObject.ObjectFromXml <T>(xmlDocument.DocumentElement, false);
                if (resolveCrossRefs)
                {
                    DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.LogErrors);
                }
                result = t;
            }
            catch (Exception ex)
            {
                Log.Error("Exception loading file at " + filePath + ". Loading defaults instead. Exception was: " + ex.ToString());
                result = Activator.CreateInstance <T>();
            }
            return(result);
        }
        private static FieldInfo GetFieldInfoForType(Type type, string token, XmlNode debugXmlNode)
        {
            Dictionary <string, FieldInfo> dictionary = DirectXmlToObject.fieldInfoLookup.TryGetValue(type, null);

            if (dictionary == null)
            {
                dictionary = new Dictionary <string, FieldInfo>();
                DirectXmlToObject.fieldInfoLookup[type] = dictionary;
            }
            FieldInfo fieldInfo = dictionary.TryGetValue(token, null);

            if (fieldInfo == null && !dictionary.ContainsKey(token))
            {
                fieldInfo = DirectXmlToObject.SearchTypeHierarchy(type, token, BindingFlags.Default);
                if (fieldInfo == null)
                {
                    fieldInfo = DirectXmlToObject.SearchTypeHierarchy(type, token, BindingFlags.IgnoreCase);
                    if (fieldInfo != null && !type.HasAttribute <CaseInsensitiveXMLParsing>())
                    {
                        string text = string.Format("Attempt to use string {0} to refer to field {1} in type {2}; xml tags are now case-sensitive", token, fieldInfo.Name, type);
                        if (debugXmlNode != null)
                        {
                            text = text + ". XML: " + debugXmlNode.OuterXml;
                        }
                        Log.Error(text, false);
                    }
                }
                dictionary[token] = fieldInfo;
            }
            return(fieldInfo);
        }
Пример #6
0
 public static T ItemFromXmlString <T>(string xmlContent, string filePath, bool resolveCrossRefs = true) where T : new()
 {
     if (resolveCrossRefs && DirectXmlCrossRefLoader.LoadingInProgress)
     {
         Log.Error("Cannot call ItemFromXmlString with resolveCrossRefs=true while loading is already in progress (forgot to resolve or clear cross refs from previous loading?).");
     }
     try
     {
         XmlDocument xmlDocument = new XmlDocument();
         xmlDocument.LoadXml(xmlContent);
         T result = DirectXmlToObject.ObjectFromXml <T>(xmlDocument.DocumentElement, doPostLoad: false);
         if (resolveCrossRefs)
         {
             try
             {
                 DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.LogErrors);
             }
             finally
             {
                 DirectXmlCrossRefLoader.Clear();
             }
         }
         return(result);
     }
     catch (Exception ex)
     {
         Log.Error("Exception loading file at " + filePath + ". Loading defaults instead. Exception was: " + ex.ToString());
         return(new T());
     }
 }
Пример #7
0
        private void LoadPatches()
        {
            DeepProfiler.Start("Loading all patches");
            patches          = new List <PatchOperation>();
            loadedAnyPatches = false;
            List <LoadableXmlAsset> list = DirectXmlLoader.XmlAssetsInModFolder(this, "Patches/").ToList();

            for (int i = 0; i < list.Count; i++)
            {
                XmlElement documentElement = list[i].xmlDoc.DocumentElement;
                if (documentElement.Name != "Patch")
                {
                    Log.Error($"Unexpected document element in patch XML; got {documentElement.Name}, expected 'Patch'");
                    continue;
                }
                foreach (XmlNode childNode in documentElement.ChildNodes)
                {
                    if (childNode.NodeType == XmlNodeType.Element)
                    {
                        if (childNode.Name != "Operation")
                        {
                            Log.Error($"Unexpected element in patch XML; got {childNode.Name}, expected 'Operation'");
                            continue;
                        }
                        PatchOperation patchOperation = DirectXmlToObject.ObjectFromXml <PatchOperation>(childNode, doPostLoad: false);
                        patchOperation.sourceFile = list[i].FullFilePath;
                        patches.Add(patchOperation);
                        loadedAnyPatches = true;
                    }
                }
            }
            DeepProfiler.End();
        }
Пример #8
0
        private static List <T> ListFromXml <T>(XmlNode listRootNode) where T : new()
        {
            List <T> list = new List <T>();

            try
            {
                bool flag = typeof(Def).IsAssignableFrom(typeof(T));
                foreach (XmlNode xmlNode in listRootNode.ChildNodes)
                {
                    if (DirectXmlToObject.ValidateListNode(xmlNode, listRootNode, typeof(T)))
                    {
                        if (flag)
                        {
                            DirectXmlCrossRefLoader.RegisterListWantsCrossRef <T>(list, xmlNode.InnerText);
                        }
                        else
                        {
                            list.Add(DirectXmlToObject.ObjectFromXml <T>(xmlNode, true));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(string.Concat(new object[]
                {
                    "Exception loading list from XML: ",
                    ex,
                    "\nXML:\n",
                    listRootNode.OuterXml
                }));
            }
            return(list);
        }
            public override void Apply()
            {
                Dictionary <K, V> dictionary = (Dictionary <K, V>)wanter;

                dictionary.Clear();
                foreach (Pair <object, object> makingDatum in makingData)
                {
                    try
                    {
                        object obj  = makingDatum.First;
                        object obj2 = makingDatum.Second;
                        if (obj is XmlNode)
                        {
                            obj = DirectXmlToObject.ObjectFromXml <K>(obj as XmlNode, doPostLoad: true);
                        }
                        if (obj2 is XmlNode)
                        {
                            obj2 = DirectXmlToObject.ObjectFromXml <V>(obj2 as XmlNode, doPostLoad: true);
                        }
                        dictionary.Add((K)obj, (V)obj2);
                    }
                    catch
                    {
                        Log.Error(string.Concat("Failed to load key/value pair: ", makingDatum.First, ", ", makingDatum.Second));
                    }
                }
            }
Пример #10
0
        public static IEnumerable <T> AllGameItemsFromAsset <T>(LoadableXmlAsset asset) where T : new()
        {
            if (DirectXmlLoader.loadingAsset != null)
            {
                Log.Error("Tried to load " + asset + " while loading " + DirectXmlLoader.loadingAsset + ". This will corrupt the internal state of DataLoader.");
            }
            if (asset.xmlDoc != null)
            {
                DirectXmlLoader.loadingAsset = asset;
                XmlNodeList assetNodes = asset.xmlDoc.DocumentElement.SelectNodes(typeof(T).Name);
                bool        gotData    = false;
                IEnumerator enumerator = assetNodes.GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        XmlNode      node        = (XmlNode)enumerator.Current;
                        XmlAttribute abstractAtt = node.Attributes["Abstract"];
                        if (abstractAtt != null && abstractAtt.Value.ToLower() == "true")
                        {
                            continue;
                        }
                        T item;
                        try
                        {
                            item    = DirectXmlToObject.ObjectFromXml <T>(node, true);
                            gotData = true;
                        }
                        catch (Exception ex)
                        {
                            Log.Error("Exception loading data from file " + asset.name + ": " + ex);
                            continue;
                        }
                        yield return(item);

                        /*Error: Unable to find new state assignment for yield return*/;
                    }
                }
                finally
                {
                    IDisposable disposable;
                    IDisposable disposable2 = disposable = (enumerator as IDisposable);
                    if (disposable != null)
                    {
                        disposable2.Dispose();
                    }
                }
                if (!gotData)
                {
                    Log.Error("Found no usable data when trying to get " + typeof(T) + "s from file " + asset.name);
                }
                DirectXmlLoader.loadingAsset = null;
            }
            yield break;
IL_0247:
            /*Error near IL_0248: Unexpected return in MoveNext()*/;
        }
Пример #11
0
 public static IEnumerable <T> AllGameItemsFromAsset <T>(LoadableXmlAsset asset) where T : new()
 {
     if (DirectXmlLoader.loadingAsset != null)
     {
         Log.Error(string.Concat(new object[]
         {
             "Tried to load ",
             asset,
             " while loading ",
             DirectXmlLoader.loadingAsset,
             ". This will corrupt the internal state of DataLoader."
         }));
     }
     if (asset.xmlDoc != null)
     {
         DirectXmlLoader.loadingAsset = asset;
         XmlNodeList assetNodes = asset.xmlDoc.DocumentElement.SelectNodes(typeof(T).Name);
         bool        gotData    = false;
         foreach (XmlNode node in assetNodes)
         {
             XmlAttribute abstractAtt = node.Attributes["Abstract"];
             if (abstractAtt == null || !(abstractAtt.Value.ToLower() == "true"))
             {
                 T item;
                 try
                 {
                     item    = DirectXmlToObject.ObjectFromXml <T>(node, true);
                     gotData = true;
                 }
                 catch (Exception ex)
                 {
                     Log.Error(string.Concat(new object[]
                     {
                         "Exception loading data from file ",
                         asset.name,
                         ": ",
                         ex
                     }));
                     continue;
                 }
                 yield return(item);
             }
         }
         if (!gotData)
         {
             Log.Error(string.Concat(new object[]
             {
                 "Found no usable data when trying to get ",
                 typeof(T),
                 "s from file ",
                 asset.name
             }));
         }
         DirectXmlLoader.loadingAsset = null;
     }
 }
            public override bool TryResolve(FailMode failReportMode)
            {
                failReportMode = FailMode.LogErrors;
                bool flag  = typeof(Def).IsAssignableFrom(typeof(K));
                bool flag2 = typeof(Def).IsAssignableFrom(typeof(V));
                List <Pair <K, V> > list = new List <Pair <K, V> >();

                foreach (XmlNode xmlNode in this.wantedDictRefs)
                {
                    XmlNode xmlNode2 = xmlNode["key"];
                    XmlNode xmlNode3 = xmlNode["value"];
                    K       first;
                    if (flag)
                    {
                        first = DirectXmlCrossRefLoader.TryResolveDef <K>(xmlNode2.InnerText, failReportMode, this.debugWanterInfo);
                    }
                    else
                    {
                        first = DirectXmlToObject.ObjectFromXml <K>(xmlNode2, true);
                    }
                    V second;
                    if (flag2)
                    {
                        second = DirectXmlCrossRefLoader.TryResolveDef <V>(xmlNode3.InnerText, failReportMode, this.debugWanterInfo);
                    }
                    else
                    {
                        second = DirectXmlToObject.ObjectFromXml <V>(xmlNode3, true);
                    }
                    list.Add(new Pair <K, V>(first, second));
                }
                Dictionary <K, V> dictionary = (Dictionary <K, V>) this.wanter;

                dictionary.Clear();
                foreach (Pair <K, V> pair in list)
                {
                    try
                    {
                        dictionary.Add(pair.First, pair.Second);
                    }
                    catch
                    {
                        Log.Error(string.Concat(new object[]
                        {
                            "Failed to load key/value pair: ",
                            pair.First,
                            ", ",
                            pair.Second
                        }), false);
                    }
                }
                return(true);
            }
        private static List <T> ListFromXml <T>(XmlNode listRootNode) where T : new()
        {
            List <T> list = new List <T>();

            try
            {
                bool        flag       = typeof(Def).IsAssignableFrom(typeof(T));
                IEnumerator enumerator = listRootNode.ChildNodes.GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        object  obj     = enumerator.Current;
                        XmlNode xmlNode = (XmlNode)obj;
                        if (DirectXmlToObject.ValidateListNode(xmlNode, listRootNode, typeof(T)))
                        {
                            if (flag)
                            {
                                DirectXmlCrossRefLoader.RegisterListWantsCrossRef <T>(list, xmlNode.InnerText, listRootNode.Name);
                            }
                            else
                            {
                                list.Add(DirectXmlToObject.ObjectFromXml <T>(xmlNode, true));
                            }
                        }
                    }
                }
                finally
                {
                    IDisposable disposable;
                    if ((disposable = (enumerator as IDisposable)) != null)
                    {
                        disposable.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(string.Concat(new object[]
                {
                    "Exception loading list from XML: ",
                    ex,
                    "\nXML:\n",
                    listRootNode.OuterXml
                }), false);
            }
            return(list);
        }
Пример #14
0
 private static bool ValidateListNode(XmlNode listEntryNode, XmlNode listRootNode, Type listItemType)
 {
     if (listEntryNode is XmlComment)
     {
         return(false);
     }
     if (listEntryNode is XmlText)
     {
         Log.Error("XML format error: Raw text found inside a list element. Did you mean to surround it with list item <li> tags? " + listRootNode.OuterXml);
         return(false);
     }
     if (listEntryNode.Name != "li" && DirectXmlToObject.CustomDataLoadMethodOf(listItemType) == null)
     {
         Log.Error("XML format error: List item found with name that is not <li>, and which does not have a custom XML loader method, in " + listRootNode.OuterXml);
         return(false);
     }
     return(true);
 }
Пример #15
0
        private static Dictionary <K, V> DictionaryFromXml <K, V>(XmlNode dictRootNode) where K : new() where V : new()
        {
            Dictionary <K, V> dictionary = new Dictionary <K, V>();

            try
            {
                bool flag  = typeof(Def).IsAssignableFrom(typeof(K));
                bool flag2 = typeof(Def).IsAssignableFrom(typeof(V));
                if (!flag && !flag2)
                {
                    foreach (XmlNode xmlNode in dictRootNode.ChildNodes)
                    {
                        if (DirectXmlToObject.ValidateListNode(xmlNode, dictRootNode, typeof(KeyValuePair <K, V>)))
                        {
                            K key   = DirectXmlToObject.ObjectFromXml <K>(xmlNode["key"], true);
                            V value = DirectXmlToObject.ObjectFromXml <V>(xmlNode["value"], true);
                            dictionary.Add(key, value);
                        }
                    }
                }
                else
                {
                    foreach (XmlNode xmlNode2 in dictRootNode.ChildNodes)
                    {
                        if (DirectXmlToObject.ValidateListNode(xmlNode2, dictRootNode, typeof(KeyValuePair <K, V>)))
                        {
                            DirectXmlCrossRefLoader.RegisterDictionaryWantsCrossRef <K, V>(dictionary, xmlNode2);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(string.Concat(new object[]
                {
                    "Malformed dictionary XML. Node: ",
                    dictRootNode.OuterXml,
                    ".\n\nException: ",
                    ex
                }));
            }
            return(dictionary);
        }
Пример #16
0
        public static Def DefFromNode(XmlNode node, LoadableXmlAsset loadingAsset)
        {
            if (node.NodeType != XmlNodeType.Element)
            {
                return(null);
            }
            XmlAttribute xmlAttribute = node.Attributes["Abstract"];

            if (xmlAttribute != null && xmlAttribute.Value.ToLower() == "true")
            {
                return(null);
            }
            Type typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(node.Name);

            if (typeInAnyAssembly == null)
            {
                return(null);
            }
            if (!typeof(Def).IsAssignableFrom(typeInAnyAssembly))
            {
                return(null);
            }
            Func <XmlNode, bool, object> objectFromXmlMethod = DirectXmlToObject.GetObjectFromXmlMethod(typeInAnyAssembly);
            Def result = null;

            try
            {
                result = (Def)objectFromXmlMethod(node, arg2: true);
                return(result);
            }
            catch (Exception ex)
            {
                Log.Error("Exception loading def from file " + ((loadingAsset != null) ? loadingAsset.name : "(unknown)") + ": " + ex);
                return(result);
            }
        }
Пример #17
0
        private void LoadPatches()
        {
            DeepProfiler.Start("Loading all patches");
            this.patches = new List <PatchOperation>();
            List <LoadableXmlAsset> list = DirectXmlLoader.XmlAssetsInModFolder(this, "Patches/").ToList <LoadableXmlAsset>();

            for (int i = 0; i < list.Count; i++)
            {
                XmlElement documentElement = list[i].xmlDoc.DocumentElement;
                if (documentElement.Name != "Patch")
                {
                    Log.Error(string.Format("Unexpected document element in patch XML; got {0}, expected 'Patch'", documentElement.Name));
                }
                else
                {
                    for (int j = 0; j < documentElement.ChildNodes.Count; j++)
                    {
                        XmlNode xmlNode = documentElement.ChildNodes[j];
                        if (xmlNode.NodeType == XmlNodeType.Element)
                        {
                            if (xmlNode.Name != "Operation")
                            {
                                Log.Error(string.Format("Unexpected element in patch XML; got {0}, expected 'Operation'", documentElement.ChildNodes[j].Name));
                            }
                            else
                            {
                                PatchOperation patchOperation = DirectXmlToObject.ObjectFromXml <PatchOperation>(xmlNode, false);
                                patchOperation.sourceFile = list[i].FullFilePath;
                                this.patches.Add(patchOperation);
                            }
                        }
                    }
                }
            }
            DeepProfiler.End();
        }
        private static Dictionary <K, V> DictionaryFromXml <K, V>(XmlNode dictRootNode) where K : new() where V : new()
        {
            Dictionary <K, V> dictionary = new Dictionary <K, V>();

            try
            {
                bool flag  = typeof(Def).IsAssignableFrom(typeof(K));
                bool flag2 = typeof(Def).IsAssignableFrom(typeof(V));
                if (!flag && !flag2)
                {
                    IEnumerator enumerator = dictRootNode.ChildNodes.GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            object  obj     = enumerator.Current;
                            XmlNode xmlNode = (XmlNode)obj;
                            if (DirectXmlToObject.ValidateListNode(xmlNode, dictRootNode, typeof(KeyValuePair <K, V>)))
                            {
                                K key   = DirectXmlToObject.ObjectFromXml <K>(xmlNode["key"], true);
                                V value = DirectXmlToObject.ObjectFromXml <V>(xmlNode["value"], true);
                                dictionary.Add(key, value);
                            }
                        }
                    }
                    finally
                    {
                        IDisposable disposable;
                        if ((disposable = (enumerator as IDisposable)) != null)
                        {
                            disposable.Dispose();
                        }
                    }
                }
                else
                {
                    IEnumerator enumerator2 = dictRootNode.ChildNodes.GetEnumerator();
                    try
                    {
                        while (enumerator2.MoveNext())
                        {
                            object  obj2     = enumerator2.Current;
                            XmlNode xmlNode2 = (XmlNode)obj2;
                            if (DirectXmlToObject.ValidateListNode(xmlNode2, dictRootNode, typeof(KeyValuePair <K, V>)))
                            {
                                DirectXmlCrossRefLoader.RegisterDictionaryWantsCrossRef <K, V>(dictionary, xmlNode2, dictRootNode.Name);
                            }
                        }
                    }
                    finally
                    {
                        IDisposable disposable2;
                        if ((disposable2 = (enumerator2 as IDisposable)) != null)
                        {
                            disposable2.Dispose();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(string.Concat(new object[]
                {
                    "Malformed dictionary XML. Node: ",
                    dictRootNode.OuterXml,
                    ".\n\nException: ",
                    ex
                }), false);
            }
            return(dictionary);
        }
Пример #19
0
        public static object Convert(object obj, Type to, object defaultValue)
        {
            if (obj == null)
            {
                return(defaultValue);
            }
            if (to.IsAssignableFrom(obj.GetType()))
            {
                return(obj);
            }
            if (to == typeof(string))
            {
                return(obj.ToString());
            }
            string text = obj as string;

            if (text != null && !to.IsPrimitive && ParseHelper.CanParse(to, (string)obj))
            {
                if (text == "")
                {
                    return(defaultValue);
                }
                return(ParseHelper.FromString(text, to));
            }
            if (text != null && typeof(Def).IsAssignableFrom(to))
            {
                if (text == "")
                {
                    return(defaultValue);
                }
                return(GenDefDatabase.GetDef(to, text));
            }
            if (text != null && to == typeof(Faction))
            {
                if (text == "")
                {
                    return(defaultValue);
                }
                List <Faction> allFactionsListForReading = Find.FactionManager.AllFactionsListForReading;
                for (int i = 0; i < allFactionsListForReading.Count; i++)
                {
                    if (allFactionsListForReading[i].GetUniqueLoadID() == text)
                    {
                        return(allFactionsListForReading[i]);
                    }
                }
                for (int j = 0; j < allFactionsListForReading.Count; j++)
                {
                    if (allFactionsListForReading[j].HasName && allFactionsListForReading[j].Name == text)
                    {
                        return(allFactionsListForReading[j]);
                    }
                }
                for (int k = 0; k < allFactionsListForReading.Count; k++)
                {
                    if (allFactionsListForReading[k].def.defName == text)
                    {
                        return(allFactionsListForReading[k]);
                    }
                }
                return(defaultValue);
            }
            if (CanConvertBetweenDataTypes(obj.GetType(), to))
            {
                return(ConvertBetweenDataTypes(obj, to));
            }
            if (IsXml(obj) && !to.IsPrimitive)
            {
                try
                {
                    Type type = to;
                    if (type == typeof(IEnumerable))
                    {
                        type = typeof(List <string>);
                    }
                    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable <>) && type.GetGenericArguments().Length >= 1)
                    {
                        type = typeof(List <>).MakeGenericType(type.GetGenericArguments()[0]);
                    }
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n" + text + "\n</root>");
                    object result = DirectXmlToObject.GetObjectFromXmlMethod(type)(xmlDocument.DocumentElement, arg2 : true);
                    DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.LogErrors);
                    return(result);
                }
                finally
                {
                    DirectXmlCrossRefLoader.Clear();
                }
            }
            if (to.IsGenericType && (to.GetGenericTypeDefinition() == typeof(IEnumerable <>) || to.GetGenericTypeDefinition() == typeof(List <>)) && to.GetGenericArguments().Length >= 1 && (!(to.GetGenericArguments()[0] == typeof(string)) || !(obj is string)))
            {
                IEnumerable enumerable = obj as IEnumerable;
                if (enumerable != null)
                {
                    Type type2 = to.GetGenericArguments()[0];
                    bool flag  = true;
                    foreach (object item in enumerable)
                    {
                        if (!CanConvert(item, type2))
                        {
                            flag = false;
                            break;
                        }
                    }
                    if (flag)
                    {
                        IList list = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(type2));
                        {
                            foreach (object item2 in enumerable)
                            {
                                list.Add(Convert(item2, type2));
                            }
                            return(list);
                        }
                    }
                }
            }
            if (obj is IEnumerable && !(obj is string))
            {
                IEnumerable e = (IEnumerable)obj;
                if (GenCollection.Count_EnumerableBase(e) == 1)
                {
                    object obj2 = GenCollection.FirstOrDefault_EnumerableBase(e);
                    if (CanConvert(obj2, to))
                    {
                        return(Convert(obj2, to));
                    }
                }
            }
            if (typeof(IList).IsAssignableFrom(to))
            {
                IList  list2            = (IList)Activator.CreateInstance(to);
                Type[] genericArguments = to.GetGenericArguments();
                if (genericArguments.Length >= 1)
                {
                    list2.Add(Convert(obj, genericArguments[0]));
                }
                else
                {
                    list2.Add(obj);
                }
                return(list2);
            }
            if (to == typeof(IEnumerable))
            {
                return(Gen.YieldSingleNonGeneric(obj));
            }
            if (to.IsGenericType && to.GetGenericTypeDefinition() == typeof(IEnumerable <>))
            {
                Type[] genericArguments2 = to.GetGenericArguments();
                if (genericArguments2.Length >= 1)
                {
                    IList obj3 = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(genericArguments2[0]));
                    obj3.Add(Convert(obj, genericArguments2[0]));
                    return(obj3);
                }
                return(Gen.YieldSingleNonGeneric(obj));
            }
            IConvertible convertible = obj as IConvertible;

            if (convertible == null)
            {
                return(defaultValue);
            }
            try
            {
                return(ConvertToPrimitive(convertible, to, defaultValue));
            }
            catch (FormatException)
            {
                return(defaultValue);
            }
        }
        public static T ObjectFromXml <T>(XmlNode xmlRoot, bool doPostLoad) where T : new()
        {
            MethodInfo methodInfo = DirectXmlToObject.CustomDataLoadMethodOf(typeof(T));
            T          result;

            if (methodInfo != null)
            {
                xmlRoot = XmlInheritance.GetResolvedNodeFor(xmlRoot);
                Type type = DirectXmlToObject.ClassTypeOf <T>(xmlRoot);
                DirectXmlToObject.currentlyInstantiatingObjectOfType.Push(type);
                T t;
                try
                {
                    t = (T)((object)Activator.CreateInstance(type));
                }
                finally
                {
                    DirectXmlToObject.currentlyInstantiatingObjectOfType.Pop();
                }
                try
                {
                    methodInfo.Invoke(t, new object[]
                    {
                        xmlRoot
                    });
                }
                catch (Exception ex)
                {
                    Log.Error(string.Concat(new object[]
                    {
                        "Exception in custom XML loader for ",
                        typeof(T),
                        ". Node is:\n ",
                        xmlRoot.OuterXml,
                        "\n\nException is:\n ",
                        ex.ToString()
                    }), false);
                    t = default(T);
                }
                if (doPostLoad)
                {
                    DirectXmlToObject.TryDoPostLoad(t);
                }
                result = t;
            }
            else if (xmlRoot.ChildNodes.Count == 1 && xmlRoot.FirstChild.NodeType == XmlNodeType.CDATA)
            {
                if (typeof(T) != typeof(string))
                {
                    Log.Error("CDATA can only be used for strings. Bad xml: " + xmlRoot.OuterXml, false);
                    result = default(T);
                }
                else
                {
                    result = (T)((object)xmlRoot.FirstChild.Value);
                }
            }
            else if (xmlRoot.ChildNodes.Count == 1 && xmlRoot.FirstChild.NodeType == XmlNodeType.Text)
            {
                try
                {
                    return((T)((object)ParseHelper.FromString(xmlRoot.InnerText, typeof(T))));
                }
                catch (Exception ex2)
                {
                    Log.Error(string.Concat(new object[]
                    {
                        "Exception parsing ",
                        xmlRoot.OuterXml,
                        " to type ",
                        typeof(T),
                        ": ",
                        ex2
                    }), false);
                }
                result = default(T);
            }
            else if (Attribute.IsDefined(typeof(T), typeof(FlagsAttribute)))
            {
                List <T> list = DirectXmlToObject.ListFromXml <T>(xmlRoot);
                int      num  = 0;
                foreach (T t2 in list)
                {
                    int num2 = (int)((object)t2);
                    num |= num2;
                }
                result = (T)((object)num);
            }
            else if (typeof(T).HasGenericDefinition(typeof(List <>)))
            {
                MethodInfo method           = typeof(DirectXmlToObject).GetMethod("ListFromXml", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                Type[]     genericArguments = typeof(T).GetGenericArguments();
                MethodInfo methodInfo2      = method.MakeGenericMethod(genericArguments);
                object[]   parameters       = new object[]
                {
                    xmlRoot
                };
                object obj = methodInfo2.Invoke(null, parameters);
                result = (T)((object)obj);
            }
            else if (typeof(T).HasGenericDefinition(typeof(Dictionary <, >)))
            {
                MethodInfo method2           = typeof(DirectXmlToObject).GetMethod("DictionaryFromXml", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                Type[]     genericArguments2 = typeof(T).GetGenericArguments();
                MethodInfo methodInfo3       = method2.MakeGenericMethod(genericArguments2);
                object[]   parameters2       = new object[]
                {
                    xmlRoot
                };
                object obj2 = methodInfo3.Invoke(null, parameters2);
                result = (T)((object)obj2);
            }
            else
            {
                if (!xmlRoot.HasChildNodes)
                {
                    if (typeof(T) == typeof(string))
                    {
                        return((T)((object)""));
                    }
                    XmlAttribute xmlAttribute = xmlRoot.Attributes["IsNull"];
                    if (xmlAttribute != null && xmlAttribute.Value.ToUpperInvariant() == "TRUE")
                    {
                        return(default(T));
                    }
                    if (typeof(T).IsGenericType)
                    {
                        Type genericTypeDefinition = typeof(T).GetGenericTypeDefinition();
                        if (genericTypeDefinition == typeof(List <>) || genericTypeDefinition == typeof(HashSet <>) || genericTypeDefinition == typeof(Dictionary <, >))
                        {
                            return(Activator.CreateInstance <T>());
                        }
                    }
                }
                xmlRoot = XmlInheritance.GetResolvedNodeFor(xmlRoot);
                Type type2 = DirectXmlToObject.ClassTypeOf <T>(xmlRoot);
                Type type3 = Nullable.GetUnderlyingType(type2) ?? type2;
                DirectXmlToObject.currentlyInstantiatingObjectOfType.Push(type3);
                T t3;
                try
                {
                    t3 = (T)((object)Activator.CreateInstance(type3));
                }
                finally
                {
                    DirectXmlToObject.currentlyInstantiatingObjectOfType.Pop();
                }
                List <string> list2 = null;
                if (xmlRoot.ChildNodes.Count > 1)
                {
                    list2 = new List <string>();
                }
                for (int i = 0; i < xmlRoot.ChildNodes.Count; i++)
                {
                    XmlNode xmlNode = xmlRoot.ChildNodes[i];
                    if (!(xmlNode is XmlComment))
                    {
                        if (xmlRoot.ChildNodes.Count > 1)
                        {
                            if (list2.Contains(xmlNode.Name))
                            {
                                Log.Error(string.Concat(new object[]
                                {
                                    "XML ",
                                    typeof(T),
                                    " defines the same field twice: ",
                                    xmlNode.Name,
                                    ".\n\nField contents: ",
                                    xmlNode.InnerText,
                                    ".\n\nWhole XML:\n\n",
                                    xmlRoot.OuterXml
                                }), false);
                            }
                            else
                            {
                                list2.Add(xmlNode.Name);
                            }
                        }
                        FieldInfo fieldInfo = DirectXmlToObject.GetFieldInfoForType(t3.GetType(), xmlNode.Name, xmlRoot);
                        if (fieldInfo == null)
                        {
                            foreach (FieldInfo fieldInfo2 in t3.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
                            {
                                foreach (object obj3 in fieldInfo2.GetCustomAttributes(typeof(LoadAliasAttribute), true))
                                {
                                    string alias = ((LoadAliasAttribute)obj3).alias;
                                    if (alias.EqualsIgnoreCase(xmlNode.Name))
                                    {
                                        fieldInfo = fieldInfo2;
                                        break;
                                    }
                                }
                                if (fieldInfo != null)
                                {
                                    break;
                                }
                            }
                        }
                        if (fieldInfo == null)
                        {
                            bool flag = false;
                            foreach (object obj4 in t3.GetType().GetCustomAttributes(typeof(IgnoreSavedElementAttribute), true))
                            {
                                string elementToIgnore = ((IgnoreSavedElementAttribute)obj4).elementToIgnore;
                                if (string.Equals(elementToIgnore, xmlNode.Name, StringComparison.OrdinalIgnoreCase))
                                {
                                    flag = true;
                                    break;
                                }
                            }
                            if (!flag)
                            {
                                Log.Error(string.Concat(new string[]
                                {
                                    "XML error: ",
                                    xmlNode.OuterXml,
                                    " doesn't correspond to any field in type ",
                                    t3.GetType().Name,
                                    ". Context: ",
                                    xmlRoot.OuterXml
                                }), false);
                            }
                        }
                        else if (typeof(Def).IsAssignableFrom(fieldInfo.FieldType))
                        {
                            if (xmlNode.InnerText.NullOrEmpty())
                            {
                                fieldInfo.SetValue(t3, null);
                            }
                            else
                            {
                                DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(t3, fieldInfo, xmlNode.InnerText);
                            }
                        }
                        else
                        {
                            object value = null;
                            try
                            {
                                MethodInfo method3     = typeof(DirectXmlToObject).GetMethod("ObjectFromXml", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                                MethodInfo methodInfo4 = method3.MakeGenericMethod(new Type[]
                                {
                                    fieldInfo.FieldType
                                });
                                value = methodInfo4.Invoke(null, new object[]
                                {
                                    xmlNode,
                                    doPostLoad
                                });
                            }
                            catch (Exception ex3)
                            {
                                Log.Error("Exception loading from " + xmlNode.ToString() + ": " + ex3.ToString(), false);
                                goto IL_863;
                            }
                            if (!typeof(T).IsValueType)
                            {
                                fieldInfo.SetValue(t3, value);
                            }
                            else
                            {
                                object obj5 = t3;
                                fieldInfo.SetValue(obj5, value);
                                t3 = (T)((object)obj5);
                            }
                        }
                    }
                    IL_863 :;
                }
                if (doPostLoad)
                {
                    DirectXmlToObject.TryDoPostLoad(t3);
                }
                result = t3;
            }
            return(result);
        }
Пример #21
0
 public void LoadDataFromXmlCustom(XmlNode xmlRoot)
 {
     foreach (XmlNode childNode in xmlRoot.ChildNodes)
     {
         if (!(childNode is XmlComment))
         {
             string text = childNode.Name.ToLower();
             if (text.StartsWith("v"))
             {
                 text = text.Substring(1);
             }
             if (!itemForVersion.ContainsKey(text))
             {
                 itemForVersion[text] = ((typeof(T) == typeof(string)) ? ((T)(object)childNode.FirstChild.Value) : DirectXmlToObject.ObjectFromXml <T>(childNode, doPostLoad: false));
             }
             else
             {
                 Log.Warning("More than one value for a same version of " + typeof(T).Name + " named " + xmlRoot.Name);
             }
         }
     }
 }
        public static T ObjectFromXml <T>(XmlNode xmlRoot, bool doPostLoad) where T : new()
        {
            MethodInfo methodInfo = DirectXmlToObject.CustomDataLoadMethodOf(typeof(T));

            if (methodInfo != null)
            {
                xmlRoot = XmlInheritance.GetResolvedNodeFor(xmlRoot);
                Type type = DirectXmlToObject.ClassTypeOf <T>(xmlRoot);
                T    val  = (T)Activator.CreateInstance(type);
                try
                {
                    methodInfo.Invoke(val, new object[1]
                    {
                        xmlRoot
                    });
                }
                catch (Exception ex)
                {
                    Log.Error("Exception in custom XML loader for " + typeof(T) + ". Node is:\n " + xmlRoot.OuterXml + "\n\nException is:\n " + ex.ToString());
                    val = default(T);
                }
                if (doPostLoad)
                {
                    DirectXmlToObject.TryDoPostLoad(val);
                }
                return(val);
            }
            if (xmlRoot.ChildNodes.Count == 1 && xmlRoot.FirstChild.NodeType == XmlNodeType.CDATA)
            {
                if (typeof(T) != typeof(string))
                {
                    Log.Error("CDATA can only be used for strings. Bad xml: " + xmlRoot.OuterXml);
                    return(default(T));
                }
                return((T)(object)xmlRoot.FirstChild.Value);
            }
            if (xmlRoot.ChildNodes.Count == 1 && xmlRoot.FirstChild.NodeType == XmlNodeType.Text)
            {
                try
                {
                    return((T)ParseHelper.FromString(xmlRoot.InnerText, typeof(T)));
                }
                catch (Exception ex2)
                {
                    Log.Error("Exception parsing " + xmlRoot.OuterXml + " to type " + typeof(T) + ": " + ex2);
                }
                return(default(T));
            }
            if (Attribute.IsDefined(typeof(T), typeof(FlagsAttribute)))
            {
                List <T> list = DirectXmlToObject.ListFromXml <T>(xmlRoot);
                int      num  = 0;
                foreach (T item in list)
                {
                    int num2 = (int)(object)item;
                    num |= num2;
                }
                return((T)(object)num);
            }
            if (typeof(T).HasGenericDefinition(typeof(List <>)))
            {
                MethodInfo method           = typeof(DirectXmlToObject).GetMethod("ListFromXml", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                Type[]     genericArguments = typeof(T).GetGenericArguments();
                MethodInfo methodInfo2      = method.MakeGenericMethod(genericArguments);
                object[]   parameters       = new object[1]
                {
                    xmlRoot
                };
                object obj = methodInfo2.Invoke(null, parameters);
                return((T)obj);
            }
            if (typeof(T).HasGenericDefinition(typeof(Dictionary <, >)))
            {
                MethodInfo method2           = typeof(DirectXmlToObject).GetMethod("DictionaryFromXml", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                Type[]     genericArguments2 = typeof(T).GetGenericArguments();
                MethodInfo methodInfo3       = method2.MakeGenericMethod(genericArguments2);
                object[]   parameters2       = new object[1]
                {
                    xmlRoot
                };
                object obj2 = methodInfo3.Invoke(null, parameters2);
                return((T)obj2);
            }
            if (!xmlRoot.HasChildNodes)
            {
                if (typeof(T) == typeof(string))
                {
                    return((T)(object)string.Empty);
                }
                XmlAttribute xmlAttribute = xmlRoot.Attributes["IsNull"];
                if (xmlAttribute != null && xmlAttribute.Value.ToUpperInvariant() == "TRUE")
                {
                    return(default(T));
                }
                if (typeof(T).IsGenericType)
                {
                    Type genericTypeDefinition = typeof(T).GetGenericTypeDefinition();
                    if (genericTypeDefinition != typeof(List <>) && genericTypeDefinition != typeof(HashSet <>) && genericTypeDefinition != typeof(Dictionary <, >))
                    {
                        goto IL_03ed;
                    }
                    return(new T());
                }
            }
            goto IL_03ed;
IL_03ed:
            xmlRoot = XmlInheritance.GetResolvedNodeFor(xmlRoot);
            Type          type2 = DirectXmlToObject.ClassTypeOf <T>(xmlRoot);
            T             val2  = (T)Activator.CreateInstance(type2);
            List <string> list2 = null;

            if (xmlRoot.ChildNodes.Count > 1)
            {
                list2 = new List <string>();
            }
            for (int i = 0; i < xmlRoot.ChildNodes.Count; i++)
            {
                XmlNode xmlNode = xmlRoot.ChildNodes[i];
                if (!(xmlNode is XmlComment))
                {
                    if (xmlRoot.ChildNodes.Count > 1)
                    {
                        if (list2.Contains(xmlNode.Name))
                        {
                            Log.Error("XML " + typeof(T) + " defines the same field twice: " + xmlNode.Name + ".\n\nField contents: " + xmlNode.InnerText + ".\n\nWhole XML:\n\n" + xmlRoot.OuterXml);
                        }
                        else
                        {
                            list2.Add(xmlNode.Name);
                        }
                    }
                    FieldInfo fieldInfo = DirectXmlToObject.GetFieldInfoForType(val2.GetType(), xmlNode.Name, xmlRoot);
                    if (fieldInfo == null)
                    {
                        FieldInfo[] fields = val2.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                        int         num3   = 0;
                        while (num3 < fields.Length)
                        {
                            FieldInfo fieldInfo2       = fields[num3];
                            object[]  customAttributes = fieldInfo2.GetCustomAttributes(typeof(LoadAliasAttribute), true);
                            foreach (object obj3 in customAttributes)
                            {
                                string alias = ((LoadAliasAttribute)obj3).alias;
                                if (alias.EqualsIgnoreCase(xmlNode.Name))
                                {
                                    fieldInfo = fieldInfo2;
                                    break;
                                }
                            }
                            if (fieldInfo == null)
                            {
                                num3++;
                                continue;
                            }
                            break;
                        }
                    }
                    if (fieldInfo == null)
                    {
                        bool     flag = false;
                        object[] customAttributes2 = val2.GetType().GetCustomAttributes(typeof(IgnoreSavedElementAttribute), true);
                        foreach (object obj4 in customAttributes2)
                        {
                            string elementToIgnore = ((IgnoreSavedElementAttribute)obj4).elementToIgnore;
                            if (string.Equals(elementToIgnore, xmlNode.Name, StringComparison.OrdinalIgnoreCase))
                            {
                                flag = true;
                                break;
                            }
                        }
                        if (!flag)
                        {
                            Log.Error("XML error: " + xmlNode.OuterXml + " doesn't correspond to any field in type " + val2.GetType().Name + ".");
                        }
                    }
                    else if (typeof(Def).IsAssignableFrom(fieldInfo.FieldType))
                    {
                        if (xmlNode.InnerText.NullOrEmpty())
                        {
                            fieldInfo.SetValue(val2, null);
                        }
                        else
                        {
                            DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(val2, fieldInfo, xmlNode.InnerText);
                        }
                    }
                    else
                    {
                        object obj5 = null;
                        try
                        {
                            MethodInfo method3     = typeof(DirectXmlToObject).GetMethod("ObjectFromXml", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                            MethodInfo methodInfo4 = method3.MakeGenericMethod(fieldInfo.FieldType);
                            obj5 = methodInfo4.Invoke(null, new object[2]
                            {
                                xmlNode,
                                doPostLoad
                            });
                        }
                        catch (Exception ex3)
                        {
                            Log.Error("Exception loading from " + xmlNode.ToString() + ": " + ex3.ToString());
                            continue;
                        }
                        if (!typeof(T).IsValueType)
                        {
                            fieldInfo.SetValue(val2, obj5);
                        }
                        else
                        {
                            object obj6 = val2;
                            fieldInfo.SetValue(obj6, obj5);
                            val2 = (T)obj6;
                        }
                    }
                }
            }
            if (doPostLoad)
            {
                DirectXmlToObject.TryDoPostLoad(val2);
            }
            return(val2);
        }