public void TestArgumentOutOfRangeException()
        {
            ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException("testArgument", "testArgument is out of range");
            this.ExecuteExceptionHandler(ex);    

            this.mockFactory.VerifyAllExpectationsHaveBeenMet();
        }
Ejemplo n.º 2
0
        public static void ConfigureExceptionHandler(this IApplicationBuilder app)
        {
            app.UseExceptionHandler(error =>
            {
                error.Run(async context =>
                {
                    var exceptionHandlerFeature = context.Features.Get <IExceptionHandlerFeature>();
                    var exception = exceptionHandlerFeature.Error;

                    var statusCode = exception switch
                    {
                        ResourceNotFoundException _ => (int)HttpStatusCode.NotFound,
                        ModelFormatException _ => (int)HttpStatusCode.PreconditionFailed,
                        ArgumentOutOfRangeException _ => (int)HttpStatusCode.BadRequest,
                        ResourceAlreadyExistsException _ => (int)HttpStatusCode.Conflict,
                        _ => (int)HttpStatusCode.InternalServerError
                    };

                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode  = statusCode;

                    await context.Response.WriteAsync(new ExceptionModel
                    {
                        StatusCode = statusCode,
                        Message    = exception.Message
                    }.ToString());
                });
            });
        }
Ejemplo n.º 3
0
 public T this[int index]
 {
     get
     {
         if (index < 0 || index >= count)
         {
             System.ArgumentException argEx = new System.ArgumentOutOfRangeException();
             throw argEx;
         }
         else
         {
             return(array[index]);
         }
     }
     set
     {
         if (index < 0 || index >= count)
         {
             System.ArgumentException argEx = new System.ArgumentOutOfRangeException();
             throw argEx;
         }
         else
         {
             array[index] = value;
         }
     }
 }
Ejemplo n.º 4
0
        static void Main(string[] args) {

            // create the tasks
            Task task1 = new Task(() => {
                ArgumentOutOfRangeException exception = new ArgumentOutOfRangeException();
                exception.Source = "task1";
                throw exception;
            });
            Task task2 = new Task(() => {
                throw new NullReferenceException();
            });
            Task task3 = new Task(() => {
                Console.WriteLine("Hello from Task 3");
            });

            // start the tasks
            task1.Start(); task2.Start(); task3.Start();

            // wait for all of the tasks to complete
            // and wrap the method in a try...catch block
            try {
                Task.WaitAll(task1, task2, task3);
            } catch (AggregateException ex) {
                // enumerate the exceptions that have been aggregated
                foreach (Exception inner in ex.InnerExceptions) {
                    Console.WriteLine("Exception type {0} from {1}",
                        inner.GetType(), inner.Source);
                }
            }

            // wait for input before exiting
            Console.WriteLine("Main method complete. Press enter to finish.");
            Console.ReadLine();
        }
        protected override void GivenThat()
        {
            base.GivenThat();

            InitialItems = Enumerable.Create("first", "second");
            _expectedException = new ArgumentOutOfRangeException("index", "Index was out of range. Must be non-negative and less than the size of the collection.");
        }
 public void ThrownExceptionsAreAddedToListByDefault()
 {
     var ex = new ArgumentOutOfRangeException();
     var list = new List<Exception>();
     list.AddThrown(() => { throw ex; });
     Assert.AreEqual(1, list.Count);
     Assert.AreSame(ex, list[0]);
 }
Ejemplo n.º 7
0
 public void Should_ThrowError_Number_LessThan1_MoreThan3999(int number)
 {
     var expected = new ArgumentOutOfRangeException(RomanConverter.ErrOutOfRange);
     Assert.Throws(Is.TypeOf<ArgumentOutOfRangeException>().And.Message.EqualTo(expected.Message), delegate
     {
         RomanConverter.Validate(number);
     });
 }
		public void DefaultConstructorWorks() {
			var ex = new ArgumentOutOfRangeException();
			Assert.IsTrue((object)ex is ArgumentOutOfRangeException, "is ArgumentOutOfRangeException");
			Assert.IsTrue(ex.ParamName == null, "ParamName");
			Assert.IsTrue(ex.InnerException == null, "InnerException");
			Assert.IsTrue(ex.ActualValue == null, "ActualValue");
			Assert.AreEqual(ex.Message, "Value is out of range.");
		}
 public void TypePropertiesAreCorrect()
 {
     Assert.AreEqual(typeof(ArgumentOutOfRangeException).GetClassName(), "Bridge.ArgumentOutOfRangeException", "Name");
     object d = new ArgumentOutOfRangeException();
     Assert.True(d is ArgumentOutOfRangeException, "is ArgumentOutOfRangeException");
     Assert.True(d is ArgumentException, "is ArgumentException");
     Assert.True(d is Exception, "is Exception");
 }
		public void ConstructorWithParamNameAndActualValueAndMessageWorks() {
			var ex = new ArgumentOutOfRangeException("someParam", 42, "The message");
			Assert.IsTrue((object)ex is ArgumentOutOfRangeException, "is ArgumentOutOfRangeException");
			Assert.AreEqual(ex.ParamName, "someParam", "ParamName");
			Assert.IsTrue(ex.InnerException == null, "InnerException");
			Assert.AreEqual(ex.ActualValue, 42, "ActualValue");
			Assert.AreEqual(ex.Message, "The message");
		}
Ejemplo n.º 11
0
        public void Create()
        {
            var list  = new Generics.List <int>();
            var list2 = new Collections.Generic.List <int>();
            var error = new Sys.ArgumentOutOfRangeException();

            Sys.ArgumentOutOfRangeException.ReferenceEquals("", "");
        }
Ejemplo n.º 12
0
 public OTPError GetErrorForException(ArgumentOutOfRangeException exception)
 {
     return new OTPError
     {
         Code = "InternalError",
         Description = "Something went wrong, please try again later."
     };
 }
		public void ConstructorWithParamNameWorks() {
			var ex = new ArgumentOutOfRangeException("someParam");
			Assert.IsTrue((object)ex is ArgumentOutOfRangeException, "is ArgumentOutOfRangeException");
			Assert.AreEqual(ex.ParamName, "someParam", "ParamName");
			Assert.IsTrue(ex.InnerException == null, "InnerException");
			Assert.IsTrue(ex.ActualValue == null, "ActualValue");
			Assert.AreEqual(ex.Message, "Value is out of range.\nParameter name: someParam");
		}
 public void Context()
 {
     var emailTemplate = EmailTemplateBuilder.New
         .WithInitialHtml("html")
         .Build();
     var htmlTeplatePartId = emailTemplate.Parts.First().Id;
     _exception = Should.Throw<ArgumentOutOfRangeException>(() => emailTemplate.CreateVariable(htmlTeplatePartId, 1, 4));
 }
		public void ConstructorWithMessageAndInnerExceptionWorks() {
			var inner = new Exception("a");
			var ex = new ArgumentOutOfRangeException("The message", inner);
			Assert.IsTrue((object)ex is ArgumentOutOfRangeException, "is ArgumentOutOfRangeException");
			Assert.IsTrue(ex.ParamName == null, "ParamName");
			Assert.IsTrue(ReferenceEquals(ex.InnerException, inner), "InnerException");
			Assert.IsTrue(ex.ActualValue == null, "ActualValue");
			Assert.AreEqual(ex.Message, "The message");
		}
Ejemplo n.º 16
0
 public static void InputNoCorrectNumberLog(ArgumentOutOfRangeException e)
 {
     List<string> log = new List<string>();
     log.Add("InputNoCorrectNumberError");
     log.Add("Fehlermeldung: " +e.Message);
     log.Add("Fehler bei der Auswahl des Songs.");
     log.Add("Fehlerbehebung: Programm mit Song erneut starten, nur 1, 2 oder 3 eingeben.");
     Errorlogs.PrintLogs(log);
 }
        public void InnerExceptionWillMatchConstructorArgument()
        {
            var expectedException = new ArgumentOutOfRangeException();
            var sut = new TypeArgumentsCannotBeInferredException("Anonymous message.", expectedException);

            var result = sut.InnerException;
            
            Assert.Equal(expectedException, result);
        }
Ejemplo n.º 18
0
        public void IsError_2()
        {
            string BadArg    = "BAD ARGS";
            object ReturnVal = new System.ArgumentOutOfRangeException(BadArg);
            object o1;

            o1 = new ArgumentOutOfRangeException();
            Assert.AreEqual(true, Information.IsError(o1));
            Assert.AreEqual(true, Information.IsError(ReturnVal));
        }
 public void HandledExceptionTypesCanBeRestricted()
 {
     var handledTypes = new List<Type> { typeof(ArgumentOutOfRangeException) };
     var ex = new ArgumentOutOfRangeException();
     var list = new List<Exception>();
     list.AddThrown(() => { throw ex; }, handledTypes);
     Assert.AreEqual(1, list.Count);
     Assert.AreSame(ex, list[0]);
     list.AddThrown(() => { throw new ArgumentNullException(); }, handledTypes);
 }
Ejemplo n.º 20
0
 public static void AssertMinLength(byte[] data, int minLength, string paramName)
 {
     AssertNotNull(data, paramName);
     if (data.Length < minLength)
     {
         var exception = new ArgumentOutOfRangeException(paramName, data.Length, Resources.InputShorterThanMinMessage);
         // DEBUG: exception.Data.Add("BinaryBlob", data.ToHex());
         throw exception;
     }
 }
 private static void EnsureIndexInt32(uint index, int listCapacity)
 {
     // We use '<=' and not '<' becasue Int32.MaxValue == index would imply
     // that Size > Int32.MaxValue:
     if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity)
     {
         Exception e = new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue"));
         e.SetErrorCode(__HResults.E_BOUNDS);
         throw e;
     }
 }
 public void InnerExceptionWillMatchConstructorArgument()
 {
     // Fixture setup
     var expectedException = new ArgumentOutOfRangeException();
     var sut = new IllegalRequestException("Anonymous message.", expectedException);
     // Exercise system
     var result = sut.InnerException;
     // Verify outcome
     Assert.Equal(expectedException, result);
     // Teardown
 }
Ejemplo n.º 23
0
            public void Execute_catches_exceptions()
            {
                var handler = new Handler();
                var operation = new Mock<Executor.OperationBase>(handler) { CallBase = true };
                var error = new ArgumentOutOfRangeException("Needs to be about 20% more cool.");

                operation.Object.Execute(() => { throw error; });

                Assert.Equal(error.GetType().FullName, handler.ErrorType);
                Assert.Equal(error.Message, handler.ErrorMessage);
                Assert.NotEmpty(handler.ErrorStackTrace);
            }
		public void TypePropertiesAreCorrect() {
			Assert.AreEqual(typeof(ArgumentOutOfRangeException).FullName, "ss.ArgumentOutOfRangeException", "Name");
			Assert.IsTrue(typeof(ArgumentOutOfRangeException).IsClass, "IsClass");
			Assert.AreEqual(typeof(ArgumentOutOfRangeException).BaseType, typeof(ArgumentException), "BaseType");
			object d = new ArgumentOutOfRangeException();
			Assert.IsTrue(d is ArgumentOutOfRangeException, "is ArgumentOutOfRangeException");
			Assert.IsTrue(d is ArgumentException, "is ArgumentException");
			Assert.IsTrue(d is Exception, "is Exception");

			var interfaces = typeof(ArgumentOutOfRangeException).GetInterfaces();
			Assert.AreEqual(interfaces.Length, 0, "Interfaces length");
		}
Ejemplo n.º 25
0
 public void AFVTau(System.Runtime.Versioning.ResourceExposureAttribute Bhpjwb, System.Web.UI.WebControls.MailMessageEventHandler lcclVgz, System.ComponentModel.DesignOnlyAttribute LJoU, System.Security.Cryptography.X509Certificates.X509ChainPolicy JAthRKz)
 {
     System.Web.Configuration.ProfilePropertySettingsCollection YPN = new System.Web.Configuration.ProfilePropertySettingsCollection();
     System.Web.UI.WebControls.CommandEventArgs         coGHdY      = new System.Web.UI.WebControls.CommandEventArgs("wyKJlYHiXhmuI", 939670288);
     System.Windows.Forms.TreeNodeConverter             TQkITGk     = new System.Windows.Forms.TreeNodeConverter();
     System.CodeDom.CodeNamespaceImport                 AMuF        = new System.CodeDom.CodeNamespaceImport();
     System.Runtime.Remoting.Channels.TransportHeaders  ZPhf        = new System.Runtime.Remoting.Channels.TransportHeaders();
     System.Web.Configuration.ProfileSettingsCollection bGxTyT      = new System.Web.Configuration.ProfileSettingsCollection();
     System.Web.UI.Triplet NKo = new System.Web.UI.Triplet(94201957, 204067286, 181795136);
     System.Web.UI.WebControls.CreateUserWizardStep                 YVz     = new System.Web.UI.WebControls.CreateUserWizardStep();
     System.Net.Configuration.HttpCachePolicyElement                gvpb    = new System.Net.Configuration.HttpCachePolicyElement();
     System.Runtime.InteropServices.IDispatchImplAttribute          JMUwahj = new System.Runtime.InteropServices.IDispatchImplAttribute(-658);
     System.Web.UI.WebControls.WebParts.ConnectionConsumerAttribute WvLbFF  = new System.Web.UI.WebControls.WebParts.ConnectionConsumerAttribute("tibFWnWRwJiTRnijF");
     System.Web.UI.WebControls.MenuItemCollection   QjImiIB = new System.Web.UI.WebControls.MenuItemCollection(new System.Web.UI.WebControls.MenuItem());
     System.ComponentModel.WarningException         Edl     = new System.ComponentModel.WarningException("hLJ", "RxUjFInvYnsN");
     System.Web.UI.WebControls.CreateUserWizardStep tnLG    = new System.Web.UI.WebControls.CreateUserWizardStep();
     System.Threading.ThreadExceptionEventArgs      oVqHzS  = new System.Threading.ThreadExceptionEventArgs(new System.Exception());
     System.Windows.Forms.ToolStripPanel            ubWJjW  = new System.Windows.Forms.ToolStripPanel();
     System.Windows.Forms.CheckedListBox            vQnk    = new System.Windows.Forms.CheckedListBox();
     System.Data.EvaluateException lZuPd = new System.Data.EvaluateException("VDiWDw");
     System.Collections.Specialized.OrderedDictionary     NrEiCx = new System.Collections.Specialized.OrderedDictionary();
     System.Web.Configuration.ExpressionBuilderCollection rKe    = new System.Web.Configuration.ExpressionBuilderCollection();
     System.Security.VerificationException               gjQbpO  = new System.Security.VerificationException("HdwsMd", new System.Exception());
     System.Web.UI.WebControls.GridView                  hKm     = new System.Web.UI.WebControls.GridView();
     System.Collections.Specialized.StringCollection     xaB     = new System.Collections.Specialized.StringCollection();
     System.Runtime.InteropServices.PreserveSigAttribute eVvQ    = new System.Runtime.InteropServices.PreserveSigAttribute();
     System.IO.IODescriptionAttribute       aNN   = new System.IO.IODescriptionAttribute("VPjQMtDWfg");
     System.ComponentModel.BooleanConverter FvgYn = new System.ComponentModel.BooleanConverter();
     System.Web.UI.WebControls.DetailsViewInsertedEventArgs PwpT     = new System.Web.UI.WebControls.DetailsViewInsertedEventArgs(1190630802, new System.Exception());
     System.Windows.Forms.ImageList                  xRwZA           = new System.Windows.Forms.ImageList();
     System.Globalization.JapaneseCalendar           afnDCPz         = new System.Globalization.JapaneseCalendar();
     System.Web.Configuration.PassportAuthentication MfCQkqL         = new System.Web.Configuration.PassportAuthentication();
     System.Runtime.Remoting.RemotingException       naDyQF          = new System.Runtime.Remoting.RemotingException();
     System.MissingFieldException                            ubX     = new System.MissingFieldException("wtnxbHmoATXw", new System.Exception());
     System.Web.UI.HtmlControls.HtmlInputText                VLBD    = new System.Web.UI.HtmlControls.HtmlInputText("gXFG");
     System.Runtime.Remoting.ActivatedServiceTypeEntry       doa     = new System.Runtime.Remoting.ActivatedServiceTypeEntry("CWPQ", "eKcxOFlcYMF");
     System.MissingMethodException                           PSQBjgG = new System.MissingMethodException("BQoFN", new System.Exception());
     System.Windows.Forms.FolderBrowserDialog                nyTD    = new System.Windows.Forms.FolderBrowserDialog();
     System.Runtime.InteropServices.OutAttribute             sBWytdq = new System.Runtime.InteropServices.OutAttribute();
     System.Web.UI.WebControls.FormViewUpdateEventArgs       wrFEU   = new System.Web.UI.WebControls.FormViewUpdateEventArgs(614564652);
     System.ArgumentOutOfRangeException                      Tyfmqs  = new System.ArgumentOutOfRangeException("XOLQzNCqfjKHnxfq", new System.Exception());
     System.Web.UI.ControlBuilder                            ubZZw   = new System.Web.UI.ControlBuilder();
     System.Windows.Forms.FlowLayoutPanel                    huyOf   = new System.Windows.Forms.FlowLayoutPanel();
     System.Configuration.UserSettingsGroup                  VkIAhTM = new System.Configuration.UserSettingsGroup();
     System.Security.Cryptography.MD5CryptoServiceProvider   ixAZ    = new System.Security.Cryptography.MD5CryptoServiceProvider();
     System.Runtime.Remoting.Metadata.SoapParameterAttribute QHvwhq  = new System.Runtime.Remoting.Metadata.SoapParameterAttribute();
     System.Reflection.AssemblyInformationalVersionAttribute IGrOTW  = new System.Reflection.AssemblyInformationalVersionAttribute("qdWByXvKzB");
     System.Windows.Forms.SelectionRangeConverter            rwbzo   = new System.Windows.Forms.SelectionRangeConverter();
     Microsoft.SqlServer.Server.SqlTriggerAttribute          PsugLs  = new Microsoft.SqlServer.Server.SqlTriggerAttribute();
     System.Globalization.ThaiBuddhistCalendar               iMwCC   = new System.Globalization.ThaiBuddhistCalendar();
 }
Ejemplo n.º 26
0
 static int End(int start)
 {
     Console.Write("Enter end number in the range [start + 10< end < 100] = ");
         int end = Number();
         if (end >= 100 || end <= (start + 10))
         {
             Exception ae = new System.ArgumentOutOfRangeException();
             HandleError(ae);
             return End(start);
         }
         else
         {
             return end;
         }
 }
Ejemplo n.º 27
0
        public static FieldInfo GetPrivateField(this Type type, string privateFieldName)
        {
            var privateField = type.FindPrivateField(privateFieldName);

            if (privateField != null)
            {
                return privateField;
            }

            var exception = new ArgumentOutOfRangeException("privateFieldName", string.Format("Cannot find {1} in {0}.", type, privateFieldName));

            exception.Data.Add("type", type);
            exception.Data.Add("privateFieldName", privateFieldName);

            throw exception;
        }
Ejemplo n.º 28
0
        public void Log_WhereInnerExceptionIsNested_ReturnsExceptionsAndTrace()
        {
            var firstException = new ExecutionEngineException("Internal workings failed");
            var secondException = new ArgumentOutOfRangeException("Unable to continue.", firstException);
            var thirdException = new ArgumentNullException("Argument not set", secondException);

            var actualResults = Error.GetAllInnerExceptions(thirdException);

            StringBuilder expectedResults = new StringBuilder();
            expectedResults.Append("System.ArgumentOutOfRangeException: Unable to continue. ---> ");
            expectedResults.Append("System.ExecutionEngineException: Internal workings failed\r\n   --- ");
            expectedResults.Append("End of inner exception stack trace ---\r\n");
            expectedResults.Append("No Stack trace recorded.\r\n");

            Assert.AreEqual(expectedResults.ToString(), actualResults);
        }
Ejemplo n.º 29
0
 private HistoryInfo GetHistoryEntryToInvoke(History history)
 {
     HistoryInfo entry = null;
     if (this._id == null)
     {
         HistoryInfo[] infoArray = history.GetEntries((long) 0L, 1L, true);
         if (infoArray.Length == 1)
         {
             return infoArray[0];
         }
         Exception exception = new InvalidOperationException(StringUtil.Format(HistoryStrings.NoLastHistoryEntryFound, new object[0]));
         base.ThrowTerminatingError(new ErrorRecord(exception, "InvokeHistoryNoLastHistoryEntryFound", ErrorCategory.InvalidOperation, null));
         return entry;
     }
     this.PopulateIdAndCommandLine();
     if (this._commandLine == null)
     {
         if (this._historyId <= 0L)
         {
             Exception exception3 = new ArgumentOutOfRangeException("Id", StringUtil.Format(HistoryStrings.InvalidIdGetHistory, this._historyId));
             base.ThrowTerminatingError(new ErrorRecord(exception3, "InvokeHistoryInvalidIdGetHistory", ErrorCategory.InvalidArgument, this._historyId));
             return entry;
         }
         entry = history.GetEntry(this._historyId);
         if ((entry == null) || (entry.Id != this._historyId))
         {
             Exception exception4 = new ArgumentException(StringUtil.Format(HistoryStrings.NoHistoryForId, this._historyId));
             base.ThrowTerminatingError(new ErrorRecord(exception4, "InvokeHistoryNoHistoryForId", ErrorCategory.ObjectNotFound, this._historyId));
         }
         return entry;
     }
     HistoryInfo[] infoArray2 = history.GetEntries((long) 0L, -1L, false);
     for (int i = infoArray2.Length - 1; i >= 0; i--)
     {
         if (infoArray2[i].CommandLine.StartsWith(this._commandLine, StringComparison.CurrentCulture))
         {
             entry = infoArray2[i];
             break;
         }
     }
     if (entry == null)
     {
         Exception exception2 = new ArgumentException(StringUtil.Format(HistoryStrings.NoHistoryForCommandline, this._commandLine));
         base.ThrowTerminatingError(new ErrorRecord(exception2, "InvokeHistoryNoHistoryForCommandline", ErrorCategory.ObjectNotFound, this._commandLine));
     }
     return entry;
 }
 /// <summary>
 /// Processing method of ArgumentOutOfRangeException.
 /// </summary>
 /// <param name="ex">Instance ArgumentOutOfRangeException.</param>
 public void ProcessingException(ArgumentOutOfRangeException ex)
 {
     var swConnectedExceptionLog = new StreamWriter("ConnectedExceptionLog.txt", true);
     swConnectedExceptionLog.WriteLine("#########################################################################################");
     swConnectedExceptionLog.WriteLine($"ArgumentOutOfRangeException DateTime: {DateTime.Now}\n");
     swConnectedExceptionLog.WriteLine($"ArgumentOutOfRangeException ActualValue: {ex.ActualValue}\n");
     swConnectedExceptionLog.WriteLine($"ArgumentOutOfRangeException Data: {ex.Data}\n");
     swConnectedExceptionLog.WriteLine($"ArgumentOutOfRangeException HelpLink: {ex.HelpLink}\n");
     swConnectedExceptionLog.WriteLine($"ArgumentOutOfRangeException HResult: {ex.HResult}\n");
     swConnectedExceptionLog.WriteLine($"ArgumentOutOfRangeException InnerException: {ex.InnerException}\n");
     swConnectedExceptionLog.WriteLine($"ArgumentOutOfRangeException Message: {ex.Message}\n");
     swConnectedExceptionLog.WriteLine($"ArgumentOutOfRangeException ParamName: {ex.ParamName}\n");
     swConnectedExceptionLog.WriteLine($"ArgumentOutOfRangeException Source: {ex.Source}\n");
     swConnectedExceptionLog.WriteLine($"ArgumentOutOfRangeException StackTrace: {ex.StackTrace}\n");
     swConnectedExceptionLog.WriteLine($"ArgumentOutOfRangeException TargetSite: {ex.TargetSite}\n");
     swConnectedExceptionLog.Close();
 }
Ejemplo n.º 31
0
        /// <summary>
        /// Invokes the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="getNext">The get next.</param>
        /// <returns></returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            Exception ex = null;
            if (input.Inputs.Count != 1) { ex = new ArgumentOutOfRangeException("Action methods can only contains one argument!"); }
            if (input.Inputs[0].GetType() != typeof(string[])) { ex = new ArgumentException("The action method argument must be of type string[]!"); }

            if (Length > -1) {
                var arg = (string[])input.Arguments[0];
                if (arg.Length != Length) { ex = new ArgumentOutOfRangeException("Invalid number of arguments!"); }
            }
            var types = input.MethodBase.GetCustomAttributes(typeof(ArgumentTypeAttribute), true);
            if (types != null && types.Count() > 0) {
                foreach (var tp in types.Cast<ArgumentTypeAttribute>()) {
                    try { Convert.ChangeType(input.Arguments[tp.Index], tp.Type); }
                    catch (InvalidCastException) { ex = new InvalidCastException(string.Format("The argument index: {0} must be of type: {1}!", tp.Index, tp.Type.ToString())); }
                }
            }
            return ex != null ? input.CreateExceptionMethodReturn(ex) : getNext()(input, getNext);
        }
Ejemplo n.º 32
0
 public long FibonacciNumber(long n)
 {
     System.Threading.Thread.Sleep(new TimeSpan(0, 0, 1));
     if (n < 0)
     {
         ArgumentOutOfRangeException exception = new ArgumentOutOfRangeException(n.ToString(), "Requires Non Negative Number");
         throw new FaultException<ArgumentOutOfRangeException>(exception);
      
     }
     long current = 0;
     long next = 1;
     long temp;
     for (int i = 0; i < n; i++)
     {
         temp = current;
         current = next;
         next = temp + current;
     }
     return current;     
 }
        internal static Object GetValue( string argument)
        {
            switch (argument)
            {
                case "ApplicationCurrentMemoryUsage":
                    return (Object)Windows.System.MemoryManager.AppMemoryUsage;
                case "DeviceFirmwareVersion":
                    return (Object)(new Windows.Security.ExchangeActiveSyncProvisioning.EasClientDeviceInformation()).SystemFirmwareVersion;
                case "DeviceHardwareVersion":
                    return (Object)(new Windows.Security.ExchangeActiveSyncProvisioning.EasClientDeviceInformation()).SystemHardwareVersion;
                case "DeviceManufacturer":
                    return (Object)(new Windows.Security.ExchangeActiveSyncProvisioning.EasClientDeviceInformation()).SystemManufacturer;
                case "DeviceName":
                    return ((Object)(new Windows.Security.ExchangeActiveSyncProvisioning.EasClientDeviceInformation()).SystemProductName);
                default:
                    ArgumentOutOfRangeException argumentOutOfRangeException = new ArgumentOutOfRangeException();
                    throw argumentOutOfRangeException;

            }
        }
Ejemplo n.º 34
0
        /// <summary>
        ///     Get a random string between 1 and 25 characters long with <paramref name="arguments" /> format items.
        /// </summary>
        /// <param name="formatItems">The number of format items to include at the end of the return string.</param>
        public static string NextFormat(int formatItems)
        {
            if (formatItems < 1)
            {
                var exception = new ArgumentOutOfRangeException("formatItems",
                    "Number of format items must be 1 or more.");

                exception.Data.Add("formatItems", formatItems);

                throw exception;
            }

            var format = new StringBuilder(Next(CharacterSets.AtoZ));

            for (var argument = 1; argument <= formatItems; argument++)
            {
                format.Append(" {" + (argument - 1) + "}");
            }

            return format.ToString();
        }
Ejemplo n.º 35
0
 /// <summary>
 /// 检验参数合法性,数值类型不能小于0,引用类型不能为null,否则抛出相应异常
 /// </summary>
 /// <param name="arg"> 待检参数 </param>
 /// <param name="argName"> 待检参数名称 </param>
 /// <param name="canZero"> 数值类型是否可以等于0 </param>
 /// <exception cref="ComponentException" />
 public static void CheckArgument(object arg, string argName, bool canZero = false)
 {
     if (arg == null)
     {
         ArgumentNullException e = new ArgumentNullException(argName);
         throw ExceptionHelper.ThrowComponentException(string.Format("参数 {0} 为空引发异常。", argName), e);
     }
     Type type = arg.GetType();
     if (type.IsValueType && type.IsNumeric())
     {
         bool flag = !canZero ? arg.CastTo(0.0) <= 0.0 : arg.CastTo(0.0) < 0.0;
         if (flag)
         {
             ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(argName);
             throw ExceptionHelper.ThrowComponentException(string.Format("参数 {0} 不在有效范围内引发异常。具体信息请查看系统日志。", argName), e);
         }
     }
     if (type == typeof(Guid) && (Guid)arg == Guid.Empty)
     {
         ArgumentNullException e = new ArgumentNullException(argName);
         throw ExceptionHelper.ThrowComponentException(string.Format("参数{0}为空Guid引发异常。", argName), e);
     }
 }
        static StackObject *Ctor_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 3);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.String @message = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Object @actualValue = (System.Object) typeof(System.Object).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.String @paramName = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);


            var result_of_this_method = new System.ArgumentOutOfRangeException(@paramName, @actualValue, @message);

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Ejemplo n.º 37
0
        public void TestWrite()
        {
            //using (Database database = new Database(DatabasePath))
            using (Stream file = new FileStream(TestFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
                using (ChunkedStream chunked = new ChunkedStream(file, ChunkSize))
                {
                    byte[] buffer = new byte[2 * ChunkSize];
                    FillArray <byte>(buffer, (byte)'a');


                    Assert.AreEqual(0, chunked.ChunkPosition);
                    Assert.AreEqual(0, chunked.Position);
                    Assert.AreEqual(0, chunked.Length);

                    chunked.Write(buffer, 0, 1);
                    Assert.AreEqual(1, file.Position);
                    Assert.AreEqual(1, chunked.Position);
                    Assert.AreEqual(1, chunked.Length);

                    System.ArgumentOutOfRangeException e = Assert.Catch <System.ArgumentOutOfRangeException>(() => chunked.Write(buffer, 0, ChunkSize));
                    Assert.AreEqual("count", e.ParamName);
                    Assert.AreEqual(ChunkSize, e.ActualValue);
                    Assert.AreEqual(1, file.Position);
                    Assert.AreEqual(1, chunked.Position);
                    Assert.AreEqual(1, chunked.Length);

                    chunked.Write(buffer, 1, ChunkSize - 1);
                    Assert.AreEqual(ChunkSize, file.Position);
                    Assert.AreEqual(ChunkSize, chunked.Position);
                    Assert.AreEqual(ChunkSize, chunked.Length);

                    e = Assert.Catch <System.ArgumentOutOfRangeException>(() => chunked.Write(buffer, 0, 1));
                    Assert.AreEqual("count", e.ParamName);
                    Assert.AreEqual(1, e.ActualValue);
                    Assert.AreEqual(ChunkSize, file.Position);
                    Assert.AreEqual(ChunkSize, chunked.Position);
                    Assert.AreEqual(ChunkSize, chunked.Length);


                    chunked.ChunkPosition = ChunkSize;
                    Assert.AreEqual(ChunkSize, chunked.ChunkPosition);
                    Assert.AreEqual(ChunkSize, file.Position);
                    Assert.AreEqual(0, chunked.Position);
                    Assert.AreEqual(0, chunked.Length);

                    chunked.Write(buffer, 0, ChunkSize);
                    Assert.AreEqual(2 * ChunkSize, file.Position);
                    Assert.AreEqual(ChunkSize, chunked.Position);
                    Assert.AreEqual(ChunkSize, chunked.Length);

                    e = Assert.Catch <System.ArgumentOutOfRangeException>(() => chunked.Write(buffer, 0, 1));
                    Assert.AreEqual("count", e.ParamName);
                    Assert.AreEqual(1, e.ActualValue);
                    Assert.AreEqual(2 * ChunkSize, file.Position);
                    Assert.AreEqual(ChunkSize, chunked.Position);
                    Assert.AreEqual(ChunkSize, chunked.Length);


                    chunked.ChunkPosition = 4 * ChunkSize;
                    Assert.AreEqual(4 * ChunkSize, chunked.ChunkPosition);
                    Assert.AreEqual(4 * ChunkSize, file.Position);
                    Assert.AreEqual(0, chunked.Position);
                    Assert.AreEqual(0, chunked.Length);

                    chunked.Write(buffer, 1, ChunkSize - 1);
                    Assert.AreEqual(5 * ChunkSize - 1, file.Position);
                    Assert.AreEqual(ChunkSize - 1, chunked.Position);
                    Assert.AreEqual(ChunkSize - 1, chunked.Length);

                    e = Assert.Catch <System.ArgumentOutOfRangeException>(() => chunked.Write(buffer, 0, ChunkSize));
                    Assert.AreEqual("count", e.ParamName);
                    Assert.AreEqual(ChunkSize, e.ActualValue);
                    Assert.AreEqual(5 * ChunkSize - 1, file.Position);
                    Assert.AreEqual(ChunkSize - 1, chunked.Position);
                    Assert.AreEqual(ChunkSize - 1, chunked.Length);

                    chunked.Write(buffer, 0, 1);
                    Assert.AreEqual(5 * ChunkSize, file.Position);
                    Assert.AreEqual(ChunkSize, chunked.Position);
                    Assert.AreEqual(ChunkSize, chunked.Length);

                    e = Assert.Catch <System.ArgumentOutOfRangeException>(() => chunked.Write(buffer, 0, 1));
                    Assert.AreEqual("count", e.ParamName);
                    Assert.AreEqual(1, e.ActualValue);
                    Assert.AreEqual(5 * ChunkSize, file.Position);
                    Assert.AreEqual(ChunkSize, chunked.Position);
                    Assert.AreEqual(ChunkSize, chunked.Length);
                }
        }
Ejemplo n.º 38
0
        public void TestWrite()
        {
            using (MemoryStream file = new MemoryStream())
                using (ChunkedStream chunked = new ChunkedStream(file, this.chunkSize))
                {
                    byte[] buffer = new byte[2 * this.chunkSize];
                    this.FillArray <byte>(buffer, (byte)'a');

                    Assert.AreEqual(0, chunked.ChunkPosition);
                    Assert.AreEqual(0, chunked.Position);
                    Assert.AreEqual(0, chunked.Length);

                    chunked.Write(buffer, 0, 1);
                    Assert.AreEqual(1, file.Position);
                    Assert.AreEqual(1, chunked.Position);
                    Assert.AreEqual(1, chunked.Length);

                    System.ArgumentOutOfRangeException e = Assert.Catch <System.ArgumentOutOfRangeException>(() => chunked.Write(buffer, 0, this.chunkSize));
                    Assert.AreEqual("count", e.ParamName);
                    Assert.AreEqual(this.chunkSize, e.ActualValue);
                    Assert.AreEqual(1, file.Position);
                    Assert.AreEqual(1, chunked.Position);
                    Assert.AreEqual(1, chunked.Length);

                    chunked.Write(buffer, 1, this.chunkSize - 1);
                    Assert.AreEqual(this.chunkSize, file.Position);
                    Assert.AreEqual(this.chunkSize, chunked.Position);
                    Assert.AreEqual(this.chunkSize, chunked.Length);

                    e = Assert.Catch <System.ArgumentOutOfRangeException>(() => chunked.Write(buffer, 0, 1));
                    Assert.AreEqual("count", e.ParamName);
                    Assert.AreEqual(1, e.ActualValue);
                    Assert.AreEqual(this.chunkSize, file.Position);
                    Assert.AreEqual(this.chunkSize, chunked.Position);
                    Assert.AreEqual(this.chunkSize, chunked.Length);

                    chunked.ChunkPosition = this.chunkSize;
                    Assert.AreEqual(this.chunkSize, chunked.ChunkPosition);
                    Assert.AreEqual(this.chunkSize, file.Position);
                    Assert.AreEqual(0, chunked.Position);
                    Assert.AreEqual(0, chunked.Length);

                    chunked.Write(buffer, 0, this.chunkSize);
                    Assert.AreEqual(2 * this.chunkSize, file.Position);
                    Assert.AreEqual(this.chunkSize, chunked.Position);
                    Assert.AreEqual(this.chunkSize, chunked.Length);

                    e = Assert.Catch <System.ArgumentOutOfRangeException>(() => chunked.Write(buffer, 0, 1));
                    Assert.AreEqual("count", e.ParamName);
                    Assert.AreEqual(1, e.ActualValue);
                    Assert.AreEqual(2 * this.chunkSize, file.Position);
                    Assert.AreEqual(this.chunkSize, chunked.Position);
                    Assert.AreEqual(this.chunkSize, chunked.Length);

                    chunked.ChunkPosition = 4 * this.chunkSize;
                    Assert.AreEqual(4 * this.chunkSize, chunked.ChunkPosition);
                    Assert.AreEqual(4 * this.chunkSize, file.Position);
                    Assert.AreEqual(0, chunked.Position);
                    Assert.AreEqual(0, chunked.Length);

                    chunked.Write(buffer, 1, this.chunkSize - 1);
                    Assert.AreEqual((5 * this.chunkSize) - 1, file.Position);
                    Assert.AreEqual(this.chunkSize - 1, chunked.Position);
                    Assert.AreEqual(this.chunkSize - 1, chunked.Length);

                    e = Assert.Catch <System.ArgumentOutOfRangeException>(() => chunked.Write(buffer, 0, this.chunkSize));
                    Assert.AreEqual("count", e.ParamName);
                    Assert.AreEqual(this.chunkSize, e.ActualValue);
                    Assert.AreEqual((5 * this.chunkSize) - 1, file.Position);
                    Assert.AreEqual(this.chunkSize - 1, chunked.Position);
                    Assert.AreEqual(this.chunkSize - 1, chunked.Length);

                    chunked.Write(buffer, 0, 1);
                    Assert.AreEqual(5 * this.chunkSize, file.Position);
                    Assert.AreEqual(this.chunkSize, chunked.Position);
                    Assert.AreEqual(this.chunkSize, chunked.Length);

                    e = Assert.Catch <System.ArgumentOutOfRangeException>(() => chunked.Write(buffer, 0, 1));
                    Assert.AreEqual("count", e.ParamName);
                    Assert.AreEqual(1, e.ActualValue);
                    Assert.AreEqual(5 * this.chunkSize, file.Position);
                    Assert.AreEqual(this.chunkSize, chunked.Position);
                    Assert.AreEqual(this.chunkSize, chunked.Length);
                }
        }