Exemplo n.º 1
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);
            }
        }
    }
Exemplo n.º 2
0
    // </Snippet1>

    // <Snippet2>
    private void SerializeException()
    {
        // Generate exception object so that it can be serialized
        try
        {
            Console.WriteLine("Attempting to load a non-existent time zone");
            TimeZoneInfo tZone = TimeZoneInfo.FindSystemTimeZoneById("Imaginary Time Zone");
            // Serialize time zone so it can be loaded by main routine
            string       tZoneString = tZone.ToSerializedString();
            StreamWriter fs          = new StreamWriter("TimeZoneNotFound.dat");
            fs.Write(tZoneString);
            fs.Close();
        }
        catch (TimeZoneNotFoundException e)
        {
            Console.WriteLine("A {0} has been thrown.", e.GetType().Name);
            // Create a new exception with an inner exception
            TimeZoneNotFoundException serializedException = new TimeZoneNotFoundException(
                "Attempting to load a non-existent time zone",
                e);
            // Serialize the exception to a file
            IFormatter exceptionFormatter = new SoapFormatter();
            Stream     exceptionStream    = new FileStream("tzNotFound.xml", FileMode.Create);
            exceptionFormatter.Serialize(exceptionStream, serializedException);
            exceptionStream.Close();
            Console.WriteLine("Serialized the exception object.");
        }
    }
Exemplo n.º 3
0
        public static void Ctor_String()
        {
            string message   = "New TimeZoneNotFoundException";
            var    exception = new TimeZoneNotFoundException(message);

            Assert.Equal(message, exception.Message);
        }
Exemplo n.º 4
0
        public static void Ctor_Empty()
        {
            var exception = new TimeZoneNotFoundException();

            Assert.NotNull(exception);
            Assert.NotEmpty(exception.Message);
        }
Exemplo n.º 5
0
Arquivo: Leo.cs Projeto: qiuosier/Leo
        public static string MillisecondsToLocalTimeString(Int64 milliseconds)
        {
            DateTime utc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(milliseconds);
            DateTime localTime;
            string   timezone = Environment.GetEnvironmentVariable("TimeZone");

            if (timezone != null)
            {
                try
                {
                    TimeZoneInfo tzInfo = TimeZoneInfo.FindSystemTimeZoneById(timezone);
                    localTime = TimeZoneInfo.ConvertTimeFromUtc(utc, tzInfo);
                }
                catch (Exception ex)
                {
                    if (ex.GetType() == typeof(TimeZoneNotFoundException))
                    {
                        string info = ex.Message + "\nAvailable Time Zones:\n";
                        ReadOnlyCollection <TimeZoneInfo> timeZones = TimeZoneInfo.GetSystemTimeZones();
                        foreach (TimeZoneInfo timeZone in timeZones)
                        {
                            info += $"{timeZone.Id}\n";
                        }
                        ex = new TimeZoneNotFoundException(info);
                    }
                    throw ex;
                }
            }
            else
            {
                localTime = utc;
            }

            return(localTime.ToShortTimeString());
        }
Exemplo n.º 6
0
        public static void Ctor_String_Exception()
        {
            string message        = "New TimeZoneNotFoundException";
            var    innerException = new Exception("Created inner exception");
            var    exception      = new TimeZoneNotFoundException(message, innerException);

            Assert.Equal(message, exception.Message);
            Assert.Equal(innerException, exception.InnerException);
            Assert.Equal(innerException.HResult, exception.InnerException.HResult);
        }
    public async Task GetValueProviderAsync_ThrowsOriginalException_IfReadingFormThrows()
    {
        // Arrange
        var exception            = new TimeZoneNotFoundException();
        var valueProviderContext = CreateThrowingContext(exception);

        var factory = new JQueryFormValueProviderFactory();

        // Act & Assert
        var ex = await Assert.ThrowsAsync <TimeZoneNotFoundException>(() => factory.CreateValueProviderAsync(valueProviderContext));

        Assert.Same(exception, ex);
    }
Exemplo n.º 8
0
        public async Task RenderRootComponentAsync_ReportsErrorDuringOnParameterSetAsync()
        {
            // Arrange
            var expected  = new TimeZoneNotFoundException();
            var renderer  = new TestRenderer();
            var component = new TestComponent {
                OnParametersSetAsyncLogic = _ => Task.FromException(expected)
            };

            // Act & Assert
            var componentId = renderer.AssignRootComponentId(component);
            var actual      = await Assert.ThrowsAsync <TimeZoneNotFoundException>(() => renderer.RenderRootComponentAsync(componentId));

            // Assert
            Assert.Same(expected, actual);
        }
Exemplo n.º 9
0
        private void Button_Click(object sender, EventArgs e)
        {
            try
            {
                A a = null;
                Console.WriteLine(a.name);
            }
            catch (Exception exception)
            {
                TimeZoneNotFoundException e2 = new TimeZoneNotFoundException(exception.Message + "Button1");
                Crashes.TrackError(e2);

                //var messageWithStacktraceId = exception.Message + $" Stack ID: [{exception.StackTrace.GetHashCode()}]";
                //var wrappedException = new WrappedException(messageWithStacktraceId, exception.StackTrace);

                //Crashes.TrackError(wrappedException, null);
            }
        }
Exemplo n.º 10
0
 private void Button2_Click(object sender, EventArgs e)
 {
     try
     {
         B b = null;
         Console.WriteLine(b.age);
     }
     catch (Exception exception)
     {
         if (i % 2 == 1)
         {
             TimeZoneNotFoundException e3 = new TimeZoneNotFoundException(exception.Message + "Error3");
             Crashes.TrackError(e3, null, new ErrorAttachmentLog[] { ErrorAttachmentLog.AttachmentWithText("1!", "hello.txt") });
         }
         else
         {
             TimeZoneNotFoundException e2 = new TimeZoneNotFoundException(exception.Message + "Error4");
             Crashes.TrackError(e2, null, new ErrorAttachmentLog[] { ErrorAttachmentLog.AttachmentWithText("2!", "hello.txt") });
         }
         i++;
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// Implementation of the ProcessRecord method for Get-TimeZone
        /// </summary>
        protected override void ProcessRecord()
        {
            // make sure we've got the latest time zone settings
            TimeZoneInfo.ClearCachedData();

            if (this.ParameterSetName.Equals("ListAvailable", StringComparison.OrdinalIgnoreCase))
            {
                // output the list of all available time zones
                WriteObject(TimeZoneInfo.GetSystemTimeZones(), true);
            }
            else if (this.ParameterSetName.Equals("Id", StringComparison.OrdinalIgnoreCase))
            {
                // lookup each time zone id
                foreach (string tzid in Id)
                {
                    try
                    {
                        WriteObject(TimeZoneInfo.FindSystemTimeZoneById(tzid));
                    }
                    catch (TimeZoneNotFoundException e)
                    {
                        WriteError(new ErrorRecord(e, TimeZoneHelper.TimeZoneNotFoundError,
                                                   ErrorCategory.InvalidArgument, "Id"));
                    }
                }
            }
            else // ParameterSetName == "Name"
            {
                if (null != Name)
                {
                    // lookup each time zone name (or wildcard pattern)
                    foreach (string tzname in Name)
                    {
                        TimeZoneInfo[] timeZones = TimeZoneHelper.LookupSystemTimeZoneInfoByName(tzname);
                        if (0 < timeZones.Length)
                        {
                            // manually process each object in the array, so if there is only a single
                            // entry then the returned type is TimeZoneInfo and not TimeZoneInfo[], and
                            // it can be pipelined to Set-TimeZone more easily
                            foreach (TimeZoneInfo timeZone in timeZones)
                            {
                                WriteObject(timeZone);
                            }
                        }
                        else
                        {
                            string message = string.Format(CultureInfo.InvariantCulture,
                                                           TimeZoneResources.TimeZoneNameNotFound, tzname);

                            Exception e = new TimeZoneNotFoundException(message);
                            WriteError(new ErrorRecord(e, TimeZoneHelper.TimeZoneNotFoundError,
                                                       ErrorCategory.InvalidArgument, "Name"));
                        }
                    }
                }
                else
                {
                    // return the current system local time zone
                    WriteObject(TimeZoneInfo.Local);
                }
            }
        }
Exemplo n.º 12
0
        protected override void ProcessRecord()
        {
            // make sure we've got fresh data, in case the requested time zone was added
            // to the system (registry) after our process was started
            TimeZoneInfo.ClearCachedData();

            // acquire a TimeZoneInfo if one wasn't supplied.
            if (this.ParameterSetName.Equals("Id", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    InputObject = TimeZoneInfo.FindSystemTimeZoneById(Id);
                }
                catch (TimeZoneNotFoundException e)
                {
                    ThrowTerminatingError(new ErrorRecord(
                                              e,
                                              TimeZoneHelper.TimeZoneNotFoundError,
                                              ErrorCategory.InvalidArgument,
                                              "Id"));
                }
            }
            else if (this.ParameterSetName.Equals("Name", StringComparison.OrdinalIgnoreCase))
            {
                // lookup the time zone name and make sure we have one (and only one) match
                TimeZoneInfo[] timeZones = TimeZoneHelper.LookupSystemTimeZoneInfoByName(Name);
                if (0 == timeZones.Length)
                {
                    string message = string.Format(CultureInfo.InvariantCulture,
                                                   TimeZoneResources.TimeZoneNameNotFound, Name);
                    Exception e = new TimeZoneNotFoundException(message);
                    ThrowTerminatingError(new ErrorRecord(e,
                                                          TimeZoneHelper.TimeZoneNotFoundError,
                                                          ErrorCategory.InvalidArgument,
                                                          "Name"));
                }
                else if (1 < timeZones.Length)
                {
                    string message = string.Format(CultureInfo.InvariantCulture,
                                                   TimeZoneResources.MultipleMatchingTimeZones, Name);
                    ThrowTerminatingError(new ErrorRecord(
                                              new PSArgumentException(message, "Name"),
                                              TimeZoneHelper.MultipleMatchingTimeZonesError,
                                              ErrorCategory.InvalidArgument,
                                              "Name"));
                }
                else
                {
                    InputObject = timeZones[0];
                }
            }
            else // ParameterSetName == "InputObject"
            {
                try
                {
                    // a TimeZoneInfo object was supplied, so use it to make sure we can find
                    // a backing system time zone, otherwise it's an error condition
                    InputObject = TimeZoneInfo.FindSystemTimeZoneById(InputObject.Id);
                }
                catch (TimeZoneNotFoundException e)
                {
                    ThrowTerminatingError(new ErrorRecord(
                                              e,
                                              TimeZoneHelper.TimeZoneNotFoundError,
                                              ErrorCategory.InvalidArgument,
                                              "InputObject"));
                }
            }

            if (ShouldProcess(TimeZoneTarget))
            {
                bool acquireAccess = false;
                try
                {
                    // check to see if permission to set the time zone is already enabled for this process
                    if (!HasAccess)
                    {
                        // acquire permissions to set the timezone
                        SetAccessToken(true);
                        acquireAccess = true;
                    }
                }
                catch (Win32Exception e)
                {
                    ThrowTerminatingError(new ErrorRecord(e,
                                                          TimeZoneHelper.InsufficientPermissionsError,
                                                          ErrorCategory.PermissionDenied, null));
                }

                try
                {
                    // construct and populate a new DYNAMIC_TIME_ZONE_INFORMATION structure
                    NativeMethods.DYNAMIC_TIME_ZONE_INFORMATION dtzi = new NativeMethods.DYNAMIC_TIME_ZONE_INFORMATION();
                    dtzi.Bias           -= (int)InputObject.BaseUtcOffset.TotalMinutes;
                    dtzi.StandardName    = InputObject.StandardName;
                    dtzi.DaylightName    = InputObject.DaylightName;
                    dtzi.TimeZoneKeyName = InputObject.Id;

                    // Request time zone transition information for the current year
                    NativeMethods.TIME_ZONE_INFORMATION tzi = new NativeMethods.TIME_ZONE_INFORMATION();
                    if (!NativeMethods.GetTimeZoneInformationForYear((ushort)DateTime.Now.Year, ref dtzi, ref tzi))
                    {
                        ThrowWin32Error();
                    }

                    // copy over the transition times
                    dtzi.StandardBias = tzi.StandardBias;
                    dtzi.StandardDate = tzi.StandardDate;
                    dtzi.DaylightBias = tzi.DaylightBias;
                    dtzi.DaylightDate = tzi.DaylightDate;

                    // set the new local time zone for the system
                    if (!NativeMethods.SetDynamicTimeZoneInformation(ref dtzi))
                    {
                        ThrowWin32Error();
                    }

                    // broadcast a WM_SETTINGCHANGE notification message to all top-level windows so that they
                    // know to update their notion of the current system time (and time zone) if applicable
                    int result = 0;
                    NativeMethods.SendMessageTimeout((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SETTINGCHANGE,
                                                     (IntPtr)0, "intl", NativeMethods.SMTO_ABORTIFHUNG, 5000, ref result);

                    // clear the time zone data or this PowerShell session
                    // will not recognize the new time zone settings
                    TimeZoneInfo.ClearCachedData();

                    if (PassThru.IsPresent)
                    {
                        // return the TimeZoneInfo object for the (new) current local time zone
                        WriteObject(TimeZoneInfo.Local);
                    }
                }
                catch (Win32Exception e)
                {
                    ThrowTerminatingError(new ErrorRecord(e,
                                                          TimeZoneHelper.SetTimeZoneFailedError,
                                                          ErrorCategory.FromStdErr, null));
                }
                finally
                {
                    if (acquireAccess)
                    {
                        // reset the permissions
                        SetAccessToken(false);
                    }
                }
            }
            else
            {
                if (PassThru.IsPresent)
                {
                    // show the user the time zone settings that would have been used.
                    WriteObject(InputObject);
                }
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Implementation of the ProcessRecord method for Get-TimeZone
        /// </summary>
        protected override void ProcessRecord()
        {
            // make sure we've got the latest time zone settings
            TimeZoneHelper.ClearCachedData();

            if (this.ParameterSetName.Equals("ListAvailable", StringComparison.OrdinalIgnoreCase))
            {
                // output the list of all available time zones
                WriteObject(TimeZoneInfo.GetSystemTimeZones(), true);
            }
            else if (this.ParameterSetName.Equals("Id", StringComparison.OrdinalIgnoreCase))
            {
                // lookup each time zone id
                foreach (string tzid in Id)
                {
                    try
                    {
                        WriteObject(TimeZoneInfo.FindSystemTimeZoneById(tzid));
                    }
#if CORECLR
                    // TimeZoneNotFoundException is thrown by TimeZoneInfo, but not
                    // publicly visible (so can't be caught), so for now we're catching
                    // the parent exception time. This should be removed once the more
                    // specific exception is available.
                    catch (Exception e)
#else
                    catch (TimeZoneNotFoundException e)
#endif
                    {
                        WriteError(new ErrorRecord(e, TimeZoneHelper.TimeZoneNotFoundError,
                                                   ErrorCategory.InvalidArgument, "Id"));
                    }
                }
            }
            else // ParameterSetName == "Name"
            {
                if (null != Name)
                {
                    // lookup each time zone name (or wildcard pattern)
                    foreach (string tzname in Name)
                    {
                        TimeZoneInfo[] timeZones = TimeZoneHelper.LookupSystemTimeZoneInfoByName(tzname);
                        if (0 < timeZones.Length)
                        {
                            // manually process each object in the array, so if there is only a single
                            // entry then the returned type is TimeZoneInfo and not TimeZoneInfo[], and
                            // it can be pipelined to Set-TimeZone more easily
                            foreach (TimeZoneInfo timeZone in timeZones)
                            {
                                WriteObject(timeZone);
                            }
                        }
                        else
                        {
                            string message = string.Format(CultureInfo.InvariantCulture,
                                                           TimeZoneResources.TimeZoneNameNotFound, tzname);
#if CORECLR
                            // Because .NET Core does not currently expose the TimeZoneNotFoundException
                            // we need to throw the more generic parent exception class for the time being.
                            // This should be removed once the correct exception class is available.
                            Exception e = new Exception(message);
#else
                            Exception e = new TimeZoneNotFoundException(message);
#endif
                            WriteError(new ErrorRecord(e, TimeZoneHelper.TimeZoneNotFoundError,
                                                       ErrorCategory.InvalidArgument, "Name"));
                        }
                    }
                }
                else
                {
                    // return the current system local time zone
                    WriteObject(TimeZoneInfo.Local);
                }
            }
        }