Ejemplo n.º 1
0
        private static List <DateTimeZone> LoadSource(Options options, out string version)
        {
            var source = options.Source;

            if (source == null)
            {
                var tzdbSource = TzdbDateTimeZoneSource.Default;
                version = tzdbSource.TzdbVersion;
                return(tzdbSource.GetIds().Select(id => tzdbSource.ForId(id)).ToList());
            }
            if (source.EndsWith(".nzd"))
            {
                var data       = LoadFileOrUrl(source);
                var tzdbSource = TzdbDateTimeZoneSource.FromStream(new MemoryStream(data));
                version = tzdbSource.TzdbVersion;
                return(tzdbSource.GetIds().Select(id => tzdbSource.ForId(id)).ToList());
            }
            else
            {
                var compiler = new TzdbZoneInfoCompiler(log: null);
                var database = compiler.Compile(source);
                version = database.Version;
                return(database.GenerateDateTimeZones()
                       .Concat(database.Aliases.Keys.Select(database.GenerateDateTimeZone))
                       .ToList());
            }
        }
Ejemplo n.º 2
0
        private static int Main(string[] args)
        {
            Options            options = new Options();
            ICommandLineParser parser  = new CommandLineParser(new CommandLineParserSettings(Console.Error));

            if (!parser.ParseArguments(args, options))
            {
                return(1);
            }
            var data = FileUtility.LoadFileOrUrl(options.Source);
            TzdbDateTimeZoneSource source = TzdbDateTimeZoneSource.FromStream(new MemoryStream(data));
            var dumper = new ZoneDumper(source, options);

            try
            {
                using (var writer = options.OutputFile is null ? Console.Out : File.CreateText(options.OutputFile))
                {
                    dumper.Dump(writer);
                }
            }
            catch (UserErrorException e)
            {
                Console.Error.WriteLine($"Error: {e.Message}");
                return(1);
            }

            return(0);
        }
Ejemplo n.º 3
0
        private void LoadData()
        {
            // init noda time
            using (var stream = File.OpenRead(Directory.GetFiles(_nzdPath)[0]))
            {
                _tzdbSource   = TzdbDateTimeZoneSource.FromStream(stream);
                _tzdbProvider = new DateTimeZoneCache(_tzdbSource);
            }

            // this has to be loaded first
            LoadMetaZones();

            // these can be loaded in parallel
            var actions = new Action[]
            {
                LoadZoneCountries,
                LoadZoneAliases,
                LoadWindowsMappings,
                LoadLanguages
            };

            Task.WhenAll(actions.Select(Task.Run)).Wait();

            // patch the data for any known issues
            PatchData();

            // this has to come last, as it relies on patched data
            LoadSelectionZones();
        }
Ejemplo n.º 4
0
        public IActionResult TimeZones(string?version = null, string?format = null)
        {
            var source = TzdbDateTimeZoneSource.Default;

            if (version != null)
            {
                var release = repository.GetRelease($"tzdb{version}.nzd");
                if (release == null)
                {
                    return(BadRequest("Unknown version"));
                }
                source = TzdbDateTimeZoneSource.FromStream(release.GetContent());
            }
            var releaseModel = IanaRelease.FromTzdbDateTimeZoneSource(source);

            if (format == "json")
            {
                return(Json(releaseModel));
            }

            var releases = repository.GetReleases()
                           .Select(release => NzdNamePattern.Match(release.Name))
                           .Where(m => m.Success)
                           .Select(m => m.Groups[1].Value)
                           .ToList();
            var model = (releases, releaseModel);

            return(View(model));
        }
Ejemplo n.º 5
0
        private static async Task <CurrentTzdbProvider> DownloadAsync()
        {
            using (var client = new HttpClient())
            {
                var latest   = new Uri((await client.GetStringAsync("http://nodatime.org/tzdb/latest.txt")).TrimEnd());
                var fileName = latest.Segments.Last();
                var path     = Path.Combine(Path.GetTempPath(), fileName);

                if (!File.Exists(path))
                {
                    using (var httpStream = await client.GetStreamAsync(latest))
                        using (var fileStream = File.Create(path))
                        {
                            await httpStream.CopyToAsync(fileStream);
                        }
                }

                using (var fileStream = File.OpenRead(path))
                {
                    var source   = TzdbDateTimeZoneSource.FromStream(fileStream);
                    var provider = new DateTimeZoneCache(source);
                    return(new CurrentTzdbProvider(provider, source.Aliases));
                }
            }
        }
Ejemplo n.º 6
0
 protected virtual void LoadTimeZoneData()
 {
     using (Stream stream = File.Open(Path.Combine(SharpIrcBotUtil.AppDirectory, Config.TimeZoneDatabaseFile), FileMode.Open, FileAccess.Read, FileShare.Read))
     {
         TzdbDateTimeZoneSource timeZoneSource = TzdbDateTimeZoneSource.FromStream(stream);
         TimeZoneProvider = new DateTimeZoneCache(timeZoneSource);
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Returns the data in this database as a <see cref="TzdbDateTimeZoneSource"/> with no
        /// Windows mappings.
        /// </summary>
        public TzdbDateTimeZoneSource ToTzdbDateTimeZoneSource()
        {
            var ms     = new MemoryStream();
            var writer = new TzdbStreamWriter(ms);

            writer.Write(this, new WindowsZones("n/a", Version, "n/a", new MapZone[0]));
            ms.Position = 0;
            return(TzdbDateTimeZoneSource.FromStream(ms));
        }
Ejemplo n.º 8
0
        private static TzdbDateTimeZoneSource Read(CompilerOptions options)
        {
            string file = Path.ChangeExtension(options.OutputFileName, "nzd");

            using (var stream = File.OpenRead(file))
            {
                return(TzdbDateTimeZoneSource.FromStream(stream));
            }
        }
Ejemplo n.º 9
0
 private TimezoneDB()
 {
     try {
         using (Stream stream = File.OpenRead(tzdbFilename)) {
             source = TzdbDateTimeZoneSource.FromStream(stream);
         }
     } catch {
         log.Warn("Custom TZDB source failed. Falling back to NodaTime.dll");
         source = TzdbDateTimeZoneSource.Default;
     }
     log.Info("Using NodaTime " + source.VersionId);
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Returns the data in this database as a <see cref="TzdbDateTimeZoneSource"/> with no
        /// Windows mappings.
        /// </summary>
        public TzdbDateTimeZoneSource ToTzdbDateTimeZoneSource()
        {
            var ms     = new MemoryStream();
            var writer = new TzdbStreamWriter();

            writer.Write(this,
                         new WindowsZones("n/a", Version, "n/a", new MapZone[0]), // No Windows mappings,
                         new Dictionary <string, string>(),                       // No additional name-to-id mappings
                         ms);
            ms.Position = 0;
            return(TzdbDateTimeZoneSource.FromStream(ms));
        }
Ejemplo n.º 11
0
        private TimezoneDB()
        {
            try {
                using (Stream stream = File.OpenRead(tzdbFile)) {
                    source = TzdbDateTimeZoneSource.FromStream(stream);
                }
            } catch {
                log.Warn("Custom TZDB source failed. Falling back to NodaTime.dll");
                source = TzdbDateTimeZoneSource.Default;
            }
            log.Info("Using NodaTime " + source.VersionId);

            Microsoft.Win32.SystemEvents.TimeChanged += SystemEvents_TimeChanged;
        }
Ejemplo n.º 12
0
        private static int Main(string[] args)
        {
            Options            options = new Options();
            ICommandLineParser parser  = new CommandLineParser(new CommandLineParserSettings(Console.Error));

            if (!parser.ParseArguments(args, options))
            {
                return(1);
            }
            if (options.FromYear > options.ToYear)
            {
                Console.WriteLine("Error: 'from' year must be not be later than 'to' year");
                return(1);
            }
            IDateTimeZoneSource source = TzdbDateTimeZoneSource.Default;

            if (options.File != null)
            {
                using (var stream = File.OpenRead(options.File))
                {
                    source = TzdbDateTimeZoneSource.FromStream(stream);
                }
            }
            Console.WriteLine("TZDB version: {0}", source.VersionId);

            var provider = new DateTimeZoneCache(source);

            if (options.Zone != null)
            {
                var zone = provider.GetZoneOrNull(options.Zone);
                if (zone == null)
                {
                    Console.WriteLine("Unknown time zone: {0}", options.Zone);
                    return(1);
                }
                DumpZone(zone, Console.Out, options.FromYear, options.ToYear);
            }
            else
            {
                foreach (var id in provider.Ids)
                {
                    DumpZone(provider[id], Console.Out, options.FromYear, options.ToYear);
                }
            }
            return(0);
        }
Ejemplo n.º 13
0
        private static async Task <bool> ValidateAsync(HttpClient httpClient, string url)
        {
            try
            {
                Console.WriteLine($"Validating {url}");
                byte[] data = await httpClient.GetByteArrayAsync(url);

                var source = TzdbDateTimeZoneSource.FromStream(new MemoryStream(data));
                source.Validate();
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine($"{e.GetType().Name}: {e.Message}");
                return(false);
            }
        }
Ejemplo n.º 14
0
 private static TzdbDateTimeZoneSource LoadSource(string source)
 {
     if (source == null)
     {
         return(TzdbDateTimeZoneSource.Default);
     }
     if (source.EndsWith(".nzd"))
     {
         var data = LoadFileOrUrl(source);
         return(TzdbDateTimeZoneSource.FromStream(new MemoryStream(data)));
     }
     else
     {
         var compiler = new TzdbZoneInfoCompiler(log: null);
         var database = compiler.Compile(source);
         return(database.ToTzdbDateTimeZoneSource());
     }
 }
Ejemplo n.º 15
0
        public void CanLoadNodaTimeResourceFromOnePointOneRelease()
        {
            var assembly = typeof(TzdbDateTimeZoneSourceTest).Assembly;
            TzdbDateTimeZoneSource source;

            using (Stream stream = assembly.GetManifestResourceStream("NodaTime.Test.TestData.Tzdb2013bFromNodaTime1.1.nzd"))
            {
                source = TzdbDateTimeZoneSource.FromStream(stream);
            }
            Assert.AreEqual("TZDB: 2013b (mapping: 8274)", source.VersionId);

            var utc = Instant.FromUtc(2007, 8, 24, 9, 30, 0);

            // Test a regular zone with rules.
            var london        = source.ForId("Europe/London");
            var inLondon      = new ZonedDateTime(utc, london);
            var expectedLocal = new LocalDateTime(2007, 8, 24, 10, 30);

            Assert.AreEqual(expectedLocal, inLondon.LocalDateTime);

            // Test a fixed-offset zone.
            var utcFixed   = source.ForId("Etc/UTC");
            var inUtcFixed = new ZonedDateTime(utc, utcFixed);

            expectedLocal = new LocalDateTime(2007, 8, 24, 9, 30);
            Assert.AreEqual(expectedLocal, inUtcFixed.LocalDateTime);

            // Test an alias.
            var jersey   = source.ForId("Japan"); // Asia/Tokyo
            var inJersey = new ZonedDateTime(utc, jersey);

            expectedLocal = new LocalDateTime(2007, 8, 24, 18, 30);
            Assert.AreEqual(expectedLocal, inJersey.LocalDateTime);

            // Test ZoneLocations.
            var france = source.ZoneLocations.Single(g => g.CountryName == "France");

            // Tolerance of about 2 seconds
            Assert.AreEqual(48.86666, france.Latitude, 0.00055);
            Assert.AreEqual(2.3333, france.Longitude, 0.00055);
            Assert.AreEqual("Europe/Paris", france.ZoneId);
            Assert.AreEqual("FR", france.CountryCode);
            Assert.AreEqual("", france.Comment);
        }
Ejemplo n.º 16
0
        private static string GetOffset(string timezone)
        {
            var result = "0";

            if (_tzdbDateTimeZoneSource == null)
            {
                using (var stream = File.OpenRead($"{AppDomain.CurrentDomain.BaseDirectory}GeoDb\\tzdb2019c.nzd"))
                {
                    _tzdbDateTimeZoneSource = TzdbDateTimeZoneSource.FromStream(stream);
                }
            }

            var zonedDateTime = _tzdbDateTimeZoneSource.ForId(timezone)
                                .AtStrictly(new LocalDateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute));

            result = TimeSpan.FromMilliseconds(zonedDateTime.Offset.Milliseconds).TotalHours.ToString();

            return(result);
        }
Ejemplo n.º 17
0
        private static async Task <TzdbDateTimeZoneSource> LoadSourceAsync(string?source)
        {
            if (source is null)
            {
                return(TzdbDateTimeZoneSource.Default);
            }
            if (source.EndsWith(".nzd"))
            {
                var data = await FileUtility.LoadFileOrUrlAsync(source);

                return(TzdbDateTimeZoneSource.FromStream(new MemoryStream(data)));
            }
            else
            {
                var compiler = new TzdbZoneInfoCompiler(log: null);
                var database = await compiler.CompileAsync(source);

                return(database.ToTzdbDateTimeZoneSource());
            }
        }
        private static ICollection <string> GetIanaTimeZoneIds()
        {
            var tempDir = Path.GetTempPath() + Path.GetRandomFileName().Substring(0, 8);

            try
            {
                TestHelpers.DownloadLatestNodaTimeDataAsync(tempDir).Wait();

                using (var stream = File.OpenRead(Directory.GetFiles(tempDir, "*.nzd")[0]))
                {
                    var source   = TzdbDateTimeZoneSource.FromStream(stream);
                    var provider = new DateTimeZoneCache(source);

                    return(provider.Ids.OrderBy(x => x).ToArray());
                }
            }
            finally
            {
                Directory.Delete(tempDir, true);
            }
        }
Ejemplo n.º 19
0
        private static TzdbDateTimeZoneSource Read(CompilerOptions options)
        {
#pragma warning disable 0618
            string file = Path.ChangeExtension(options.OutputFileName, Extensions[options.OutputType]);
            switch (options.OutputType)
            {
            case OutputType.ResX:
                return(new TzdbDateTimeZoneSource(new ResourceSet(new ResXResourceReader(file))));

            case OutputType.Resource:
                return(new TzdbDateTimeZoneSource(new ResourceSet(new ResourceReader(file))));

            case OutputType.NodaZoneData:
                using (var stream = File.OpenRead(file))
                {
                    return(TzdbDateTimeZoneSource.FromStream(stream));
                }

            default:
                throw new ArgumentException("Invalid output type: " + options.OutputType, "options");
            }
#pragma warning restore 0618
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Gets the time zone provider.
        /// It reads the file form its configuration settings
        /// This is for making an updatable file outside the program source
        /// </summary>
        /// <returns></returns>
        public static IDateTimeZoneProvider GetTimeZoneProvider()
        {
            if (provider != null)
            {
                return(provider);
            }

            lock (lockObject)
            {
                if (provider != null)
                {
                    return(provider);
                }
                // Or use Assembly.GetManifestResourceStream for an embedded file
                string tzdbFileName     = FWUtils.ConfigUtils.GetAppSettings().Localization.TzdbFile;
                string tzdbFileFullName = System.IO.Path.Combine(FWUtils.ConfigUtils.ApplicationPath, tzdbFileName);
                using (var stream = System.IO.File.OpenRead(tzdbFileFullName))
                {
                    var source = TzdbDateTimeZoneSource.FromStream(stream);
                    provider = new DateTimeZoneCache(source);
                }
            }
            return(provider);
        }
Ejemplo n.º 21
0
        private static List <DateTimeZone> LoadSource(Options options)
        {
            var source = options.Source;

            if (source == null)
            {
                var provider = DateTimeZoneProviders.Tzdb;
                return(provider.Ids.Select(id => provider[id]).ToList());
            }
            if (source.EndsWith(".nzd"))
            {
                var data       = LoadFileOrUrl(source);
                var tzdbSource = TzdbDateTimeZoneSource.FromStream(new MemoryStream(data));
                return(tzdbSource.GetIds().Select(id => tzdbSource.ForId(id)).ToList());
            }
            else
            {
                var compiler = new TzdbZoneInfoCompiler(log: null);
                var database = compiler.Compile(source);
                return(database.GenerateDateTimeZones()
                       .Concat(database.Aliases.Keys.Select(database.GenerateDateTimeZone))
                       .ToList());
            }
        }
Ejemplo n.º 22
0
        // Usage:
        // $ dotnet run -- [--help] [--start_year start] [--until_year until]
        //      [--nzd_file {file}]
        //      < zones.txt
        //      > validation_data.json
        //
        // Based on the equivalent Java program 'compare_java'.
        //
        static void Main(string[] args)
        {
            // Parse command line flags
            int argc = args.Length;
            int argi = 0;

            /*
             * if (argc == 0) {
             *  UsageAndExit(1);
             * }
             */
            string start       = "2000";
            string until       = "2050";
            string nzdFilePath = "";

            while (argc > 0)
            {
                string arg0 = args[argi];
                if ("--start_year".Equals(arg0))
                {
                    { argc--; argi++; arg0 = args[argi]; } // shift-left
                    start = arg0;
                }
                else if ("--until_year".Equals(arg0))
                {
                    { argc--; argi++; arg0 = args[argi]; } // shift-left
                    until = arg0;
                }
                else if ("--nzd_file".Equals(arg0))
                {
                    { argc--; argi++; arg0 = args[argi]; } // shift-left
                    nzdFilePath = arg0;
                }
                else if ("--help".Equals(arg0))
                {
                    UsageAndExit(0);
                    break;
                }
                else if ("--".Equals(arg0))
                {
                    break;
                }
                else if (arg0.StartsWith("-"))
                {
                    Console.Error.WriteLine($"Unknown flag '{arg0}'");
                    UsageAndExit(1);
                }
                else if (!arg0.StartsWith("-"))
                {
                    break;
                }
                { argc--; argi++; } // shift-left
            }

            int startYear = int.Parse(start);
            int untilYear = int.Parse(until);

            // https://nodatime.org/3.0.x/userguide/tzdb
            IDateTimeZoneProvider provider;

            if (!string.IsNullOrEmpty(nzdFilePath))
            {
                // Read the TZDB file from disk.
                using (var stream = File.OpenRead(nzdFilePath))
                {
                    var source = TzdbDateTimeZoneSource.FromStream(stream);
                    provider = new DateTimeZoneCache(source);
                }
            }
            else
            {
                provider = DateTimeZoneProviders.Tzdb;
            }

            List <string> zones     = ReadZones();
            GenerateData  generator = new GenerateData(startYear, untilYear, provider);
            IDictionary <string, List <TestItem> > testData = generator.CreateTestData(zones);

            generator.PrintJson(testData);
        }
Ejemplo n.º 23
0
        public static IDateTimeZoneProvider LoadTzdb(string path = null)
        {
            IDateTimeZoneProvider provider;

            // Load the time zone database from a file, if specified.
            path = path ?? UtilityConfiguration.Active.TimeZoneDB;
            if (!string.IsNullOrWhiteSpace(path))
            {
                Uri uri = new Uri(path.TrimStart('\\', '/'), UriKind.RelativeOrAbsolute);
                if (!uri.IsAbsoluteUri)
                {
                    uri = new Uri(UtilityExtensions.AppDomainBaseUri, uri);
                }

                // If the URI is a file, load it from the file system, otherwise download it
                if (uri.IsFile)
                {
                    path = uri.LocalPath;
                    if (!File.Exists(path))
                    {
                        throw new FileNotFoundException(
                                  // ReSharper disable once AssignNullToNotNullAttribute
                                  string.Format(Resources.TimeHelper_TimeHelper_TimeZoneDB_Not_Found, path));
                    }

                    try
                    {
                        using (FileStream stream = File.OpenRead(path))
                            // ReSharper disable once AssignNullToNotNullAttribute
                            provider = new DateTimeZoneCache(TzdbDateTimeZoneSource.FromStream(stream));
                    }
                    catch (Exception e)
                    {
                        // ReSharper disable once AssignNullToNotNullAttribute
                        throw new FileLoadException(
                                  string.Format(Resources.TimeHelper_TimeHelper_TimeZoneDB_Failed, path),
                                  e);
                    }
                }
                else
                {
                    path = uri.AbsoluteUri;
                    try
                    {
                        // ReSharper disable AssignNullToNotNullAttribute
                        WebRequest request = WebRequest.Create(uri);
                        using (WebResponse response = request.GetResponse())
                            using (Stream stream = response.GetResponseStream())
                                provider = new DateTimeZoneCache(TzdbDateTimeZoneSource.FromStream(stream));
                        // ReSharper restore AssignNullToNotNullAttribute
                    }
                    catch (Exception e)
                    {
                        // ReSharper disable once AssignNullToNotNullAttribute
                        throw new FileLoadException(
                                  string.Format(Resources.TimeHelper_TimeHelper_TimeZoneDB_Failed, path),
                                  e);
                    }
                }
            }
            // ReSharper disable once AssignNullToNotNullAttribute
            else
            {
                // ReSharper disable once AssignNullToNotNullAttribute
                provider = DateTimeZoneProviders.Tzdb;
            }

            Debug.Assert(provider != null);

            return(provider);
        }