Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/EasyXmlGenerator.cs @ 3935

Last change on this file since 3935 was 3935, checked in by epitzer, 14 years ago

Add EasyXmlGenerator for easier review of generated XML. (#1139)

File size: 7.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.Collections.Generic;
23using System;
24using System.Text;
25using HeuristicLab.Persistence.Interfaces;
26using HeuristicLab.Persistence.Core;
27using System.IO;
28using ICSharpCode.SharpZipLib.Zip;
29using HeuristicLab.Tracing;
30using HeuristicLab.Persistence.Core.Tokens;
31using System.IO.Compression;
32using HeuristicLab.Persistence.Auxiliary;
33
34namespace HeuristicLab.Persistence.Default.Xml {
35
36
37  /// <summary>
38  /// Main entry point of persistence to XML. Use the static methods to serialize
39  /// to a file or to a stream.
40  /// </summary>
41  public class ReadableXmlGenerator : XmlGenerator {
42
43    protected Dictionary<int, string> typeCache = new Dictionary<int, string>();
44
45    /// <summary>
46    /// Formats the specified begin token.
47    /// </summary>
48    /// <param name="beginToken">The begin token.</param>
49    /// <returns>The token in serialized form.</returns>
50    protected override string Format(BeginToken beginToken) {
51      var dict = new Dictionary<string, object> {
52          {"name", beginToken.Name},
53          {"id", beginToken.Id}};
54      return CreateNodeStart(typeCache[beginToken.TypeId], dict);       
55    }
56
57    /// <summary>
58    /// Formats the specified end token.
59    /// </summary>
60    /// <param name="endToken">The end token.</param>
61    /// <returns>The token in serialized form.</returns>
62    protected override string Format(EndToken endToken) {
63      return CreateNodeEnd(typeCache[endToken.TypeId]);
64    }
65
66    /// <summary>
67    /// Formats the specified data token.
68    /// </summary>
69    /// <param name="dataToken">The data token.</param>
70    /// <returns>The token in serialized form.</returns>
71    protected override string Format(PrimitiveToken dataToken) {
72      var dict = new Dictionary<string, object> {
73            {"name", dataToken.Name},
74            {"id", dataToken.Id}};
75      return CreateNode(typeCache[dataToken.TypeId], dict,
76        ((XmlString)dataToken.SerialData).Data);
77    }
78
79    /// <summary>
80    /// Formats the specified ref token.
81    /// </summary>
82    /// <param name="refToken">The ref token.</param>
83    /// <returns>The token in serialized form.</returns>
84    protected override string Format(ReferenceToken refToken) {
85      return CreateNode(refToken.Id.ToString(),
86        new Dictionary<string, object> {
87          {"name", refToken.Name}});
88    }
89
90    /// <summary>
91    /// Formats the specified null ref token.
92    /// </summary>
93    /// <param name="nullRefToken">The null ref token.</param>
94    /// <returns>The token in serialized form.</returns>
95    protected override string Format(NullReferenceToken nullRefToken) {
96      return CreateNode(XmlStringConstants.NULL,
97        new Dictionary<string, object>{
98          {"name", nullRefToken.Name}});
99    }
100
101    /// <summary>
102    /// Formats the specified meta info begin token.
103    /// </summary>
104    /// <param name="metaInfoBeginToken">The meta info begin token.</param>
105    /// <returns>The token in serialized form.</returns>
106    protected override string Format(MetaInfoBeginToken metaInfoBeginToken) {
107      return CreateNodeStart(XmlStringConstants.METAINFO);
108    }
109
110    /// <summary>
111    /// Formats the specified meta info end token.
112    /// </summary>
113    /// <param name="metaInfoEndToken">The meta info end token.</param>
114    /// <returns>The token in serialized form.</returns>
115    protected override string Format(MetaInfoEndToken metaInfoEndToken) {
116      return CreateNodeEnd(XmlStringConstants.METAINFO);
117    }
118
119    /// <summary>
120    /// Formats the specified token.
121    /// </summary>
122    /// <param name="token">The token.</param>
123    /// <returns>The token in serialized form.</returns>
124    protected override string Format(TypeToken token) {
125      typeCache[token.Id] = TypeNameParser.Parse(token.TypeName).GetTypeNameInCode(false);
126      return "";
127    }
128
129    /// <summary>
130    /// Serialize an object into a file.
131    /// The XML configuration is obtained from the <c>ConfigurationService</c>.
132    /// The file is actually a ZIP file.
133    /// Compression level is set to 5 and needed assemblies are not included.
134    /// </summary>
135    /// <param name="o">The object.</param>
136    /// <param name="filename">The filename.</param>
137    public static void Serialize(object o, string filename) {
138      Serialize(o, filename, ConfigurationService.Instance.GetConfiguration(new XmlFormat()));
139    }
140
141    /// <summary>
142    /// Serializes the specified object into a file.
143    /// Needed assemblies are not included, ZIP compression level is set to 5.
144    /// </summary>
145    /// <param name="obj">The object.</param>
146    /// <param name="filename">The filename.</param>
147    /// <param name="config">The configuration.</param>
148    public static void Serialize(object obj, string filename, Configuration config) {     
149      try {
150        string tempfile = Path.GetTempFileName();
151        DateTime start = DateTime.Now;
152        using (FileStream stream = File.Create(tempfile)) {
153          Serialize(obj, stream, config);
154        }
155        Logger.Info(String.Format("easy serialization took {0} seconds",
156          (DateTime.Now - start).TotalSeconds));
157        File.Copy(tempfile, filename, true);
158        File.Delete(tempfile);
159      } catch (Exception) {
160        Logger.Warn("Exception caught, no data has been written.");
161        throw;
162      }
163    }
164
165    /// <summary>
166    /// Serializes the specified object into a stream using the <see cref="XmlFormat"/>
167    /// obtained from the <see cref="ConfigurationService"/>.
168    /// </summary>
169    /// <param name="obj">The object.</param>
170    /// <param name="stream">The stream.</param>
171    public static void Serialize(object obj, Stream stream) {
172      Serialize(obj, stream, ConfigurationService.Instance.GetConfiguration(new XmlFormat()));
173    }
174
175
176    /// <summary>
177    /// Serializes the specified object into a stream.
178    /// </summary>
179    /// <param name="obj">The object.</param>
180    /// <param name="stream">The stream.</param>
181    /// <param name="config">The configuration.</param>
182    public static void Serialize(object obj, Stream stream, Configuration config) {     
183      try {
184        using (StreamWriter writer = new StreamWriter(stream)) {
185          Serializer serializer = new Serializer(obj, config);
186          serializer.InterleaveTypeInformation = true;
187          ReadableXmlGenerator generator = new ReadableXmlGenerator();
188          foreach (ISerializationToken token in serializer) {
189            string line = generator.Format(token);
190            writer.Write(line);
191          }
192          writer.Flush();
193        }
194      } catch (PersistenceException) {
195        throw;
196      } catch (Exception e) {
197        throw new PersistenceException("Unexpected exception during Serialization.", e);
198      }
199    }
200  }
201}
Note: See TracBrowser for help on using the repository browser.