Beispiel #1
0
        internal static void SetNodeData(Node node, object data, Type type, FileStyle style)
        {
            if (data == null)
            {
                throw new Exception("you can't serialize null");
            }

            string dataAsString = data as string;

            if (type == typeof(string) && (dataAsString.ContainsNewLine() || node.ChildNodes.Count > 0))
            {
                BaseTypes.SerializeSpecialStringCase(dataAsString, node, style);
            }

            else if (BaseTypes.IsBaseType(type))
            {
                node.Value = BaseTypes.SerializeBaseType(data, type, style);
            }

            else if (CollectionTypes.TrySetCollection(node, data, type, style))
            {
                return;
            }

            else
            {
                ComplexTypes.SetComplexNode(node, data, type, style);
            }
        }
Beispiel #2
0
        /// <summary> Save this file as a dictionary, using the dictionary's keys as top-level keys in the file. </summary>
        /// <remarks> TKey must be a Base Type </remarks>
        public void SaveAsDictionary <TKey, TValue>(IDictionary <TKey, TValue> dictionary)
        {
            if (!BaseTypes.IsBaseType(typeof(TKey)))
            {
                throw new Exception("When using GetAsDictionary, TKey must be a base type");
            }

            bool _autosave = AutoSave;

            AutoSave = false; // don't write to disk when we don't have to

            try
            {
                var CurrentKeys = new List <string>(capacity: dictionary.Count);
                foreach (var key in dictionary.Keys)
                {
                    var keyText = BaseTypes.SerializeBaseType(key, Style);
                    if (!Utilities.IsValidKey(keyText, out string whyNot))
                    {
                        throw new Exception($"can't save file as this dictionary. A key ({keyText}) is not valid: {whyNot}");
                    }

                    CurrentKeys.Add(keyText);
                    Set(keyText, dictionary[key]);
                }

                // make sure that old data in the file is deleted when a new dictionary is saved.
                foreach (var key in this.GetTopLevelKeys())
                {
                    if (!CurrentKeys.Contains(key))
                    {
                        this.TopLevelNodes.Remove(key);
                    }
                }
            }
            finally
            {
                AutoSave = _autosave;
            }

            if (AutoSave)
            {
                SaveAllData();
            }
        }