public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Using ctor1 to test the message property");

        try
        {
            string randValue = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH);
            ArgumentOutOfRangeException argumentOutOfRangeException = new ArgumentOutOfRangeException(randValue);
            if ((argumentOutOfRangeException.Message != "Specified argument was out of the range of valid values." + TestLibrary.Env.NewLine + "Parameter name: " + randValue) &
                (!argumentOutOfRangeException.Message.Contains("[Arg_ArgumentOutOfRangeException]")))
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: Call ctor with a null argument to construct a new instance");

        try
        {
            string randValue = null;
            ArgumentOutOfRangeException argumentOutOfRangeException = new ArgumentOutOfRangeException(randValue);
            if (argumentOutOfRangeException == null)
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
                retVal = false;
            }
            if ((argumentOutOfRangeException.Message != "Specified argument was out of the range of valid values.") &
                (!argumentOutOfRangeException.Message.Contains("[Arg_ArgumentOutOfRangeException]")))
            {
                TestLibrary.TestFramework.LogError("005", "The result is not the value as expected" + argumentOutOfRangeException.Message);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Call ctor with a random string argument to construct a new instance");

        try
        {
            string randValue = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH);
            ArgumentOutOfRangeException argumentOutOfRangeException = new ArgumentOutOfRangeException(randValue);
            if (argumentOutOfRangeException == null)
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
                retVal = false;
            }
            if ((argumentOutOfRangeException.Message != "Specified argument was out of the range of valid values."+Environment.NewLine+"Parameter name: " + randValue) &
                (!argumentOutOfRangeException.Message.Contains("[Arg_ArgumentOutOfRangeException]")))
            {
                TestLibrary.TestFramework.LogError("002", "The result is not the value as expected" + argumentOutOfRangeException.Message);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
示例#4
0
            public void TakeMustBeGreaterThanZero()
            {
                var expectedEx = new ArgumentOutOfRangeException("take", 0, Exceptions.ArgumentNotGreaterThanValue.FormatWith(0));
                var actualEx = Assert.Throws<ArgumentOutOfRangeException>(() => new Page(0, 0));

                Assert.Equal(expectedEx.Message, actualEx.Message);
            }
            public void MustOverrideWithUtcTime()
            {
                var expectedEx = new ArgumentOutOfRangeException("timeRetriever", DateTimeKind.Local, Exceptions.ArgumentNotEqualToValue.FormatWith(DateTimeKind.Utc));
                var actualEx = Assert.Throws<ArgumentOutOfRangeException>(() => SystemTime.OverrideWith(() => DateTime.Now));

                Assert.Equal(expectedEx.Message, actualEx.Message);
            }
            public void VersionMustBeGreaterThanZero()
            {
                var expectedEx = new ArgumentOutOfRangeException("version", 0, Exceptions.ArgumentNotGreaterThanValue.FormatWith(0));
                var actualEx = Assert.Throws<ArgumentOutOfRangeException>(() => new Snapshot(Guid.NewGuid(), 0, new Object()));

                Assert.Equal(expectedEx.Message, actualEx.Message);
            }
示例#7
0
            public void SkipMustBeGreaterThanOrEqualToZero()
            {
                var expectedEx = new ArgumentOutOfRangeException("skip", -1, Exceptions.ArgumentNotGreaterThanOrEqualToValue.FormatWith(0));
                var actualEx = Assert.Throws<ArgumentOutOfRangeException>(() => new Page(-1, 10));

                Assert.Equal(expectedEx.Message, actualEx.Message);
            }
    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: Using ctor2 to test the message property");

        try
        {
            string randValue = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH);
            string paramName = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH);
            ArgumentOutOfRangeException argumentOutOfRangeException = new ArgumentOutOfRangeException(paramName, randValue);
            if ((argumentOutOfRangeException.Message != randValue + "" + TestLibrary.Env.NewLine + "Parameter name: " + paramName) &
                (argumentOutOfRangeException.Message != randValue))
            {
                TestLibrary.TestFramework.LogError("003", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
            public void PageSizeMustBeGreaterThanZero()
            {
                var expectedEx = new ArgumentOutOfRangeException("pageSize", 0, Exceptions.ArgumentNotGreaterThanValue.FormatWith(0));
                var actualEx = Assert.Throws<ArgumentOutOfRangeException>(() => new PagedResult<Object>(0, (lastResult, page) => Enumerable.Empty<Object>()));

                Assert.Equal(expectedEx.Message, actualEx.Message);
            }
    public static StringBuilder Substring(this StringBuilder stringBuilder, int startIndex)
    {
        ArgumentOutOfRangeException outOfRangeException = new ArgumentOutOfRangeException("No such index!", "You must enter positive number smaller than the size of the collection");
        if (startIndex < 0 || startIndex >= stringBuilder.Length)
        {
            throw outOfRangeException;
        }

        string build = stringBuilder.ToString().Substring(startIndex);

        stringBuilder.Clear();
        stringBuilder.Append(build);

        return stringBuilder;
    }
 static int ReadNumberInRange(int start, int end)
 {
     int number = 0;
     try
     {
         number = int.Parse(Console.ReadLine());
         if ((number < start) || (number > end))
         {
             ArgumentOutOfRangeException outOfRange = new ArgumentOutOfRangeException();
             Console.WriteLine("Error: {0}", outOfRange.Message);
         }
     }
     catch (FormatException fe)
     {
         Console.Error.WriteLine("Error: {0}", fe.Message);
     }
     return number;
 }
示例#12
0
 static int ReadNumberInRange(int start, int end)
 {
     int number = 0;
     try
     {
         number = int.Parse(Console.ReadLine());
         if ((number < start) || (number > end))
         {
             ArgumentOutOfRangeException outOfRange = new ArgumentOutOfRangeException();
             Console.WriteLine("Error: {0}", outOfRange.Message);
             Console.WriteLine("Each next number should be smaller than the previous one!");
         }
     }
     catch (FormatException fe)
     {
         Console.Error.WriteLine("Error: {0}", fe.Message);
         //Console.WriteLine("Invalid input! Please enter a number!");
     }
     return number;
 }
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Call ctor to construct a new instance");

        try
        {
            ArgumentOutOfRangeException argumentOutOfRangeException = new ArgumentOutOfRangeException();
            if (argumentOutOfRangeException == null)
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
        } // GetScopeByID

        /// <summary>
        /// Given a scope ID, walks the scope list to the appropriate scope and returns it.
        /// </summary>
        ///
        /// <param name="scopeID">
        /// The numeric indexer to the scope relative to the current scope.
        /// </param>
        ///
        /// <returns>
        /// The scope at the index specified.  The index is relative to the current
        /// scope.
        /// </returns>
        ///
        /// <exception cref="ArgumentOutOfRangeException">
        /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
        /// active scopes.
        /// </exception>
        ///
        internal SessionStateScope GetScopeByID(int scopeID)
        {
            SessionStateScope processingScope = _currentScope;
            int originalID = scopeID;

            while (scopeID > 0 && processingScope != null)
            {
                processingScope = processingScope.Parent;
                scopeID--;
            }

            if (processingScope == null && scopeID >= 0)
            {
                ArgumentOutOfRangeException outOfRange =
                    PSTraceSource.NewArgumentOutOfRangeException(
                        "scopeID",
                        originalID,
                        SessionStateStrings.ScopeIDExceedsAvailableScopes,
                        originalID);
                throw outOfRange;
            }

            return processingScope;
        } // GetScopeByID
示例#15
0
        /// <summary>
        /// Executes an availability test for a Url
        /// </summary>
        /// <param name="log"></param>
        /// <param name="testName"></param>
        /// <param name="uri"></param>
        /// <returns></returns>
        private async static Task RunAvailbiltyTestAsync(ILogger log, HttpClient client, AvailabilityTest test, EndPoint endpoint, TelemetryClient telemetryClient)
        {
            if (null == test)
            {
                Exception ex = new ArgumentOutOfRangeException("test", "The 'test' object is null.");
                log.LogError($"Invalid Test Settings : {ex.Message}");
                throw ex;
            }
            if (null == telemetryClient)
            {
                Exception ex = new ArgumentOutOfRangeException("telemetryClient", "The 'telemetryClient' object is null.");
                log.LogError($"Invalid Test Settings : {ex.Message}");
                throw ex;
            }
            if (null == endpoint)
            {
                Exception ex = new ArgumentOutOfRangeException("telemetryClient", "The 'telemetryClient' object is null.");
                log.LogError($"Invalid Test Settings : {ex.Message}");
                throw ex;
            }

            if (String.IsNullOrEmpty(endpoint.Name))
            {
                Exception ex = new ArgumentOutOfRangeException("Name", "No 'Name' was provided in the config.");
                log.LogError($"Invalid Test Settings : {ex.Message}");
                throw ex;
            }

            Uri goodUri = null;

            Uri.TryCreate(endpoint.PageUrl, UriKind.Absolute, out goodUri);
            if (null == goodUri)
            {
                Exception ex = new ArgumentOutOfRangeException("uri", $"The provided uri {endpoint.PageUrl} is invalid.");
                log.LogError($"Invalid Test Settings : {ex.Message}");
                throw ex;
            }

            //setup the telemetry
            string operationId  = Guid.NewGuid().ToString("N");
            var    availability = new AvailabilityTelemetry
            {
                Id          = operationId,
                Name        = $"{test.ApplicationName} : {endpoint.Name}",
                RunLocation = System.Environment.MachineName,
                Success     = false
            };

            //start the timer
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            //try it
            try
            {
                await ExecuteWebGet(log, availability, client, goodUri).ConfigureAwait(false);
            }
            catch (HttpRequestException ex)
            {
                //grab the inner exception if the Request fails outright
                availability.Message = ex.InnerException.Message;

                var exceptionTelemetry = new ExceptionTelemetry(ex);
                exceptionTelemetry.Context.Operation.Id = operationId;
                exceptionTelemetry.Properties.Add("TestName", endpoint.Name);
                exceptionTelemetry.Properties.Add("TestLocation", System.Environment.MachineName);
                telemetryClient.TrackException(exceptionTelemetry);
            }
            catch (Exception ex)
            {
                availability.Message = ex.Message;

                var exceptionTelemetry = new ExceptionTelemetry(ex);
                exceptionTelemetry.Context.Operation.Id = operationId;
                exceptionTelemetry.Properties.Add("TestName", endpoint.Name);
                exceptionTelemetry.Properties.Add("TestLocation", System.Environment.MachineName);
                telemetryClient.TrackException(exceptionTelemetry);
            }
            finally
            {
                stopwatch.Stop();
                availability.Duration  = stopwatch.Elapsed;
                availability.Timestamp = DateTimeOffset.UtcNow;
                telemetryClient.TrackAvailability(availability);
                // call flush to ensure telemetry is sent
                telemetryClient.Flush();
            }
        }
        public static Exception ToIotHubClientContract(Error error)
        {
            Exception retException;

            if (error == null)
            {
                retException = new IotHubException("Unknown error.");
                return(retException);
            }

            string message = error.Description;

            string trackingId = null;

            if (error.Info != null && error.Info.TryGetValue(AmqpIotConstants.TrackingId, out trackingId))
            {
                message = "{0}{1}{2}".FormatInvariant(message, Environment.NewLine, "Tracking Id:" + trackingId);
            }

            if (error.Condition.Equals(TimeoutError))
            {
                retException = new TimeoutException(message);
            }
            else if (error.Condition.Equals(AmqpErrorCode.NotFound))
            {
                retException = new DeviceNotFoundException(message, (Exception)null);
            }
            else if (error.Condition.Equals(AmqpErrorCode.NotImplemented))
            {
                retException = new NotSupportedException(message);
            }
            else if (error.Condition.Equals(MessageLockLostError))
            {
                retException = new DeviceMessageLockLostException(message);
            }
            else if (error.Condition.Equals(AmqpErrorCode.NotAllowed))
            {
                retException = new InvalidOperationException(message);
            }
            else if (error.Condition.Equals(AmqpErrorCode.UnauthorizedAccess))
            {
                retException = new UnauthorizedException(message);
            }
            else if (error.Condition.Equals(ArgumentError))
            {
                retException = new ArgumentException(message);
            }
            else if (error.Condition.Equals(ArgumentOutOfRangeError))
            {
                retException = new ArgumentOutOfRangeException(message);
            }
            else if (error.Condition.Equals(AmqpErrorCode.MessageSizeExceeded))
            {
                retException = new MessageTooLargeException(message);
            }
            else if (error.Condition.Equals(AmqpErrorCode.ResourceLimitExceeded))
            {
                // Note: The DeviceMaximumQueueDepthExceededException is not supposed to be thrown here as it is being mapped to the incorrect error code
                // Error code 403004 is only applicable to C2D (Service client); see https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-troubleshoot-error-403004-devicemaximumqueuedepthexceeded
                // Error code 403002 is applicable to D2C (Device client); see https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-troubleshoot-error-403002-iothubquotaexceeded
                // We have opted not to change the exception type thrown here since it will be a breaking change, alternatively, we are adding the correct exception type
                // as the inner exception.
                retException = new DeviceMaximumQueueDepthExceededException(
                    $"Please check the inner exception for more information.\n " +
                    $"The correct exception type is `{nameof(QuotaExceededException)}` " +
                    $"but since that is a breaking change to the current behavior in the SDK, you can refer to the inner exception " +
                    $"for more information. Exception message: {message}",
                    new QuotaExceededException(message));
            }
            else if (error.Condition.Equals(DeviceContainerThrottled))
            {
                retException = new IotHubThrottledException(message, null);
            }
            else if (error.Condition.Equals(IotHubSuspended))
            {
                retException = new IotHubSuspendedException(message);
            }
            else
            {
                retException = new IotHubException(message);
            }

            if (trackingId != null && retException is IotHubException)
            {
                var iotHubException = (IotHubException)retException;
                iotHubException.TrackingId = trackingId;
            }
            return(retException);
        }
示例#17
0
 public virtual void NegativePreallocationSizeThrows()
 {
     string filePath = GetTestFilePath();
     ArgumentOutOfRangeException ex = Assert.Throws <ArgumentOutOfRangeException>(
         () => CreateFileStream(filePath, FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 1, FileOptions.None, preallocationSize: -1));
 }
示例#18
0
 public virtual void NegativePreallocationSizeThrows()
 {
     string filePath = GetPathToNonExistingFile();
     ArgumentOutOfRangeException ex = Assert.Throws <ArgumentOutOfRangeException>(
         () => new FileStream(filePath, GetOptions(FileMode.CreateNew, FileAccess.Write, FileShare.None, FileOptions.None, -1)));
 }
示例#19
0
        /// <summary>
        /// Initializes the Level.
        /// </summary>
        /// <param name="randomSeed">Randomizer Seed</param>
        /// <param name="slots">List of Slots</param>
        public void Init(int randomSeed, params LevelSlot[] slots)
        {
            // Init only allowed in Uninit-Mode.
            if (Mode != LevelMode.Uninit)
            {
                throw new NotSupportedException("Level is not ready for init");
            }

            // Initialize the Randomizer.
            RandomSeed = (int)DateTime.Now.Ticks;
            if (randomSeed != 0)
            {
                RandomSeed = randomSeed;
            }

            // Generate the Simulation Context for this Level.
            Context = new SimulationContext(
                Context.Resolver,
                Context.Settings,
                new Random(RandomSeed));

            // Check for the right number of Slots.
            if (slots.Length > MAX_SLOTS)
            {
                var exception = new ArgumentOutOfRangeException("There are too many Slots");
                SetMode(LevelMode.InitFailed, exception);
                throw exception;
            }

            // Generate Engine
            engine = new Engine(Context.Resolver);

            // Generate Map and validate.
            Map map = GetMap();

            if (map == null)
            {
                var exception = new NotSupportedException("No Map was created");
                SetMode(LevelMode.InitFailed, exception);
                throw exception;
            }
            map.CheckMap();

            int minPlayer = LevelDescription.MinPlayerCount;
            int maxPlayer = LevelDescription.MaxPlayerCount;

            // TODO: Ermitteln der Filter Attribute
            //object[] levelFilters = GetType().GetCustomAttributes(typeof(FactionFilterAttribute), false);
            //var filters = new Dictionary<int, List<FactionFilterAttribute>>();
            //foreach (FactionFilterAttribute item in levelFilters)
            //{
            //    if (!filters.ContainsKey(item.SlotIndex))
            //        filters.Add(item.SlotIndex, new List<FactionFilterAttribute>());
            //    filters[item.SlotIndex].Add(item);
            //}

            // Check for Color Collisions.
            var colors = new List <PlayerColor>();

            foreach (var slot in slots)
            {
                if (slot != null)
                {
                    if (colors.Contains(slot.Color))
                    {
                        var exception = new NotSupportedException("There are two Players with the same color");
                        SetMode(LevelMode.InitFailed, exception);
                        throw exception;
                    }
                    colors.Add(slot.Color);
                }
            }

            // Gegencheck mit Level-Attributen
            int playerCount = 0;
            int highestSlot = 0;

            for (int i = 0; i < slots.Length; i++)
            {
                if (slots[i] != null)
                {
                    // Counter
                    playerCount++;
                    highestSlot = i;

                    // TODO: Filter
                    //if (filters.ContainsKey(i) && filters[i].Count > 0)
                    //{
                    //    if (filters[i].Any(item => item.FactionType == slots[i].GetType()))
                    //        continue;

                    //    Mode = LevelMode.InitFailed;
                    //    Factions = null;
                    //    throw new NotSupportedException(string.Format(
                    //        "Faction '{0}' is not allowed in Slot {1}",
                    //        slots[i].GetType(), i));
                    //}
                }
            }

            // Faction Counts mit Map- und Level-Requirements gegenchecken
            if (playerCount < minPlayer)
            {
                var exception = new NotSupportedException(string.Format("Not enought player. Requires {0} Player", minPlayer));
                SetMode(LevelMode.InitFailed, exception);
                throw exception;
            }

            if (playerCount > maxPlayer)
            {
                var exception = new NotSupportedException(string.Format("Too many player. Requires a Maximum of {0} Player", maxPlayer));
                SetMode(LevelMode.InitFailed, exception);
                throw exception;
            }

            if (highestSlot > map.GetPlayerCount())
            {
                var exception = new NotSupportedException(string.Format("Too many Slots used. Map has only {0} Slots", map.GetPlayerCount()));
                SetMode(LevelMode.InitFailed, exception);
                throw exception;
            }

            // Factions erzeugen
            Factions = new Faction[MAX_SLOTS];
            for (int i = 0; i < slots.Length; i++)
            {
                if (slots[i] == null)
                {
                    continue;
                }

                SimulationContext factionContext = new SimulationContext(Context.Resolver, slotSettings[i]);

                // Identify and generate Faction
                try
                {
                    Factions[i] = Context.Resolver.CreateFaction(factionContext, slots[i].FactoryType, this);
                }
                catch (Exception ex)
                {
                    SetMode(LevelMode.InitFailed, ex);
                    throw;
                }

                // In Case the Faction could not be found...
                if (Factions[i] == null)
                {
                    var exception = new Exception(string.Format("Cound not identify Faction for player {0}.", slots[i].Name));
                    SetMode(LevelMode.InitFailed, exception);
                    throw exception;
                }
            }

            // State erzeugen
            mapState             = new MapState();
            mapState.BlockBorder = map.BlockBorder;
            mapState.Tiles       = (MapTile[, ])map.Tiles.Clone();

            engine.Init(map);
            engine.OnInsertItem += engine_OnInsertItem;
            engine.OnRemoveItem += engine_OnRemoveItem;

            // Fraktionen ins Spiel einbetten
            for (byte i = 0; i < Factions.Length; i++)
            {
                try
                {
                    InitFaction(i, slots[i], Factions[i]);
                }
                catch (Exception ex)
                {
                    SetMode(LevelMode.PlayerException, ex, i);
                    Factions = null;
                    throw;
                }
            }

            // Initialisierung des Levels
            try
            {
                OnInit();
            }
            catch (Exception ex)
            {
                SetMode(LevelMode.InitFailed, ex);
                Factions = null;
                throw;
            }

            SetMode(LevelMode.Running);
        }
示例#20
0
 internal static ArgumentOutOfRangeException ArgumentOutOfRange(string parameterName)
 {
     ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName);
     return e;
 }
示例#21
0
            public void NullActualValueThrowArgumentOutOfRangeException()
            {
                var expectedEx = new ArgumentOutOfRangeException("paramName", Exceptions.ArgumentNotLessThanOrEqualToValue.FormatWith(0));
                var actualEx = Assert.Throws<ArgumentOutOfRangeException>(() => Verify.LessThanOrEqual((Comparable)0, null, "paramName"));

                Assert.Equal(expectedEx.Message, actualEx.Message);
            }
        public void HandleForwardsHandlingToConfiguredExceptionEntry()
        {
            var policies       = new Dictionary <string, ExceptionPolicyDefinition>();
            var policy1Entries = new Dictionary <Type, ExceptionPolicyEntry>
            {
                {
                    typeof(ArithmeticException),
                    new ExceptionPolicyEntry(typeof(ArithmeticException),
                                             PostHandlingAction.NotifyRethrow,
                                             new IExceptionHandler[] { new TestExceptionHandler("handler11") })
                },
                {
                    typeof(ArgumentException),
                    new ExceptionPolicyEntry(typeof(ArgumentException),
                                             PostHandlingAction.ThrowNewException,
                                             new IExceptionHandler[] { new TestExceptionHandler("handler12") })
                },
                {
                    typeof(ArgumentOutOfRangeException),
                    new ExceptionPolicyEntry(typeof(ArgumentOutOfRangeException),
                                             PostHandlingAction.None,
                                             new IExceptionHandler[] { new TestExceptionHandler("handler13") })
                }
            };

            policies.Add("policy1", new ExceptionPolicyDefinition("policy1", policy1Entries));

            var manager = new ExceptionManager(policies);

            // is the exception rethrown?
            Exception thrownException = new ArithmeticException();

            Assert.IsTrue(manager.HandleException(thrownException, "policy1"));
            Assert.AreEqual(1, TestExceptionHandler.HandlingNames.Count);
            Assert.AreEqual("handler11", TestExceptionHandler.HandlingNames[0]);

            // is the new exception thrown?
            TestExceptionHandler.HandlingNames.Clear();
            thrownException = new ArgumentException();
            try
            {
                manager.HandleException(thrownException, "policy1");
                Assert.Fail("should have thrown");
            }
            catch (Exception e)
            {
                Assert.AreSame(thrownException, e.InnerException);
                Assert.AreEqual(1, TestExceptionHandler.HandlingNames.Count);
                Assert.AreEqual("handler12", TestExceptionHandler.HandlingNames[0]);
            }

            // is the exception swallowed? action == None
            TestExceptionHandler.HandlingNames.Clear();
            thrownException = new ArgumentOutOfRangeException();
            Assert.IsFalse(manager.HandleException(thrownException, "policy1"));
            Assert.AreEqual(1, TestExceptionHandler.HandlingNames.Count);
            Assert.AreEqual("handler13", TestExceptionHandler.HandlingNames[0]);

            // is the unknwon exception rethrown?
            TestExceptionHandler.HandlingNames.Clear();
            thrownException = new Exception();
            Assert.IsTrue(manager.HandleException(thrownException, "policy1"));
            Assert.AreEqual(0, TestExceptionHandler.HandlingNames.Count);
        }
        public void ProcessWithReturnValueProcessesExceptionsOnThrow()
        {
            var policies       = new Dictionary <string, ExceptionPolicyDefinition>();
            var policy1Entries = new Dictionary <Type, ExceptionPolicyEntry>
            {
                {
                    typeof(ArithmeticException),
                    new ExceptionPolicyEntry(typeof(ArithmeticException),
                                             PostHandlingAction.NotifyRethrow,
                                             new IExceptionHandler[] { new TestExceptionHandler("handler11") })
                },
                {
                    typeof(ArgumentException),
                    new ExceptionPolicyEntry(typeof(ArgumentException),
                                             PostHandlingAction.ThrowNewException,
                                             new IExceptionHandler[] { new TestExceptionHandler("handler12") })
                },
                {
                    typeof(ArgumentOutOfRangeException),
                    new ExceptionPolicyEntry(typeof(ArgumentOutOfRangeException),
                                             PostHandlingAction.None,
                                             new IExceptionHandler[] { new TestExceptionHandler("handler13") })
                }
            };

            policies.Add("policy1", new ExceptionPolicyDefinition("policy1", policy1Entries));

            var manager = new ExceptionManager(policies);

            // is the exception rethrown?
            Exception thrownException = new ArithmeticException();

            try
            {
                Exception ex1    = thrownException;
                int       result = manager.Process(() =>
                {
                    throw ex1;
#pragma warning disable 162 // Unreachable code
                    return(37);

#pragma warning restore 162
                }, "policy1");
                Assert.Fail("should have thrown");
            }
            catch (Exception e)
            {
                Assert.AreSame(thrownException, e);
                Assert.AreEqual(1, TestExceptionHandler.HandlingNames.Count);
                Assert.AreEqual("handler11", TestExceptionHandler.HandlingNames[0]);
            }

            // is the exception swallowed? action == None
            TestExceptionHandler.HandlingNames.Clear();
            thrownException = new ArgumentOutOfRangeException();
            Exception ex3             = thrownException;
            int       swallowedResult = manager.Process(() =>
            {
                throw ex3;
#pragma warning disable 162 // Unreachable code
                return(17);

#pragma warning restore 162
            }, -20, "policy1");

            Assert.AreEqual(1, TestExceptionHandler.HandlingNames.Count);
            Assert.AreEqual("handler13", TestExceptionHandler.HandlingNames[0]);
            Assert.AreEqual(-20, swallowedResult);
        }
示例#24
0
        /// <summary>
        /// post as json as an asynchronous operation.
        /// </summary>
        /// <param name="payloadBundle">The payload bundle.</param>
        /// <returns>Task&lt;RollbarResponse&gt;.</returns>
        public async Task <RollbarResponse> PostAsJsonAsync(PayloadBundle payloadBundle)
        {
            Assumption.AssertNotNull(payloadBundle, nameof(payloadBundle));

            Payload payload = payloadBundle.GetPayload();

            Assumption.AssertNotNull(payload, nameof(payload));

            if (payloadBundle.AsHttpContentToSend == null)
            {
                if (this._payloadTruncationStrategy.Truncate(payload) > this._payloadTruncationStrategy.MaxPayloadSizeInBytes)
                {
                    var exception = new ArgumentOutOfRangeException(
                        paramName: nameof(payload),
                        message: $"Payload size exceeds {this._payloadTruncationStrategy.MaxPayloadSizeInBytes} bytes limit!"
                        );

                    RollbarErrorUtility.Report(
                        this._rollbarLogger,
                        payload,
                        InternalRollbarError.PayloadTruncationError,
                        "While truncating a payload...",
                        exception,
                        payloadBundle
                        );
                }

                string jsonData = null;
                try
                {
                    jsonData = JsonConvert.SerializeObject(payload);
                }
                catch (System.Exception exception)
                {
                    RollbarErrorUtility.Report(
                        this._rollbarLogger,
                        payload,
                        InternalRollbarError.PayloadSerializationError,
                        "While serializing a payload...",
                        exception,
                        payloadBundle
                        );

                    return(null);
                }

                try
                {
                    jsonData = ScrubPayload(jsonData, this._rollbarLogger.Config.GetFieldsToScrub());
                }
                catch (System.Exception exception)
                {
                    RollbarErrorUtility.Report(
                        this._rollbarLogger,
                        payload,
                        InternalRollbarError.PayloadScrubbingError,
                        "While scrubbing a payload...",
                        exception,
                        payloadBundle
                        );

                    return(null);
                }

                payloadBundle.AsHttpContentToSend =
                    new StringContent(jsonData, Encoding.UTF8, "application/json"); //CONTENT-TYPE header
            }

            Assumption.AssertNotNull(payloadBundle.AsHttpContentToSend, nameof(payloadBundle.AsHttpContentToSend));
            Assumption.AssertTrue(string.Equals(payload.AccessToken, this._rollbarLogger.Config.AccessToken), nameof(payload.AccessToken));

            HttpRequestMessage request           = new HttpRequestMessage(HttpMethod.Post, this._payloadPostUri);
            const string       accessTokenHeader = "X-Rollbar-Access-Token";

            request.Headers.Add(accessTokenHeader, this._rollbarLogger.Config.AccessToken);
            request.Content = payloadBundle.AsHttpContentToSend;

            var postResponse = await this._httpClient.SendAsync(request);

            RollbarResponse response = null;

            if (postResponse.IsSuccessStatusCode)
            {
                string reply =
                    await postResponse.Content.ReadAsStringAsync();

                response =
                    JsonConvert.DeserializeObject <RollbarResponse>(reply);
                response.RollbarRateLimit =
                    new RollbarRateLimit(postResponse.Headers);
                response.HttpDetails =
                    $"Response: {postResponse}"
                    + Environment.NewLine
                    + $"Request: {postResponse.RequestMessage}"
                    + Environment.NewLine
                ;
            }
            else
            {
                postResponse.EnsureSuccessStatusCode();
            }

            return(response);
        }
	// Test the ArgumentOutOfRangeException class.
	public void TestArgumentOutOfRangeException()
			{
				ArgumentOutOfRangeException e;

				e = new ArgumentOutOfRangeException();
				AssertNull("ArgumentOutOfRangeException (1)", e.ParamName);
				AssertNotNull("ArgumentOutOfRangeException (2)", e.Message);
				AssertNull("ArgumentOutOfRangeException (3)", e.ActualValue);
				ExceptionTester.CheckHResult
						("ArgumentOutOfRangeException (4)", e,
						 unchecked((int)0x80131502));

				e = new ArgumentOutOfRangeException("p");
				AssertEquals("ArgumentOutOfRangeException (5)",
							 "p", e.ParamName);
				AssertNotNull("ArgumentOutOfRangeException (6)", e.Message);
				AssertNull("ArgumentOutOfRangeException (7)", e.ActualValue);
				ExceptionTester.CheckHResult
						("ArgumentOutOfRangeException (8)", e,
						 unchecked((int)0x80131502));

				e = new ArgumentOutOfRangeException("p", "msg");
				AssertEquals("ArgumentOutOfRangeException (9)",
							 "p", e.ParamName);
				AssertEquals("ArgumentOutOfRangeException (10)",
							 "msg", e.Message);
				AssertNull("ArgumentOutOfRangeException (11)", e.ActualValue);
				ExceptionTester.CheckHResult
						("ArgumentOutOfRangeException (12)", e,
						 unchecked((int)0x80131502));

				e = new ArgumentOutOfRangeException("p", 3, "msg");
				AssertEquals("ArgumentOutOfRangeException (13)",
							 "p", e.ParamName);
				Assert("ArgumentOutOfRangeException (14)",
					   e.Message.StartsWith("msg"));
				AssertEquals("ArgumentOutOfRangeException (15)",
							 3, e.ActualValue);
				ExceptionTester.CheckHResult
						("ArgumentOutOfRangeException (16)", e,
						 unchecked((int)0x80131502));
			}
    public bool PosTest4()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest4: The message is string empty");

        try
        {
            string Value = string.Empty;
            string paramName = null;
            ArgumentOutOfRangeException argumentOutOfRangeException = new ArgumentOutOfRangeException(paramName, Value);
            if (!argumentOutOfRangeException.Message.Equals(string.Empty))
            {
                TestLibrary.TestFramework.LogError("007", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
    public bool PosTest5()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest5: The message is white space");

        try
        {
            string Value = " ";
            string paramName = null;
            ArgumentOutOfRangeException argumentOutOfRangeException = new ArgumentOutOfRangeException(paramName, Value);
            if (argumentOutOfRangeException.Message != " ")
            {
                TestLibrary.TestFramework.LogError("009", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
        public IAsyncOperationWithProgress<IBuffer, UInt32> ReadAsync(IBuffer buffer, UInt32 count, InputStreamOptions options)
        {
            if (buffer == null)
            {
                // Mapped to E_POINTER.
                throw new ArgumentNullException("buffer");
            }

            if (count < 0 || Int32.MaxValue < count)
            {
                ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException("count");
                ex.SetErrorCode(HResults.E_INVALIDARG);
                throw ex;
            }

            if (buffer.Capacity < count)
            {
                ArgumentException ex = new ArgumentException(SR.Argument_InsufficientBufferCapacity);
                ex.SetErrorCode(HResults.E_INVALIDARG);
                throw ex;
            }

            if (!(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead))
            {
                ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException("options",
                                                                                 SR.ArgumentOutOfRange_InvalidInputStreamOptionsEnumValue);
                ex.SetErrorCode(HResults.E_INVALIDARG);
                throw ex;
            }

            // Commented due to a reported CCRewrite bug. Should uncomment when fixed:
            //Contract.Ensures(Contract.Result<IAsyncOperationWithProgress<IBuffer, UInt32>>() != null);
            //Contract.EndContractBlock();

            Stream str = EnsureNotDisposed();

            IAsyncOperationWithProgress<IBuffer, UInt32> readAsyncOperation;
            switch (_readOptimization)
            {
                case StreamReadOperationOptimization.MemoryStream:
                    readAsyncOperation = StreamOperationsImplementation.ReadAsync_MemoryStream(str, buffer, count);
                    break;

                case StreamReadOperationOptimization.AbstractStream:
                    readAsyncOperation = StreamOperationsImplementation.ReadAsync_AbstractStream(str, buffer, count, options);
                    break;

                // Use this pattern to add more optimisation options if necessary:
                //case StreamReadOperationOptimization.XxxxStream:
                //    readAsyncOperation = StreamOperationsImplementation.ReadAsync_XxxxStream(str, buffer, count, options);
                //    break;

                default:
                    Debug.Assert(false, "We should never get here. Someone forgot to handle an input stream optimisation option.");
                    readAsyncOperation = null;
                    break;
            }

            return readAsyncOperation;
        }
示例#29
0
        public void ApplePushMessage_AlertExpiration_ThrowsOnInvalidTimeSpan()
        {
            ArgumentOutOfRangeException ex = Assert.Throws <ArgumentOutOfRangeException>(() => new ApplePushMessage("Read This!", TimeSpan.FromMinutes(-1)));

            Assert.Equal("The value must be greater than 00:00:00.\r\nParameter name: expiration\r\nActual value was -00:01:00.", ex.Message);
        }
示例#30
0
        public void InvalidModeThrows()
        {
            ArgumentOutOfRangeException aoore = Assert.Throws <ArgumentOutOfRangeException>(() => new FileStream(GetTestFilePath(), ~FileMode.Open));

            Assert.Equal("mode", aoore.ParamName);
        }
示例#31
0
            public void NotEqualThrowsArgumentException()
            {
                var actual = Guid.NewGuid();
                var expectedEx = new ArgumentOutOfRangeException("paramName", actual, Exceptions.ArgumentNotEqualToValue.FormatWith(Guid.Empty));
                var actualEx = Assert.Throws<ArgumentOutOfRangeException>(() => Verify.Equal(Guid.Empty, actual, "paramName"));

                Assert.Equal(expectedEx.Message, actualEx.Message);
            }
        public void Validate_Throws_IfValueIsNotInEnum()
        {
            ArgumentOutOfRangeException ex = Assert.Throws <ArgumentOutOfRangeException>(() => this.helper.Validate(this.invalidValue, "value"));

            Assert.Contains("The value must be from the '{0}' enumeration.".FormatForUser(typeof(TEnum).Name), ex.Message);
        }
      private void Page_Load(object sender, EventArgs e)
      {
          HtmlForm form1 = (HtmlForm)(HtmlForm)this.FindControl("Form1");

          this.GHTTestBegin(form1);
          this.GHTSubTestBegin("GHTSubTest1");
          try
          {
              this.Application.Clear();
              this.Application["var1"] = "variable1";
              this.Application["var2"] = "variable2";
              this.Application["var3"] = "variable3";
              this.Application.RemoveAt(2);
              int num8 = this.Application.Count - 1;
              for (int num1 = 0; num1 <= num8; num1++)
              {
                  this.GHTSubTestAddResult((string)("Application.Item(" + num1.ToString() + ") = " + this.Application[num1]));
              }
          }
          catch (Exception exception8)
          {
              // ProjectData.SetProjectError(exception8);
              Exception exception1 = exception8;
              this.GHTSubTestUnexpectedExceptionCaught(exception1);
              // ProjectData.ClearProjectError();
          }
          this.GHTSubTestEnd();
          this.GHTSubTestBegin("GHTSubTest2");
          try
          {
              this.Application.RemoveAt(2);
              int num7 = this.Application.Count - 1;
              for (int num2 = 0; num2 <= num7; num2++)
              {
                  this.GHTSubTestAddResult((string)("Application.Item(" + num2.ToString() + ") = " + this.Application[num2]));
              }
              this.GHTSubTestExpectedExceptionNotCaught("ArgumentOutOfRangeException");
          }
          catch (ArgumentOutOfRangeException exception9)
          {
              // ProjectData.SetProjectError(exception9);
              ArgumentOutOfRangeException exception2 = exception9;
              this.GHTSubTestExpectedExceptionCaught(exception2);
              // ProjectData.ClearProjectError();
          }
          catch (Exception exception10)
          {
              // ProjectData.SetProjectError(exception10);
              Exception exception3 = exception10;
              this.GHTSubTestUnexpectedExceptionCaught(exception3);
              // ProjectData.ClearProjectError();
          }
          this.GHTSubTestEnd();
          this.GHTSubTestBegin("GHTSubTest3");
          try
          {
              this.Application.RemoveAt(0x7d);
              int num6 = this.Application.Count - 1;
              for (int num3 = 0; num3 <= num6; num3++)
              {
                  this.GHTSubTestAddResult((string)("Application.Item(" + num3.ToString() + ") = " + this.Application[num3]));
              }
              this.GHTSubTestExpectedExceptionNotCaught("ArgumentOutOfRangeException");
          }
          catch (ArgumentOutOfRangeException exception11)
          {
              // ProjectData.SetProjectError(exception11);
              ArgumentOutOfRangeException exception4 = exception11;
              this.GHTSubTestExpectedExceptionCaught(exception4);
              // ProjectData.ClearProjectError();
          }
          catch (Exception exception12)
          {
              // ProjectData.SetProjectError(exception12);
              Exception exception5 = exception12;
              this.GHTSubTestUnexpectedExceptionCaught(exception5);
              // ProjectData.ClearProjectError();
          }
          this.GHTSubTestEnd();
          this.GHTSubTestBegin("GHTSubTest4");
          try
          {
              this.Application.RemoveAt(-125);
              int num5 = this.Application.Count - 1;
              for (int num4 = 0; num4 <= num5; num4++)
              {
                  this.GHTSubTestAddResult((string)("Application.Item(" + num4.ToString() + ") = " + this.Application[num4].ToString()));
              }
              this.GHTSubTestExpectedExceptionNotCaught("ArgumentOutOfRangeException");
          }
          catch (ArgumentOutOfRangeException exception13)
          {
              // ProjectData.SetProjectError(exception13);
              ArgumentOutOfRangeException exception6 = exception13;
              this.GHTSubTestExpectedExceptionCaught(exception6);
              // ProjectData.ClearProjectError();
          }
          catch (Exception exception14)
          {
              // ProjectData.SetProjectError(exception14);
              Exception exception7 = exception14;
              this.GHTSubTestUnexpectedExceptionCaught(exception7);
              // ProjectData.ClearProjectError();
          }
          this.GHTSubTestEnd();
      }
示例#34
0
        private BitmapImage SwitchDoing(Image b, string file, string thumbFolder, Border border, SolidBrush outerBorderBrush, int outerBorderSize,
                                        SolidBrush innerBorderBrush, int innerBorderSize, ShowPreview preview, bool saveThumb)
        {
            string logMessage;

            switch (border)
            {
            case Border.Single:
                b = imageService.CreateSingleBorder(b, outerBorderBrush, outerBorderSize);
                break;

            case Border.Double:
                b = imageService.CreateDoubleBorder(b, outerBorderBrush, innerBorderBrush, outerBorderSize, innerBorderSize);
                break;

            case Border.None:
                break;

            default:
                var ex = new ArgumentOutOfRangeException(nameof(border), border, null);

                logMessage = $"[{GetType().Name}] Exception at {MethodBase.GetCurrentMethod()}: {ex}";
                unityContainer.Resolve <ILoggerFacade>().Log(logMessage, Category.Exception, Priority.High);

                DialogService.Exception(ex, DialogService.ExceptionType.Universal);
                throw ex;
            }

            switch (preview)
            {
            case ShowPreview.No:
                if (!saveThumb)
                {
                    return(null);
                }

                var newFile = Path.Combine(Path.GetDirectoryName(file) + @"\", thumbFolder) + @"\" + Path.GetFileName(file);

                b.Save(newFile, ImageFormat.Jpeg);

                logMessage = $"[{GetType().Name}] File ({newFile}) was created";
                unityContainer.Resolve <ILoggerFacade>().Log(logMessage, Category.Debug, Priority.None);

                return(null);

            case ShowPreview.Original:
                logMessage = $"[{GetType().Name}] Preview in original size was created";
                unityContainer.Resolve <ILoggerFacade>().Log(logMessage, Category.Debug, Priority.None);

                return(imageService.GetBitmapImageFromImage(b, ImageFormat.Jpeg));

            case ShowPreview.Thumbnail:
                logMessage = $"[{GetType().Name}] Preview in thumbnail size was created";
                unityContainer.Resolve <ILoggerFacade>().Log(logMessage, Category.Debug, Priority.None);

                return(imageService.GetBitmapImageFromImage(b, ImageFormat.Jpeg));

            default:
                var ex = new ArgumentOutOfRangeException(nameof(preview), preview, null);

                logMessage = $"[{GetType().Name}] Exception at {MethodBase.GetCurrentMethod()}: {ex}";
                unityContainer.Resolve <ILoggerFacade>().Log(logMessage, Category.Exception, Priority.High);

                DialogService.Exception(ex, DialogService.ExceptionType.Universal);
                throw ex;
            }
        }
示例#35
0
        internal static ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName)
        {
            ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, message);

            return(e);
        }
示例#36
0
        /// <summary>
        /// This does a mapping from hr to the exception and also takes care of making default exception in case of classic COM as COMException.
        /// and in winrt and marshal APIs as Exception.
        /// </summary>
        /// <param name="errorCode"></param>
        /// <param name="message"></param>
        /// <param name="createCOMException"></param>
        /// <returns></returns>
        internal static Exception GetMappingExceptionForHR(int errorCode, string message, bool createCOMException, bool hasErrorInfo)
        {
            if (errorCode >= 0)
            {
                return(null);
            }

            Exception exception = null;

            bool shouldDisplayHR = false;

            switch (errorCode)
            {
            case __HResults.COR_E_NOTFINITENUMBER:     // NotFiniteNumberException
            case __HResults.COR_E_ARITHMETIC:
                exception = new ArithmeticException();
                break;

            case __HResults.COR_E_ARGUMENT:
            case unchecked ((int)0x800A01C1):
            case unchecked ((int)0x800A01C2):
            case __HResults.CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT:
                exception = new ArgumentException();

                if (errorCode != __HResults.COR_E_ARGUMENT)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.E_BOUNDS:
            case __HResults.COR_E_ARGUMENTOUTOFRANGE:
            case __HResults.ERROR_NO_UNICODE_TRANSLATION:
                exception = new ArgumentOutOfRangeException();

                if (errorCode != __HResults.COR_E_ARGUMENTOUTOFRANGE)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_ARRAYTYPEMISMATCH:
                exception = new ArrayTypeMismatchException();
                break;

            case __HResults.COR_E_BADIMAGEFORMAT:
            case __HResults.CLDB_E_FILE_OLDVER:
            case __HResults.CLDB_E_INDEX_NOTFOUND:
            case __HResults.CLDB_E_FILE_CORRUPT:
            case __HResults.COR_E_NEWER_RUNTIME:
            case __HResults.COR_E_ASSEMBLYEXPECTED:
            case __HResults.ERROR_BAD_EXE_FORMAT:
            case __HResults.ERROR_EXE_MARKED_INVALID:
            case __HResults.CORSEC_E_INVALID_IMAGE_FORMAT:
            case __HResults.ERROR_NOACCESS:
            case __HResults.ERROR_INVALID_ORDINAL:
            case __HResults.ERROR_INVALID_DLL:
            case __HResults.ERROR_FILE_CORRUPT:
            case __HResults.COR_E_LOADING_REFERENCE_ASSEMBLY:
            case __HResults.META_E_BAD_SIGNATURE:
                exception = new BadImageFormatException();

                // Always show HR for BadImageFormatException
                shouldDisplayHR = true;

                break;

            case __HResults.COR_E_CUSTOMATTRIBUTEFORMAT:
                exception = new FormatException();
                break;     // CustomAttributeFormatException

            case __HResults.COR_E_DATAMISALIGNED:
                exception = InteropExtensions.CreateDataMisalignedException(message);     // TODO: Do we need to add msg here?
                break;

            case __HResults.COR_E_DIVIDEBYZERO:
            case __HResults.CTL_E_DIVISIONBYZERO:
                exception = new DivideByZeroException();

                if (errorCode != __HResults.COR_E_DIVIDEBYZERO)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_DLLNOTFOUND:
#if ENABLE_WINRT
                exception = new DllNotFoundException();
#endif
                break;

            case __HResults.COR_E_DUPLICATEWAITOBJECT:
                exception = new ArgumentException();
                break;     // DuplicateWaitObjectException

            case __HResults.COR_E_ENDOFSTREAM:
            case unchecked ((int)0x800A003E):
                exception = new CoreFX_IO::System.IO.EndOfStreamException();

                if (errorCode != __HResults.COR_E_ENDOFSTREAM)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_TYPEACCESS:     // TypeAccessException
            case __HResults.COR_E_ENTRYPOINTNOTFOUND:
                exception = new TypeLoadException();

                break;     // EntryPointNotFoundException

            case __HResults.COR_E_EXCEPTION:
                exception = new Exception();
                break;

            case __HResults.COR_E_DIRECTORYNOTFOUND:
            case __HResults.STG_E_PATHNOTFOUND:
            case __HResults.CTL_E_PATHNOTFOUND:
                exception = new System.IO.DirectoryNotFoundException();

                if (errorCode != __HResults.COR_E_DIRECTORYNOTFOUND)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_FILELOAD:
            case __HResults.FUSION_E_INVALID_PRIVATE_ASM_LOCATION:
            case __HResults.FUSION_E_SIGNATURE_CHECK_FAILED:
            case __HResults.FUSION_E_LOADFROM_BLOCKED:
            case __HResults.FUSION_E_CACHEFILE_FAILED:
            case __HResults.FUSION_E_ASM_MODULE_MISSING:
            case __HResults.FUSION_E_INVALID_NAME:
            case __HResults.FUSION_E_PRIVATE_ASM_DISALLOWED:
            case __HResults.FUSION_E_HOST_GAC_ASM_MISMATCH:
            case __HResults.COR_E_MODULE_HASH_CHECK_FAILED:
            case __HResults.FUSION_E_REF_DEF_MISMATCH:
            case __HResults.SECURITY_E_INCOMPATIBLE_SHARE:
            case __HResults.SECURITY_E_INCOMPATIBLE_EVIDENCE:
            case __HResults.SECURITY_E_UNVERIFIABLE:
            case __HResults.COR_E_FIXUPSINEXE:
            case __HResults.ERROR_TOO_MANY_OPEN_FILES:
            case __HResults.ERROR_SHARING_VIOLATION:
            case __HResults.ERROR_LOCK_VIOLATION:
            case __HResults.ERROR_OPEN_FAILED:
            case __HResults.ERROR_DISK_CORRUPT:
            case __HResults.ERROR_UNRECOGNIZED_VOLUME:
            case __HResults.ERROR_DLL_INIT_FAILED:
            case __HResults.FUSION_E_CODE_DOWNLOAD_DISABLED:
            case __HResults.CORSEC_E_MISSING_STRONGNAME:
            case __HResults.MSEE_E_ASSEMBLYLOADINPROGRESS:
            case __HResults.ERROR_FILE_INVALID:
                exception = new System.IO.FileLoadException();

                shouldDisplayHR = true;
                break;

            case __HResults.COR_E_PATHTOOLONG:
                exception = new System.IO.PathTooLongException();
                break;

            case __HResults.COR_E_IO:
            case __HResults.CTL_E_DEVICEIOERROR:
            case unchecked ((int)0x800A793C):
            case unchecked ((int)0x800A793D):
                exception = new System.IO.IOException();

                if (errorCode != __HResults.COR_E_IO)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.ERROR_FILE_NOT_FOUND:
            case __HResults.ERROR_MOD_NOT_FOUND:
            case __HResults.ERROR_INVALID_NAME:
            case __HResults.CTL_E_FILENOTFOUND:
            case __HResults.ERROR_BAD_NET_NAME:
            case __HResults.ERROR_BAD_NETPATH:
            case __HResults.ERROR_NOT_READY:
            case __HResults.ERROR_WRONG_TARGET_NAME:
            case __HResults.INET_E_UNKNOWN_PROTOCOL:
            case __HResults.INET_E_CONNECTION_TIMEOUT:
            case __HResults.INET_E_CANNOT_CONNECT:
            case __HResults.INET_E_RESOURCE_NOT_FOUND:
            case __HResults.INET_E_OBJECT_NOT_FOUND:
            case __HResults.INET_E_DOWNLOAD_FAILURE:
            case __HResults.INET_E_DATA_NOT_AVAILABLE:
            case __HResults.ERROR_DLL_NOT_FOUND:
            case __HResults.CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW:
            case __HResults.CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH:
            case __HResults.CLR_E_BIND_ASSEMBLY_NOT_FOUND:
                exception = new System.IO.FileNotFoundException();

                shouldDisplayHR = true;
                break;

            case __HResults.COR_E_FORMAT:
                exception = new FormatException();
                break;

            case __HResults.COR_E_INDEXOUTOFRANGE:
            case unchecked ((int)0x800a0009):
                exception = new IndexOutOfRangeException();

                if (errorCode != __HResults.COR_E_INDEXOUTOFRANGE)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_INVALIDCAST:
                exception = new InvalidCastException();
                break;

            case __HResults.COR_E_INVALIDCOMOBJECT:
                exception = new InvalidComObjectException();
                break;

            case __HResults.COR_E_INVALIDOLEVARIANTTYPE:
                exception = new InvalidOleVariantTypeException();
                break;

            case __HResults.COR_E_INVALIDOPERATION:
            case __HResults.E_ILLEGAL_STATE_CHANGE:
            case __HResults.E_ILLEGAL_METHOD_CALL:
            case __HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT:
            case __HResults.APPMODEL_ERROR_NO_PACKAGE:
                exception = new InvalidOperationException();

                if (errorCode != __HResults.COR_E_INVALIDOPERATION)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_MARSHALDIRECTIVE:
                exception = new MarshalDirectiveException();
                break;

            case __HResults.COR_E_METHODACCESS:            // MethodAccessException
            case __HResults.META_E_CA_FRIENDS_SN_REQUIRED: // MethodAccessException
            case __HResults.COR_E_FIELDACCESS:
            case __HResults.COR_E_MEMBERACCESS:
                exception = new MemberAccessException();

                if (errorCode != __HResults.COR_E_METHODACCESS)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_MISSINGFIELD:     // MissingFieldException
            case __HResults.COR_E_MISSINGMETHOD:    // MissingMethodException
            case __HResults.COR_E_MISSINGMEMBER:
            case unchecked ((int)0x800A01CD):
                exception = new MissingMemberException();
                break;

            case __HResults.COR_E_MISSINGMANIFESTRESOURCE:
                exception = new System.Resources.MissingManifestResourceException();
                break;

            case __HResults.COR_E_NOTSUPPORTED:
            case unchecked ((int)0x800A01B6):
            case unchecked ((int)0x800A01BD):
            case unchecked ((int)0x800A01CA):
            case unchecked ((int)0x800A01CB):
                exception = new NotSupportedException();

                if (errorCode != __HResults.COR_E_NOTSUPPORTED)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_NULLREFERENCE:
                exception = new NullReferenceException();
                break;

            case __HResults.COR_E_OBJECTDISPOSED:
            case __HResults.RO_E_CLOSED:
                // No default constructor
                exception = new ObjectDisposedException(String.Empty);
                break;

            case __HResults.COR_E_OPERATIONCANCELED:
#if ENABLE_WINRT
                exception = new OperationCanceledException();
#endif
                break;

            case __HResults.COR_E_OVERFLOW:
            case __HResults.CTL_E_OVERFLOW:
                exception = new OverflowException();
                break;

            case __HResults.COR_E_PLATFORMNOTSUPPORTED:
                exception = new PlatformNotSupportedException(message);
                break;

            case __HResults.COR_E_RANK:
                exception = new RankException();
                break;

            case __HResults.COR_E_REFLECTIONTYPELOAD:
#if ENABLE_WINRT
                exception = new System.Reflection.ReflectionTypeLoadException(null, null);
#endif
                break;

            case __HResults.COR_E_SECURITY:
            case __HResults.CORSEC_E_INVALID_STRONGNAME:
            case __HResults.CTL_E_PERMISSIONDENIED:
            case unchecked ((int)0x800A01A3):
            case __HResults.CORSEC_E_INVALID_PUBLICKEY:
            case __HResults.CORSEC_E_SIGNATURE_MISMATCH:
                exception = new System.Security.SecurityException();
                break;

            case __HResults.COR_E_SAFEARRAYRANKMISMATCH:
                exception = new SafeArrayRankMismatchException();
                break;

            case __HResults.COR_E_SAFEARRAYTYPEMISMATCH:
                exception = new SafeArrayTypeMismatchException();
                break;

            case __HResults.COR_E_SERIALIZATION:
                exception = new System.Runtime.Serialization.SerializationException(message);
                break;

            case __HResults.COR_E_SYNCHRONIZATIONLOCK:
                exception = new System.Threading.SynchronizationLockException();
                break;

            case __HResults.COR_E_TARGETINVOCATION:
                exception = new System.Reflection.TargetInvocationException(null);
                break;

            case __HResults.COR_E_TARGETPARAMCOUNT:
                exception = new System.Reflection.TargetParameterCountException();
                break;

            case __HResults.COR_E_TYPEINITIALIZATION:
                exception = InteropExtensions.CreateTypeInitializationException(message);
                break;

            case __HResults.COR_E_TYPELOAD:
            case __HResults.RO_E_METADATA_NAME_NOT_FOUND:
            case __HResults.CLR_E_BIND_TYPE_NOT_FOUND:
                exception = new TypeLoadException();

                if (errorCode != __HResults.COR_E_TYPELOAD)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_UNAUTHORIZEDACCESS:
            case __HResults.CTL_E_PATHFILEACCESSERROR:
            case unchecked ((int)0x800A014F):
                exception = new UnauthorizedAccessException();

                shouldDisplayHR = true;

                break;

            case __HResults.COR_E_VERIFICATION:
                exception = new System.Security.VerificationException();
                break;

            case __HResults.E_NOTIMPL:
                exception = new NotImplementedException();
                break;

            case __HResults.E_OUTOFMEMORY:
            case __HResults.CTL_E_OUTOFMEMORY:
            case unchecked ((int)0x800A7919):
                exception = new OutOfMemoryException();

                if (errorCode != __HResults.E_OUTOFMEMORY)
                {
                    shouldDisplayHR = true;
                }

                break;

#if ENABLE_WINRT
            case __HResults.E_XAMLPARSEFAILED:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.Markup.XamlParseException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;

            case __HResults.E_ELEMENTNOTAVAILABLE:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.Automation.ElementNotAvailableException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;

            case __HResults.E_ELEMENTNOTENABLED:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.Automation.ElementNotEnabledException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;

            case __HResults.E_LAYOUTCYCLE:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.LayoutCycleException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;
#endif // ENABLE_WINRT
            case __HResults.COR_E_AMBIGUOUSMATCH:     // AmbiguousMatchException
            case __HResults.COR_E_APPLICATION:     // ApplicationException
            case __HResults.COR_E_APPDOMAINUNLOADED:          // AppDomainUnloadedException
            case __HResults.COR_E_CANNOTUNLOADAPPDOMAIN:      // CannotUnloadAppDomainException
            case __HResults.COR_E_CODECONTRACTFAILED:         // ContractException
            case __HResults.COR_E_CONTEXTMARSHAL:             // ContextMarshalException
            case __HResults.CORSEC_E_CRYPTO:                  // CryptographicException
            case __HResults.CORSEC_E_CRYPTO_UNEX_OPER:        // CryptographicUnexpectedOperationException
            case __HResults.COR_E_EXECUTIONENGINE:            // ExecutionEngineException
            case __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK: // InsufficientExecutionStackException
            case __HResults.COR_E_INVALIDFILTERCRITERIA:      // InvalidFilterCriteriaException
            case __HResults.COR_E_INVALIDPROGRAM:             // InvalidProgramException
            case __HResults.COR_E_MULTICASTNOTSUPPORTED:      // MulticastNotSupportedException
            case __HResults.COR_E_REMOTING:                   // RemotingException
            case __HResults.COR_E_RUNTIMEWRAPPED:             // RuntimeWrappedException
            case __HResults.COR_E_SERVER:                     // ServerException
            case __HResults.COR_E_STACKOVERFLOW:              // StackOverflowException
            case __HResults.CTL_E_OUTOFSTACKSPACE:            // StackOverflowException
            case __HResults.COR_E_SYSTEM:                     // SystemException
            case __HResults.COR_E_TARGET:                     // TargetException
            case __HResults.COR_E_THREADABORTED:              // TargetException
            case __HResults.COR_E_THREADINTERRUPTED:          // ThreadInterruptedException
            case __HResults.COR_E_THREADSTATE:                // ThreadStateException
            case __HResults.COR_E_THREADSTART:                // ThreadStartException
            case __HResults.COR_E_TYPEUNLOADED:               // TypeUnloadedException
            case __HResults.CORSEC_E_POLICY_EXCEPTION:        // PolicyException
            case __HResults.CORSEC_E_NO_EXEC_PERM:            // PolicyException
            case __HResults.CORSEC_E_MIN_GRANT_FAIL:          // PolicyException
            case __HResults.CORSEC_E_XMLSYNTAX:               // XmlSyntaxException
            case __HResults.ISS_E_ALLOC_TOO_LARGE:            // IsolatedStorageException
            case __HResults.ISS_E_BLOCK_SIZE_TOO_SMALL:       // IsolatedStorageException
            case __HResults.ISS_E_CALLER:                     // IsolatedStorageException
            case __HResults.ISS_E_CORRUPTED_STORE_FILE:       // IsolatedStorageException
            case __HResults.ISS_E_CREATE_DIR:                 // IsolatedStorageException
            case __HResults.ISS_E_CREATE_MUTEX:               // IsolatedStorageException
            case __HResults.ISS_E_DEPRECATE:                  // IsolatedStorageException
            case __HResults.ISS_E_FILE_NOT_MAPPED:            // IsolatedStorageException
            case __HResults.ISS_E_FILE_WRITE:                 // IsolatedStorageException
            case __HResults.ISS_E_GET_FILE_SIZE:              // IsolatedStorageException
            case __HResults.ISS_E_ISOSTORE:                   // IsolatedStorageException
            case __HResults.ISS_E_LOCK_FAILED:                // IsolatedStorageException
            case __HResults.ISS_E_MACHINE:                    // IsolatedStorageException
            case __HResults.ISS_E_MACHINE_DACL:               // IsolatedStorageException
            case __HResults.ISS_E_MAP_VIEW_OF_FILE:           // IsolatedStorageException
            case __HResults.ISS_E_OPEN_FILE_MAPPING:          // IsolatedStorageException
            case __HResults.ISS_E_OPEN_STORE_FILE:            // IsolatedStorageException
            case __HResults.ISS_E_PATH_LENGTH:                // IsolatedStorageException
            case __HResults.ISS_E_SET_FILE_POINTER:           // IsolatedStorageException
            case __HResults.ISS_E_STORE_NOT_OPEN:             // IsolatedStorageException
            case __HResults.ISS_E_STORE_VERSION:              // IsolatedStorageException
            case __HResults.ISS_E_TABLE_ROW_NOT_FOUND:        // IsolatedStorageException
            case __HResults.ISS_E_USAGE_WILL_EXCEED_QUOTA:    // IsolatedStorageException
            case __HResults.E_FAIL:
            default:
                break;
            }

            if (exception == null)
            {
                if (createCOMException)
                {
                    exception = new COMException();
                    if (errorCode != __HResults.E_FAIL)
                    {
                        shouldDisplayHR = true;
                    }
                }
                else
                {
                    exception = new Exception();
                    if (errorCode != __HResults.COR_E_EXCEPTION)
                    {
                        shouldDisplayHR = true;
                    }
                }
            }

            bool shouldConstructMessage = false;
            if (hasErrorInfo)
            {
                // If there is a IErrorInfo/IRestrictedErrorInfo, only construct a new error message if
                // the message is not available and do not use the shouldDisplayHR setting
                if (message == null)
                {
                    shouldConstructMessage = true;
                }
            }
            else
            {
                // If there is no IErrorInfo, use the shouldDisplayHR setting from the big switch/case above
                shouldConstructMessage = shouldDisplayHR;
            }

            if (shouldConstructMessage)
            {
                //
                // Append the HR into error message, just in case the app wants to look at the HR in
                // message to determine behavior.  We didn't expose HResult property until v4.5 and
                // GetHRFromException has side effects so probably Message was their only choice.
                // This behavior is probably not exactly the same as in desktop but it is fine to append
                // more message at the end. In any case, having the HR in the error message are helpful
                // to developers.
                // This makes sure:
                // 1. We always have a HR 0xNNNNNNNN in the message
                // 2. Put in a nice "Exception thrown from HRESULT" message if we can
                // 3. Wrap it in () if there is an existing message
                //

                // TODO: Add Symbolic Name into Messaage, convert 0x80020006 to DISP_E_UNKNOWNNAME
                string hrMessage = String.Format("{0} 0x{1}", SR.Excep_FromHResult, errorCode.LowLevelToString());

                message = ExternalInterop.GetMessage(errorCode);

                // Always make sure we have at least the HRESULT part in retail build or when the message
                // is empty.
                if (message == null)
                {
                    message = hrMessage;
                }
                else
                {
                    message = message + " (" + hrMessage + ")";
                }
            }

            if (message != null)
            {
                // Set message explicitly rather than calling constructor because certain ctors would append a
                // prefix to the message and that is not what we want
                InteropExtensions.SetExceptionMessage(exception, message);
            }

            InteropExtensions.SetExceptionErrorCode(exception, errorCode);

            return(exception);
        }
示例#37
0
        public static Exception ToIotHubClientContract(Error error)
        {
            Exception retException;

            if (error == null)
            {
                retException = new IotHubException("Unknown error.");
                return(retException);
            }

            string message = error.Description;

            string trackingId = null;

            if (error.Info != null && error.Info.TryGetValue(TrackingId, out trackingId))
            {
                message = "{0}{1}{2}".FormatInvariant(message, Environment.NewLine, "Tracking Id:" + trackingId);
            }

            if (error.Condition.Equals(TimeoutError))
            {
                retException = new TimeoutException(message);
            }
            else if (error.Condition.Equals(AmqpErrorCode.NotFound))
            {
                retException = new DeviceNotFoundException(message, (Exception)null);
            }
            else if (error.Condition.Equals(AmqpErrorCode.NotImplemented))
            {
                retException = new NotSupportedException(message);
            }
            else if (error.Condition.Equals(MessageLockLostError))
            {
                retException = new DeviceMessageLockLostException(message);
            }
            else if (error.Condition.Equals(AmqpErrorCode.NotAllowed))
            {
                retException = new InvalidOperationException(message);
            }
            else if (error.Condition.Equals(AmqpErrorCode.UnauthorizedAccess))
            {
                retException = new UnauthorizedException(message);
            }
            else if (error.Condition.Equals(ArgumentError))
            {
                retException = new ArgumentException(message);
            }
            else if (error.Condition.Equals(ArgumentOutOfRangeError))
            {
                retException = new ArgumentOutOfRangeException(message);
            }
            else if (error.Condition.Equals(AmqpErrorCode.MessageSizeExceeded))
            {
                retException = new MessageTooLargeException(message);
            }
            else if (error.Condition.Equals(AmqpErrorCode.ResourceLimitExceeded))
            {
                retException = new DeviceMaximumQueueDepthExceededException(message);
            }
            else if (error.Condition.Equals(DeviceAlreadyExists))
            {
                retException = new DeviceAlreadyExistsException(message, null);
            }
            else if (error.Condition.Equals(DeviceContainerThrottled))
            {
                retException = new IotHubThrottledException(message, null);
            }
            else if (error.Condition.Equals(IotHubSuspended))
            {
                retException = new IotHubSuspendedException(message);
            }
            else
            {
                retException = new IotHubException(message);
            }

            if (trackingId != null && retException is IotHubException)
            {
                IotHubException iotHubException = (IotHubException)retException;
                iotHubException.TrackingId = trackingId;
            }
            return(retException);
        }
示例#38
0
 static internal ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName)
 {
     ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, message);
     return e;
 }
      private void Page_Load(object sender, EventArgs e)
      {
          HtmlForm form1 = (HtmlForm)(HtmlForm)this.FindControl("Form1");

          this.GHTTestBegin(form1);
          this.Session.Clear();
          this.GHTSubTestBegin("GHTSubTest1");
          try
          {
              this.Session["var1"] = "variable1";
              this.GHTSubTestAddResult((string)(this.Session[0]));
          }
          catch (Exception exception10)
          {
              // ProjectData.SetProjectError(exception10);
              Exception exception1 = exception10;
              this.GHTSubTestUnexpectedExceptionCaught(exception1);
              // ProjectData.ClearProjectError();
          }
          this.GHTSubTestEnd();
          this.GHTSubTestBegin("GHTSubTest2");
          try
          {
              this.GHTSubTestAddResult((string)(this.Session[0]));
          }
          catch (Exception exception11)
          {
              // ProjectData.SetProjectError(exception11);
              Exception exception2 = exception11;
              this.GHTSubTestUnexpectedExceptionCaught(exception2);
              // ProjectData.ClearProjectError();
          }
          this.GHTSubTestEnd();
          this.GHTSubTestBegin("GHTSubTest3");
          try
          {
              this.Session[0] = "changed variable1";
              this.GHTSubTestAddResult((string)(this.Session[0]));
          }
          catch (Exception exception12)
          {
              // ProjectData.SetProjectError(exception12);
              Exception exception3 = exception12;
              this.GHTSubTestUnexpectedExceptionCaught(exception3);
              // ProjectData.ClearProjectError();
          }
          this.GHTSubTestEnd();
          this.GHTSubTestBegin("GHTSubTest4");
          try
          {
              this.GHTSubTestAddResult((string)(this.Session[0x7d]));
              this.GHTSubTestExpectedExceptionNotCaught("ArgumentOutOfRangeException");
          }
          catch (ArgumentOutOfRangeException exception13)
          {
              // ProjectData.SetProjectError(exception13);
              ArgumentOutOfRangeException exception4 = exception13;
              this.GHTSubTestExpectedExceptionCaught(exception4);
              // ProjectData.ClearProjectError();
          }
          catch (Exception exception14)
          {
              // ProjectData.SetProjectError(exception14);
              Exception exception5 = exception14;
              this.GHTSubTestUnexpectedExceptionCaught(exception5);
              // ProjectData.ClearProjectError();
          }
          this.GHTSubTestEnd();
          this.GHTSubTestBegin("GHTSubTest5");
          try
          {
              this.GHTSubTestAddResult((string)(this.Session[-1]));
              this.GHTSubTestExpectedExceptionNotCaught("ArgumentOutOfRangeException");
          }
          catch (ArgumentOutOfRangeException exception15)
          {
              // ProjectData.SetProjectError(exception15);
              ArgumentOutOfRangeException exception6 = exception15;
              this.GHTSubTestExpectedExceptionCaught(exception6);
              // ProjectData.ClearProjectError();
          }
          catch (Exception exception16)
          {
              // ProjectData.SetProjectError(exception16);
              Exception exception7 = exception16;
              this.GHTSubTestUnexpectedExceptionCaught(exception7);
              // ProjectData.ClearProjectError();
          }
          this.GHTSubTestEnd();
          this.GHTSubTestBegin("GHTSubTest6");
          try
          {
              this.Session[0] = null;
              this.GHTSubTestAddResult((string)(this.Session[0]));
              this.GHTSubTestExpectedExceptionNotCaught("ArgumentOutOfRangeException");
          }
          catch (ArgumentOutOfRangeException exception17)
          {
              // ProjectData.SetProjectError(exception17);
              ArgumentOutOfRangeException exception8 = exception17;
              this.GHTSubTestExpectedExceptionCaught(exception8);
              // ProjectData.ClearProjectError();
          }
          catch (Exception exception18)
          {
              // ProjectData.SetProjectError(exception18);
              Exception exception9 = exception18;
              this.GHTSubTestUnexpectedExceptionCaught(exception9);
              // ProjectData.ClearProjectError();
          }
          this.GHTSubTestEnd();
          this.GHTTestEnd();
      }
示例#40
0
 public void MustHaveAtleast2Points()
 {
     ArgumentOutOfRangeException error = Assert.Throws <ArgumentOutOfRangeException>(() => new LinearLineSegment(new[] { new PointF(0, 0) }));
 }
示例#41
0
        public void ParseAndPopulateOptions(ref Noun noun, string[] args)
        {
            using (LogContext.PushProperty("method", nameof(ParseAndPopulateOptions)))
                using (LogContext.PushProperty("args", new { noun, args }))
                {
                    var verbKeyValuePair = noun.Verbs.Single();
                    var verb             = verbKeyValuePair.Value;

                    var candidateArguments = args.Skip(2).ToArray();

                    _logger.Information("found {@numberOfCandidateArguments}; specifically {@candidateArguments}", candidateArguments.Length, candidateArguments);

                    var ordinals      = verb.GetOrdinalOptions;
                    var parameterized = verb.GetParametrizedOptions;

                    for (var i = 0; i < candidateArguments.Length; i++)
                    {
                        var argument = candidateArguments.ElementAtOrDefault(i);
                        // todo nullcheck return

                        // check ordinal fields
                        var ordinal = ordinals.ElementAtOrDefault(i);
                        if (ordinal != null)
                        {
                            var ordinalLikelyValue = string.Empty;

                            // has the ordinal been named
                            if (ordinal.IsNamed(argument))
                            {
                                ordinalLikelyValue = candidateArguments.ElementAtOrDefault(i + 1);
                                i++;
                            }
                            else
                            {
                                ordinalLikelyValue = argument;
                            }

                            ordinal.Value = ordinalLikelyValue;

                            // todo log found

                            continue;
                        }

                        // now parametrized
                        var optionNamed       = verb.GetOptionNamed(argument);
                        var optionLikelyValue = candidateArguments.ElementAtOrDefault(i + 1);
                        if (optionNamed != null)
                        {
                            if (optionLikelyValue != null)
                            {
                                optionNamed.Value = optionLikelyValue;
                                i++;
                            }

                            continue;
                        }
                        else
                        {
                            var outOfRangeException = new ArgumentOutOfRangeException(argument, optionLikelyValue, $"'{noun.GetDefaultName} {verb.GetDefaultName}' Doesn't understand an argument of '{argument}'");
                            _logger.Error(outOfRangeException, "'{@noun.GetFullNameFormatted} {@verb.GetFullNameFormatted}' Doesn't understand an argument of '{@argument}'", noun.GetDefaultName, verb.GetDefaultName, verb.GetDefaultName, argument);

                            throw outOfRangeException;
                        }
                    }
                }
        }
        public string GetParsedCommands(MessageLine line)
        {
            //TODO(Robin): Move to CommandTokens?
            Func <string, bool, string> purify = (s, replaceEnvironment) =>
            {
                s = s.Replace("\\n", "\n")
                    .Replace("$k\n", "$k\\n");
                if (replaceEnvironment)
                {
                    s = s.Replace("\n", Environment.NewLine);
                }
                return(s);
            };

            if (line.SpokenText != string.Empty)
            {
                line.UpdateRawWithNewDialogue();
                line.RawLine = purify(line.RawLine, false);
            }

            line.SpokenText = line.RawLine;

            for (var i = 0; i < line.SpokenText.Length; i++)
            {
                if (line.SpokenText[i] != '$')
                {
                    continue;
                }

                var res = MessageBlock.ParseCommand(line.SpokenText, i);
                line.SpokenText = res.Item1;

                var command = res.Item2;
                var @params = command.Params;
                if (command.numParams > 0)
                {
                    if (@params[0] == "ベロア")
                    {
                        @params[0] = "べロア"; // Velour Fix
                    }
                }
                switch (command.CommandWithPrefix)
                {
                case CommandTokens.E:
                    var emotion = @params[0] != "," ? @params[0] : DefaultEmotion;
                    if (string.IsNullOrEmpty(charActive) || charActive != charB)
                    {
                        emotionA = emotion;
                    }
                    else
                    {
                        Debug.Assert(charActive == charB, $"{charActive} == {charB}");
                        emotionB = emotion;
                    }
                    break;

                case CommandTokens.Ws:
                    charActive = @params[0];
                    break;

                case CommandTokens.Wm:
                    CharSide = Convert.ToInt32(@params[1]);

                    //NOTE(Robin): Prepare an exception for multiple possible fail states below
                    var unexpectedCharSideException = new ArgumentOutOfRangeException(nameof(CharSide), CharSide,
                                                                                      "Unexpected character side parameter.");

                    switch (conversationType)
                    {
                    case ConversationTypes.Type0:
                    {
                        switch (CharSide)
                        {
                        case 0:
                        case 2:
                            charA    = @params[0];
                            emotionA = DefaultEmotion;
                            break;

                        case 6:
                            charB    = @params[0];
                            emotionB = DefaultEmotion;
                            break;

                        default:
                            throw unexpectedCharSideException;
                        }
                        break;
                    }

                    case ConversationTypes.Type1:
                    {
                        switch (CharSide)
                        {
                        case 3:
                            charA    = @params[0];
                            emotionA = DefaultEmotion;
                            break;

                        case 7:
                            charB    = @params[0];
                            emotionB = DefaultEmotion;
                            break;

                        default:
                            throw unexpectedCharSideException;
                        }
                        break;
                    }

                    default:
                        throw new ArgumentOutOfRangeException(nameof(conversationType), conversationType,
                                                              "Unexpected conversation type.");
                    }
                    break;

                case CommandTokens.Wd:
                    if (charActive == charB)
                    {
                        charActive = charA;
                        charB      = string.Empty;
                    }
                    else
                    {
                        Debug.Assert(charActive == charA, $"{nameof(charActive)} == {nameof(charA)}");
                        charA = string.Empty;
                    }
                    break;

                case CommandTokens.a:
                    hasPerms = true;
                    break;

                case CommandTokens.t0:
                    if (!setType)
                    {
                        conversationType = ConversationTypes.Type0;
                    }
                    setType = true;
                    break;

                case CommandTokens.t1:
                    if (!setType)
                    {
                        conversationType = ConversationTypes.Type1;
                    }
                    setType = true;
                    break;

                case CommandTokens.Nu:
                    line.SpokenText = $"{line.SpokenText.Substring(0, i)}$Nu{line.SpokenText.Substring(i)}";
                    i += 2;
                    break;

                default:
                    Debug.WriteLine($"Unhandled command: {command.CommandWithPrefix}");
                    if (!CommandTokens.IsValid(command.CommandWithPrefix))
                    {
                        throw new ArgumentOutOfRangeException(nameof(command.CommandWithPrefix),
                                                              command.CommandWithPrefix,
                                                              "Unexpected command.");
                    }
                    break;
                }
                i--;
            }

            if (string.IsNullOrWhiteSpace(line.SpokenText))
            {
                line.SpokenText = string.Empty;
            }

            line.SpeechIndex = line.RawLine.LastIndexOf(line.SpokenText, StringComparison.Ordinal);


            line.RawLine    = purify(line.RawLine, false);
            line.SpokenText = purify(line.SpokenText, true);

            return(line.SpokenText);
        }
示例#43
0
        protected override void BeginProcessing()
        {
            string str;

            string[] strArrays = this._computerName;
            for (int i = 0; i < (int)strArrays.Length; i++)
            {
                string str1 = strArrays[i];
                if (str1.Equals("localhost", StringComparison.CurrentCultureIgnoreCase) || str1.Equals(".", StringComparison.OrdinalIgnoreCase))
                {
                    str = "localhost";
                }
                else
                {
                    str = str1;
                }
                string[] strArrays1 = this._logName;
                for (int j = 0; j < (int)strArrays1.Length; j++)
                {
                    string str2 = strArrays1[j];
                    try
                    {
                        if (EventLog.Exists(str2, str1))
                        {
                            if (base.ShouldProcess(StringUtil.Format(EventlogResources.LimitEventLogWarning, str2, str)))
                            {
                                EventLog       eventLog             = new EventLog(str2, str1);
                                int            minimumRetentionDays = eventLog.MinimumRetentionDays;
                                OverflowAction overflowAction       = eventLog.OverflowAction;
                                if (!this.retentionSpecified || !this.overflowSpecified)
                                {
                                    if (!this.retentionSpecified || this.overflowSpecified)
                                    {
                                        if (!this.retentionSpecified && this.overflowSpecified)
                                        {
                                            eventLog.ModifyOverflowPolicy(this._overflowaction, minimumRetentionDays);
                                        }
                                    }
                                    else
                                    {
                                        if (overflowAction.CompareTo(OverflowAction.OverwriteOlder) != 0)
                                        {
                                            ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.InvalidOverflowAction, new object[0])), null, ErrorCategory.InvalidOperation, null);
                                            base.WriteError(errorRecord);
                                            goto Label0;
                                        }
                                        else
                                        {
                                            eventLog.ModifyOverflowPolicy(overflowAction, this._retention);
                                        }
                                    }
                                }
                                else
                                {
                                    if (this._overflowaction.CompareTo(OverflowAction.OverwriteOlder) != 0)
                                    {
                                        ErrorRecord errorRecord1 = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.InvalidOverflowAction, new object[0])), null, ErrorCategory.InvalidOperation, null);
                                        base.WriteError(errorRecord1);
                                        goto Label0;
                                    }
                                    else
                                    {
                                        eventLog.ModifyOverflowPolicy(this._overflowaction, this._retention);
                                    }
                                }
                                if (this.maxkbSpecified)
                                {
                                    int num = 0x400;
                                    this._maximumKilobytes    = this._maximumKilobytes / (long)num;
                                    eventLog.MaximumKilobytes = this._maximumKilobytes;
                                }
                            }
                        }
                        else
                        {
                            ErrorRecord errorRecord2 = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, str2, str)), null, ErrorCategory.InvalidOperation, null);
                            base.WriteError(errorRecord2);
                        }
                    }
                    catch (InvalidOperationException invalidOperationException1)
                    {
                        InvalidOperationException invalidOperationException = invalidOperationException1;
                        this.WriteNonTerminatingError(invalidOperationException, EventlogResources.PermissionDenied, "PermissionDenied", ErrorCategory.PermissionDenied, str2, str);
                    }
                    catch (IOException oException1)
                    {
                        IOException oException = oException1;
                        this.WriteNonTerminatingError(oException, EventlogResources.PathDoesNotExist, "PathDoesNotExist", ErrorCategory.InvalidOperation, null, str);
                    }
                    catch (ArgumentOutOfRangeException argumentOutOfRangeException1)
                    {
                        ArgumentOutOfRangeException argumentOutOfRangeException = argumentOutOfRangeException1;
                        if (this.retentionSpecified || this.maxkbSpecified)
                        {
                            this.WriteNonTerminatingError(argumentOutOfRangeException, EventlogResources.ValueOutofRange, "ValueOutofRange", ErrorCategory.InvalidData, null, null);
                        }
                        else
                        {
                            this.WriteNonTerminatingError(argumentOutOfRangeException, EventlogResources.InvalidArgument, "InvalidArgument", ErrorCategory.InvalidData, null, null);
                        }
                    }
Label0:
                    continue;
                }
            }
        }
示例#44
0
        public static void ThrowIfNecessary(
            this Error error, [CanBeNull] Func <Error, string> message = null)
        {
            if (error == Error.Ok)
            {
                return;
            }

            var code = Enum.GetName(typeof(Error), error);
            var arg  = message?.Invoke(error) ?? $"Operation failed with code: '{code}(error)'";

            Exception exception;

            switch (error)
            {
            case Error.Unauthorized:
            case Error.FileNoPermission:
                exception = new UnauthorizedAccessException(arg);
                break;

            case Error.ParameterRangeError:
                exception = new ArgumentOutOfRangeException(null, arg);
                break;

            case Error.OutOfMemory:
                exception = new OutOfMemoryException(arg);
                break;

            case Error.FileBadDrive:
            case Error.FileBadPath:
            case Error.FileNotFound:
                exception = new FileNotFoundException(arg);
                break;

            case Error.FileAlreadyInUse:
            case Error.FileCantOpen:
            case Error.FileCantRead:
            case Error.FileCorrupt:
            case Error.FileMissingDependencies:
            case Error.FileUnrecognized:
                exception = new FileLoadException(arg);
                break;

            case Error.FileEof:
                exception = new EndOfStreamException(arg);
                break;

            case Error.FileCantWrite:
            case Error.CantAcquireResource:
            case Error.CantOpen:
            case Error.CantCreate:
            case Error.AlreadyInUse:
            case Error.Locked:
                exception = new IOException(arg);
                break;

            case Error.Timeout:
                exception = new TimeoutException(arg);
                break;

            case Error.InvalidData:
                exception = new InvalidDataException(arg);
                break;

            case Error.InvalidParameter:
                exception = new ArgumentException(null, arg);
                break;

            default:
                exception = new InvalidOperationException(arg);
                break;
            }

            throw exception;
        }
示例#45
0
        public IAsyncOperationWithProgress <IBuffer, UInt32> ReadAsync(IBuffer buffer, UInt32 count, InputStreamOptions options)
        {
            if (buffer == null)
            {
                // Mapped to E_POINTER.
                throw new ArgumentNullException("buffer");
            }

            if (count < 0 || Int32.MaxValue < count)
            {
                ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException("count");
                ex.SetErrorCode(HResults.E_INVALIDARG);
                throw ex;
            }

            if (buffer.Capacity < count)
            {
                ArgumentException ex = new ArgumentException(SR.Argument_InsufficientBufferCapacity);
                ex.SetErrorCode(HResults.E_INVALIDARG);
                throw ex;
            }

            if (!(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead))
            {
                ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException("options",
                                                                                 SR.ArgumentOutOfRange_InvalidInputStreamOptionsEnumValue);
                ex.SetErrorCode(HResults.E_INVALIDARG);
                throw ex;
            }

            // Commented due to a reported CCRewrite bug. Should uncomment when fixed:
            //Contract.Ensures(Contract.Result<IAsyncOperationWithProgress<IBuffer, UInt32>>() != null);
            //Contract.EndContractBlock();

            Stream str = EnsureNotDisposed();

            IAsyncOperationWithProgress <IBuffer, UInt32> readAsyncOperation;

            switch (_readOptimization)
            {
            case StreamReadOperationOptimization.MemoryStream:
                readAsyncOperation = StreamOperationsImplementation.ReadAsync_MemoryStream(str, buffer, count);
                break;

            case StreamReadOperationOptimization.AbstractStream:
                readAsyncOperation = StreamOperationsImplementation.ReadAsync_AbstractStream(str, buffer, count, options);
                break;

            // Use this pattern to add more optimisation options if necessary:
            //case StreamReadOperationOptimization.XxxxStream:
            //    readAsyncOperation = StreamOperationsImplementation.ReadAsync_XxxxStream(str, buffer, count, options);
            //    break;

            default:
                Debug.Assert(false, "We should never get here. Someone forgot to handle an input stream optimisation option.");
                readAsyncOperation = null;
                break;
            }

            return(readAsyncOperation);
        }
示例#46
0
        internal void ParsePFDEntry(ushort uTag, ushort uType, uint uCount, uint uValue, byte[] data)
        {
            switch (uTag)
            {
            case WMPMeta.WMP_tagPixelFormat:
                byte[] guidBytes = new byte[16];
                for (int i = 0; i < 16; i++)
                {
                    guidBytes[i] = data[uValue + i];
                }
                Guid guid = new Guid(guidBytes);

                // check if this format is supported
                PixelFormatLookup(guid);
                break;

            case WMPMeta.WMP_tagImageWidth:
            case WMPMeta.WMP_tagImageHeight:
                if (0 == uValue)
                {
                    throw new ArgumentOutOfRangeException("uTag", "WMP_tagImageHeight");
                }
                break;

            case WMPMeta.WMP_tagImageOffset:
                if (1 != uCount)
                {
                    throw new ArgumentOutOfRangeException("uTag", "WMP_tagImageOffset");
                }
                wmiDEMisc.uImageOffset = uValue;
                break;

            case WMPMeta.WMP_tagImageByteCount:
                if (1 != uCount)
                {
                    throw new ArgumentOutOfRangeException("uTag", "WMP_tagImageByteCount");
                }
                wmiDEMisc.uImageByteCount = uValue;
                break;

            case WMPMeta.WMP_tagAlphaOffset:
                if (1 != uCount)
                {
                    throw new ArgumentOutOfRangeException("uTag", "WMP_tagAlphaOffset");
                }
                wmiDEMisc.uAlphaOffset = uValue;
                break;

            case WMPMeta.WMP_tagAlphaByteCount:
                if (1 != uCount)
                {
                    throw new ArgumentOutOfRangeException("uTag", "WMP_tagAlphaByteCount");
                }
                wmiDEMisc.uAlphaByteCount = uValue;
                break;

            case WMPMeta.WMP_tagWidthResolution:
                if (1 != uCount)
                {
                    throw new ArgumentOutOfRangeException("uTag", "WMP_tagWidthResolution");
                }
                //fResX = FloatBits.ToSingle(uValue);
                break;

            case WMPMeta.WMP_tagHeightResolution:
                if (1 != uCount)
                {
                    throw new ArgumentOutOfRangeException("uTag", "WMP_tagHeightResolution");
                }
                //fResX = FloatBits.ToSingle(uValue);
                break;

            case WMPMeta.WMP_tagXMPMetadata:
            case WMPMeta.WMP_tagIccProfile:
            case WMPMeta.WMP_tagEXIFMetadata:
            case WMPMeta.WMP_tagTransformation:
            case WMPMeta.WMP_tagCompression:
            case WMPMeta.WMP_tagImageType:
            case WMPMeta.WMP_tagImageDataDiscard:
            case WMPMeta.WMP_tagAlphaDataDiscard:
                break;

            default:
                // unrecognized WMP_, we hope to continue without problems
                Exception ex = new ArgumentOutOfRangeException("uTag", "Unrecognized PDF entry");
                //ElevationAdjustmentServicePlugin.LogException(
                //    new ExceptionInfo(ex),
                //    "uTag = " + uTag + ", uType = " + uType + ", uCount = " + uCount
                //    + ", uValue = " + uValue,
                //    true);
                break;
            }
        }
示例#47
0
            public void NullValuesThrowArgumentOutOfRangeException()
            {
                var expectedEx = new ArgumentOutOfRangeException("paramName", Exceptions.ArgumentNotLessThanValue.FormatWith(String.Empty));
                var actualEx = Assert.Throws<ArgumentOutOfRangeException>(() => Verify.LessThan(default(IComparable), null, "paramName"));

                Assert.Equal(expectedEx.Message, actualEx.Message);
            }
示例#48
0
        /// <summary>
        /// Helper method that creates the consumer binding.
        /// </summary>
        /// <param name="variableName">Name of the variable.</param>
        /// <param name="typeInfo">The encoding.</param>
        /// <returns>IConsumerBinding.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">variableName</exception>
        private IConsumerBinding GetConsumerBinding(string variableName, UATypeInfo typeInfo)
        {
            _logger.EnteringMethodBinding();
            IConsumerBinding returnValue = null;

            if (typeInfo.ValueRank == 0 || typeInfo.ValueRank > 1)
            {
                ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException(nameof(typeInfo.ValueRank));
                _logger.LogException(nameof(PartIBindingFactory), ex);
                throw ex;
            }
            switch (typeInfo.BuiltInType)
            {
            case BuiltInType.Boolean:
                if (typeInfo.ValueRank < 0)
                {
                    returnValue = AddBinding <bool>(variableName, typeInfo);
                }
                else
                {
                    returnValue = AddBinding <bool[]>(variableName, typeInfo);
                }
                break;

            case BuiltInType.SByte:
                if (typeInfo.ValueRank < 0)
                {
                    returnValue = AddBinding <sbyte>(variableName, typeInfo);
                }
                else
                {
                    returnValue = AddBinding <sbyte[]>(variableName, typeInfo);
                }
                break;

            case BuiltInType.Byte:
                if (typeInfo.ValueRank < 0)
                {
                    returnValue = AddBinding <byte>(variableName, typeInfo);
                }
                else
                {
                    returnValue = AddBinding <byte[]>(variableName, typeInfo);
                }
                break;

            case BuiltInType.Int16:
                if (typeInfo.ValueRank < 0)
                {
                    returnValue = AddBinding <short>(variableName, typeInfo);
                }
                else
                {
                    returnValue = AddBinding <short[]>(variableName, typeInfo);
                }
                break;

            case BuiltInType.UInt16:
                if (typeInfo.ValueRank < 0)
                {
                    returnValue = AddBinding <ushort>(variableName, typeInfo);
                }
                else
                {
                    returnValue = AddBinding <ushort[]>(variableName, typeInfo);
                }
                break;

            case BuiltInType.Int32:
                if (typeInfo.ValueRank < 0)
                {
                    returnValue = AddBinding <int>(variableName, typeInfo);
                }
                else
                {
                    returnValue = AddBinding <int[]>(variableName, typeInfo);
                }
                break;

            case BuiltInType.UInt32:
                if (typeInfo.ValueRank < 0)
                {
                    returnValue = AddBinding <uint>(variableName, typeInfo);
                }
                else
                {
                    returnValue = AddBinding <uint[]>(variableName, typeInfo);
                }
                break;

            case BuiltInType.Int64:
                if (typeInfo.ValueRank < 0)
                {
                    returnValue = AddBinding <long>(variableName, typeInfo);
                }
                else
                {
                    returnValue = AddBinding <long[]>(variableName, typeInfo);
                }
                break;

            case BuiltInType.UInt64:
                if (typeInfo.ValueRank < 0)
                {
                    returnValue = AddBinding <ulong>(variableName, typeInfo);
                }
                else
                {
                    returnValue = AddBinding <ulong[]>(variableName, typeInfo);
                }
                break;

            case BuiltInType.Float:
                if (typeInfo.ValueRank < 0)
                {
                    returnValue = AddBinding <float>(variableName, typeInfo);
                }
                else
                {
                    returnValue = AddBinding <float[]>(variableName, typeInfo);
                }
                break;

            case BuiltInType.Double:
                if (typeInfo.ValueRank < 0)
                {
                    returnValue = AddBinding <double>(variableName, typeInfo);
                }
                else
                {
                    returnValue = AddBinding <double[]>(variableName, typeInfo);
                }
                break;

            case BuiltInType.String:
                if (typeInfo.ValueRank < 0)
                {
                    returnValue = AddBinding <string>(variableName, typeInfo);
                }
                else
                {
                    returnValue = AddBinding <string[]>(variableName, typeInfo);
                }
                break;

            case BuiltInType.DateTime:
                if (typeInfo.ValueRank < 0)
                {
                    returnValue = AddBinding <DateTime>(variableName, typeInfo);
                }
                else
                {
                    returnValue = AddBinding <DateTime[]>(variableName, typeInfo);
                }
                break;

            case BuiltInType.Guid:
                if (typeInfo.ValueRank < 0)
                {
                    returnValue = AddBinding <Guid>(variableName, typeInfo);
                }
                else
                {
                    returnValue = AddBinding <Guid[]>(variableName, typeInfo);
                }
                break;

            case BuiltInType.ByteString:
                if (typeInfo.ValueRank < 0)
                {
                    returnValue = AddBinding <byte[]>(variableName, typeInfo);
                }
                else
                {
                    returnValue = AddBinding <byte[][]>(variableName, typeInfo);
                }
                break;

            case BuiltInType.Null:
            case BuiltInType.XmlElement:
            case BuiltInType.NodeId:
            case BuiltInType.ExpandedNodeId:
            case BuiltInType.StatusCode:
            case BuiltInType.QualifiedName:
            case BuiltInType.LocalizedText:
            case BuiltInType.ExtensionObject:
            case BuiltInType.DataValue:
            case BuiltInType.Variant:
            case BuiltInType.DiagnosticInfo:
            case BuiltInType.Enumeration:
            default:
                throw new ArgumentOutOfRangeException("encoding");
            }
            return(returnValue);
        }
示例#49
0
            public void ActualGreaterThanExpectedThrowsArgumentOutOfRangeException()
            {
                var expectedEx = new ArgumentOutOfRangeException("paramName", 2, Exceptions.ArgumentNotLessThanOrEqualToValue.FormatWith(1));
                var actualEx = Assert.Throws<ArgumentOutOfRangeException>(() => Verify.LessThanOrEqual(1, 2, "paramName"));

                Assert.Equal(expectedEx.Message, actualEx.Message);
            }
        internal static Exception Create <T>(string message, DataGridControl dataGridControl, string argument = "")
        {
            Exception exception;

            var exceptionType = typeof(T);

            if (typeof(ArgumentException) == exceptionType)
            {
                exception = new ArgumentException(message, argument);
            }
            else if (typeof(ArgumentNullException) == exceptionType)
            {
                exception = new ArgumentNullException(message);
            }
            else if (typeof(ArgumentOutOfRangeException) == exceptionType)
            {
                exception = new ArgumentOutOfRangeException(argument, message);
            }
            else if (typeof(IndexOutOfRangeException) == exceptionType)
            {
                exception = new IndexOutOfRangeException(message);
            }
            else if (typeof(InvalidOperationException) == exceptionType)
            {
                exception = new InvalidOperationException(message);
            }
            else if (typeof(NotSupportedException) == exceptionType)
            {
                exception = new NotSupportedException(message);
            }
            else if (typeof(DataGridException) == exceptionType)
            {
                return(new DataGridException(message, dataGridControl));
            }
            else if (typeof(DataGridInternalException) == exceptionType)
            {
                return(new DataGridInternalException(message, dataGridControl));
            }
            else
            {
                exception = new Exception(message);
            }

            if (dataGridControl != null)
            {
                var name = dataGridControl.GridUniqueName;
                if (string.IsNullOrEmpty(name))
                {
                    name = dataGridControl.Name;
                }

                if (!string.IsNullOrEmpty(name))
                {
                    exception.Source = name;
                }
            }

            Debug.Assert(exception != null);

            return(exception);
        }
示例#51
0
            /// <summary>
            /// Decompresses an individual record.
            /// </summary>
            /// <param name="arzFile">ARZ file which we are decompressing.</param>
            /// <returns>decompressed DBRecord.</returns>
            public DBRecordCollection Decompress(ArzFile arzFile)
            {
                // record variables have this format:
                // 0x00 int16 specifies data type:
                //      0x0000 = int - data will be an int32
                //      0x0001 = float - data will be a Single
                //      0x0002 = string - data will be an int32 that is index into string table
                //      0x0003 = bool - data will be an int32
                // 0x02 int16 specifies number of values (usually 1, but sometimes more (for arrays)
                // 0x04 int32 key string ID (the id into the string table for this variable name
                // 0x08 data value
                byte[] data = this.DecompressBytes(arzFile);

                int numberOfDWords = data.Length / 4;

                if (data.Length % 4 != 0)
                {
                    var ex = new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Error while parsing arz record {0}, data Length = {1} which is not a multiple of 4", this.ID, (int)data.Length));
                    Log.ErrorException(ex);
                    throw ex;
                }

                DBRecordCollection record = new DBRecordCollection(this.ID, this.RecordType);

                // Create a memory stream to read the binary data
                using (BinaryReader inReader = new BinaryReader(new MemoryStream(data, false)))
                {
                    int i = 0;
                    while (i < numberOfDWords)
                    {
                        short  dataType     = inReader.ReadInt16();
                        short  valCount     = inReader.ReadInt16();
                        int    variableID   = inReader.ReadInt32();
                        string variableName = arzFile.Getstring(variableID);

                        if (variableName == null)
                        {
                            var ex = new ArgumentNullException(string.Format(CultureInfo.InvariantCulture, "Error while parsing arz record {0}, variable is NULL", this.ID));
                            Log.ErrorFormat(CultureInfo.InvariantCulture, "Error in ARZFile - {0}", arzFile.fileName);
                            Log.ErrorException(ex);
                            throw ex;
                        }

                        if (dataType < 0 || dataType > 3)
                        {
                            var ex = new ArgumentOutOfRangeException(string.Format(CultureInfo.InvariantCulture, "Error while parsing arz record {0}, variable {1}, bad dataType {2}", this.ID, variableName, dataType));
                            Log.ErrorFormat(CultureInfo.InvariantCulture, "Error in ARZFile - {0}", arzFile.fileName);
                            Log.ErrorException(ex);
                            throw ex;
                        }

                        Variable v = new Variable(variableName, (VariableDataType)dataType, valCount);

                        if (valCount < 1)
                        {
                            var ex = new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Error while parsing arz record {0}, variable {1}, bad valCount {2}", this.ID, variableName, valCount));
                            Log.ErrorFormat(CultureInfo.InvariantCulture, "Error in ARZFile - {0}", arzFile.fileName);
                            Log.ErrorException(ex);
                            throw ex;
                        }

                        // increment our dword count
                        i += 2 + valCount;

                        for (int j = 0; j < valCount; ++j)
                        {
                            switch (v.DataType)
                            {
                            case VariableDataType.Integer:
                            case VariableDataType.Boolean:
                            {
                                int val = inReader.ReadInt32();
                                v[j] = val;
                                break;
                            }

                            case VariableDataType.Float:
                            {
                                float val = inReader.ReadSingle();
                                v[j] = val;
                                break;
                            }

                            case VariableDataType.StringVar:
                            {
                                int    id  = inReader.ReadInt32();
                                string val = arzFile.Getstring(id);
                                if (val == null)
                                {
                                    val = string.Empty;
                                }
                                else
                                {
                                    val = val.Trim();
                                }

                                v[j] = val;
                                break;
                            }

                            default:
                            {
                                int val = inReader.ReadInt32();
                                v[j] = val;
                                break;
                            }
                            }
                        }

                        record.Set(v);
                    }
                }

                return(record);
            }
    public bool PosTest3()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest3: The string argument for message is a null reference");

        try
        {
            string paramName = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH);
            string Value = null;
            ArgumentOutOfRangeException argumentOutOfRangeException = new ArgumentOutOfRangeException(paramName, Value);
            if ((argumentOutOfRangeException.Message != "Exception of type 'System.ArgumentOutOfRangeException' was thrown." + TestLibrary.Env.NewLine + "Parameter name: " + paramName) &
                (argumentOutOfRangeException.Message != "Exception of type 'System.ArgumentOutOfRangeException' was thrown."))
            {
                TestLibrary.TestFramework.LogError("005", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
        public void Allocate_IncorrectAmount_ThrowsCorrect_ArgumentOutOfRangeException(int length)
        {
            ArgumentOutOfRangeException ex = Assert.Throws <ArgumentOutOfRangeException>(() => this.MemoryAllocator.Allocate <BigStruct>(length));

            Assert.Equal("length", ex.ParamName);
        }
示例#54
0
        public override void RunCommand(object sender)
        {
            var engine           = (AutomationEngineInstance)sender;
            var exceptionMessage = v_ExceptionMessage.ConvertUserVariableToString(engine);

            Exception ex;

            switch (v_ExceptionType)
            {
            case "AccessViolationException":
                ex = new AccessViolationException(exceptionMessage);
                break;

            case "ArgumentException":
                ex = new ArgumentException(exceptionMessage);
                break;

            case "ArgumentNullException":
                ex = new ArgumentNullException(exceptionMessage);
                break;

            case "ArgumentOutOfRangeException":
                ex = new ArgumentOutOfRangeException(exceptionMessage);
                break;

            case "DivideByZeroException":
                ex = new DivideByZeroException(exceptionMessage);
                break;

            case "Exception":
                ex = new Exception(exceptionMessage);
                break;

            case "FileNotFoundException":
                ex = new FileNotFoundException(exceptionMessage);
                break;

            case "FormatException":
                ex = new FormatException(exceptionMessage);
                break;

            case "IndexOutOfRangeException":
                ex = new IndexOutOfRangeException(exceptionMessage);
                break;

            case "InvalidDataException":
                ex = new InvalidDataException(exceptionMessage);
                break;

            case "InvalidOperationException":
                ex = new InvalidOperationException(exceptionMessage);
                break;

            case "KeyNotFoundException":
                ex = new KeyNotFoundException(exceptionMessage);
                break;

            case "NotSupportedException":
                ex = new NotSupportedException(exceptionMessage);
                break;

            case "NullReferenceException":
                ex = new NullReferenceException(exceptionMessage);
                break;

            case "OverflowException":
                ex = new OverflowException(exceptionMessage);
                break;

            case "TimeoutException":
                ex = new TimeoutException(exceptionMessage);
                break;

            default:
                throw new NotImplementedException("Selected exception type " + v_ExceptionType + " is not implemented.");
            }
            throw ex;
        }