public void DeserializeAndUseEasternTimeZone()
        {
            var et       = TimeZoneInfo.FromSerializedString(@"Eastern Standard Time;-300;(UTC-05:00) Eastern Time (US & Canada);Eastern Standard Time;Eastern Daylight Time;[01:01:0001;12:31:2006;60;[0;02:00:00;4;1;0;];[0;02:00:00;10;5;0;];][01:01:2007;12:31:9999;60;[0;02:00:00;3;2;0;];[0;02:00:00;11;1;0;];];");
            var testDate = new DateTime(2014, 8, 1, 6, 0, 0, DateTimeKind.Unspecified);

            Assert.AreEqual(TimeSpan.FromHours(-4), et.GetUtcOffset(testDate));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// To load the state of paper trading parameters.
        /// </summary>
        /// <param name="storage">Storage.</param>
        public virtual void Load(SettingsStorage storage)
        {
            DepthExpirationTime       = storage.GetValue(nameof(DepthExpirationTime), DepthExpirationTime);
            MatchOnTouch              = storage.GetValue(nameof(MatchOnTouch), MatchOnTouch);
            Failing                   = storage.GetValue(nameof(Failing), Failing);
            Latency                   = storage.GetValue(nameof(Latency), Latency);
            IsSupportAtomicReRegister = storage.GetValue(nameof(IsSupportAtomicReRegister), IsSupportAtomicReRegister);
            BufferTime                = storage.GetValue(nameof(BufferTime), BufferTime);
            //UseCandlesTimeFrame = storage.GetValue(nameof(UseCandlesTimeFrame), UseCandlesTimeFrame);
            InitialOrderId          = storage.GetValue(nameof(InitialOrderId), InitialOrderId);
            InitialTradeId          = storage.GetValue(nameof(InitialTradeId), InitialTradeId);
            InitialTransactionId    = storage.GetValue(nameof(InitialTransactionId), InitialTransactionId);
            SpreadSize              = storage.GetValue(nameof(SpreadSize), SpreadSize);
            MaxDepth                = storage.GetValue(nameof(MaxDepth), MaxDepth);
            VolumeMultiplier        = storage.GetValue(nameof(VolumeMultiplier), VolumeMultiplier);
            PortfolioRecalcInterval = storage.GetValue(nameof(PortfolioRecalcInterval), PortfolioRecalcInterval);
            ConvertTime             = storage.GetValue(nameof(ConvertTime), ConvertTime);
            PriceLimitOffset        = storage.GetValue(nameof(PriceLimitOffset), PriceLimitOffset);
            IncreaseDepthVolume     = storage.GetValue(nameof(IncreaseDepthVolume), IncreaseDepthVolume);

            if (storage.Contains(nameof(TimeZone)))
            {
                TimeZone = TimeZoneInfo.FromSerializedString(storage.GetValue <string>(nameof(TimeZone)));
            }
        }
Ejemplo n.º 3
0
        private async Task <CheckResult> Check(string standartCode, string homologationCode, string timeZone)
        {
            var homologation = await _homologationRepository.GetByCode(homologationCode);

            var standart = await(homologation != null
                ? _standartRepository.GetByCode(homologation.StandartId.ToString())
                : _standartRepository.GetByCode(standartCode));

            var timeZoneInfo = TimeZoneInfo.FromSerializedString(timeZone);

            if (timeZoneInfo == null)
            {
                timeZoneInfo = TimeZoneInfo.Utc;
            }

            var dateTimeNowClient = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, timeZoneInfo);

            if (standart == null)
            {
                return(FailedCheck(dateTimeNowClient));
            }

            if (standart != null && (standart.EndDate <= dateTimeNowClient || standart.StartDate > dateTimeNowClient))
            {
                return(FailedCheck(dateTimeNowClient));
            }

            if (homologation != null && homologation.HomologationItems.Any(x => x.EndDate <= dateTimeNowClient || x.StartDate > dateTimeNowClient))
            {
                return(WarningCheck(homologation, standart, dateTimeNowClient));
            }

            return(SuccessCheck(homologation, standart, dateTimeNowClient));
        }
Ejemplo n.º 4
0
    // </Snippet2>

    // <Snippet3>
    private void DeserializeException()
    {
        TimeZoneInfo timeZone;

        try
        {
            Console.WriteLine("Attempting to load a non-existent time zone again");
            timeZone = TimeZoneInfo.FindSystemTimeZoneById("Imaginary Time Zone");
        }
        catch (TimeZoneNotFoundException)
        {
            try
            {
                // Attempt to deserialize time zone to throw FileNotFoundException
                StreamReader reader   = new StreamReader("TimeZoneInfo.dat");
                string       contents = reader.ReadToEnd();
                reader.Close();
                timeZone = TimeZoneInfo.FromSerializedString(contents);
                Console.WriteLine(timeZone.Id);
            }
            catch (FileNotFoundException eInner)
            {
                Console.WriteLine(eInner.GetType().Name);
                // file not found, therefore object not serialized:
                // deserialize original exception information
                Console.WriteLine("Deserializing the original exception.");
                FileStream exceptionStream    = new FileStream("tzNotFound.xml", FileMode.Open);
                IFormatter exceptionFormatter = new SoapFormatter();
                TimeZoneNotFoundException serializedException =
                    exceptionFormatter.Deserialize(exceptionStream) as TimeZoneNotFoundException;
                Console.WriteLine("Original error message: {0}", serializedException.Message);
            }
        }
    }
Ejemplo n.º 5
0
        /// <summary>
        /// To load the state of paper trading parameters.
        /// </summary>
        /// <param name="storage">Storage.</param>
        public virtual void Load(SettingsStorage storage)
        {
            DepthExpirationTime       = storage.GetValue("DepthExpirationTime", DepthExpirationTime);
            MatchOnTouch              = storage.GetValue("MatchOnTouch", MatchOnTouch);
            Failing                   = storage.GetValue("Failing", Failing);
            Latency                   = storage.GetValue("Latency", Latency);
            IsSupportAtomicReRegister = storage.GetValue("IsSupportAtomicReRegister", IsSupportAtomicReRegister);
            BufferTime                = storage.GetValue("BufferTime", BufferTime);
            //UseCandlesTimeFrame = storage.GetValue("UseCandlesTimeFrame", UseCandlesTimeFrame);
            InitialOrderId          = storage.GetValue("InitialOrderId", InitialOrderId);
            InitialTradeId          = storage.GetValue("InitialTradeId", InitialTradeId);
            InitialTransactionId    = storage.GetValue("InitialTransactionId", InitialTransactionId);
            SpreadSize              = storage.GetValue("SpreadSize", SpreadSize);
            MaxDepth                = storage.GetValue("MaxDepth", MaxDepth);
            VolumeMultiplier        = storage.GetValue("VolumeMultiplier", VolumeMultiplier);
            PortfolioRecalcInterval = storage.GetValue("PortfolioRecalcInterval", PortfolioRecalcInterval);
            ConvertTime             = storage.GetValue("ConvertTime", ConvertTime);
            PriceLimitOffset        = storage.GetValue("PriceLimitOffset", PriceLimitOffset);
            IncreaseDepthVolume     = storage.GetValue("IncreaseDepthVolume", IncreaseDepthVolume);

            if (storage.Contains("TimeZone"))
            {
                TimeZone = TimeZoneInfo.FromSerializedString(storage.GetValue <string>("TimeZone"));
            }
        }
Ejemplo n.º 6
0
        public static void ToSerializedString_FromSerializedString_RoundTrips(TimeZoneInfo timeZone)
        {
            string       serialized           = timeZone.ToSerializedString();
            TimeZoneInfo deserializedTimeZone = TimeZoneInfo.FromSerializedString(serialized);

            Assert.Equal(timeZone, deserializedTimeZone);
            Assert.Equal(serialized, deserializedTimeZone.ToSerializedString());
        }
Ejemplo n.º 7
0
        public static Tuple <TimeZoneInfo, DateTime> ReadLocalDate(this IValueReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            return(new Tuple <TimeZoneInfo, DateTime> (TimeZoneInfo.FromSerializedString(reader.ReadString()),
                                                       new DateTime(reader.ReadInt64(), DateTimeKind.Unspecified)));
        }
Ejemplo n.º 8
0
 public static TimeZoneInfo GetTimeZoneInfo([NotNull] this IStorage storage, [NotNull, LocalizationRequired(false)] string key)
 {
     try {
         var value = storage.GetString(key);
         return(value == null ? null : TimeZoneInfo.FromSerializedString(value));
     } catch (Exception e) {
         Logging.Error(e);
         return(null);
     }
 }
        public void DeserializeUtc()
        {
            var utc = TimeZoneInfo.FromSerializedString("UTC;0;UTC;UTC;UTC;;");

            Assert.AreEqual("UTC", utc.Id);
            Assert.AreEqual("UTC", utc.DisplayName);
            Assert.AreEqual("UTC", utc.StandardName);
            Assert.IsFalse(utc.SupportsDaylightSavingTime);
            Assert.AreEqual(0, utc.GetAdjustmentRules().Length);
        }
    // <Snippet4>
    private TimeZoneInfo InitializeTimeZone()
    {
        TimeZoneInfo southPole = null;

        // Determine if South Pole time zone is defined in system
        try
        {
            southPole = TimeZoneInfo.FindSystemTimeZoneById("Antarctica/South Pole Standard Time");
        }
        // Time zone does not exist; create it, store it in a text file, and return it
        catch
        {
            const string filename = @".\TimeZoneInfo.txt";
            bool         found    = false;

            if (File.Exists(filename))
            {
                StreamReader reader = new StreamReader(filename);
                string       timeZoneInfo;
                while (reader.Peek() >= 0)
                {
                    timeZoneInfo = reader.ReadLine();
                    if (timeZoneInfo.Contains("Antarctica/South Pole"))
                    {
                        southPole = TimeZoneInfo.FromSerializedString(timeZoneInfo);
                        reader.Close();
                        found = true;
                        break;
                    }
                }
            }
            if (!found)
            {
                // Define transition times to/from DST
                TimeZoneInfo.TransitionTime startTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 1, DayOfWeek.Sunday);
                TimeZoneInfo.TransitionTime endTransition   = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 3, DayOfWeek.Sunday);
                // Define adjustment rule
                TimeSpan delta = new TimeSpan(1, 0, 0);
                TimeZoneInfo.AdjustmentRule adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1989, 10, 1), DateTime.MaxValue.Date, delta, startTransition, endTransition);
                // Create array for adjustment rules
                TimeZoneInfo.AdjustmentRule[] adjustments = { adjustment };
                // Define other custom time zone arguments
                string   displayName  = "(GMT+12:00) Antarctica/South Pole";
                string   standardName = "Antarctica/South Pole Standard Time";
                string   daylightName = "Antarctica/South Pole Daylight Time";
                TimeSpan offset       = new TimeSpan(12, 0, 0);
                southPole = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, displayName, standardName, daylightName, adjustments);
                // Write time zone to the file
                StreamWriter writer = new StreamWriter(filename, true);
                writer.WriteLine(southPole.ToSerializedString());
                writer.Close();
            }
        }
        return(southPole);
    }
Ejemplo n.º 11
0
 static DateTimeConverter()
 {
     try
     {
         _timeZone = TimeZoneInfo.FindSystemTimeZoneById("FLE Standard Time");
     }
     catch
     {
         _timeZone = TimeZoneInfo.FromSerializedString("FLE Standard Time;120;(UTC+02:00) Вільнюс, Гельсінкі, Київ, Рига, Софія, Таллінн;Фінляндія (зима);Фінляндія (літо);[01:01:0001;12:31:9999;60;[0;03:00:00;3;5;0;];[0;04:00:00;10;5;0;];];");
     }
 }
 [Category("NotWorking")] // https://github.com/dotnet/coreclr/issues/20837
 public void SystemTimeZoneSerializationTests()
 {
     foreach (var tmz in TimeZoneInfo.GetSystemTimeZones())
     {
         var tmzClone = TimeZoneInfo.FromSerializedString(tmz.ToSerializedString());
         Assert.AreEqual(tmz, tmzClone);
         Assert.AreEqual(tmz.DisplayName, tmzClone.DisplayName);
         Assert.AreEqual(tmz.StandardName, tmzClone.StandardName);
         Assert.AreEqual(tmz.SupportsDaylightSavingTime, tmzClone.SupportsDaylightSavingTime);
         Assert.AreEqual(tmz.DaylightName, tmzClone.DaylightName);
     }
 }
        public async Task <TimeZoneInfo> FindSystemTimeZoneByIdAsync(string timeZoneId)
        {
            IHttpRestRequest request = GetRequest(APIControllerRoutes.GlobalisationController.GETTIMEZONEINFOBYID, HttpMethod.Post);

            request.AddJsonBody(timeZoneId);

            IHttpRestResponse response = await ExecuteAsync(request).ConfigureAwait(false);

            var timeZoneString = response.Content;

            return(TimeZoneInfo.FromSerializedString(timeZoneString));
        }
        public TimeZoneInfo FindSystemTimeZoneById(string timeZoneId)
        {
            IHttpRestRequest request = GetRequest(APIControllerRoutes.GlobalisationController.GETTIMEZONEINFOBYID, HttpMethod.Post);

            request.AddJsonBody(timeZoneId);

            IHttpRestResponse response = Execute(request);

            var timeZoneString = response.Content;

            return(TimeZoneInfo.FromSerializedString(timeZoneString));
        }
Ejemplo n.º 15
0
        private static ReadOnlyCollection <TimeZoneInfo> ReadTimeZonesFromEmbeddedResource()
        {
            Type timeZoneType = typeof(TimeZones);
            var  timeZones    = new List <TimeZoneInfo>();

            using (var reader = new StreamReader(timeZoneType.Assembly.GetManifestResourceStream(timeZoneType.FullName + ".txt")))
            {
                while (!reader.EndOfStream)
                {
                    timeZones.Add(TimeZoneInfo.FromSerializedString(reader.ReadLine()));
                }
            }
            return(new ReadOnlyCollection <TimeZoneInfo>(timeZones));
        }
Ejemplo n.º 16
0
        public static TimeZoneInfo TryFromSerializedStringOrDefault(string timezoneId)
        {
            TimeZoneInfo result;

            try
            {
                result = TimeZoneInfo.FromSerializedString(timezoneId);
            }
            catch (Exception e)
            {
                result = TimeZoneInfo.FindSystemTimeZoneById(DefaultTimeZoneId);
            }

            return(result);
        }
Ejemplo n.º 17
0
 private static DateTime ConvertUtcTime(DateTime utcDate, TimeZoneInfo tz)
 {
     // Use time zone object from registry
     if (utcDate.Year > 1917)
     {
         return(TimeZoneInfo.ConvertTimeFromUtc(utcDate, tz));
     }
     // Handle dates before introduction of DST
     else
     {
         // Restore serialized time zone object
         tz = TimeZoneInfo.FromSerializedString(serializedEst);
         return(TimeZoneInfo.ConvertTimeFromUtc(utcDate, tz));
     }
 }
Ejemplo n.º 18
0
        public TimeZoneInfo GetCurrenTimeZone()
        {
            TimeZoneInfo tif = null;

            try
            {
                tif = TimeZoneInfo.FromSerializedString(_sttings.ReadSetting(SettingsNames.TimeZone));
            }
            catch
            {
                // ignored
            }
            if (tif == null)
            {
                tif = TimeZoneInfo.Local;
                _sttings.WriteSettings(SettingsNames.TimeZone, tif.ToSerializedString());
            }
            return(tif);
        }
 /// <summary>
 /// Give a string that corresponds to a TimeZoneInfo Id or ToString representation,
 /// or to one of our simplified representations, return the corresponding TimeZoneInfo.
 /// </summary>
 public static TimeZoneInfo TimeZoneInfoFromStdString(string standardString)
 {
     if (standardString.Equals(_sEST))
     {
         return(TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
     }
     else if (standardString.Equals(_sCST))
     {
         return(TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));
     }
     else if (standardString.Equals(_sMST))
     {
         return(TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time"));
     }
     else if (standardString.Equals(_sPST))
     {
         return(TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"));
     }
     return(TimeZoneInfo.FromSerializedString(standardString));
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Constructor for <see cref="CampaignTimerElement"/>.
 /// </summary>
 /// <param name="source">Instance of <see cref="CampaignTimerElement"/>.</param>
 /// <param name="dictToRebind">Dictionary to rebind schema elements' ids.</param>
 /// <param name="parentSchema">Parent campaign schema.</param>
 public CampaignTimerElement(CampaignTimerElement source, Dictionary <Guid, Guid> dictToRebind,
                             Core.Campaign.CampaignSchema parentSchema) : base(source, dictToRebind, parentSchema)
 {
     ExpressionType   = source.ExpressionType;
     StartDateTime    = source.StartDateTime;
     UseStartDateTime = source.UseStartDateTime;
     EndDateTime      = source.EndDateTime;
     UseEndDateTime   = source.UseEndDateTime;
     PeriodStartTime  = source.PeriodStartTime;
     PeriodEndTime    = source.PeriodEndTime;
     ExactTime        = source.ExactTime;
     UseExactTime     = source.UseExactTime;
     CronExpression   = source.CronExpression?.Clone() as CronExpression
                        ?? new CronExpression(DefaultCronExpression);
     UseCustomTimeZone = source.UseCustomTimeZone;
     if (source.TimeZoneOffset != null)
     {
         TimeZoneOffset = TimeZoneInfo.FromSerializedString(source.TimeZoneOffset.ToSerializedString());
     }
 }
        public void DeserializeCustomZoneWithOddNamingAndMultipleDaylightRules()
        {
            var rule1 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1, 1, 1), new DateTime(2012, 12, 31), TimeSpan.FromMinutes(23), TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 15, 59, 999), 3, 2, DayOfWeek.Tuesday), TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 15, 59, 999), 6, 2, DayOfWeek.Tuesday));
            var rule2 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2013, 1, 1), new DateTime(9999, 12, 31), TimeSpan.FromMinutes(48), TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 15, 59, 999), 3, 2, DayOfWeek.Tuesday), TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 15, 59, 999), 6, 2, DayOfWeek.Tuesday));

            var tz1 = TimeZoneInfo.FromSerializedString("My\\; Zone 5;-405;My Zone\\; 5 Name;My Zone 5\\; Standard Time;My Zone 5 Daylight\\; Time;[01:01:0001;12:31:2012;23;[0;02:15:59.999;3;2;2;];[0;02:15:59.999;6;2;2;];][01:01:2013;12:31:9999;48;[0;02:15:59.999;3;2;2;];[0;02:15:59.999;6;2;2;];];");

            Assert.AreEqual("My; Zone 5", tz1.Id);
            Assert.AreEqual("My Zone; 5 Name", tz1.DisplayName);
            Assert.AreEqual("My Zone 5; Standard Time", tz1.StandardName);
            Assert.AreEqual("My Zone 5 Daylight; Time", tz1.DaylightName);
            Assert.AreEqual(TimeSpan.FromMinutes(-405), tz1.BaseUtcOffset);
            Assert.IsTrue(tz1.SupportsDaylightSavingTime);

            var deserializedRules = tz1.GetAdjustmentRules();

            Assert.AreEqual(2, deserializedRules.Length);
            Assert.IsFalse(deserializedRules [0].Equals(deserializedRules [1]));
            Assert.IsFalse(rule1.Equals(deserializedRules [0]));
            Assert.IsFalse(rule2.Equals(deserializedRules [1]));
        }
Ejemplo n.º 22
0
 public void HeaderValidator <T>(T model) where T : FullHeader_BindingModel
 {
     if (!Languages.Contains(CultureInfo.GetCultureInfoByIetfLanguageTag(model.Language)))
     {
         model.Language = new CultureInfo("en-US").IetfLanguageTag;
         //BadRequest(_stringLocalizer[SharedResource.UnsupportedLanguage]);
     }
     if (!TimeZones.Contains(TimeZoneInfo.FromSerializedString(model.TimeZone)))
     {
         model.TimeZone = TimeZoneInfo.Utc.ToSerializedString();
         //BadRequest(_stringLocalizer[SharedResource.UnsupportedTimeZone]);
     }
     if (!string.IsNullOrWhiteSpace(model.Token))
     {
         BadRequest(_stringLocalizer[SharedResource.TokenNotFound]);
     }
     if (!string.IsNullOrWhiteSpace(model.DeviceId))
     {
         BadRequest(_stringLocalizer[SharedResource.DeviceIdNotFound]);
     }
 }
Ejemplo n.º 23
0
 public ITrigger Build(string id, Dictionary <string, string> properties)
 {
     return(TriggerBuilder.Create().WithCronSchedule(properties.GetValue(SwarmConts.CronProperty),
                                                     bd =>
     {
         var tzpStr = properties.GetValue(SwarmConts.TimeZoneProperty);
         if (string.IsNullOrWhiteSpace(tzpStr))
         {
             return;
         }
         try
         {
             var tzp = TimeZoneInfo.FromSerializedString(tzpStr);
             bd.InTimeZone(tzp);
         }
         catch
         {
             throw new SwarmException("TimeZone string is uncorrected");
         }
     })
            .WithIdentity(id).Build());
 }
Ejemplo n.º 24
0
 private static JobDescriptor ToJobDescriptor(Job job)
 {
     return(new JobDescriptor
     {
         Id = job.Id.ToString(),
         Name = job.Name,
         // Cron = job.Cron,
         Scheduled = job.Scheduled,
         TimeZone = job.TimeZone == null
             ? null
             : TimeZoneInfo.FromSerializedString(job.TimeZone),
         Status = job.Status,
         Call = new JobCall
         {
             Type = job.Type,
             Method = job.Method,
             Returns = job.Returns,
             IsStatic = job.IsStatic,
             Arguments = DeserializeArguments(job.Parameters, job.Arguments)
         }
     });
 }
Ejemplo n.º 25
0
        public GetTimeZones()
        {
#if _WINDOWS
            string[] serializedTimezones = timeZones.Select(x => x.ToSerializedString()).ToArray();
            SaveAndLoad.SaveFile(serializedTimezones, Program.DataPath, "timezones.json");
#else
            string[] deserializedTimeZones;
            SaveAndLoad.LoadFile(out deserializedTimeZones, Program.DataPath, "timezones.json");

            if (deserializedTimeZones == null || deserializedTimeZones.Length == 0)
            {
                timeZones = new TimeZoneInfo[] { };
                return;
            }
            else
            {
                timeZones = deserializedTimeZones
                            .Select(x => TimeZoneInfo.FromSerializedString(x))
                            .ToArray();
            }
#endif
        }
Ejemplo n.º 26
0
    // </Snippet1>

    // <Snippet3>
    private void DeserializeTimeZones()
    {
        TimeZoneInfo    cst, palmer;
        string          timeZoneString;
        ResourceManager resMgr = new ResourceManager("SerializeTimeZoneData.SerializedTimeZones", this.GetType().Assembly);

        // Attempt to retrieve time zone from system
        try
        {
            cst = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
        }
        catch (TimeZoneNotFoundException)
        {
            // Time zone not in system; retrieve from resource
            timeZoneString = resMgr.GetString("CentralStandardTime");
            if (!String.IsNullOrEmpty(timeZoneString))
            {
                cst = TimeZoneInfo.FromSerializedString(timeZoneString);
            }
            else
            {
                MessageBox.Show("Unable to create Central Standard Time Zone. Application must exit.", "Application Error");
                return;
            }
        }
        // Retrieve custom time zone
        try
        {
            timeZoneString = resMgr.GetString("PalmerStandardTime");
            palmer         = TimeZoneInfo.FromSerializedString(timeZoneString);
        }
        catch (MissingManifestResourceException)
        {
            MessageBox.Show("Unable to retrieve the Palmer Standard Time Zone from the resource file. Application must exit.");
            return;
        }
    }
Ejemplo n.º 27
0
        public static TimeInfo Read(string s)
        {
            try
            {
                XDocument xDoc = XDocument.Parse(s);

                TimeZoneInfo tzi = TimeZoneInfo.FromSerializedString(xDoc.Element("TimeInfo").Attribute("TimeZoneInfo").Value);

                TimeInfo ti = new TimeInfo(tzi);

                string displayName = xDoc.Element("TimeInfo").Attribute("DisplayName").Value.Trim();

                if (displayName != string.Empty)
                {
                    ti.DisplayName = displayName;
                }

                return(ti);
            }
            catch
            {
                return(null);
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        ///     Create new instance of <see cref="ObjectMapper" />.
        /// </summary>
        public ObjectMapper()
        {
            var assemblyName = new AssemblyName("Dextrys_ILEmit_TypeMaps");

            _moduleBuilder =
                AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName,
                                                              AssemblyBuilderAccess.RunAndSave)
                .DefineDynamicModule(assemblyName.Name, assemblyName.Name + ".dll", false);
            _converters = new ConverterCollection(this);
            _converters.Add(new PrimitiveConverter {
                Intrinsic = true
            });
            _converters.Add(new ObjectToStringConverter {
                Intrinsic = true
            });
            _converters.Add(new FromStringConverter {
                Intrinsic = true
            });

            #region bool Converters

            // sbyte -> bool
            Converters.AddIntrinsic((sbyte source) => source != 0);
            // byte -> bool
            Converters.AddIntrinsic((byte source) => source != 0);
            // char -> bool
            Converters.AddIntrinsic((char source) => source != 0);
            // int -> bool
            Converters.AddIntrinsic((int source) => source != 0);
            // uint -> bool
            Converters.AddIntrinsic((uint source) => source != 0);
            // long -> bool
            Converters.AddIntrinsic((long source) => source != 0);
            // ulong -> bool
            Converters.AddIntrinsic((ulong source) => source != 0);
            // short -> bool
            Converters.AddIntrinsic((short source) => source != 0);
            // ushort -> bool
            Converters.AddIntrinsic((ushort source) => source != 0);
            // decimal -> bool
            Converters.AddIntrinsic((decimal source) => source != 0);
            // float -> bool
            Converters.AddIntrinsic((float source) => source != 0);
            // double -> bool
            Converters.AddIntrinsic((double source) => source != 0);

            // bool -> int
            Converters.AddIntrinsic((bool source) => (source ? 1 : 0));
            // bool -> char
            Converters.AddIntrinsic((bool source) => source ? 'T' : 'F');
            // bool -> byte
            Converters.AddIntrinsic((bool source) => (byte)(source ? 1 : 0));
            // bool -> short
            Converters.AddIntrinsic((bool source) => (short)(source ? 1 : 0));
            // bool -> ushort
            Converters.AddIntrinsic((bool source) => (ushort)(source ? 1 : 0));
            // bool -> uint
            Converters.AddIntrinsic((bool source) => (uint)(source ? 1 : 0));
            // bool -> long
            Converters.AddIntrinsic((bool source) => (long)(source ? 1 : 0));
            // bool -> ulong
            Converters.AddIntrinsic((bool source) => (ulong)(source ? 1 : 0));
            // bool -> decimal
            Converters.AddIntrinsic((bool source) => (decimal)(source ? 1 : 0));
            // bool -> float
            Converters.AddIntrinsic((bool source) => (float)(source ? 1 : 0));
            // bool -> double
            Converters.AddIntrinsic((bool source) => (double)(source ? 1 : 0));
            // bool -> sbyte
            Converters.AddIntrinsic((bool source) => (sbyte)(source ? 1 : 0));

            #endregion

            #region DateTime Converters

            // DateTime -> long
            Converters.AddIntrinsic((DateTime source) => source.Ticks);
            // DateTime -> ulong
            Converters.AddIntrinsic((DateTime source) => (ulong)source.Ticks);

            // sbyte -> DateTime
            Converters.AddIntrinsic((sbyte source) => new DateTime(source));
            // byte -> DateTime
            Converters.AddIntrinsic((byte source) => new DateTime(source));
            // char -> DateTime
            Converters.AddIntrinsic((char source) => new DateTime(source));
            // int -> DateTime
            Converters.AddIntrinsic((int source) => new DateTime(source));
            // uint -> DateTime
            Converters.AddIntrinsic((uint source) => new DateTime(source));
            // long -> DateTime
            Converters.AddIntrinsic((long source) => new DateTime(source));
            // ulong -> DateTime
            Converters.AddIntrinsic((ulong source) => new DateTime((long)source));
            // short -> DateTime
            Converters.AddIntrinsic((short source) => new DateTime(source));
            // ushort -> DateTime
            Converters.AddIntrinsic((ushort source) => new DateTime(source));
            // decimal -> DateTime
            Converters.AddIntrinsic((decimal source) => new DateTime((long)source));
            // float -> DateTime
            Converters.AddIntrinsic((float source) => new DateTime((long)source));
            // double -> DateTime
            Converters.AddIntrinsic((double source) => new DateTime((long)source));

            #endregion

            #region TimeSpan Converters

            // TimeSpan -> long
            Converters.AddIntrinsic((TimeSpan source) => source.Ticks);
            // TimeSpan -> ulong
            Converters.AddIntrinsic((TimeSpan source) => (ulong)source.Ticks);

            // sbyte -> TimeSpan
            Converters.AddIntrinsic((sbyte source) => new TimeSpan(source));
            // byte -> TimeSpan
            Converters.AddIntrinsic((byte source) => new TimeSpan(source));
            // char -> TimeSpan
            Converters.AddIntrinsic((char source) => new TimeSpan(source));
            // int -> TimeSpan
            Converters.AddIntrinsic((int source) => new TimeSpan(source));
            // uint -> TimeSpan
            Converters.AddIntrinsic((uint source) => new TimeSpan(source));
            // long -> TimeSpan
            Converters.AddIntrinsic((long source) => new TimeSpan(source));
            // ulong -> TimeSpan
            Converters.AddIntrinsic((ulong source) => new TimeSpan((long)source));
            // short -> TimeSpan
            Converters.AddIntrinsic((short source) => new TimeSpan(source));
            // ushort -> TimeSpan
            Converters.AddIntrinsic((ushort source) => new TimeSpan(source));
            // decimal -> TimeSpan
            Converters.AddIntrinsic((decimal source) => new TimeSpan((long)source));
            // float -> TimeSpan
            Converters.AddIntrinsic((float source) => new TimeSpan((long)source));
            // double -> TimeSpan
            Converters.AddIntrinsic((double source) => new TimeSpan((long)source));

            #endregion

            #region Byte Array Converters

            // bool -> byte[]
            Converters.AddIntrinsic((bool source) => BitConverter.GetBytes(source));
            // byte[] -> bool
            Converters.AddIntrinsic((byte[] source) => source != null && BitConverter.ToBoolean(source, 0));

            // char -> byte[]
            Converters.AddIntrinsic((char source) => BitConverter.GetBytes(source));
            // byte[] -> char
            Converters.AddIntrinsic((byte[] source) => source == null ? '\0' : BitConverter.ToChar(source, 0));

            // double -> byte[]
            Converters.AddIntrinsic((double source) => BitConverter.GetBytes(source));
            // byte[] -> double
            Converters.AddIntrinsic((byte[] source) => source == null ? (double)0 : BitConverter.ToDouble(source, 0));

            // float -> byte[]
            Converters.AddIntrinsic((float source) => BitConverter.GetBytes(source));
            // byte[] -> float
            Converters.AddIntrinsic((byte[] source) => source == null ? (float)0 : BitConverter.ToSingle(source, 0));

            // short -> byte[]
            Converters.AddIntrinsic((short source) => BitConverter.GetBytes(source));
            // byte[] -> short
            Converters.AddIntrinsic((byte[] source) => source == null ? (short)0 : BitConverter.ToInt16(source, 0));

            // ushort -> byte[]
            Converters.AddIntrinsic((ushort source) => BitConverter.GetBytes(source));
            // byte[] -> ushort
            Converters.AddIntrinsic((byte[] source) => source == null ? (ushort)0 : BitConverter.ToUInt16(source, 0));

            // int -> byte[]
            Converters.AddIntrinsic((int source) => BitConverter.GetBytes(source));
            // byte[] -> int
            Converters.AddIntrinsic((byte[] source) => source == null ? 0 : BitConverter.ToInt32(source, 0));

            // uint -> byte[]
            Converters.AddIntrinsic((uint source) => BitConverter.GetBytes(source));
            // byte[] -> uint
            Converters.AddIntrinsic((byte[] source) => source == null ? (uint)0 : BitConverter.ToUInt32(source, 0));

            // long -> byte[]
            Converters.AddIntrinsic((long source) => BitConverter.GetBytes(source));
            // byte[] -> long
            Converters.AddIntrinsic((byte[] source) => source == null ? (long)0 : BitConverter.ToInt64(source, 0));

            // ulong -> byte[]
            Converters.AddIntrinsic((ulong source) => BitConverter.GetBytes(source));
            // byte[] -> ulong
            Converters.AddIntrinsic((byte[] source) => source == null ? (ulong)0 : BitConverter.ToUInt64(source, 0));

            #endregion

            #region Spartial

            Converters.AddIntrinsic((DbGeography source) => source);
            Converters.AddIntrinsic((DbGeography source) => source == null ? null : source.AsText());
            Converters.AddIntrinsic((DbGeography source) => source == null ? null : source.AsBinary());
            Converters.AddIntrinsic((string source) => string.IsNullOrWhiteSpace(source) ? null : DbGeography.FromText(source));
            Converters.AddIntrinsic((DbGeography source) => source.AsBinary());
            Converters.AddIntrinsic((byte[] source) => source == null ? null : DbGeography.FromBinary(source));

            Converters.AddIntrinsic((DbGeometry source) => source);
            Converters.AddIntrinsic((DbGeometry source) => source.AsText());
            Converters.AddIntrinsic((string source) => string.IsNullOrWhiteSpace(source) ? null : DbGeometry.FromText(source));
            Converters.AddIntrinsic((DbGeometry source) => source.AsBinary());
            Converters.AddIntrinsic((byte[] source) => source == null ? null : DbGeometry.FromBinary(source));

            #endregion

            #region Misc Converters

            // DateTime -> DateTimeOffset
            Converters.AddIntrinsic((DateTime source) => new DateTimeOffset(source));
            // Guid -> byte[]
            Converters.AddIntrinsic((Guid source) => source.ToByteArray());
            // byte[] -> Guid
            Converters.AddIntrinsic((byte[] source) => source == null ? Guid.Empty : new Guid(source));
            // byte[] -> IPAddress
            Converters.AddIntrinsic((byte[] source) => source != null ? new IPAddress(source) : null);
            // IPAddress -> byte[]
            Converters.AddIntrinsic((IPAddress source) => source == null ? (byte[])null : source.GetAddressBytes());
            // Type -> string
            Converters.AddIntrinsic((Type source) => source == null ? null : source.AssemblyQualifiedName);
            // TimeZoneInfo -> string
            Converters.AddIntrinsic((TimeZoneInfo source) => source == null ? null : source.ToSerializedString());

            // string -> Uri
            Converters.AddIntrinsic((string source) => string.IsNullOrWhiteSpace(source) ? null : new Uri(source.Trim()));
            // string -> Type
            Converters.AddIntrinsic(
                (string source) =>
                string.IsNullOrWhiteSpace(source)
                        ? null
                        : HostingEnvironment.IsHosted ? BuildManager.GetType(source, true) : Type.GetType(source.Trim(), true));
            // string -> TimeZoneInfo
            Converters.AddIntrinsic(
                (string source) => string.IsNullOrWhiteSpace(source) ? null : TimeZoneInfo.FromSerializedString(source.Trim()));

            #endregion

            Conventions.Add <MatchNameConvention>();
        }
Ejemplo n.º 29
0
 public UserTimeProvider(LocalStorageService localStorage)
 {
     _localStorage   = localStorage;
     _serverTimeZone = TimeZoneInfo.FromSerializedString("Eastern Standard Time;-300;(UTC-05:00) Eastern Time (US & Canada);Eastern Standard Time;Eastern Daylight Time;[01:01:0001;12:31:2006;60;[0;02:00:00;4;1;0;];[0;02:00:00;10;5;0;];][01:01:2007;12:31:9999;60;[0;02:00:00;3;2;0;];[0;02:00:00;11;1;0;];];");
     _ = InitializeAsync();
 }
Ejemplo n.º 30
0
        private void RefreshOutput()
        {
            // Since date.
            var sinceDate      = Convert.ToDateTime(Config.SinceDate);
            var sinceTotalDays = Convert.ToInt32(Math.Floor((DateTime.Now - sinceDate).TotalDays));

            if (sinceTotalDays > 0)
            {
                lblDaysSince.Text = String.Format("It's been {0} days since {1}.", sinceTotalDays, sinceDate.ToLongDateString());
            }
            else if (sinceTotalDays == 0)
            {
                lblDaysSince.Text = String.Format("Today is the day of the since date, {0}.", sinceDate.ToLongDateString());
            }
            else
            {
                lblDaysSince.Text = "Error: the since date is in the future.";
            }

            // Countdown date.
            var countdownDateEnabled = Convert.ToBoolean(Config.CountdownDateEnabled);

            if (countdownDateEnabled)
            {
                grpDateCountdown.Visible = true;

                var countdownDate       = Convert.ToDateTime(Config.CountdownDate);
                var countdownTotalDays  = Math.Ceiling((countdownDate - DateTime.Now).TotalDays);
                var countdownDifference = DateTime.Compare(countdownDate, DateTime.Now);

                if (countdownDifference > 0)
                {
                    lblDateCountdown.Text = String.Format("There are {0} days left until {1}.", countdownTotalDays, countdownDate.ToLongDateString());
                }
                else if (countdownDate.Date == DateTime.Now.Date)
                {
                    lblDateCountdown.Text = String.Format("Today is the day of the countdown date, {0}.", countdownDate.ToLongDateString());
                }
                else
                {
                    lblDateCountdown.Text = String.Format("Today is pass the countdown date, {0}, which was {1} days ago.", countdownDate.ToLongDateString(), Convert.ToInt32(Math.Floor((DateTime.Now - countdownDate).TotalDays)));
                }
            }
            else
            {
                grpDateCountdown.Visible = false;
            }

            // Time zones.
            var timeZonesEnabled = Convert.ToBoolean(Config.TimeZonesEnabled);

            if (timeZonesEnabled)
            {
                grpTimeZones.Visible = true;

                _timeZone1 = TimeZoneInfo.FromSerializedString(Config.TimeZone1);
                _timeZone2 = TimeZoneInfo.FromSerializedString(Config.TimeZone2);

                RefreshTimeZones();

                tmrTimeZones.Enabled = true;
                tmrTimeZones.Start();
            }
            else
            {
                grpTimeZones.Visible = false;
                tmrTimeZones.Enabled = false;
                tmrTimeZones.Stop();
            }

            // Update display to fit the height of visible group boxes.
            const short SPACE  = 10;
            int         height = mnuMain.Height;

            grpDaysSince.Top = height + SPACE;
            height          += grpDaysSince.Top + grpDaysSince.Height + SPACE;

            if (countdownDateEnabled)
            {
                grpDateCountdown.Top = grpDaysSince.Top + grpDaysSince.Height + SPACE;
                height += SPACE + grpDateCountdown.Height;
            }

            if (timeZonesEnabled)
            {
                if (countdownDateEnabled)
                {
                    grpTimeZones.Top = grpDateCountdown.Top + grpDateCountdown.Height + SPACE;
                }
                else
                {
                    grpTimeZones.Top = grpDaysSince.Top + grpDaysSince.Height + SPACE;
                }

                height += SPACE + grpTimeZones.Height;
            }

            Height = height + (SPACE * 2);
        }