public static void TryDispose([NotNull] this IDisposable obj, [DoesNotReturnIf(true)] bool throwException)
        {
            if (obj is null)
            {
                return;
            }

            try
            {
                if (obj is IAsyncDisposable asyncDisposable)
                {
                    ValueTask result = asyncDisposable.DisposeAsync();

                    if (result.IsFaulted)
                    {
                        ExceptionThrower.ThrowInvalidOperationException(Resources.ThereIsAnIssueDisposingOfTheObjectUsingAsyncDispose);
                    }
                }
                else
                {
                    obj.Dispose();
                }
            }
            catch
            {
                if (throwException)
                {
                    throw;
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Initializes the fields of an object.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <exception cref="ArgumentNullException">Input cannot be null.</exception>
        public static void InitializeFields(this object obj)
        {
            if (obj.IsNull())
            {
                ExceptionThrower.ThrowArgumentNullException(nameof(obj));
            }

            var fieldInfos = obj.GetType().GetRuntimeFields().ToList();

            for (var fieldCount = 0; fieldCount < fieldInfos.Count; fieldCount++)
            {
                var fieldInfo    = fieldInfos[fieldCount];
                var objectValue  = fieldInfo.GetValue(obj);
                var runtimeField = obj.GetType().GetRuntimeField(fieldInfo.Name);

                if (runtimeField != null)
                {
                    var t         = Nullable.GetUnderlyingType(runtimeField.FieldType) ?? runtimeField.FieldType;
                    var safeValue = (objectValue == null)
                        ? null
                        : Convert.ChangeType(objectValue, t, CultureInfo.InvariantCulture);
                    runtimeField.SetValue(obj, safeValue);
                }
            }
        }
        void ICollection <T> .CopyTo([NotNull] T[] array, int arrayIndex)
        {
            array = array.ArgumentItemsExists(nameof(array));

            var locksAcquired = 0;

            try
            {
                this.AcquireAllLocks(ref locksAcquired);

                var count = 0;

                for (var lockCount = 0; lockCount < this._tables._locks.Length && count >= 0; lockCount++)
                {
                    count += this._tables._countPerLock[lockCount];
                }

                // "count" itself or "count + arrayIndex" can overflow
                if (array.Length - count < arrayIndex || count < 0)
                {
                    ExceptionThrower.ThrowArgumentInvalidException(nameof(array), "The index is equal to or greater than the length of the array, or the number of elements in the set is greater than the available space from index to the end of the destination array.");
                }

                this.CopyToItems(array, arrayIndex);
            }
            finally
            {
                this.ReleaseLocks(0, locksAcquired);
            }
        }
        public static (int exitCode, string output) RunProcessAndReadOutput(string fileName, string arguments, TimeSpan timeout)
        {
            if (string.IsNullOrEmpty(fileName) && File.Exists(fileName) == false)
            {
                ExceptionThrower.ThrowArgumentException(string.Format(Resources.FileIsNullEmptyOrDoesNotExist, nameof(fileName)), nameof(fileName));
            }

            var startInfo = new ProcessStartInfo
            {
                FileName  = fileName,
                Arguments = arguments,
                RedirectStandardOutput = true,
                UseShellExecute        = false
            };

            using var process = Process.Start(startInfo);
            if (process.WaitForExit((int)timeout.TotalMilliseconds))
            {
                return(process.ExitCode, process.StandardOutput.ReadToEnd());
            }
            else
            {
                process.Kill();
            }

            return(process.ExitCode, default);
        public static int RunProcessAndIgnoreOutput(string fileName, string arguments, TimeSpan timeout)
        {
            if (string.IsNullOrEmpty(fileName) && File.Exists(fileName) == false)
            {
                ExceptionThrower.ThrowArgumentException(string.Format(Resources.FileIsNullEmptyOrDoesNotExist, nameof(fileName)), nameof(fileName));
            }

            var startInfo = new ProcessStartInfo
            {
                FileName  = fileName,
                Arguments = arguments,
                RedirectStandardOutput = false,
                RedirectStandardError  = false,
                UseShellExecute        = false,
                CreateNoWindow         = true
            };

            using var process = Process.Start(startInfo);
            if (!process.WaitForExit((int)timeout.TotalMilliseconds))
            {
                process.Kill();
            }

            return(process.ExitCode);
        }
Exemplo n.º 6
0
        public static string Concat(this string input, string delimiter, bool addLineFeed, params string[] args)
        {
            if (input.IsNullOrEmpty())
            {
                ExceptionThrower.ThrowArgumentNullException(nameof(input));
            }

            if (delimiter.IsNullOrEmpty())
            {
                delimiter = string.Empty;
            }

            var sb = new StringBuilder(input);

            if (args.HasItems())
            {
                for (var argCount = 0; argCount < args.Length; argCount++)
                {
                    var value = args[argCount];
                    if (addLineFeed)
                    {
                        sb.AppendLine(value);
                    }
                    else
                    {
                        sb.Append(string.Concat(value, delimiter));
                    }
                }
            }

            return(sb.ToString());
        }
Exemplo n.º 7
0
        /// <summary>
        /// Indents the specified length.
        /// </summary>
        /// <param name="input">The string.</param>
        /// <param name="length">The length.</param>
        /// <param name="indentationCharacter">The indentation character.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="ArgumentException">input.</exception>
        /// <exception cref="ArgumentNullException">length.</exception>
        public static string Indent(this string input, int length, char indentationCharacter)
        {
            if (input.IsNullOrEmpty())
            {
                ExceptionThrower.ThrowArgumentNullException(nameof(input));
            }

            if (length == 0)
            {
                ExceptionThrower.ThrowArgumentOutOfRangeException(nameof(length));
            }

            var sb = new StringBuilder();

            if (length < 0)
            {
                sb.Append(input);
            }

            for (var charCount = 1; charCount <= Math.Abs(length); charCount++)
            {
                sb.Append(indentationCharacter);
            }

            if (length > 0)
            {
                sb.Append(input);
            }

            return(sb.ToString());
        }
Exemplo n.º 8
0
        public void 驗證ExceptionProperty()
        {
            var target = new ExceptionThrower();

            var ex = Assert.Throws <CustomException>(() => target.ThrowException("test"));

            Assert.AreEqual("Detail:test", ex.Detail);
        }
Exemplo n.º 9
0
        public static void Top_stack_frame_is_user_code(ExceptionThrower exceptionThrower)
        {
            var exception = exceptionThrower.Catch() !;

            var stackTraceLines = exception.StackTrace !.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

            stackTraceLines.First().ShouldContain(exceptionThrower.ThrowingAction.Method.Name);
        }
        void ICollection <T> .Add([NotNull] T item)
        {
            if (item is null)
            {
                ExceptionThrower.ThrowArgumentNullException(nameof(item));
            }

            _ = this.Add(item);
        }
        /// <summary>
        /// Tries to add the specified item to the <see cref="DistinctBlockingCollection{T}" />
        /// within the specified time period, while observing a cancellation token.
        /// </summary>
        /// <param name="item">The item to be added to the collection.</param>
        /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see cref="Timeout.Infinite" /> (-1) to wait
        /// indefinitely.</param>
        /// <param name="cancellationToken">A cancellation token to observe.</param>
        /// <returns>true if the <paramref name="item" /> could be added to the collection within the specified time; otherwise,
        /// false. If the item is a duplicate, and the underlying collection does not accept duplicate items, then an
        /// <see cref="InvalidOperationException" /> is thrown.</returns>
        public new bool TryAdd([NotNull] T item, int millisecondsTimeout, CancellationToken cancellationToken)
        {
            if (item is null)
            {
                ExceptionThrower.ThrowArgumentNullException(nameof(item));
            }

            return(this.ItemNotInCollection(item) && base.TryAdd(item, millisecondsTimeout, cancellationToken));
        }
        /// <summary>
        /// Tries to add the specified item to the <see cref="DistinctBlockingCollection{T}" />.
        /// </summary>
        /// <param name="item">The item to be added to the collection.</param>
        /// <param name="timeout">A <see cref="TimeSpan" /> that represents the number of milliseconds to wait, or a <see cref="TimeSpan" /> that represents -1 milliseconds to wait indefinitely.</param>
        /// <returns>true if the <paramref name="item" /> could be added to the collection within the specified time span;
        /// otherwise, false.</returns>
        public new bool TryAdd([NotNull] T item, TimeSpan timeout)
        {
            if (item is null)
            {
                ExceptionThrower.ThrowArgumentNullException(nameof(item));
            }

            return(this.ItemNotInCollection(item) && base.TryAdd(item, timeout));
        }
        /// <summary>
        /// Tries to add the specified item to the <see cref="DistinctBlockingCollection{T}" />.
        /// </summary>
        /// <param name="item">The item to be added to the collection.</param>
        /// <returns><see langword="true" /> if <paramref name="item" /> could be added; otherwise, <see langword="false" />. If the item is a duplicate, and the underlying collection does not accept duplicate items, then an <see cref="InvalidOperationException" /> is thrown.</returns>
        public new bool TryAdd([NotNull] T item)
        {
            if (item is null)
            {
                ExceptionThrower.ThrowArgumentNullException(nameof(item));
            }

            return(base.TryAdd(item));
        }
        public void ActionShouldThrow_Throws_ReturnsException()
        {
            Exception expectedExeption = new Exception();
            ExceptionThrower thrower = new ExceptionThrower(expectedExeption);

            ActualException<Exception> result = Should.Throw(() => thrower.Throw());

            Assert.AreSame(expectedExeption, result.And);
        }
Exemplo n.º 15
0
        public static bool IsInRangeThrowsException(this decimal value, decimal lower, decimal upper)
        {
            if (value.IsInRange(lower, upper) == false)
            {
                ExceptionThrower.ThrowArgumentOutOfRangeException(nameof(value));
            }

            return(true);
        }
Exemplo n.º 16
0
        public static string ToFormattedString(this double input, [NotNull] NumericFormat format)
        {
            if (format == NumericFormat.Decimal || format == NumericFormat.Hexadecimal)
            {
                ExceptionThrower.ThrowArgumentInvalidException("Invalid number format.", nameof(format));
            }

            return(input.ToString(format.DisplayName, CultureInfo.CurrentCulture));
        }
Exemplo n.º 17
0
        public static bool IsIntervalThrowsException(this int value, int interval, string paramName)
        {
            if (value.IsInterval(interval) == false)
            {
                ExceptionThrower.ThrowArgumentOutOfRangeException(paramName);
            }

            return(true);
        }
Exemplo n.º 18
0
        public void AddLast([NotNull] T item)
        {
            if (item is null)
            {
                ExceptionThrower.ThrowArgumentNullException(nameof(item));
            }

            Extensions.AddLast(this, item);
        }
        public static bool IsInRangeThrowsException(this DateTimeOffset value, DateTimeOffset beginningTime, DateTimeOffset endTime, string paramName = "")
        {
            if (value.IsInRange(beginningTime, endTime) is false)
            {
                ExceptionThrower.ThrowArgumentOutOfRangeException(paramName);
            }

            return(true);
        }
Exemplo n.º 20
0
        public bool AddIfNotExists([NotNull] T item)
        {
            if (item is null)
            {
                ExceptionThrower.ThrowArgumentNullException(nameof(item));
            }

            return(Extensions.AddIfNotExists(this, item));
        }
Exemplo n.º 21
0
        /// <summary>
        /// Serializes object to Json.
        /// </summary>
        /// <param name="obj">The instance.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="ArgumentNullException">obj.</exception>
        public static string ToJson(this object obj)
        {
            if (obj is null)
            {
                ExceptionThrower.ThrowArgumentNullException(nameof(obj));
            }

            return(JsonSerializer.Serialize(obj));
        }
        public static bool IsInRangeThrowsException(this TimeSpan value, TimeSpan beginningTime, TimeSpan endTime, string paramName)
        {
            if (value.IsInRange(beginningTime, endTime) is false)
            {
                ExceptionThrower.ThrowArgumentOutOfRangeException(paramName);
            }

            return(true);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Splits the specified input using ',' and removes empty entries.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns>IEnumerable&lt;System.String&gt;.</returns>
        /// <exception cref="ArgumentException">input.</exception>
        public static IEnumerable <string> SplitRemoveEmpty(this string input)
        {
            if (input.IsNullOrEmpty())
            {
                ExceptionThrower.ThrowArgumentNullException(nameof(input));
            }

            return(input.Trim().Split(new char[] { ',' }, options: StringSplitOptions.RemoveEmptyEntries));
        }
Exemplo n.º 24
0
        public static string ToFormattedString(this ushort input, [NotNull] NumericFormat format)
        {
            if (format == NumericFormat.RoundTrip)
            {
                ExceptionThrower.ThrowArgumentInvalidException("Invalid number format.", nameof(format));
            }

            return(input.ToString(format.DisplayName, CultureInfo.CurrentCulture));
        }
        /// <summary>
        /// Compares to.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <returns>System.Int32.</returns>
        /// <exception cref="ArgumentException">obj</exception>
        public int CompareTo(object obj)
        {
            if (obj is not CoordinateProper)
            {
                ExceptionThrower.ThrowArgumentInvalidException(nameof(obj), $"{nameof(obj)} is not a {nameof(CoordinateProper)}");
            }

            return(this.CompareTo((CoordinateProper)obj));
        }
Exemplo n.º 26
0
        /// <summary>
        /// Determines whether the specified value has value.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="value">Checks for a specific value.</param>
        /// <returns><c>true</c> if the specified value has value; otherwise, <c>false</c>.</returns>
        /// <exception cref="ArgumentException">value.</exception>
        public static bool HasValue(this string input, string value)
        {
            if (input.IsNullOrEmpty())
            {
                ExceptionThrower.ThrowArgumentNullException(nameof(input));
            }

            return((input == null) ? false : (input.Trim() == value.Trim()));
        }
        public static bool IsInRangeThrowsException(this long value, long lower, long upper)
        {
            if (value.IsInRange(lower, upper) is false)
            {
                ExceptionThrower.ThrowArgumentOutOfRangeException(nameof(value));
            }

            return(true);
        }
Exemplo n.º 28
0
        public void ExceptionThrower_Should_Throw_An_Exception()
        {
            var exception = new InvalidOperationException();
            var affector  = new ExceptionThrower(exception);

            var e = Assert.Throws <InvalidOperationException>(() => affector.Affect());

            Assert.Equal(e, exception);
        }
        public static string ToFormattedString(this DateTimeOffset input, DateTimeFormat format)
        {
            if (format == null)
            {
                ExceptionThrower.ThrowArgumentNullException(nameof(format));
            }

            return(input.ToString(format.DisplayName, CultureInfo.CurrentCulture));
        }
Exemplo n.º 30
0
        public static bool IsInRangeThrowsException(this int value, int lower, int upper, string paramName)
        {
            if (value.IsInRange(lower, upper) == false)
            {
                ExceptionThrower.ThrowArgumentOutOfRangeException(paramName);
            }

            return(true);
        }
Exemplo n.º 31
0
        public static string ToTitleCase(this string input)
        {
            if (input.IsNullOrEmpty())
            {
                ExceptionThrower.ThrowArgumentNullException(nameof(input));
            }

            return(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input));
        }
        public void ActionShouldThrowType_ThrowsWrongType_FailsWithActualExceptionAsInnerException()
        {
            Exception expectedException = new Exception();
            ExceptionThrower thrower = new ExceptionThrower(expectedException);

            EasyAssertionException result = Assert.Throws<EasyAssertionException>(() =>
                Should.Throw<InvalidOperationException>(() => thrower.Throw()));

            Assert.AreSame(expectedException, result.InnerException);
        }
        public void ActionShouldThrowType_ThrowsWrongType_FailsWithWrongExceptionMessage()
        {
            ExceptionThrower thrower = new ExceptionThrower(new Exception());
            Expression<Action> throwsException = () => thrower.Throw();
            MockFormatter.WrongException(typeof(InvalidOperationException), typeof(Exception), throwsException, "foo").Returns("bar");

            EasyAssertionException result = Assert.Throws<EasyAssertionException>(() =>
                Should.Throw<InvalidOperationException>(throwsException, "foo"));

            Assert.AreEqual("bar", result.Message);
        }
        public void FuncShouldThrowType_ThrowsCorrectType_ReturnsException()
        {
            Exception expectedException = new Exception();
            ExceptionThrower thrower = new ExceptionThrower(expectedException);

            ActualException<Exception> result = Should.Throw<Exception>(() => thrower.ThrowingProperty);

            Assert.AreSame(expectedException, result.And);
        }