Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Persistence Test/HeuristicLab.Core/3.2/PersistenceManager.cs @ 3928

Last change on this file since 3928 was 2143, checked in by swagner, 15 years ago

Refactoring of the saving mechanism for editors (#685)

File size: 10.3 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      string tempfile = Path.GetTempFileName();
111      using (FileStream stream = File.Create(tempfile)) {
112        Save(instance, stream);
113        stream.Close();
114      }
115      File.Copy(tempfile, filename, true);
116      File.Delete(tempfile);
117    }
118    /// <summary>
119    /// Saves the specified <paramref name="instance"/> in the specified <paramref name="stream"/>
120    /// through creating an <see cref="XmlDocument"/>.
121    /// </summary>
122    /// <param name="instance">The object that should be saved.</param>
123    /// <param name="stream">The (file) stream where the object should be saved.</param>
124    public static void Save(IStorable instance, Stream stream) {
125      XmlDocument document = PersistenceManager.CreateXmlDocument();
126      Dictionary<Guid, IStorable> dictionary = new Dictionary<Guid, IStorable>();
127      XmlNode rootNode = document.CreateElement("Root");
128      document.AppendChild(rootNode);
129      rootNode.AppendChild(Persist(instance, document, dictionary));
130      document.Save(stream);
131    }
132    /// <summary>
133    /// Loads an object from a file with the specified <paramref name="filename"/>.
134    /// </summary>
135    /// <remarks>The object must be saved as an <see cref="XmlDocument"/>. <br/>
136    /// Calls <see cref="Restore"/>.</remarks>
137    /// <param name="filename">The filename of the file where the data is saved.</param>
138    /// <returns>The loaded object.</returns>
139    public static IStorable Load(string filename) {
140      using(FileStream stream = File.OpenRead(filename)) {
141        IStorable storable = Load(stream);
142        stream.Close();
143        return storable;
144      }
145    }
146    /// <summary>
147    /// Loads an object from the specified <paramref name="stream"/>.
148    /// </summary>
149    /// <remarks>The object must be saved as an <see cref="XmlDocument"/>. <br/>
150    /// Calls <see cref="Restore"/>.</remarks>
151    /// <param name="stream">The stream from where to load the data.</param>
152    /// <returns>The loaded object.</returns>
153    public static IStorable Load(Stream stream) {
154      XmlDocument doc = new XmlDocument();
155      doc.Load(stream);
156      XmlNode rootNode = doc.ChildNodes[1];
157      if(rootNode.Name == "Root") {
158        XmlNode bodyNode;
159        if (rootNode.ChildNodes.Count == 2) bodyNode = rootNode.ChildNodes[1];
160        else bodyNode = rootNode.ChildNodes[0];
161        // load documents that have a list of necessary plugins at the top
162        return PersistenceManager.Restore(bodyNode, new Dictionary<Guid, IStorable>());
163      } else {
164        // compatibility to load documents without list of necessary plugins
165        return PersistenceManager.Restore(rootNode, new Dictionary<Guid, IStorable>());
166      }
167    }
168
169    /// <summary>
170    /// Loads an object from a zip file.
171    /// </summary>
172    /// <param name="serializedStorable">The zip file from where to load as byte array.</param>
173    /// <returns>The loaded object.</returns>
174    public static IStorable RestoreFromGZip(byte[] serializedStorable) {
175      GZipStream stream = new GZipStream(new MemoryStream(serializedStorable), CompressionMode.Decompress);
176      return Load(stream);
177    }
178
179    /// <summary>
180    /// Saves the specified <paramref name="storable"/> in a zip file.
181    /// </summary>
182    /// <remarks>Calls <see cref="Save(HeuristicLab.Core.IStorable, Stream)"/>.</remarks>
183    /// <param name="storable">The object to save.</param>
184    /// <returns>The zip stream as byte array.</returns>
185    public static byte[] SaveToGZip(IStorable storable) {
186      MemoryStream memStream = new MemoryStream();
187      GZipStream stream = new GZipStream(memStream, CompressionMode.Compress, true);
188      Save(storable, stream);
189      stream.Close();
190      return memStream.ToArray();
191    }
192
193    /// <summary>
194    /// Builds a meaningful string for the given <paramref name="type"/> with the namespace information,
195    /// all its arguments, the assembly name...
196    /// </summary>
197    /// <param name="type">The type for which a string should be created.</param>
198    /// <returns>A string value of this type containing different additional information.</returns>
199    public static string BuildTypeString(Type type) {
200      string assembly = type.Assembly.FullName;
201      assembly = assembly.Substring(0, assembly.IndexOf(", "));
202
203      StringBuilder builder = new StringBuilder();
204      builder.Append(type.Namespace);
205      builder.Append(".");
206      builder.Append(type.Name);
207      Type[] args = type.GetGenericArguments();
208      if(args.Length > 0) {
209        builder.Append("[[");
210        builder.Append(BuildTypeString(args[0]));
211        builder.Append("]");
212        for(int i = 1; i < args.Length; i++) {
213          builder.Append(",[");
214          builder.Append(BuildTypeString(args[i]));
215          builder.Append("]");
216        }
217        builder.Append("]");
218      }
219      builder.Append(", ");
220      builder.Append(assembly);
221      return builder.ToString();
222    }
223  }
224}
Note: See TracBrowser for help on using the repository browser.