Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 1529 was 1529, checked in by gkronber, 15 years ago

Moved source files of plugins AdvancedOptimizationFrontEnd ... Grid into version-specific sub-folders. #576

File size: 11.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      XmlNode necessaryPluginsNode = document.CreateElement("NecessaryPlugins");
127      rootNode.AppendChild(necessaryPluginsNode);
128      rootNode.AppendChild(Persist(instance, document, dictionary));
129      // determine the list of necessary plugins for this document
130      DiscoveryService service = new DiscoveryService();
131      List<PluginInfo> plugins = new List<PluginInfo>();
132      foreach(IStorable storeable in dictionary.Values) {
133        PluginInfo pluginInfo = service.GetDeclaringPlugin(storeable.GetType());
134        if(!plugins.Contains(pluginInfo)) plugins.Add(pluginInfo);
135      }
136      foreach(PluginInfo uniquePlugin in plugins) {
137        XmlNode necessaryPluginNode = document.CreateElement("Plugin");
138        XmlAttribute nameAttr = document.CreateAttribute("Name");
139        nameAttr.Value = uniquePlugin.Name;
140        XmlAttribute versionAttr = document.CreateAttribute("Version");
141        versionAttr.Value = uniquePlugin.Version.ToString();
142        necessaryPluginNode.Attributes.Append(nameAttr);
143        necessaryPluginNode.Attributes.Append(versionAttr);
144        necessaryPluginsNode.AppendChild(necessaryPluginNode);
145      }
146      document.Save(stream);
147    }
148    /// <summary>
149    /// Loads an object from a file with the specified <paramref name="filename"/>.
150    /// </summary>
151    /// <remarks>The object must be saved as an <see cref="XmlDocument"/>. <br/>
152    /// Calls <see cref="Restore"/>.</remarks>
153    /// <param name="filename">The filename of the file where the data is saved.</param>
154    /// <returns>The loaded object.</returns>
155    public static IStorable Load(string filename) {
156      using(FileStream stream = File.OpenRead(filename)) {
157        IStorable storable = Load(stream);
158        stream.Close();
159        return storable;
160      }
161    }
162    /// <summary>
163    /// Loads an object from the specified <paramref name="stream"/>.
164    /// </summary>
165    /// <remarks>The object must be saved as an <see cref="XmlDocument"/>. <br/>
166    /// Calls <see cref="Restore"/>.</remarks>
167    /// <param name="stream">The stream from where to load the data.</param>
168    /// <returns>The loaded object.</returns>
169    public static IStorable Load(Stream stream) {
170      XmlDocument doc = new XmlDocument();
171      doc.Load(stream);
172      XmlNode rootNode = doc.ChildNodes[1];
173      if(rootNode.Name == "Root" && rootNode.ChildNodes.Count == 2) {
174        // load documents that have a list of necessary plugins at the top
175        return PersistenceManager.Restore(rootNode.ChildNodes[1], new Dictionary<Guid, IStorable>());
176      } else {
177        // compatibility to load documents without list of necessary plugins
178        return PersistenceManager.Restore(rootNode, new Dictionary<Guid, IStorable>());
179      }
180    }
181
182    /// <summary>
183    /// Loads an object from a zip file.
184    /// </summary>
185    /// <param name="serializedStorable">The zip file from where to load as byte array.</param>
186    /// <returns>The loaded object.</returns>
187    public static IStorable RestoreFromGZip(byte[] serializedStorable) {
188      GZipStream stream = new GZipStream(new MemoryStream(serializedStorable), CompressionMode.Decompress);
189      return Load(stream);
190    }
191
192    /// <summary>
193    /// Saves the specified <paramref name="storable"/> in a zip file.
194    /// </summary>
195    /// <remarks>Calls <see cref="Save(HeuristicLab.Core.IStorable, Stream)"/>.</remarks>
196    /// <param name="storable">The object to save.</param>
197    /// <returns>The zip stream as byte array.</returns>
198    public static byte[] SaveToGZip(IStorable storable) {
199      MemoryStream memStream = new MemoryStream();
200      GZipStream stream = new GZipStream(memStream, CompressionMode.Compress, true);
201      Save(storable, stream);
202      stream.Close();
203      return memStream.ToArray();
204    }
205
206    /// <summary>
207    /// Builds a meaningful string for the given <paramref name="type"/> with the namespace information,
208    /// all its arguments, the assembly name...
209    /// </summary>
210    /// <param name="type">The type for which a string should be created.</param>
211    /// <returns>A string value of this type containing different additional information.</returns>
212    public static string BuildTypeString(Type type) {
213      string assembly = type.Assembly.FullName;
214      assembly = assembly.Substring(0, assembly.IndexOf(", "));
215
216      StringBuilder builder = new StringBuilder();
217      builder.Append(type.Namespace);
218      builder.Append(".");
219      builder.Append(type.Name);
220      Type[] args = type.GetGenericArguments();
221      if(args.Length > 0) {
222        builder.Append("[[");
223        builder.Append(BuildTypeString(args[0]));
224        builder.Append("]");
225        for(int i = 1; i < args.Length; i++) {
226          builder.Append(",[");
227          builder.Append(BuildTypeString(args[i]));
228          builder.Append("]");
229        }
230        builder.Append("]");
231      }
232      builder.Append(", ");
233      builder.Append(assembly);
234      return builder.ToString();
235    }
236  }
237}
Note: See TracBrowser for help on using the repository browser.