Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Core/3.2/PersistenceManager.cs @ 1728

Last change on this file since 1728 was 1722, checked in by gkronber, 16 years ago

Fixed a bug in old deserialization code (#339).

File size: 10.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Text;
25using System.Xml;
26using System.IO;
27using System.IO.Compression;
28using HeuristicLab.PluginInfrastructure;
29
30namespace HeuristicLab.Core {
31  /// <summary>
32  /// Static class for serializing and deserializing objects.
33  /// </summary>
34  public static class PersistenceManager {
35    /// <summary>
36    /// Creates an <see cref="XmlDocument"/> to persist an object with xml declaration.
37    /// </summary>
38    /// <returns>The created <see cref="XmlDocument"/>.</returns>
39    public static XmlDocument CreateXmlDocument() {
40      XmlDocument document = new XmlDocument();
41      document.AppendChild(document.CreateXmlDeclaration("1.0", null, null));
42      return document;
43    }
44    /// <summary>
45    /// Saves the specified <paramref name="instance"/> in the specified <paramref name="document"/>
46    /// if it has not already been serialized.
47    /// </summary>
48    /// <remarks>The tag name of the saved instance is its type name.<br/>
49    /// The guid is saved as an <see cref="XmlAttribute"/> with tag name <c>GUID</c>.</remarks>
50    /// <param name="instance">The object that should be saved.</param>
51    /// <param name="document">The <see cref="XmlDocument"/> where to save the data.</param>
52    /// <param name="persistedObjects">The dictionary of all already persisted objects. (Needed to avoid cycles.)</param>
53    /// <returns>The saved <see cref="XmlNode"/>.</returns>
54    public static XmlNode Persist(IStorable instance, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
55      string name = instance.GetType().Name;
56      name = name.Replace('`', '_');
57      return Persist(name, instance, document, persistedObjects);
58    }
59    /// <summary>
60    /// Saves the specified <paramref name="instance"/> in the specified <paramref name="document"/>
61    /// if it has not already been serialized.
62    /// </summary>
63    /// <param name="name">The (tag)name of the <see cref="XmlNode"/>.</param>
64    /// <param name="instance">The object that should be saved.</param>
65    /// <param name="document">The <see cref="XmlDocument"/> where to save the data.</param>
66    /// <param name="persistedObjects">The dictionary of all already persisted objects. (Needed to avoid cycles.)</param>
67    /// <returns>The saved <see cref="XmlNode"/>.</returns>
68    public static XmlNode Persist(string name, IStorable instance, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
69      if(persistedObjects.ContainsKey(instance.Guid)) {
70        XmlNode node = document.CreateNode(XmlNodeType.Element, name, null);
71        XmlAttribute guidAttribute = document.CreateAttribute("GUID");
72        guidAttribute.Value = instance.Guid.ToString();
73        node.Attributes.Append(guidAttribute);
74        return node;
75      } else {
76        persistedObjects.Add(instance.Guid, instance);
77        XmlNode node = instance.GetXmlNode(name, document, persistedObjects);
78        return node;
79      }
80    }
81    /// <summary>
82    /// Loads a persisted object from the specified <paramref name="node"/>.
83    /// </summary>
84    /// <remarks>The guid is saved as an attribute with tag name <c>GUID</c>. The type of the
85    /// persisted object is saved as attribute with tag name <c>Type</c>.<br/>
86    /// Calls <c>instance.Populate</c>.</remarks>
87    /// <param name="node">The <see cref="XmlNode"/> where the object is saved.</param>
88    /// <param name="restoredObjects">A dictionary of all already restored objects.
89    /// (Needed to avoid cycles.)</param>
90    /// <returns>The loaded object.</returns>
91    public static IStorable Restore(XmlNode node, IDictionary<Guid,IStorable> restoredObjects) {
92      Guid guid = new Guid(node.Attributes["GUID"].Value);
93      if(restoredObjects.ContainsKey(guid)) {
94        return restoredObjects[guid];
95      } else {
96        Type type = Type.GetType(node.Attributes["Type"].Value, true);
97        IStorable instance = (IStorable)Activator.CreateInstance(type);
98        restoredObjects.Add(guid, instance);
99        instance.Populate(node, restoredObjects);
100        return instance;
101      }
102    }
103    /// <summary>
104    /// Saves the specified <paramref name="instance"/> in the specified file through creating an
105    /// <see cref="XmlDocument"/>.
106    /// </summary>
107    /// <param name="instance">The object that should be saved.</param>
108    /// <param name="filename">The name of the file where the <paramref name="object"/> should be saved.</param>
109    public static void Save(IStorable instance, string filename) {
110      using(FileStream stream = File.Create(filename)) {
111        Save(instance, stream);
112        stream.Close();
113      }
114    }
115    /// <summary>
116    /// Saves the specified <paramref name="instance"/> in the specified <paramref name="stream"/>
117    /// through creating an <see cref="XmlDocument"/>.
118    /// </summary>
119    /// <param name="instance">The object that should be saved.</param>
120    /// <param name="stream">The (file) stream where the object should be saved.</param>
121    public static void Save(IStorable instance, Stream stream) {
122      XmlDocument document = PersistenceManager.CreateXmlDocument();
123      Dictionary<Guid, IStorable> dictionary = new Dictionary<Guid, IStorable>();
124      XmlNode rootNode = document.CreateElement("Root");
125      document.AppendChild(rootNode);
126      rootNode.AppendChild(Persist(instance, document, dictionary));
127      document.Save(stream);
128    }
129    /// <summary>
130    /// Loads an object from a file with the specified <paramref name="filename"/>.
131    /// </summary>
132    /// <remarks>The object must be saved as an <see cref="XmlDocument"/>. <br/>
133    /// Calls <see cref="Restore"/>.</remarks>
134    /// <param name="filename">The filename of the file where the data is saved.</param>
135    /// <returns>The loaded object.</returns>
136    public static IStorable Load(string filename) {
137      using(FileStream stream = File.OpenRead(filename)) {
138        IStorable storable = Load(stream);
139        stream.Close();
140        return storable;
141      }
142    }
143    /// <summary>
144    /// Loads an object from the specified <paramref name="stream"/>.
145    /// </summary>
146    /// <remarks>The object must be saved as an <see cref="XmlDocument"/>. <br/>
147    /// Calls <see cref="Restore"/>.</remarks>
148    /// <param name="stream">The stream from where to load the data.</param>
149    /// <returns>The loaded object.</returns>
150    public static IStorable Load(Stream stream) {
151      XmlDocument doc = new XmlDocument();
152      doc.Load(stream);
153      XmlNode rootNode = doc.ChildNodes[1];
154      if(rootNode.Name == "Root") {
155        XmlNode bodyNode;
156        if (rootNode.ChildNodes.Count == 2) bodyNode = rootNode.ChildNodes[1];
157        else bodyNode = rootNode.ChildNodes[0];
158        // load documents that have a list of necessary plugins at the top
159        return PersistenceManager.Restore(bodyNode, new Dictionary<Guid, IStorable>());
160      } else {
161        // compatibility to load documents without list of necessary plugins
162        return PersistenceManager.Restore(rootNode, new Dictionary<Guid, IStorable>());
163      }
164    }
165
166    /// <summary>
167    /// Loads an object from a zip file.
168    /// </summary>
169    /// <param name="serializedStorable">The zip file from where to load as byte array.</param>
170    /// <returns>The loaded object.</returns>
171    public static IStorable RestoreFromGZip(byte[] serializedStorable) {
172      GZipStream stream = new GZipStream(new MemoryStream(serializedStorable), CompressionMode.Decompress);
173      return Load(stream);
174    }
175
176    /// <summary>
177    /// Saves the specified <paramref name="storable"/> in a zip file.
178    /// </summary>
179    /// <remarks>Calls <see cref="Save(HeuristicLab.Core.IStorable, Stream)"/>.</remarks>
180    /// <param name="storable">The object to save.</param>
181    /// <returns>The zip stream as byte array.</returns>
182    public static byte[] SaveToGZip(IStorable storable) {
183      MemoryStream memStream = new MemoryStream();
184      GZipStream stream = new GZipStream(memStream, CompressionMode.Compress, true);
185      Save(storable, stream);
186      stream.Close();
187      return memStream.ToArray();
188    }
189
190    /// <summary>
191    /// Builds a meaningful string for the given <paramref name="type"/> with the namespace information,
192    /// all its arguments, the assembly name...
193    /// </summary>
194    /// <param name="type">The type for which a string should be created.</param>
195    /// <returns>A string value of this type containing different additional information.</returns>
196    public static string BuildTypeString(Type type) {
197      string assembly = type.Assembly.FullName;
198      assembly = assembly.Substring(0, assembly.IndexOf(", "));
199
200      StringBuilder builder = new StringBuilder();
201      builder.Append(type.Namespace);
202      builder.Append(".");
203      builder.Append(type.Name);
204      Type[] args = type.GetGenericArguments();
205      if(args.Length > 0) {
206        builder.Append("[[");
207        builder.Append(BuildTypeString(args[0]));
208        builder.Append("]");
209        for(int i = 1; i < args.Length; i++) {
210          builder.Append(",[");
211          builder.Append(BuildTypeString(args[i]));
212          builder.Append("]");
213        }
214        builder.Append("]");
215      }
216      builder.Append(", ");
217      builder.Append(assembly);
218      return builder.ToString();
219    }
220  }
221}
Note: See TracBrowser for help on using the repository browser.