예제 #1
0
        public void SetPublicationTime(DateTime publicationDate, bool isLocal)
        {
            TimeZoneInfo.ClearCachedData();

            if (isLocal)
            {
                Globals.SitecoreAddin.Log("SetPublicationTime: Setting date field to [" + publicationDate.Date.ToString() + "].");
                uxWebPublishDate.Value = publicationDate.Date;
                Globals.SitecoreAddin.Log("SetPublicationTime: Setting time field to [" + publicationDate.TimeOfDay.ToString() + "].");
                uxWebPublishTime.Value = publicationDate;
            }
            else
            {
                Globals.SitecoreAddin.Log("SetPublicationTime: Date before DateTime conversion: [" +
                                          publicationDate.Date.ToString() + "].");
                Globals.SitecoreAddin.Log("SetPublicationTime: Time before DateTime conversion:  [" +
                                          publicationDate.TimeOfDay.ToString() + "].");

                //DateTime convertedTime = TimeZoneInfo.ConvertTime(publicationDate, TimeZoneInfo.Utc, TimeZoneInfo.Local);
                //DateTime convertedTime = TimeZoneInfo.ConvertTime(publicationDate, TimeZoneInfo.Utc).ToLocalTime();
                DateTime convertedTime = publicationDate;
                Globals.SitecoreAddin.Log("SetPublicationTime: Date after DateTime conversion: [" +
                                          convertedTime.Date.ToString() + "].");
                Globals.SitecoreAddin.Log("SetPublicationTime: Time after DateTime conversion:  [" +
                                          convertedTime.TimeOfDay.ToString() + "].");

                uxWebPublishDate.Value = convertedTime.Date;
                uxWebPublishTime.Value = convertedTime;
            }
        }
예제 #2
0
        public async Task SpecializeHostCoreAsync()
        {
            // Go async immediately to ensure that any async context from
            // the PlaceholderSpecializationMiddleware is properly suppressed.
            await Task.Yield();

            _logger.LogInformation(Resources.HostSpecializationTrace);

            // After specialization, we need to ensure that custom timezone
            // settings configured by the user (WEBSITE_TIME_ZONE) are honored.
            // DateTime caches timezone information, so we need to clear the cache.
            TimeZoneInfo.ClearCachedData();

            // Trigger a configuration reload to pick up all current settings
            _configuration?.Reload();

            _hostNameProvider.Reset();

            await _languageWorkerChannelManager.SpecializeAsync();

            NotifyChange();
            await _scriptHostManager.RestartHostAsync();

            await _scriptHostManager.DelayUntilHostReady();
        }
예제 #3
0
    private static void RestoreDates()
    {
        TimeZoneInfo.ClearCachedData();
        Console.WriteLine("Current Time Zone: {0}",
                          TimeZoneInfo.Local.DisplayName);
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
        StreamReader sr = new StreamReader(filename);

        string[] inputValues = sr.ReadToEnd().Split(new char[] { '|' },
                                                    StringSplitOptions.RemoveEmptyEntries);
        sr.Close();
        Console.WriteLine("The dates on an {0} system:",
                          Thread.CurrentThread.CurrentCulture.Name);
        foreach (var inputValue in inputValues)
        {
            DateTime dateValue;
            if (DateTime.TryParseExact(inputValue, "O", CultureInfo.InvariantCulture,
                                       DateTimeStyles.RoundtripKind, out dateValue))
            {
                Console.WriteLine("'{0}' --> {1:f}",
                                  inputValue, dateValue.ToLocalTime());
            }
            else
            {
                Console.WriteLine("Cannot parse '{0}'", inputValue);
            }
        }
        Console.WriteLine("Restored dates...");
    }
예제 #4
0
        private static void RestoreLocalDatesFromString()
        {
            TimeZoneInfo.ClearCachedData();
            Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}");
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
            StreamReader sr = new StreamReader(filenameTxt);

            string[] inputValues = sr.ReadToEnd().Split(new char[] { '|' },
                                                        StringSplitOptions.RemoveEmptyEntries);
            sr.Close();
            Console.WriteLine("The dates on an {0} system:",
                              Thread.CurrentThread.CurrentCulture.Name);
            foreach (var inputValue in inputValues)
            {
                DateTime dateValue;
                if (DateTime.TryParse(inputValue, out dateValue))
                {
                    Console.WriteLine($"'{inputValue}' --> {dateValue:f}");
                }
                else
                {
                    Console.WriteLine("Cannot parse '{inputValue}'");
                }
            }
            Console.WriteLine("Restored dates...");
        }
예제 #5
0
        public ActionResult NeedSomething(Request obj)
        {
            TimeZoneInfo.ClearCachedData();

            int      expHours = Convert.ToInt32(Regex.Match(obj.Expiration.ToString(), @"\d+").Value);
            DateTime now      = DateTime.Now;
            DateTime expTime  = now.AddHours(expHours);

            connection();
            SqlCommand com = new SqlCommand("AddRequest", con);

            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@Name", obj.Name);
            com.Parameters.AddWithValue("@Category", obj.Category);
            com.Parameters.AddWithValue("@Description", obj.Description);
            com.Parameters.AddWithValue("@Expiration", obj.Expiration);
            com.Parameters.AddWithValue("@Status", "pending");
            com.Parameters.AddWithValue("@ExpireTime", expTime);
            com.Parameters.AddWithValue("@NeighborhoodID", "2");

            con.Open();
            com.ExecuteNonQuery();
            con.Close();

            return(View());
        }
예제 #6
0
 /// <summary>
 ///
 /// </summary>
 protected override void OnInitialized()
 {
     TimeZoneInfo.ClearCachedData();
     TimezoneItems = TimeZoneInfo.GetSystemTimeZones().Select(i => new SelectedItem(i.Id, i.DisplayName));
     TimezoneId    = TimeZoneInfo.Local.Id;
     TimezoneValue = TimeZoneInfo.Local.BaseUtcOffset;
 }
예제 #7
0
        public static DateTime ObtemDataHoraSistema()
        {
            DateTime retorno;

            try
            {
                TimeZoneInformation tmznfo = new TimeZoneInformation();
                GetTimeZoneInformation(out tmznfo);

                SYSTEMTIME datahorasistema = new SYSTEMTIME();
                GetSystemTime(out datahorasistema);

                DateTime datalocal = new DateTime(datahorasistema.wYear, datahorasistema.wMonth, datahorasistema.wDay, datahorasistema.wHour, datahorasistema.wMinute, datahorasistema.wSecond, datahorasistema.wMilliseconds);

                TimeZoneInfo.ClearCachedData();
                TimeZoneInfo nfo = TimeZoneInfo.Local;

                datalocal = datalocal.AddMinutes(-tmznfo.bias);

                if (!nfo.IsDaylightSavingTime(datalocal))
                {
                    retorno = datalocal;
                }
                else
                {
                    retorno = datalocal.AddMinutes(-tmznfo.daylightBias);
                }
            }
            catch
            {
                retorno = DateTime.Now;
            }

            return(retorno);
        }
예제 #8
0
        /// <summary>
        /// 设置本地时区
        /// </summary>
        /// <param name="timeZoneName_en"></param>
        /// <returns></returns>
        public static bool SetLocalTimeZone(string timeZoneName_en)
        {
            if (PrivilegeAPI.GrantPrivilege(PrivilegeConstants.SE_TIME_ZONE_NAME))
            {
                DynamicTimeZoneInformation dtzi = timeZoneName2DynamicTimeZoneInformation(timeZoneName_en);
                bool success = false;

                // 检测当前系统是否为旧系统
                if (IsOldOsVersion())
                {
                    Console.WriteLine("检测当前系统为: Old OS Version");
                    TimeZoneInformation tzi = DynamicTimeZoneInformation2TimeZoneInformation(dtzi);
                    success = SetTimeZoneInformation(ref tzi);
                }
                else
                {
                    success = SetDynamicTimeZoneInformation(ref dtzi);
                }

                if (success)
                {
                    TimeZoneInfo.ClearCachedData();  // 清除缓存
                }

                if (!PrivilegeAPI.RevokePrivilege(PrivilegeConstants.SE_TIME_ZONE_NAME))
                {
                    Console.WriteLine("撤权失败: 更改时区");
                }

                return(success);
            }

            Console.WriteLine("授权失败: 更改时区");
            return(false);
        }
예제 #9
0
        /// <summary>
        /// 转化CST(北京)时间为GMT(也就是UTC时间)
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static DateTime CSTConvertToGMT(this DateTime dateTime)
        {
            TimeZoneInfo.ClearCachedData();
            TimeZoneInfo timeZoneSource      = TimeZoneInfo.FindSystemTimeZoneById(ConstName.Linux_ShangHaiTimeZoneId);
            TimeZoneInfo timeZoneDestination = TimeZoneInfo.FindSystemTimeZoneById("UTC");

            return(TimeZoneInfo.ConvertTime(dateTime, timeZoneSource, timeZoneDestination));
        }
예제 #10
0
        /// <summary>
        /// 服务器本地时间转换为北京时间(CST)
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static DateTime LoaclConvertToCST(this DateTime dateTime)
        {
            TimeZoneInfo.ClearCachedData();
            dateTime = DateTime.Now;
            TimeZoneInfo timeZoneSource      = TimeZoneInfo.Local;
            TimeZoneInfo timeZoneDestination = TimeZoneInfo.FindSystemTimeZoneById(ConstName.Linux_ShangHaiTimeZoneId);

            return(TimeZoneInfo.ConvertTime(dateTime, timeZoneSource, timeZoneDestination));
        }
예제 #11
0
 static Time()
 {
     TimeZoneInfo.ClearCachedData();
     System.Collections.ObjectModel.ReadOnlyCollection <TimeZoneInfo> stz = TimeZoneInfo.GetSystemTimeZones();
     foreach (TimeZoneInfo tzi in stz)
     {
         s_TimeZones.Add(tzi.Id, tzi);
     }
 }
예제 #12
0
        /// <summary>
        /// Clear the cached TimeZoneInfo data.  Note that since TimeZoneInfo.ClearCachedData
        /// does not exist in .NET Core there is an alternative mechanism (which doesn't seem
        /// to affect clearing out the cache under the full desktop version of .NET)
        /// </summary>
        internal static void ClearCachedData()
        {
#if CORECLR
            // NOTE: .NET Core does not expose the ClearCachedData method, but executing
            // the specific ConvertTime request below should have the same effect.
            TimeZoneInfo.ConvertTime(new DateTime(0), TimeZoneInfo.Local);
#else
            TimeZoneInfo.ClearCachedData();
#endif
        }
 private void TimeZoneChanged(object sender, EventArgs e)
 {
     TimeZoneInfo.ClearCachedData();
     if (TimeZoneInfo.Local.DisplayName != _currentTimezone)
     {
         ProcessCommand(ShutdownType);
         //to avoid error or non-shutdown/restart/log off operation
         OnCancel();
     }
 }
 public override void OnActivated(UIApplication uiApplication)
 {
     if (_application != null && _isSuspended)
     {
         _isSuspended = false;
         CultureInfo.CurrentCulture.ClearCachedData();
         TimeZoneInfo.ClearCachedData();
         _application.SendResume();
     }
 }
 public void ClearCachedData()
 {
     s_userDefaultUICulture         = null;
     s_userDefaultCulture           = null;
     RegionInfo.s_currentRegionInfo = null;
     TimeZone.ResetTimeZone();
     TimeZoneInfo.ClearCachedData();
     s_LcidCachedCultures = null;
     s_NameCachedCultures = null;
     CultureData.ClearCachedData();
 }
예제 #16
0
        public static void ClearCachedData()
        {
            TimeZoneInfo cst   = TimeZoneInfo.FindSystemTimeZoneById(s_strSydney);
            TimeZoneInfo local = TimeZoneInfo.Local;

            TimeZoneInfo.ClearCachedData();
            Assert.ThrowsAny <ArgumentException>(() =>
            {
                TimeZoneInfo.ConvertTime(DateTime.Now, local, cst);
            });
        }
예제 #17
0
        private void Init()
        {
            TimeZoneInfo.ClearCachedData();
            timeData              = Interface.Oxide.DataFileSystem.GetDatafile("WorkingMan/timeData");
            config                = Config.ReadObject <PluginConfig>();
            dayWarningThreshold1  = (int)config.minutesPerDay - (int)config.warningThreshold1;
            dayWarningThreshold2  = (int)config.minutesPerDay - (int)config.warningThreshold2;
            weekWarningThreshold1 = (int)config.minutesPerWeek - (int)config.warningThreshold1;
            weekWarningThreshold2 = (int)config.minutesPerWeek - (int)config.warningThreshold2;

            timer.Every(60f, UpdateLoop);
        }
예제 #18
0
 // about to become foreground, last minute preparatuin
 public override void OnActivated(UIApplication uiApplication)
 {
     // applicationDidBecomeActive
     // execute any OpenGL ES drawing calls
     if (_application != null && _isSuspended)
     {
         _isSuspended = false;
         CultureInfo.CurrentCulture.ClearCachedData();
         TimeZoneInfo.ClearCachedData();
         _application.SendResume();
     }
 }
예제 #19
0
        // TODO: FACAVAL (WEBHOOKS)
        //public WebHookReceiverManager GetWebHookReceiverManager(WebHostSettings settings)
        //{
        //    if (_activeReceiverManager != null)
        //    {
        //        return _activeReceiverManager;
        //    }

        //    lock (_syncLock)
        //    {
        //        EnsureInitialized(settings);

        //        return _activeReceiverManager ?? _standbyReceiverManager;
        //    }
        //}

        internal void EnsureInitialized(WebHostSettings settings)
        {
            if (!WebScriptHostManager.InStandbyMode)
            {
                // standby mode can only change from true to false
                // when standby mode changes, we reset all instances
                if (_activeHostManager == null)
                {
                    _settingsManager.Reset();

                    _activeScriptHostConfig = CreateScriptHostConfiguration(settings);
                    _activeHostManager      = new WebScriptHostManager(_activeScriptHostConfig, _secretManagerFactory, _eventManager, _settingsManager, settings, _router, _loggerFactoryBuilder);
                    //_activeReceiverManager = new WebHookReceiverManager(_activeHostManager.SecretManager);
                    InitializeFileSystem();

                    if (_standbyHostManager != null)
                    {
                        // we're starting the one and only one
                        // standby mode specialization
                        _activeScriptHostConfig.TraceWriter.Info(Resources.HostSpecializationTrace);

                        // After specialization, we need to ensure that custom timezone
                        // settings configured by the user (WEBSITE_TIME_ZONE) are honored.
                        // DateTime caches timezone information, so we need to clear the cache.
                        TimeZoneInfo.ClearCachedData();
                    }

                    if (_standbyHostManager != null)
                    {
                        _standbyHostManager.Stop();
                        _standbyHostManager.Dispose();
                    }
                    //_standbyReceiverManager?.Dispose();
                    _standbyScriptHostConfig = null;
                    _standbyHostManager      = null;
                    //_standbyReceiverManager = null;
                }
            }
            else
            {
                if (_standbyHostManager == null)
                {
                    var standbySettings = CreateStandbySettings(settings);
                    _standbyScriptHostConfig = CreateScriptHostConfiguration(standbySettings, true);
                    _standbyHostManager      = new WebScriptHostManager(_standbyScriptHostConfig, _secretManagerFactory, _eventManager, _settingsManager, standbySettings, _router, _loggerFactoryBuilder);
                    // _standbyReceiverManager = new WebHookReceiverManager(_standbyHostManager.SecretManager);

                    InitializeFileSystem();
                    StandbyManager.Initialize(_standbyScriptHostConfig);
                }
            }
        }
예제 #20
0
        private static void RestoreDatesAsInts()
        {
            TimeZoneInfo.ClearCachedData();
            Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}");
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
            FileStream   fs = new FileStream(filenameInts, FileMode.Open);
            BinaryReader br = new BinaryReader(fs);
            int          items;

            DateTime[] dates;

            try
            {
                items = br.ReadInt32();
                dates = new DateTime[items];

                for (int ctr = 0; ctr < items; ctr++)
                {
                    long ticks = br.ReadInt64();
                    dates[ctr] = new DateTime(ticks).ToLocalTime();
                }
            }
            catch (EndOfStreamException)
            {
                Console.WriteLine("File corruption detected. Unable to restore data...");
                return;
            }
            catch (IOException)
            {
                Console.WriteLine("Unspecified I/O error. Unable to restore data...");
                return;
            }
            // Thrown during array initialization.
            catch (OutOfMemoryException)
            {
                Console.WriteLine("File corruption detected. Unable to restore data...");
                return;
            }
            finally
            {
                br.Close();
            }

            Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:");
            foreach (var value in dates)
            {
                Console.WriteLine(value.ToString("f"));
            }

            Console.WriteLine("Restored dates...");
        }
예제 #21
0
        /// <summary>
        /// Get the end of month day date and time.
        /// </summary>
        /// <returns>
        ///  end of month day date and time
        /// </returns>
        public static IType EOMonth()
        {
            TimeZoneInfo.ClearCachedData();
            TimeZoneInfo tz = TimeZoneInfo.Local;

            tz = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id);
            DateTime today          = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tz);
            DateTime endOfMonth     = new DateTime(today.Year, today.Month, 1).AddMonths(2).AddDays(-1);
            var      bankNow        = TimeZoneInfo.ConvertTimeFromUtc(endOfMonth, tz);
            var      processingDate = bankNow.Date;
            var      timeToRun      = TimeZoneInfo.ConvertTimeToUtc(processingDate.AddDays(1), tz);

            return(DataType.Create(DataType.DateTime, timeToRun, CultureInfo.InvariantCulture));
        }
 private void OnStart()
 {
     try
     {
         TimeZoneInfo.ClearCachedData();
         _currentTimezone          = TimeZoneInfo.Local.DisplayName;
         SystemEvents.TimeChanged += TimeZoneChanged;
         IsRunning = true;
         IsEnabled = false;
     }
     catch (Exception ex)
     {
         OnErrorOccured(ex.Message);
     }
 }
예제 #23
0
        public static void SetSystemTimeZone(string timeZoneId)
        {
            var process = Process.Start(new ProcessStartInfo
            {
                FileName        = "tzutil.exe",
                Arguments       = "/s \"" + timeZoneId + "\"",
                UseShellExecute = false,
                CreateNoWindow  = true
            });

            if (process != null)
            {
                process.WaitForExit();
                TimeZoneInfo.ClearCachedData();
            }
        }
예제 #24
0
파일: CultureInfo.cs 프로젝트: relaxar/.net
        public void ClearCachedData()
        {
            // reset the default culture values
            s_userDefaultCulture   = GetUserDefaultCulture();
            s_userDefaultUICulture = GetUserDefaultUICulture();

            RegionInfo.s_currentRegionInfo = null;
            #pragma warning disable 0618 // disable the obsolete warning
            TimeZone.ResetTimeZone();
            #pragma warning restore 0618
            TimeZoneInfo.ClearCachedData();
            s_LcidCachedCultures = null;
            s_NameCachedCultures = null;

            CultureData.ClearCachedData();
        }
예제 #25
0
        public void ClearCachedData()
        {
            lock (shared_table_lock) {
                shared_by_number = null;
                shared_by_name   = null;
            }

            //
            // ClearCachedData method does not refresh the information in
            // the Thread.CurrentCulture property for existing threads
            //
            default_current_culture = null;

            RegionInfo.ClearCachedData();
            TimeZone.ClearCachedData();
            TimeZoneInfo.ClearCachedData();
        }
예제 #26
0
        public async Task SpecializeHostCoreAsync()
        {
            _logger.LogInformation(Resources.HostSpecializationTrace);

            // After specialization, we need to ensure that custom timezone
            // settings configured by the user (WEBSITE_TIME_ZONE) are honored.
            // DateTime caches timezone information, so we need to clear the cache.
            TimeZoneInfo.ClearCachedData();

            // Trigger a configuration reload to pick up all current settings
            _configuration?.Reload();

            NotifyChange();

            await _scriptHostManager.RestartHostAsync();

            await _scriptHostManager.DelayUntilHostReady();
        }
예제 #27
0
        public static DateTime GetClientTime()
        {
            DateTime vLocalTime = DateTime.Now;

            TimeZoneInfo cst   = TimeZoneInfo.FindSystemTimeZoneById(TimeZone.CurrentTimeZone.StandardName);
            TimeZoneInfo local = TimeZoneInfo.Local;

            vLocalTime = TimeZoneInfo.ConvertTime(DateTime.Now, local, cst);

            TimeZoneInfo.ClearCachedData();
            try
            {
                return(TimeZoneInfo.ConvertTime(DateTime.Now, local, cst));
            }
            catch
            {
                return(vLocalTime);
            }
        }
    private void NoCachedReferences()
    {
        // <Snippet1>
        TimeZoneInfo cst   = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
        TimeZoneInfo local = TimeZoneInfo.Local;

        Console.WriteLine(TimeZoneInfo.ConvertTime(DateTime.Now, local, cst));

        TimeZoneInfo.ClearCachedData();
        try
        {
            Console.WriteLine(TimeZoneInfo.ConvertTime(DateTime.Now, local, cst));
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e.GetType().Name + "\n   " + e.Message);
        }
        // </Snippet1>
    }
예제 #29
0
        private static void RestoreDatesBinary()
        {
            TimeZoneInfo.ClearCachedData();
            Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}");
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");

            FileStream      fs    = new FileStream(filenameBin, FileMode.Open);
            BinaryFormatter bin   = new BinaryFormatter();
            var             dates = (DateTime[])bin.Deserialize(fs);

            fs.Close();

            Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:");
            foreach (var value in dates)
            {
                Console.WriteLine(value.ToLocalTime().ToString("f"));
            }

            Console.WriteLine("Restored dates...");
        }
        public async Task SpecializeHostCoreAsync()
        {
            // Go async immediately to ensure that any async context from
            // the PlaceholderSpecializationMiddleware is properly suppressed.
            await Task.Yield();

            _logger.LogInformation(Resources.HostSpecializationTrace);

            // After specialization, we need to ensure that custom timezone
            // settings configured by the user (WEBSITE_TIME_ZONE) are honored.
            // DateTime caches timezone information, so we need to clear the cache.
            TimeZoneInfo.ClearCachedData();

            // Trigger a configuration reload to pick up all current settings
            _configuration?.Reload();

            _hostNameProvider.Reset();

            // Reset the shared load context to ensure we're reloading
            // user dependencies
            FunctionAssemblyLoadContext.ResetSharedContext();

            // Signals change of JobHost options from placeholder mode
            // (ex: ScriptPath is updated)
            NotifyChange();

            using (_metricsLogger.LatencyEvent(MetricEventNames.SpecializationLanguageWorkerChannelManagerSpecialize))
            {
                await _rpcWorkerChannelManager.SpecializeAsync();
            }

            using (_metricsLogger.LatencyEvent(MetricEventNames.SpecializationRestartHost))
            {
                await _scriptHostManager.RestartHostAsync();
            }

            using (_metricsLogger.LatencyEvent(MetricEventNames.SpecializationDelayUntilHostReady))
            {
                await _scriptHostManager.DelayUntilHostReady();
            }
        }