[MSBuild] Fix minor assembly resolution issue
[mono.git] / mcs / class / corlib / System / TimeZoneInfo.Android.cs
1 /*
2  * System.TimeZoneInfo Android Support
3  *
4  * Author(s)
5  *      Jonathan Pryor  <jpryor@novell.com>
6  *      The Android Open Source Project
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  */
20
21 #if MONODROID
22
23 using System;
24 using System.Collections.Generic;
25 using System.IO;
26 using System.Runtime.CompilerServices;
27 using System.Runtime.InteropServices;
28 using System.Text;
29
30 namespace System {
31
32         interface IAndroidTimeZoneDB {
33                 IEnumerable<string>   GetAvailableIds ();
34                 byte[]                GetTimeZoneData (string id);
35         }
36
37         [StructLayout (LayoutKind.Sequential, Pack=1)]
38         unsafe struct AndroidTzDataHeader {
39                 public fixed byte signature [12];
40                 public int        indexOffset;
41                 public int        dataOffset;
42                 public int        zoneTabOffset;
43         }
44
45         [StructLayout (LayoutKind.Sequential, Pack=1)]
46         unsafe struct AndroidTzDataEntry {
47                 public fixed byte id [40];
48                 public int        byteOffset;
49                 public int        length;
50                 public int        rawUtcOffset;
51         }
52
53         /*
54          * Android v4.3 Timezone support infrastructure.
55          *
56          * This is a C# port of libcore.util.ZoneInfoDB:
57          *
58          *    https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/ZoneInfoDB.java
59          *
60          * This is needed in order to read Android v4.3 tzdata files.
61          */
62         sealed class AndroidTzData : IAndroidTimeZoneDB {
63
64                 internal static readonly string[] Paths = new string[]{
65                         Environment.GetEnvironmentVariable ("ANDROID_DATA") + "/misc/zoneinfo/tzdata",
66                         Environment.GetEnvironmentVariable ("ANDROID_ROOT") + "/usr/share/zoneinfo/tzdata",
67                 };
68
69                 string    tzdataPath;
70                 Stream    data;
71                 string    version;
72                 string    zoneTab;
73
74                 string[]  ids;
75                 int[]     byteOffsets;
76                 int[]     lengths;
77
78                 public AndroidTzData (params string[] paths)
79                 {
80                         foreach (var path in paths)
81                                 if (LoadData (path)) {
82                                         tzdataPath = path;
83                                         return;
84                                 }
85
86                         Console.Error.WriteLine ("Couldn't find any tzdata!");
87                         tzdataPath  = "/";
88                         version     = "missing";
89                         zoneTab     = "# Emergency fallback data.\n";
90                         ids         = new[]{ "GMT" };
91                 }
92
93                 public string Version {
94                         get {return version;}
95                 }
96
97                 public string ZoneTab {
98                         get {return zoneTab;}
99                 }
100
101                 bool LoadData (string path)
102                 {
103                         if (!File.Exists (path))
104                                 return false;
105                         try {
106                                 data = File.OpenRead (path);
107                         } catch (IOException) {
108                                 return false;
109                         } catch (UnauthorizedAccessException) {
110                                 return false;
111                         }
112
113                         try {
114                                 ReadHeader ();
115                                 return true;
116                         } catch (Exception e) {
117                                 Console.Error.WriteLine ("tzdata file \"{0}\" was present but invalid: {1}", path, e);
118                         }
119                         return false;
120                 }
121
122                 unsafe void ReadHeader ()
123                 {
124                         int size   = System.Math.Max (Marshal.SizeOf (typeof (AndroidTzDataHeader)), Marshal.SizeOf (typeof (AndroidTzDataEntry)));
125                         var buffer = new byte [size];
126                         var header = ReadAt<AndroidTzDataHeader>(0, buffer);
127
128                         header.indexOffset    = NetworkToHostOrder (header.indexOffset);
129                         header.dataOffset     = NetworkToHostOrder (header.dataOffset);
130                         header.zoneTabOffset  = NetworkToHostOrder (header.zoneTabOffset);
131
132                         sbyte* s = (sbyte*) header.signature;
133                         string magic = new string (s, 0, 6, Encoding.ASCII);
134                         if (magic != "tzdata" || header.signature [11] != 0) {
135                                 var b = new StringBuilder ();
136                                 b.Append ("bad tzdata magic:");
137                                 for (int i = 0; i < 12; ++i) {
138                                         b.Append (" ").Append (((byte) s [i]).ToString ("x2"));
139                                 }
140                                 throw new InvalidOperationException ("bad tzdata magic: " + b.ToString ());
141                         }
142
143                         version = new string (s, 6, 5, Encoding.ASCII);
144
145                         ReadIndex (header.indexOffset, header.dataOffset, buffer);
146                         ReadZoneTab (header.zoneTabOffset, checked ((int) data.Length) - header.zoneTabOffset);
147                 }
148
149                 unsafe T ReadAt<T> (long position, byte[] buffer)
150                         where T : struct
151                 {
152                         int size = Marshal.SizeOf (typeof (T));
153                         if (buffer.Length < size)
154                                 throw new InvalidOperationException ("Internal error: buffer too small");
155
156                         data.Position = position;
157                         int r;
158                         if ((r = data.Read (buffer, 0, size)) < size)
159                                 throw new InvalidOperationException (
160                                                 string.Format ("Error reading '{0}': read {1} bytes, expected {2}", tzdataPath, r, size));
161
162                         fixed (byte* b = buffer)
163                                 return (T) Marshal.PtrToStructure ((IntPtr) b, typeof (T));
164                 }
165
166                 static int NetworkToHostOrder (int value)
167                 {
168                         if (!BitConverter.IsLittleEndian)
169                                 return value;
170
171                         return
172                                 (((value >> 24) & 0xFF) |
173                                  ((value >> 08) & 0xFF00) |
174                                  ((value << 08) & 0xFF0000) |
175                                  ((value << 24)));
176                 }
177
178                 unsafe void ReadIndex (int indexOffset, int dataOffset, byte[] buffer)
179                 {
180                         int indexSize   = dataOffset - indexOffset;
181                         int entryCount  = indexSize / Marshal.SizeOf (typeof (AndroidTzDataEntry));
182                         int entrySize   = Marshal.SizeOf (typeof (AndroidTzDataEntry));
183
184                         byteOffsets   = new int [entryCount];
185                         ids           = new string [entryCount];
186                         lengths       = new int [entryCount];
187
188                         for (int i = 0; i < entryCount; ++i) {
189                                 var entry = ReadAt<AndroidTzDataEntry>(indexOffset + (entrySize*i), buffer);
190                                 var p     = (sbyte*) entry.id;
191
192                                 byteOffsets [i]   = NetworkToHostOrder (entry.byteOffset) + dataOffset;
193                                 ids [i]           = new string (p, 0, GetStringLength (p, 40), Encoding.ASCII);
194                                 lengths [i]       = NetworkToHostOrder (entry.length);
195
196                                 if (lengths [i] < Marshal.SizeOf (typeof (AndroidTzDataHeader)))
197                                         throw new InvalidOperationException ("Length in index file < sizeof(tzhead)");
198                         }
199                 }
200
201                 static unsafe int GetStringLength (sbyte* s, int maxLength)
202                 {
203                         int len;
204                         for (len = 0; len < maxLength; len++, s++) {
205                                 if (*s == 0)
206                                         break;
207                         }
208                         return len;
209                 }
210
211                 unsafe void ReadZoneTab (int zoneTabOffset, int zoneTabSize)
212                 {
213                         byte[] zoneTab = new byte [zoneTabSize];
214
215                         data.Position = zoneTabOffset;
216
217                         int r;
218                         if ((r = data.Read (zoneTab, 0, zoneTab.Length)) < zoneTab.Length)
219                                 throw new InvalidOperationException (
220                                                 string.Format ("Error reading zonetab: read {0} bytes, expected {1}", r, zoneTabSize));
221
222                         this.zoneTab = Encoding.ASCII.GetString (zoneTab, 0, zoneTab.Length);
223                 }
224
225                 public IEnumerable<string> GetAvailableIds ()
226                 {
227                         return ids;
228                 }
229
230                 public byte[] GetTimeZoneData (string id)
231                 {
232                         int i = Array.BinarySearch (ids, id, StringComparer.Ordinal);
233                         if (i < 0)
234                                 return null;
235
236                         int offset = byteOffsets [i];
237                         int length = lengths [i];
238                         var buffer = new byte [length];
239
240                         lock (data) {
241                                 data.Position = offset;
242                                 int r;
243                                 if ((r = data.Read (buffer, 0, buffer.Length)) < buffer.Length)
244                                         throw new InvalidOperationException (
245                                                         string.Format ("Unable to fully read from file '{0}' at offset {1} length {2}; read {3} bytes expected {4}.",
246                                                                 tzdataPath, offset, length, r, buffer.Length));
247                         }
248
249                         TimeZoneInfo.DumpTimeZoneDataToFile (id, buffer);
250                         return buffer;
251                 }
252         }
253
254         partial class TimeZoneInfo {
255
256                 /*
257                  * Android < v4.3 Timezone support infrastructure.
258                  *
259                  * This is a C# port of org.apache.harmony.luni.internal.util.ZoneInfoDB:
260                  *
261                  *    http://android.git.kernel.org/?p=platform/libcore.git;a=blob;f=luni/src/main/java/org/apache/harmony/luni/internal/util/ZoneInfoDB.java;h=3e7bdc3a952b24da535806d434a3a27690feae26;hb=HEAD
262                  *
263                  * From the ZoneInfoDB source:
264                  *
265                  *    However, to conserve disk space the data for all time zones are 
266                  *    concatenated into a single file, and a second file is used to indicate 
267                  *    the starting position of each time zone record.  A third file indicates
268                  *    the version of the zoneinfo databse used to generate the data.
269                  *
270                  * which succinctly describes why we can't just use the LIBC implementation in
271                  * TimeZoneInfo.cs -- the "standard Unixy" directory structure is NOT used.
272                  */
273                 sealed class ZoneInfoDB : IAndroidTimeZoneDB {
274                         const int TimeZoneNameLength  = 40;
275                         const int TimeZoneIntSize     = 4;
276
277                         internal static readonly string ZoneDirectoryName  = Environment.GetEnvironmentVariable ("ANDROID_ROOT") + "/usr/share/zoneinfo/";
278
279                         const    string ZoneFileName       = "zoneinfo.dat";
280                         const    string IndexFileName      = "zoneinfo.idx";
281                         const    string DefaultVersion     = "2007h";
282                         const    string VersionFileName    = "zoneinfo.version";
283
284                         readonly string    zoneRoot;
285                         readonly string    version;
286                         readonly string[]  names;
287                         readonly int[]     starts;
288                         readonly int[]     lengths;
289                         readonly int[]     offsets;
290
291                         public ZoneInfoDB (string zoneInfoDB = null)
292                         {
293                                 zoneRoot = zoneInfoDB ?? ZoneDirectoryName;
294                                 try {
295                                         version = ReadVersion (Path.Combine (zoneRoot, VersionFileName));
296                                 } catch {
297                                         version = DefaultVersion;
298                                 }
299
300                                 try {
301                                         ReadDatabase (Path.Combine (zoneRoot, IndexFileName), out names, out starts, out lengths, out offsets);
302                                 } catch {
303                                         names   = new string [0];
304                                         starts  = new int [0];
305                                         lengths = new int [0];
306                                         offsets = new int [0];
307                                 }
308                         }
309
310                         static string ReadVersion (string path)
311                         {
312                                 using (var file = new StreamReader (path, Encoding.GetEncoding ("iso-8859-1"))) {
313                                         return file.ReadToEnd ().Trim ();
314                                 }
315                         }
316
317                         void ReadDatabase (string path, out string[] names, out int[] starts, out int[] lengths, out int[] offsets)
318                         {
319                                 using (var file = File.OpenRead (path)) {
320                                         var nbuf = new byte [TimeZoneNameLength];
321
322                                         int numEntries = (int) (file.Length / (TimeZoneNameLength + 3*TimeZoneIntSize));
323
324                                         char[]  namebuf = new char [TimeZoneNameLength];
325
326                                         names   = new string [numEntries];
327                                         starts  = new int [numEntries];
328                                         lengths = new int [numEntries];
329                                         offsets = new int [numEntries];
330
331                                         for (int i = 0; i < numEntries; ++i) {
332                                                 Fill (file, nbuf, nbuf.Length);
333                                                 int namelen;
334                                                 for (namelen = 0; namelen < nbuf.Length; ++namelen) {
335                                                         if (nbuf [namelen] == '\0')
336                                                                 break;
337                                                         namebuf [namelen] = (char) (nbuf [namelen] & 0xFF);
338                                                 }
339
340                                                 names   [i] = new string (namebuf, 0, namelen);
341                                                 starts  [i] = ReadInt32 (file, nbuf);
342                                                 lengths [i] = ReadInt32 (file, nbuf);
343                                                 offsets [i] = ReadInt32 (file, nbuf);
344                                         }
345                                 }
346                         }
347
348                         static void Fill (Stream stream, byte[] nbuf, int required)
349                         {
350                                 int read = 0, offset = 0;
351                                 while (offset < required && (read = stream.Read (nbuf, offset, required - offset)) > 0)
352                                         offset += read;
353                                 if (read != required)
354                                         throw new EndOfStreamException ("Needed to read " + required + " bytes; read " + read + " bytes");
355                         }
356
357                         // From java.io.RandomAccessFioe.readInt(), as we need to use the same
358                         // byte ordering as Java uses.
359                         static int ReadInt32 (Stream stream, byte[] nbuf)
360                         {
361                                 Fill (stream, nbuf, 4);
362                                 return ((nbuf [0] & 0xff) << 24) + ((nbuf [1] & 0xff) << 16) +
363                                         ((nbuf [2] & 0xff) << 8) + (nbuf [3] & 0xff);
364                         }
365
366                         internal string Version {
367                                 get {return version;}
368                         }
369
370                         public IEnumerable<string> GetAvailableIds ()
371                         {
372                                 return GetAvailableIds (0, false);
373                         }
374
375                         IEnumerable<string> GetAvailableIds (int rawOffset)
376                         {
377                                 return GetAvailableIds (rawOffset, true);
378                         }
379
380                         IEnumerable<string> GetAvailableIds (int rawOffset, bool checkOffset)
381                         {
382                                 for (int i = 0; i < offsets.Length; ++i) {
383                                         if (!checkOffset || offsets [i] == rawOffset)
384                                                 yield return names [i];
385                                 }
386                         }
387
388                         public byte[] GetTimeZoneData (string id)
389                         {
390                                 int start, length;
391                                 using (var stream = GetTimeZoneData (id, out start, out length)) {
392                                         if (stream == null)
393                                                 return null;
394                                         byte[] buf = new byte [length];
395                                         Fill (stream, buf, buf.Length);
396                                         return buf;
397                                 }
398                         }
399
400                         FileStream GetTimeZoneData (string name, out int start, out int length)
401                         {
402                                 if (name == null) { // Just in case, to avoid NREX as in xambug #4902
403                                         start = 0;
404                                         length = 0;
405                                         return null;
406                                 }
407                                 
408                                 var f = new FileInfo (Path.Combine (zoneRoot, name));
409                                 if (f.Exists) {
410                                         start   = 0;
411                                         length  = (int) f.Length;
412                                         return f.OpenRead ();
413                                 }
414
415                                 start = length = 0;
416
417                                 int i = Array.BinarySearch (names, name, StringComparer.Ordinal);
418                                 if (i < 0)
419                                         return null;
420
421                                 start   = starts [i];
422                                 length  = lengths [i];
423
424                                 var stream = File.OpenRead (Path.Combine (zoneRoot, ZoneFileName));
425                                 stream.Seek (start, SeekOrigin.Begin);
426
427                                 return stream;
428                         }
429                 }
430
431                 static class AndroidTimeZones {
432
433                         static IAndroidTimeZoneDB db;
434
435                         static AndroidTimeZones ()
436                         {
437                                 db = GetDefaultTimeZoneDB ();
438                         }
439
440                         static IAndroidTimeZoneDB GetDefaultTimeZoneDB ()
441                         {
442                                 foreach (var p in AndroidTzData.Paths)
443                                         if (File.Exists (p))
444                                                 return new AndroidTzData (AndroidTzData.Paths);
445                                 if (Directory.Exists (ZoneInfoDB.ZoneDirectoryName))
446                                         return new ZoneInfoDB ();
447                                 return null;
448                         }
449
450                         internal static IEnumerable<string> GetAvailableIds ()
451                         {
452                                 return db == null
453                                         ? new string [0]
454                                         : db.GetAvailableIds ();
455                         }
456
457                         static TimeZoneInfo _GetTimeZone (string id, string name)
458                         {
459                                 if (db == null)
460                                         return null;
461                                 byte[] buffer = db.GetTimeZoneData (name);
462                                 if (buffer == null)
463                                         return null;
464                                 return TimeZoneInfo.ParseTZBuffer (id, buffer, buffer.Length);
465                         }
466
467                         internal static TimeZoneInfo GetTimeZone (string id, string name)
468                         {
469                                 if (name != null) {
470                                         if (name == "GMT" || name == "UTC")
471                                                 return new TimeZoneInfo (id, TimeSpan.FromSeconds (0), id, name, name, null, disableDaylightSavingTime:true);
472                                         if (name.StartsWith ("GMT"))
473                                                 return new TimeZoneInfo (id,
474                                                                 TimeSpan.FromSeconds (ParseNumericZone (name)),
475                                                                 id, name, name, null, disableDaylightSavingTime:true);
476                                 }
477
478                                 try {
479                                         return _GetTimeZone (id, name);
480                                 } catch (Exception) {
481                                         return null;
482                                 }
483                         }
484
485                         static int ParseNumericZone (string name)
486                         {
487                                 if (name == null || !name.StartsWith ("GMT") || name.Length <= 3)
488                                         return 0;
489
490                                 int sign;
491                                 if (name [3] == '+')
492                                         sign = 1;
493                                 else if (name [3] == '-')
494                                         sign = -1;
495                                 else
496                                         return 0;
497
498                                 int where;
499                                 int hour = 0;
500                                 bool colon = false;
501                                 for (where = 4; where < name.Length; where++) {
502                                         char c = name [where];
503
504                                         if (c == ':') {
505                                                 where++;
506                                                 colon = true;
507                                                 break;
508                                         }
509
510                                         if (c >= '0' && c <= '9')
511                                                 hour = hour * 10 + c - '0';
512                                         else
513                                                 return 0;
514                                 }
515
516                                 int min = 0;
517                                 for (; where < name.Length; where++) {
518                                         char c = name [where];
519
520                                         if (c >= '0' && c <= '9')
521                                                 min = min * 10 + c - '0';
522                                         else
523                                                 return 0;
524                                 }
525
526                                 if (colon)
527                                         return sign * (hour * 60 + min) * 60;
528                                 else if (hour >= 100)
529                                         return sign * ((hour / 100) * 60 + (hour % 100)) * 60;
530                                 else
531                                         return sign * (hour * 60) * 60;
532                         }
533
534                         static TimeZoneInfo defaultZone;
535                         internal static TimeZoneInfo Local {
536                                 get {
537                                         var id  = GetDefaultTimeZoneName ();
538                                         return defaultZone = GetTimeZone (id, id);
539                                 }
540                         }
541                         
542                         [DllImport ("__Internal")]
543                         static extern int monodroid_get_system_property (string name, ref IntPtr value);
544
545                         [DllImport ("__Internal")]
546                         static extern void monodroid_free (IntPtr ptr);
547                         
548                         static string GetDefaultTimeZoneName ()
549                         {
550                                 IntPtr value = IntPtr.Zero;
551                                 int n = 0;
552                                 string defaultTimeZone  = Environment.GetEnvironmentVariable ("__XA_OVERRIDE_TIMEZONE_ID__");
553
554                                 if (!string.IsNullOrEmpty (defaultTimeZone))
555                                         return defaultTimeZone;
556
557                                 // Used by the tests
558                                 if (Environment.GetEnvironmentVariable ("__XA_USE_JAVA_DEFAULT_TIMEZONE_ID__") == null)
559                                         n = monodroid_get_system_property ("persist.sys.timezone", ref value);
560                                 
561                                 if (n > 0 && value != IntPtr.Zero) {
562                                         defaultTimeZone = (Marshal.PtrToStringAnsi (value) ?? String.Empty).Trim ();
563                                         monodroid_free (value);
564                                         if (!String.IsNullOrEmpty (defaultTimeZone))
565                                                 return defaultTimeZone;
566                                 }
567                                 
568                                 defaultTimeZone = (AndroidPlatform.GetDefaultTimeZone () ?? String.Empty).Trim ();
569                                 if (!String.IsNullOrEmpty (defaultTimeZone))
570                                         return defaultTimeZone;
571
572                                 return null;
573                         }
574
575 #if SELF_TEST
576                         /*
577                          * Compile:
578                          *    mcs /debug+ /out:tzi.exe /unsafe "/d:INSIDE_CORLIB;MONODROID;NET_4_0;LIBC;SELF_TEST" ../corlib/System/AndroidPlatform.cs System/TimeZone*.cs ../../build/common/Consts.cs ../Mono.Options/Mono.Options/Options.cs
579                          * Prep:
580                          *    mkdir -p android/tzdb/usr/share/zoneinfo
581                          *    mkdir -p android/tzdb/misc/zoneinfo/zoneinfo
582                          *    android_root=`adb shell echo '$ANDROID_ROOT' | tr -d "\r"`
583                          *    android_data=`adb shell echo '$ANDROID_DATA' | tr -d "\r"`
584                          *    adb pull $android_root/usr/share/zoneinfo   android/tzdb/usr/share/zoneinfo
585                          *    adb pull $android_data/misc/zoneinfo/tzdata android/tzdb/misc/zoneinfo
586                          * Run:
587                          *    # Dump all timezone names
588                          *    __XA_OVERRIDE_TIMEZONE_ID__=America/New_York ANDROID_ROOT=`pwd` ANDROID_DATA=`pwd` mono --debug tzi.exe --offset=1969-01-01
589                          *
590                          *    # Dump TimeZone data to files under path `tzdata`
591                          *    __XA_OVERRIDE_TIMEZONE_ID__=America/New_York ANDROID_ROOT=`pwd` ANDROID_DATA=`pwd` mono --debug tzi.exe -o android/tzdata
592                          *
593                          *    # Dump TimeZone rules for specific timezone data (as dumped above)
594                          *    mono tzi.exe --offset=2012-10-24 -i=tzdata/Asia/Amman
595                          */
596                         static void Main (string[] args)
597                         {
598                                 DateTime? offset           = null;
599                                 Func<IAndroidTimeZoneDB> c = () => GetDefaultTimeZoneDB ();
600                                 bool dump_rules            = false;
601                                 Mono.Options.OptionSet p = null;
602                                 p = new Mono.Options.OptionSet () {
603                                         { "i=",
604                                           "TimeZone data {FILE} to parse and dump",
605                                           v => DumpTimeZoneFile (v, offset)
606                                         },
607                                         { "o=",
608                                           "Write TimeZone data files to {PATH}",
609                                           v => TimeZoneInfo.TimeZoneDataExportPath = v
610                                         },
611                                         { "T=", "Create AndroidTzData from {PATH}.", v => {
612                                                         c = () => new AndroidTzData (v);
613                                         } },
614                                         { "Z=", "Create ZoneInfoDB from {DIR}.", v => {
615                                                         c = () => new ZoneInfoDB (v);
616                                         } },
617                                         { "offset=", "Show timezone info offset for DateTime {OFFSET}.", v => {
618                                                 offset = DateTime.Parse (v);
619                                                 Console.WriteLine ("Using DateTime Offset: {0}", offset);
620                                         } },
621                                         { "R|dump-rules",
622                                           "Show timezone info offset for DateTime {OFFSET}.",
623                                           v => dump_rules = v != null },
624                                         { "help", "Show this message and exit", v => {
625                                                         p.WriteOptionDescriptions (Console.Out);
626                                                         Environment.Exit (0);
627                                         } },
628                                 };
629                                 p.Parse (args);
630                                 AndroidTimeZones.db = c ();
631                                 Console.WriteLine ("DB type: {0}", AndroidTimeZones.db.GetType ().FullName);
632                                 foreach (var id in GetAvailableIds ()) {
633                                         Console.Write ("name={0,-40}", id);
634                                         try {
635                                                 TimeZoneInfo zone = _GetTimeZone (id, id);
636                                                 if (zone != null) {
637                                                         Console.Write (" {0,-40}", zone);
638                                                         if (offset.HasValue) {
639                                                                 Console.Write ("From Offset: {0}", zone.GetUtcOffset (offset.Value));
640                                                         }
641                                                         if (dump_rules) {
642                                                                 WriteZoneRules (zone);
643                                                         }
644                                                 }
645                                                 else {
646                                                         Console.Write (" ERROR:null");
647                                                 }
648                                         } catch (Exception e) {
649                                                 Console.WriteLine ();
650                                                 Console.Write ("ERROR: {0}", e);
651                                         }
652                                         Console.WriteLine ();
653                                 }
654                         }
655
656                         static void WriteZoneRules (TimeZoneInfo zone)
657                         {
658                                 var rules = zone.GetAdjustmentRules ();
659                                 for (int i = 0; i < rules.Length; ++i) {
660                                         var rule = rules [i];
661                                         Console.WriteLine ();
662                                         Console.Write ("\tAdjustmentRules[{0,3}]: DaylightDelta={1}; DateStart={2:yyyy-MM}; DateEnd={3:yyyy-MM}; DaylightTransitionStart={4:D2}-{5:D2}T{6}; DaylightTransitionEnd={7:D2}-{8:D2}T{9}",
663                                                 i,
664                                                 rule.DaylightDelta,
665                                                 rule.DateStart, rule.DateEnd,
666                                                 rule.DaylightTransitionStart.Month, rule.DaylightTransitionStart.Day, rule.DaylightTransitionStart.TimeOfDay.TimeOfDay,
667                                                 rule.DaylightTransitionEnd.Month, rule.DaylightTransitionEnd.Day, rule.DaylightTransitionEnd.TimeOfDay.TimeOfDay);
668                                 }
669                         }
670
671                         static void DumpTimeZoneFile (string path, DateTime? time)
672                         {
673                                 var buffer = File.ReadAllBytes (path);
674                                 var zone = ParseTZBuffer (path, buffer, buffer.Length);
675                                 Console.Write ("Rules for: {0}", path);
676                                 WriteZoneRules (zone);
677                                 Console.WriteLine ();
678                                 if (time.HasValue) {
679                                         var offset = zone.GetUtcOffset (time.Value);
680                                         var isDst  = zone.IsDaylightSavingTime (time.Value);
681                                         Console.WriteLine ("\tDate({0}): Offset({1}) IsDST({2})", time.Value, offset, isDst);
682                                 }
683
684                                 if (zone.transitions != null) {
685                                         Console.WriteLine ("Transitions for: {0}", path);
686                                         foreach (var transition in zone.transitions) {
687                                                 Console.WriteLine ("\t Date({0}): {1}", transition.Key, transition.Value);
688                                         }
689                                 }
690                         }
691 #endif
692                 }
693
694 #if SELF_TEST
695                 static string TimeZoneDataExportPath;
696 #endif
697
698                 internal static void DumpTimeZoneDataToFile (string id, byte[] buffer)
699                 {
700 #if SELF_TEST
701                         int p = id.LastIndexOf ('/');
702                         var o = Path.Combine (TimeZoneDataExportPath,
703                                         p >= 0 ? id.Substring (0, p) : id);
704                         if (p >= 0)
705                                 o = Path.Combine (o, id.Substring (p+1));
706                         Directory.CreateDirectory (Path.GetDirectoryName (o));
707                         using (var f = File.OpenWrite (o))
708                                 f.Write (buffer, 0, buffer.Length);
709 #endif
710                 }
711         }
712 }
713
714 #endif // MONODROID
715