Free cookie consent management tool by TermsFeed Policy Generator

source: branches/histogram/HeuristicLab.Persistence/3.3/Default/Xml/EasyXmlGenerator.cs @ 6022

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

Add new keywords to avoid warnings during compilation (#1419)

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