This should fix #76928. This fix incorporates ideas from a patch
[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                                 textwriter = new StreamWriter (stream, Encoding.UTF8);
96                         }
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, string typename, byte [] value, int offset, int length)
142                 {
143                         writer.WriteStartElement ("data");
144                         writer.WriteAttributeString ("name", name);
145
146                         if (typename != null) {
147                                 writer.WriteAttributeString ("type", typename);
148                                 writer.WriteStartElement ("value");
149                                 WriteNiceBase64(value, offset, length);
150                         } else {
151                                 writer.WriteAttributeString ("mimetype",
152                                                 "application/x-microsoft.net.object.binary.base64");
153                                 writer.WriteStartElement ("value");
154                                 writer.WriteBase64 (value, offset, length);
155                         }
156
157                         writer.WriteEndElement ();
158                         writer.WriteEndElement ();
159                 }
160
161                 void WriteBytes (string name, string typename, byte [] value)
162                 {
163                         WriteBytes (name, typename, value, 0, value.Length);
164                 }
165
166                 void WriteString (string name, string value)
167                 {
168                         WriteString (name, value, null);
169                 }
170
171                 void WriteString (string name, string value, string typename)
172                 {
173                         writer.WriteStartElement ("data");
174                         writer.WriteAttributeString ("name", name);
175                         if (typename != null)
176                                 writer.WriteAttributeString ("type", typename);
177                         writer.WriteStartElement ("value");
178                         writer.WriteString (value);
179                         writer.WriteEndElement ();
180                         writer.WriteEndElement ();
181                         writer.WriteWhitespace ("\n  ");
182                 }
183
184                 public void AddResource (string name, byte [] value)
185                 {
186                         if (name == null)
187                                 throw new ArgumentNullException ("name");
188
189                         if (value == null)
190                                 throw new ArgumentNullException ("value");
191
192                         if (written)
193                                 throw new InvalidOperationException ("The resource is already generated.");
194
195                         if (writer == null)
196                                 InitWriter ();
197
198                         WriteBytes (name, value.GetType ().AssemblyQualifiedName, value);
199                 }
200
201                 public void AddResource (string name, object value)
202                 {
203                         if (value is string) {
204                                 AddResource (name, (string) value);
205                                 return;
206                         }
207
208                         if (value is byte[]) {
209                                 AddResource (name, (byte[]) value);
210                                 return;
211                         }
212
213                         if (name == null)
214                                 throw new ArgumentNullException ("name");
215
216                         if (value == null)
217                                 throw new ArgumentNullException ("value");
218
219                         if (written)
220                                 throw new InvalidOperationException ("The resource is already generated.");
221
222                         if (writer == null)
223                                 InitWriter ();
224
225                         TypeConverter converter = TypeDescriptor.GetConverter (value);
226                         if (converter != null && converter.CanConvertTo (typeof (string)) && converter.CanConvertFrom (typeof (string))) {
227                                 string str = (string) converter.ConvertToInvariantString (value);
228                                 WriteString (name, str, value.GetType ().AssemblyQualifiedName);
229                                 return;
230                         }
231                         
232                         if (converter != null && converter.CanConvertTo (typeof (byte[])) && converter.CanConvertFrom (typeof (byte[]))) {
233                                 byte[] b = (byte[]) converter.ConvertTo (value, typeof (byte[]));
234                                 WriteBytes (name, value.GetType().AssemblyQualifiedName, b);
235                                 return;
236                         }
237                         
238                         MemoryStream ms = new MemoryStream ();
239                         BinaryFormatter fmt = new BinaryFormatter ();
240                         try {
241                                 fmt.Serialize (ms, value);
242                         } catch (Exception e) {
243                                 throw new InvalidOperationException ("Cannot add a " + value.GetType () +
244                                                                      "because it cannot be serialized: " +
245                                                                      e.Message);
246                         }
247
248                         WriteBytes (name, null, ms.GetBuffer (), 0, (int) ms.Length);
249                         ms.Close ();
250                 }
251                 
252                 public void AddResource (string name, string value)
253                 {
254                         if (name == null)
255                                 throw new ArgumentNullException ("name");
256
257                         if (value == null)
258                                 throw new ArgumentNullException ("value");
259
260                         if (written)
261                                 throw new InvalidOperationException ("The resource is already generated.");
262
263                         if (writer == null)
264                                 InitWriter ();
265
266                         WriteString (name, value);
267                 }
268
269                 public void Close ()
270                 {
271                         if (!written) {
272                                 Generate ();
273                         }
274
275                         if (writer != null) {
276                                 writer.Close ();
277                                 stream = null;
278                                 filename = null;
279                                 textwriter = null;
280                         }
281                 }
282                 
283                 public void Dispose ()
284                 {
285                         Dispose(true);
286                         GC.SuppressFinalize(this);
287                 }
288
289                 public void Generate ()
290                 {
291                         if (written)
292                                 throw new InvalidOperationException ("The resource is already generated.");
293
294                         written = true;
295                         writer.WriteEndElement ();
296                         writer.Flush ();
297                 }
298
299                 protected virtual void Dispose(bool disposing) {
300                         if (disposing) {
301                                 Close();
302                         }
303                 }
304
305                 static string schema = @"
306   <xsd:schema id='root' xmlns='' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'>
307     <xsd:element name='root' msdata:IsDataSet='true'>
308       <xsd:complexType>
309         <xsd:choice maxOccurs='unbounded'>
310           <xsd:element name='data'>
311             <xsd:complexType>
312               <xsd:sequence>
313                 <xsd:element name='value' type='xsd:string' minOccurs='0' msdata:Ordinal='1' />
314                 <xsd:element name='comment' type='xsd:string' minOccurs='0' msdata:Ordinal='2' />
315               </xsd:sequence>
316               <xsd:attribute name='name' type='xsd:string' msdata:Ordinal='1' />
317               <xsd:attribute name='type' type='xsd:string' msdata:Ordinal='3' />
318               <xsd:attribute name='mimetype' type='xsd:string' msdata:Ordinal='4' />
319             </xsd:complexType>
320           </xsd:element>
321           <xsd:element name='resheader'>
322             <xsd:complexType>
323               <xsd:sequence>
324                 <xsd:element name='value' type='xsd:string' minOccurs='0' msdata:Ordinal='1' />
325               </xsd:sequence>
326               <xsd:attribute name='name' type='xsd:string' use='required' />
327             </xsd:complexType>
328           </xsd:element>
329         </xsd:choice>
330       </xsd:complexType>
331     </xsd:element>
332   </xsd:schema>
333 ".Replace ("'", "\"");
334         }
335 }
336