New test.
[mono.git] / mcs / class / Managed.Windows.Forms / System.Resources / ResXResourceWriter.cs
1 // Permission is hereby granted, free of charge, to any person obtaining
2 // a copy of this software and associated documentation files (the
3 // "Software"), to deal in the Software without restriction, including
4 // without limitation the rights to use, copy, modify, merge, publish,
5 // distribute, sublicense, and/or sell copies of the Software, and to
6 // permit persons to whom the Software is furnished to do so, subject to
7 // the following conditions:
8 // 
9 // The above copyright notice and this permission notice shall be
10 // included in all copies or substantial portions of the Software.
11 // 
12 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
13 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
15 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
16 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
17 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
18 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19 //
20 // Copyright (c) 2004-2005 Novell, Inc.
21 //
22 // Authors:
23 //      Duncan Mak              duncan@ximian.com
24 //      Gonzalo Paniagua Javier gonzalo@ximian.com
25 //      Peter Bartok            pbartok@novell.com
26 //
27
28 // COMPLETE
29
30 using System.ComponentModel;
31 using System.IO;
32 using System.Runtime.Serialization.Formatters.Binary;
33 using System.Text;
34 using System.Xml;
35
36 namespace System.Resources
37 {
38         public class ResXResourceWriter : IResourceWriter, IDisposable
39         {
40                 #region Local Variables
41                 private string          filename;
42                 private Stream          stream;
43                 private TextWriter      textwriter;
44                 private XmlTextWriter   writer;
45                 private bool            written;
46                 #endregion      // Local Variables
47
48                 #region Static Fields
49                 public static readonly string BinSerializedObjectMimeType       = "application/x-microsoft.net.object.binary.base64";
50                 public static readonly string ByteArraySerializedObjectMimeType = "application/x-microsoft.net.object.bytearray.base64";
51                 public static readonly string DefaultSerializedObjectMimeType   = BinSerializedObjectMimeType;
52                 public static readonly string ResMimeType                       = "text/microsoft-resx";
53                 public static readonly string ResourceSchema                    = schema;\r
54                 public static readonly string SoapSerializedObjectMimeType      = "application/x-microsoft.net.object.soap.base64";
55                 public static readonly string Version                           = "1.3";
56                 #endregion      // Static Fields
57
58                 #region Constructors & Destructor
59                 public ResXResourceWriter (Stream stream)
60                 {
61                         if (stream == null)
62                                 throw new ArgumentNullException ("stream");
63
64                         if (stream.CanWrite == false)
65                                 throw new ArgumentException ("stream is not writable.", "stream");
66
67                         this.stream = stream;
68                 }
69
70                 public ResXResourceWriter (TextWriter textwriter)
71                 {
72                         if (textwriter == null)
73                                 throw new ArgumentNullException ("textwriter");
74
75                         this.textwriter = textwriter;
76                 }
77                 
78                 public ResXResourceWriter (string fileName)
79                 {
80                         if (fileName == null)
81                                 throw new ArgumentNullException ("fileName");
82
83                         this.filename = fileName;
84                 }
85
86                 ~ResXResourceWriter() {
87                         Dispose(false);
88                 }
89                 #endregion      // Constructors & Destructor
90
91                 void InitWriter ()
92                 {
93                         if (filename != null)
94                                 stream = File.OpenWrite (filename);
95                         if (textwriter == null)
96                                 textwriter = new StreamWriter (stream, Encoding.UTF8);
97
98                         writer = new XmlTextWriter (textwriter);
99                         writer.Formatting = Formatting.Indented;
100                         writer.WriteStartDocument ();
101                         writer.WriteStartElement ("root");
102                         writer.WriteRaw (schema);
103                         WriteHeader ("resmimetype", "text/microsoft-resx");
104                         WriteHeader ("version", "1.3");
105                         WriteHeader ("reader", typeof (ResXResourceReader).AssemblyQualifiedName);
106                         WriteHeader ("writer", typeof (ResXResourceWriter).AssemblyQualifiedName);
107                 }
108
109                 void WriteHeader (string name, string value)
110                 {
111                         writer.WriteStartElement ("resheader");
112                         writer.WriteAttributeString ("name", name);
113                         writer.WriteStartElement ("value");
114                         writer.WriteString (value);
115                         writer.WriteEndElement ();
116                         writer.WriteEndElement ();
117                 }
118
119                 void WriteNiceBase64(byte[] value, int offset, int length) {
120                         string          b64;
121                         StringBuilder   sb;
122                         int             pos;
123                         int             inc;
124                         string          ins;
125
126                         b64 = Convert.ToBase64String(value, offset, length);
127
128                         // Wild guess; two extra newlines, and one newline/tab pair for every 80 chars
129                         sb = new StringBuilder(b64, b64.Length + ((b64.Length + 160) / 80) * 3);
130                         pos = 0;
131                         inc = 80 + Environment.NewLine.Length + 1;
132                         ins = Environment.NewLine + "\t";
133                         while (pos < sb.Length) {
134                                 sb.Insert(pos, ins);
135                                 pos += inc;
136                         }
137                         sb.Insert(sb.Length, Environment.NewLine);
138                         writer.WriteString(sb.ToString());
139                 }
140
141                 void WriteBytes (string name, Type type, byte [] value, int offset, int length)
142                 {
143                         writer.WriteStartElement ("data");
144                         writer.WriteAttributeString ("name", name);
145
146                         if (type != null) {
147                                 writer.WriteAttributeString ("type", type.AssemblyQualifiedName);
148                                 // byte[] should never get a mimetype, otherwise MS.NET won't be able
149                                 // to parse the data.
150                                 if (type != typeof (byte[]))
151                                     writer.WriteAttributeString ("mimetype", ByteArraySerializedObjectMimeType);
152                                 writer.WriteStartElement ("value");
153                                 WriteNiceBase64(value, offset, length);
154                         } else {
155                                 writer.WriteAttributeString ("mimetype", BinSerializedObjectMimeType);
156                                 writer.WriteStartElement ("value");
157                                 writer.WriteBase64 (value, offset, length);
158                         }
159
160                         writer.WriteEndElement ();
161                         writer.WriteEndElement ();
162                 }
163
164                 void WriteBytes (string name, Type type, byte [] value)
165                 {
166                         WriteBytes (name, type, value, 0, value.Length);
167                 }
168
169                 void WriteString (string name, string value)
170                 {
171                         WriteString (name, value, null);
172                 }
173
174                 void WriteString (string name, string value, Type type)
175                 {
176                         writer.WriteStartElement ("data");
177                         writer.WriteAttributeString ("name", name);
178                         if (type != null)
179                                 writer.WriteAttributeString ("type", type.AssemblyQualifiedName);
180                         writer.WriteStartElement ("value");
181                         writer.WriteString (value);
182                         writer.WriteEndElement ();
183                         writer.WriteEndElement ();
184                         writer.WriteWhitespace ("\n  ");
185                 }
186
187                 public void AddResource (string name, byte [] value)
188                 {
189                         if (name == null)
190                                 throw new ArgumentNullException ("name");
191
192                         if (value == null)
193                                 throw new ArgumentNullException ("value");
194
195                         if (written)
196                                 throw new InvalidOperationException ("The resource is already generated.");
197
198                         if (writer == null)
199                                 InitWriter ();
200
201                         WriteBytes (name, value.GetType (), value);
202                 }
203
204                 public void AddResource (string name, object value)
205                 {
206                         if (value is string) {
207                                 AddResource (name, (string) value);
208                                 return;
209                         }
210
211                         if (value is byte[]) {
212                                 AddResource (name, (byte[]) value);
213                                 return;
214                         }
215
216                         if (name == null)
217                                 throw new ArgumentNullException ("name");
218
219                         if (value == null)
220                                 throw new ArgumentNullException ("value");
221
222                         if (!value.GetType ().IsSerializable)
223                                 throw new InvalidOperationException (String.Format ("The element '{0}' of type '{1}' is not serializable.", name, value.GetType ().Name));
224
225                         if (written)
226                                 throw new InvalidOperationException ("The resource is already generated.");
227
228                         if (writer == null)
229                                 InitWriter ();
230
231                         TypeConverter converter = TypeDescriptor.GetConverter (value);
232                         if (converter != null && converter.CanConvertTo (typeof (string)) && converter.CanConvertFrom (typeof (string))) {
233                                 string str = (string) converter.ConvertToInvariantString (value);
234                                 WriteString (name, str, value.GetType ());
235                                 return;
236                         }
237                         
238                         if (converter != null && converter.CanConvertTo (typeof (byte[])) && converter.CanConvertFrom (typeof (byte[]))) {
239                                 byte[] b = (byte[]) converter.ConvertTo (value, typeof (byte[]));
240                                 WriteBytes (name, value.GetType (), b);
241                                 return;
242                         }
243                         
244                         MemoryStream ms = new MemoryStream ();
245                         BinaryFormatter fmt = new BinaryFormatter ();
246                         try {
247                                 fmt.Serialize (ms, value);
248                         } catch (Exception e) {
249                                 throw new InvalidOperationException ("Cannot add a " + value.GetType () +
250                                                                      "because it cannot be serialized: " +
251                                                                      e.Message);
252                         }
253
254                         WriteBytes (name, null, ms.GetBuffer (), 0, (int) ms.Length);
255                         ms.Close ();
256                 }
257                 
258                 public void AddResource (string name, string value)
259                 {
260                         if (name == null)
261                                 throw new ArgumentNullException ("name");
262
263                         if (value == null)
264                                 throw new ArgumentNullException ("value");
265
266                         if (written)
267                                 throw new InvalidOperationException ("The resource is already generated.");
268
269                         if (writer == null)
270                                 InitWriter ();
271
272                         WriteString (name, value);
273                 }
274
275                 public void Close ()
276                 {
277                         if (!written) {
278                                 Generate ();
279                         }
280
281                         if (writer != null) {
282                                 writer.Close ();
283                                 stream = null;
284                                 filename = null;
285                                 textwriter = null;
286                         }
287                 }
288                 
289                 public virtual void Dispose ()
290                 {
291                         Dispose(true);
292                         GC.SuppressFinalize(this);
293                 }
294
295                 public void Generate ()
296                 {
297                         if (written)
298                                 throw new InvalidOperationException ("The resource is already generated.");
299
300                         written = true;
301                         writer.WriteEndElement ();
302                         writer.Flush ();
303                 }
304
305                 protected virtual void Dispose(bool disposing) {
306                         if (disposing) {
307                                 Close();
308                         }
309                 }
310
311                 static string schema = @"
312   <xsd:schema id='root' xmlns='' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'>
313     <xsd:element name='root' msdata:IsDataSet='true'>
314       <xsd:complexType>
315         <xsd:choice maxOccurs='unbounded'>
316           <xsd:element name='data'>
317             <xsd:complexType>
318               <xsd:sequence>
319                 <xsd:element name='value' type='xsd:string' minOccurs='0' msdata:Ordinal='1' />
320                 <xsd:element name='comment' type='xsd:string' minOccurs='0' msdata:Ordinal='2' />
321               </xsd:sequence>
322               <xsd:attribute name='name' type='xsd:string' msdata:Ordinal='1' />
323               <xsd:attribute name='type' type='xsd:string' msdata:Ordinal='3' />
324               <xsd:attribute name='mimetype' type='xsd:string' msdata:Ordinal='4' />
325             </xsd:complexType>
326           </xsd:element>
327           <xsd:element name='resheader'>
328             <xsd:complexType>
329               <xsd:sequence>
330                 <xsd:element name='value' type='xsd:string' minOccurs='0' msdata:Ordinal='1' />
331               </xsd:sequence>
332               <xsd:attribute name='name' type='xsd:string' use='required' />
333             </xsd:complexType>
334           </xsd:element>
335         </xsd:choice>
336       </xsd:complexType>
337     </xsd:element>
338   </xsd:schema>
339 ".Replace ("'", "\"");
340         }
341 }
342