Example #1
0
        internal static IndexOutOfRangeException IndexOutOfRange(string error)
        {
            IndexOutOfRangeException e = new IndexOutOfRangeException(error);

            TraceExceptionAsReturnValue(e);
            return(e);
        }
Example #2
0
        public void ShouldReturnException_WhenIncorrectAttackCoordinatesProvided(
            int boardRows, int boardColumns,
            int placementRow, int placementColumn,
            int attackRow, int attackColumn,
            ShipType shipType)
        {
            //arrange

            //first create a board
            var boardCreator = new BoardCreator();
            var board        = boardCreator.CreateBoard(boardRows, boardColumns);

            //then create a ship
            var shipCreator = new ShipCreator();
            var ship        = shipCreator.CreateShip(shipType);

            //place the ship on the board
            var shipPlacer = new ShipPlacer();

            shipPlacer.AddShipToBoard(ship, board, placementRow, placementColumn);

            //act
            //now attack the ship at the given position
            var attacker = new Attacker();
            IndexOutOfRangeException ex = Assert.Throws <IndexOutOfRangeException>(() =>
                                                                                   attacker.Attack(board, attackRow, attackColumn));

            //assert
            Assert.Equal("Attack position is out of bounds", ex.Message);
        }
Example #3
0
        public bool put(string strId, string strToken, string strValue)
        {
            IDENTIFIER idTemp = (IDENTIFIER)hashSymbolTable[strId];

            if (idTemp == null || idTemp.Scope == "NULL" && idTemp.Lexeme == "NULL")
            {
                IndexOutOfRangeException e = new IndexOutOfRangeException();

                throw e;
            }

            if (strToken != KEEP)
            {
                idTemp.Token = strToken;
                idTemp.CheckForArr();
            }

            if (strValue != KEEP)
            {
                idTemp.Value = strValue;
                idTemp.CheckForArr();
            }

            hashSymbolTable[strId] = idTemp;

            return(true);
        }
Example #4
0
        /* This method returns the value of the desired index of the desired table entry, for array entries. You should
         * pass the key of the entry you desire to get the value of, and the index (1 indexing for the array)
         * (index 0 is the size of the array do not change the size of the array). You can check other scopes by using
         * the hashkey(string, string) method.
         */
        /* Variable             Type                Purpose
         * charArray            char[]              it is used as the parameter of string split method
         * id                   string              it hold the key to be referenced
         * idEntry              IDENTIFIER          it hold the returned identier
         * value                int                 it holds the index of the desired element in the array
         * strArray             string[]            it is used to hold the substring generated by string split
         */
        public string get(string id, int value)
        {
            IndexOutOfRangeException e = new IndexOutOfRangeException();

            IDENTIFIER idEntry = new IDENTIFIER((IDENTIFIER)hashSymbolTable[id]);

            if (idEntry.Scope == "NULL")
            {
                throw (e);
            }

            char[] charArray = new char[1];

            charArray[0] = ' ';

            string[] strArray = new string[100];

            strArray = idEntry.Value.Split(charArray);

            try
            {
                return(strArray[value]);
            }
            catch (IndexOutOfRangeException)
            {
                return("NOT_FOUND");
            }
        }
Example #5
0
        public void LoadImageTest_ThrowsIndexOutOfRangeException_indexZero()
        {
            IndexOutOfRangeException indexOutOfRangeException = Should.Throw <IndexOutOfRangeException>(() =>
                                                                                                        WimgApi.LoadImage(TestWimHandle, 0));

            indexOutOfRangeException.Message.ShouldBe("There is no image at index 0.");
        }
        public void IsBadRequestException_CustomBadRequestException()
        {
            HystrixCommandBase.RegisterCustomBadRequestExceptionChecker("custom", ex => ex is IndexOutOfRangeException);
            Exception ex2 = new IndexOutOfRangeException();

            Assert.IsTrue(ex2.IsBadRequestException());
        }
Example #7
0
        public static T GetColumnValue <T>(this IDataReader reader, params string[] columnNames)
        {
            bool foundValue = false;
            T    value      = default(T);
            IndexOutOfRangeException lastException = null;

            foreach (string columnName in columnNames)
            {
                try
                {
                    int ordinal = reader.GetOrdinal(columnName);
                    value      = (T)reader.GetValue(ordinal);
                    foundValue = true;
                }
                catch (IndexOutOfRangeException ex)
                {
                    lastException = ex;
                }
            }

            if (!foundValue)
            {
                string message = string.Format("Column(s) {0} could not be not found.",
                                               string.Join(", ", columnNames));

                throw new IndexOutOfRangeException(message, lastException);
            }

            return(value);
        }
Example #8
0
        /// <summary>
        /// 从列表中随机返回一个项
        /// </summary>
        /// <typeparam name="T">泛型类型</typeparam>
        /// <param name="list">扩展方法的实例对象</param>
        /// <param name="random">随机数生成器</param>
        /// <returns>列表中的随机项</returns>
        public static T GetRandomItem <T>(this List <T> list, Random random = null)
        {
            if (random == null)
            {
                random = selfRandom;
            }

            T result;

            if (list.Count == 0)
            {
                IndexOutOfRangeException e = new IndexOutOfRangeException("列表内容为空");
                throw e;
            }

            if (list.Count == 1)
            {
                result = list[0];
            }
            else
            {
                result = list[random.Next(0, list.Count - 1)];
            }
            return(result);
        }
Example #9
0
 public int this[int index, int index2]
 {
     get
     {
         try
         {
             return(_data[index, index2]);
         }
         catch (IndexOutOfRangeException ex)
         {
             IndexOutOfRangeException argEx = new IndexOutOfRangeException("Inaccessible index of matrix", ex);
             throw argEx;
         }
     }
     set
     {
         try
         {
             _data[index, index2] = value;
         }
         catch (IndexOutOfRangeException ex)
         {
             IndexOutOfRangeException argEx = new IndexOutOfRangeException("Inaccessible index of matrix", ex);
             throw argEx;
         }
     }
 }
Example #10
0
        public void DeleteImageTest_ThrowsIndexOutOfRangeException_indexOutOfRange()
        {
            IndexOutOfRangeException indexOutOfRangeException = Should.Throw <IndexOutOfRangeException>(() =>
                                                                                                        WimgApi.DeleteImage(TestWimHandle, 10));

            indexOutOfRangeException.Message.ShouldBe("There is no image at index 10.");
        }
Example #11
0
 public static TestFactory GetTest(int index)
 {
     #region checks
     if (Functions == null)
     {
         throw new NullReferenceException("Functions == null");
     }
     if (index >= Functions.Count)
     {
         var ex = new IndexOutOfRangeException
                      ($"Запрашиваемый индекс(={index}) превышает количество={Functions.Count} Functions.");
         ex.Data.Add("indexToGet", index);
         ex.Data.Add("totalCount", Functions.Count);
         throw ex;
     }
     #endregion
     var objectClass = Functions[index]?.Target;
     if (objectClass != null)
     {
         if (objectClass.GetType() == typeof(TestFactory))
         {
             return((TestFactory)objectClass);
         }
         logger.Trace($"тип теста = {objectClass.GetType()}");
     }
     return(null);
 }
        public void Offline_Error_Fused()
        {
            var ms = new MonocastSubject <int>();
            var ex = new IndexOutOfRangeException();

            ms.OnNext(1);
            ms.OnNext(2);
            ms.OnNext(3);
            ms.OnError(ex);

            Assert.False(ms.HasObservers);
            Assert.True(ms.HasException());
            Assert.False(ms.HasCompleted());
            Assert.AreEqual(ex, ms.GetException());

            var to = ms.Test(fusionMode: FusionSupport.Any);

            Assert.False(ms.HasObservers);

            to.AssertFuseable()
            .AssertFusionMode(FusionSupport.Async);

            to.AssertFailure(typeof(IndexOutOfRangeException), 1, 2, 3);


            ms.Test().AssertFailure(typeof(InvalidOperationException));
        }
Example #13
0
        public void ShouldFailToPlaceAShip_WhenIncorrectCorrectPositionsProvided(
            int boardRows, int boardColumns,
            int placementRow, int placementColumn,
            ShipType shipType)
        {
            //arrange

            //first create a board
            var boardCreator = new BoardCreator();
            var board        = boardCreator.CreateBoard(boardRows, boardColumns);

            //then create a ship
            var shipCreator = new ShipCreator();
            var ship        = shipCreator.CreateShip(shipType);

            //act
            //now place the ship on the board
            var shipPlacer = new ShipPlacer();

            IndexOutOfRangeException ex = Assert.Throws <IndexOutOfRangeException>(() =>
                                                                                   shipPlacer.AddShipToBoard(ship, board, placementRow, placementColumn));

            //assert
            Assert.Equal("Ship's placement position is out of bounds", ex.Message);
        }
Example #14
0
        public void ShouldReactToThirdFailure()
        {
            var normalPeriod = TimeSpan.FromMilliseconds(50);
            var maxPeriod    = TimeSpan.FromSeconds(2);

            var exception1 = new InvalidOperationException("Boom");

            var exception2 = new InvalidCastException("Boom2");

            var exception3 = new IndexOutOfRangeException("Boom3");

            var failContext = new FailureContext(normalPeriod, maxPeriod, () => DateTime.Now);

            failContext.SetException(exception1);

            var timeOfFirstFailure = failContext.FirstFailureDateTime;

            failContext.SetException(exception2);

            // call

            failContext.SetException(exception3);

            // assert
            failContext.FirstFailureDateTime.Should().Be(timeOfFirstFailure);


            failContext.Period.Should().Be(normalPeriod);
            failContext.CurrentPeriod.Should().Be(TimeSpan.FromMilliseconds(200));
            failContext.MaxPeriod.Should().Be(maxPeriod);

            failContext.FailCount.Should().Be(3);
            failContext.Exception.Should().Be(exception3);
        }
Example #15
0
    protected void ddlExceptionType_SelectedIndexChanged(object sender, EventArgs e)
    {
        string exType = ddlExceptionType.SelectedValue;

        switch (exType)
        {
        case "InvalidOperationException":
            InvalidOperationException ioe = new InvalidOperationException("This is a test.");
            throw ioe;

        case "ArgumentException":
            ArgumentException ae = new ArgumentException("This is a test.");
            throw ae;

        case "NullReferenceException":
            NullReferenceException ne = new NullReferenceException("This is a test.");
            throw ne;

        case "AccessViolationException":
            AccessViolationException ave = new AccessViolationException("This is a test.");
            throw ave;

        case "IndexOutOfRangeException":
            IndexOutOfRangeException iore = new IndexOutOfRangeException("This is a test.");
            throw iore;

        case "StackOverflowException":
            StackOverflowException soe = new StackOverflowException("This is a test.");
            throw soe;

        default:
            throw new Exception("This is a test.");
        }
    }
Example #16
0
        public static T GetColumnValue <T>(this IDataReader reader, params string[] columnNames)
        {
            bool foundValue = false;
            T    value      = default(T);
            IndexOutOfRangeException lastException = null;

            foreach (string columnName in columnNames)
            {
                try
                {
                    int ordinal = reader.GetOrdinal(columnName);
                    if (!reader.IsDBNull(ordinal))
                    {
                        value = (T)reader.GetValue(ordinal);
                    }
                    foundValue = true;//may be found but is db-null
                }
                catch (IndexOutOfRangeException ex)
                {
                    lastException = ex;
                }
            }

            if (!foundValue)
            {
                var    names   = string.Join(", ", columnNames);
                string message = $"Column(s) {names} could not be not found.";

                throw new IndexOutOfRangeException(message, lastException);
            }

            return(value);
        }
Example #17
0
        /// <summary>
        /// Loads the service app which should be added to the pool of service apps.
        /// </summary>
        /// <param name="appName">Name of the application.</param>
        /// <param name="dao">The DAO.</param>
        /// <returns>A string containing an error message if a recoverable error occured.</returns>
        /// <exception cref="System.IndexOutOfRangeException">The ServiceApp could not be found in the container.</exception>
        /// <exception cref="System.InvalidOperationException">The ServiceApp is not in a stopped state.</exception>
        public string InitializeServiceApp(string appName, IServiceAppDao dao)
        {
            ServiceAppProcess process = this.ServiceAppProcesses[appName];

            if (process == null)
            {
                var e = new IndexOutOfRangeException(string.Format("ServiceApp '{0}' could not be found to initialize.", appName));
                this._log.Error("Error in InitializeServiceApp", e);
                throw e;
            }
            else if (process.IsProcessRunning)
            {
                var e = new InvalidOperationException(string.Format("ServiceApp '{0}' must be stopped before it can be reinitialized.", appName));
                this._log.Error("Error in InitializeServiceApp", e);
                throw e;
            }

            if (process.ServiceApp.StartupTypeEnum != StartupType.Disabled)
            {
                process.Start();
                return(string.Empty);
            }
            else
            {
                return(string.Format("ServiceApp '{0}' is disabled", appName));
            }
        }
        public void When_retrying_a_task_that_throws_aggregate_exception_two()
        {
            var counter = 0;

            var retryEx = Should.Throw <RetryException>(async() =>
            {
                await Retry.On <IndexOutOfRangeException>(
                    () => Task.Factory.StartNew(() =>
                {
                    counter++;
                    var inner1 = new ArgumentNullException("someArg1");
                    var inner2 = new IndexOutOfRangeException("someArg2");
                    throw new AggregateException(inner1, inner2);
                    return(1);
                }),
                    100.Milliseconds(),
                    100.Milliseconds(),
                    100.Milliseconds());
            });

            retryEx.RetryCount.ShouldBe((uint)3);
            retryEx.InnerException.ShouldBeOfType <AggregateException>();
            retryEx.Message.ShouldBe("Retry failed after: 3 attempts.");

            counter.ShouldBe(4);
        }
Example #19
0
        public void TestIobExceptionOnInvalidIndex()
        {
            IWorkbook                 wb            = new HSSFWorkbook();
            ISheet                    sheet         = new SheetBuilder(wb, numericCells).Build();
            CellRangeAddress          rangeAddress  = CellRangeAddress.ValueOf("A2:E2");
            IChartDataSource <double> numDataSource = DataSources.FromNumericCellRange(sheet, rangeAddress);
            IndexOutOfRangeException  exception     = null;

            try
            {
                numDataSource.GetPointAt(-1);
            }
            catch (IndexOutOfRangeException e)
            {
                exception = e;
            }
            Assert.IsNotNull(exception);

            exception = null;
            try
            {
                numDataSource.GetPointAt(numDataSource.PointCount);
            }
            catch (IndexOutOfRangeException e)
            {
                exception = e;
            }
            Assert.IsNotNull(exception);
        }
Example #20
0
        internal static Exception CreateException(NNStreamerError err, string msg)
        {
            Exception exp;

            switch (err)
            {
            case NNStreamerError.InvalidParameter:
                exp = new ArgumentException(msg);
                break;

            case NNStreamerError.NotSupported:
                exp = new NotSupportedException(msg);
                break;

            case NNStreamerError.StreamsPipe:
            case NNStreamerError.TryAgain:
                exp = new IOException(msg);
                break;

            case NNStreamerError.TimedOut:
                exp = new TimeoutException(msg);
                break;

            case NNStreamerError.QuotaExceeded:
                exp = new IndexOutOfRangeException(msg);
                break;

            default:
                exp = new NotSupportedException(msg);
                break;
            }
            return(exp);
        }
        public static void Ctor_String()
        {
            string message   = "out of range";
            var    exception = new IndexOutOfRangeException(message);

            ExceptionUtility.ValidateExceptionProperties(exception, hResult: COR_E_INDEXOUTOFRANGE, message: message);
        }
Example #22
0
        // RemoveAt(int index) method - just like the List<T> RemoveAt(int index) method
        public void RemoveAt(int index)
        {
            if (index < 0 || index >= this.count || this.count == 0)
            {
                IndexOutOfRangeException indexOutOfRangeException = new IndexOutOfRangeException();
                throw new IndexOutOfRangeException(indexOutOfRangeException.Message);
            }

            T[] arrayClone = (T[])this.array.Clone();
            this.array = new T[this.capacity];

            // Copy all the elements from 0 to index - 1
            for (int i = 0; i < index; i++)
            {
                this.array[i] = arrayClone[i];
            }

            // Copy all the elements from index + 1 to count - 1
            for (int i = index + 1; i < this.count; i++)
            {
                this.array[i - 1] = arrayClone[i];
            }

            this.count--;
        }
Example #23
0
        // Insert(int index, T element) method - just like the List<T> Insert(int index, T element) method
        public void Insert(int index, T element)
        {
            if (index < 0 || index >= this.count || this.count == 0)
            {
                IndexOutOfRangeException indexOutOfRangeException = new IndexOutOfRangeException();
                throw new IndexOutOfRangeException(indexOutOfRangeException.Message);
            }

            T[] arrayClone = (T[])this.array.Clone();

            if (this.count == this.capacity)
            {
                this.array    = new T[2 * this.capacity];
                this.capacity = 2 * this.capacity;
            }

            for (int i = 0; i < index; i++)
            {
                this.array[i] = arrayClone[i];
            }

            this.array[index] = element;

            for (int i = index + 1; i <= count; i++)
            {
                this.array[i] = arrayClone[i - 1];
            }

            count++;
        }
        public void Execute_DoesNotWrapThrownExceptionsInAggregateExceptions()
        {
            // Arrange
            var expected = new IndexOutOfRangeException();

            var view = new Mock <IView>();

            view.Setup(v => v.RenderAsync(It.IsAny <ViewContext>()))
            .Throws(expected)
            .Verifiable();

            var viewEngine = new Mock <IViewEngine>(MockBehavior.Strict);

            viewEngine.Setup(e => e.FindPartialView(It.IsAny <ActionContext>(), It.IsAny <string>()))
            .Returns(ViewEngineResult.Found("some-view", view.Object))
            .Verifiable();

            var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());

            var result = new ViewViewComponentResult
            {
                ViewEngine = viewEngine.Object,
                ViewName   = "some-view",
                ViewData   = viewData
            };

            var viewComponentContext = GetViewComponentContext(view.Object, viewData);

            // Act
            var actual = Record.Exception(() => result.Execute(viewComponentContext));

            // Assert
            Assert.Same(expected, actual);
            view.Verify();
        }
        public ActionResult Index(SearchModel model)
        {
            model.Results = _searchProvider.Search(model.SearchText);

            // Send the event
            TelemetryClient client = new TelemetryClient();

            var properties = new Dictionary <string, string>
            {
                { "searchText", model.SearchText }
            };
            var measurements = new Dictionary <string, double>
            {
                { "results", model.Results.Count }
            };

            Random r    = new Random();
            int    rInt = r.Next(0, 100);

            if (rInt > 80)
            {
                var exception = new IndexOutOfRangeException();
                client.TrackException(exception, properties, measurements);
            }

            client.TrackEvent("Search Screen", properties, measurements);

            return(View(model));
        }
        public void DefaultConstructorWorks()
        {
            var ex = new IndexOutOfRangeException();

            Assert.True((object)ex is IndexOutOfRangeException, "is IndexOutOfRangeException");
            Assert.AreEqual(null, ex.InnerException, "InnerException");
            Assert.AreEqual(IndexOutOfRangeExceptionTests.DefaultMessage, ex.Message);
        }
        public void ConstructorWithMessageWorks()
        {
            var ex = new IndexOutOfRangeException("The message");

            Assert.True((object)ex is IndexOutOfRangeException, "is IndexOutOfRangeException");
            Assert.AreEqual(null, ex.InnerException, "InnerException");
            Assert.AreEqual("The message", ex.Message);
        }
Example #28
0
        public static void Ctor_String_Exception()
        {
            string message        = "out of range";
            var    innerException = new Exception("Inner exception");
            var    exception      = new IndexOutOfRangeException(message, innerException);

            ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_INDEXOUTOFRANGE, innerException: innerException, message: message);
        }
Example #29
0
 public void Add(int row, int col, int value)
 {
     if (this.matrix.GetLength(0) <= row || col >= this.matrix.GetLength(1))
     {
         IndexOutOfRangeException ioore = new IndexOutOfRangeException();
         Console.Error.WriteLine(ioore.Message);
     }
     matrix[row, col] = value;
 }
Example #30
0
        public void ReportException_PropagatedAsEventPayload()
        {
            (DiagnosticListener listener, MockObserver mockObserver) = MockObserver.CreateListener();
            Exception exception = new IndexOutOfRangeException();

            listener.ReportException(exception);

            mockObserver.AssertException(exception);
        }
 public bool PosTest1()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest1:Initialize the IndexOutOfRangeException instance");
     try
     {
         IndexOutOfRangeException myException = new IndexOutOfRangeException();
         if (myException == null)
         {
             TestLibrary.TestFramework.LogError("001", "the IndexOutOfRangeException instance creating failed");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
         retVal = false;
     }
     return retVal;
 }
 public bool PosTest1()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest1:Initialize the IndexOutOfRangeException instance with message 1");
     try
     {
         string message = "HelloWorld";
         IndexOutOfRangeException myException = new IndexOutOfRangeException(message);
         if (myException == null || myException.Message != message)
         {
             TestLibrary.TestFramework.LogError("001", "the IndexOutOfRangeException with message instance creating failed");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
         retVal = false;
     }
     return retVal;
 }
 public bool PosTest3()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest3:Initialize the IndexOutOfRangeException instance with message and InnerException 3");
     try
     {
         string message = null;
         IndexOutOfRangeException myException = new IndexOutOfRangeException(message, null);
         if (myException == null || myException.Message == null || myException.InnerException != null)
         {
             TestLibrary.TestFramework.LogError("005", "Initialize the IndexOutOfRangeException instance with null message and null InnerException not succeed");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
         retVal = false;
     }
     return retVal;
 }
 public bool PosTest2()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest2:Initialize the IndexOutOfRangeException instance with message 2");
     try
     {
         string message = null;
         IndexOutOfRangeException myException = new IndexOutOfRangeException(message);
         if (myException == null || myException.Message == null)
         {
             TestLibrary.TestFramework.LogError("003", "Initialize the IndexOutOfRangeException instance with null message not create");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
         retVal = false;
     }
     return retVal;
 }
 public bool PosTest2()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest2:Initialize the IndexOutOfRangeException instance with message and InnerException 2");
     try
     {
         string message = null;
         ArgumentException innerException = new ArgumentException();
         IndexOutOfRangeException myException = new IndexOutOfRangeException(message,innerException);
         if (myException == null || myException.Message == null || !myException.InnerException.Equals(innerException))
         {
             TestLibrary.TestFramework.LogError("003", "Initialize the IndexOutOfRangeException instance with null message not succeed");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
         retVal = false;
     }
     return retVal;
 }
Example #36
0
 static internal IndexOutOfRangeException IndexOutOfRange(int value)
 {
     IndexOutOfRangeException e = new IndexOutOfRangeException(value.ToString(CultureInfo.InvariantCulture));
     return e;
 }
Example #37
0
 static internal IndexOutOfRangeException IndexOutOfRange()
 {
     IndexOutOfRangeException e = new IndexOutOfRangeException();
     return e;
 }
Example #38
0
 static internal IndexOutOfRangeException IndexOutOfRange(string error)
 {
     IndexOutOfRangeException e = new IndexOutOfRangeException(error);
     return e;
 }