public bool PosTest1()
    {
        bool retVal = true;

        const string c_TEST_ID = "P001";
        string c_TEST_DESC = "PosTest1: initialize an instance of type TargetInvocationException using an emtpy string message";
        string errorDesc;

        string message = string.Empty;
        Exception innerException = new ArgumentNullException();

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
        try
        {
            TargetInvocationException e = new TargetInvocationException(message, innerException);
            if (null == e || e.Message != message || e.InnerException != innerException)
            {
                errorDesc = "Failed to initialize an instance of type TargetInvocationException.";
                errorDesc += "\nInput message is emtpy string";
                errorDesc += "\nInner exception is " + innerException;
                TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            errorDesc = "Unexpected exception: " + e;
            errorDesc += "\nInput message is emtpy string";
            errorDesc += "\nInner exception is " + innerException;
            TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc);
            retVal = false;
        }

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

        const string c_TEST_ID = "P001";
        string c_TEST_DESC = "PosTest1: initialize an instance of type TargetInvocationException via default constructor";
        string errorDesc;

        Exception innerException = new ArgumentNullException();

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
        try
        {
            TargetInvocationException ex = new TargetInvocationException(innerException);
            if (null == ex)
            {
                errorDesc = "Failed to initialize an instance of type TargetInvocationException via default constructor.";
                errorDesc += "\nInner exception is " + innerException;
                TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            errorDesc = "Unexpected exception: " + e;
            errorDesc += "\nInner exception is " + innerException;
            TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc);
            retVal = false;
        }

        return retVal;
    }
Example #3
0
    /// <summary>
    /// Unwraps an exception to remove any wrappers, like <see cref="TargetInvocationException"/>.
    /// </summary>
    /// <param name="ex">The exception to unwrap.</param>
    /// <returns>The unwrapped exception.</returns>
    public static Exception Unwrap(this Exception ex)
    {
        while (true)
        {
            TargetInvocationException tiex = ex as TargetInvocationException;
            if (tiex == null)
            {
                return(ex);
            }

            ex = tiex.InnerException;
        }
    }
Example #4
0
        public void TestInvalidKeySize()
        {
            byte[] key = Utility.GenerateRandomBytes(48);
            for (int i = 0; i < key.Length; i++)
            {
                key[i] = 0x00;
            }
            TargetInvocationException e = Assert.Throws <TargetInvocationException>(() =>
                                                                                    Utility.EncryptDataUsingAED(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, key, Utility.CColumnEncryptionType.Deterministic));
            string expectedMessage = "The column encryption key has been successfully decrypted but it's length: 48 does not match the length: 32 for algorithm 'AEAD_AES_256_CBC_HMAC_SHA256'. Verify the encrypted value of the column encryption key in the database.\r\nParameter name: encryptionKey";

            Assert.Contains(expectedMessage, e.InnerException.Message);
        }
        private static void CheckInnerException <T>(TargetInvocationException e) where T : Exception
        {
            var originalException = e;

            while (e.InnerException is TargetInvocationException)
            {
                e = e.InnerException as TargetInvocationException;
            }
            if (!(e.InnerException is T))
            {
                throw originalException;
            }
        }
Example #6
0
        /// <summary>
        /// Handle the exception, displaying a nice message and converting to <seealso cref="EPException"/>.
        /// </summary>
        /// <param name="statementName">Name of the statement.</param>
        /// <param name="logger">is the logger to use for error logging</param>
        /// <param name="e">is the exception</param>
        /// <param name="paramList">the method parameters</param>
        /// <param name="subscriber">the object to deliver to</param>
        /// <param name="method">the method to call</param>
        /// <throws>EPException converted from the passed invocation exception</throws>
        protected internal static void Handle(string statementName,
                                              ILog logger,
                                              TargetInvocationException e,
                                              object[] paramList,
                                              object subscriber,
                                              FastMethod method)
        {
            var message = TypeHelper.GetMessageInvocationTarget(statementName, method.Target,
                                                                subscriber.GetType().FullName,
                                                                paramList, e);

            logger.Error(message, e.InnerException);
        }
Example #7
0
        public void TestNullColumnEncryptionAlgorithm()
        {
            string expectedMessage = "Internal error. Encryption algorithm cannot be null. Valid algorithms are: 'AES_256_CBC', 'AEAD_AES_256_CBC_HMAC_SHA256'.\r\nParameter name: encryptionAlgorithm";
            Object cipherMD = Utility.GetSqlCipherMetadata(0, 0, null, 1, 0x01);
            Utility.AddEncryptionKeyToCipherMD(cipherMD, CertFixture.encryptedCek, 0, 0, 0, new byte[] { 0x01, 0x02, 0x03 }, CertFixture.certificatePath, "MSSQL_CERTIFICATE_STORE", "RSA_OAEP");
            byte[] plainText = Encoding.Unicode.GetBytes("HelloWorld");
            byte[] cipherText = Utility.EncryptDataUsingAED(plainText, CertFixture.cek, CColumnEncryptionType.Deterministic);

            TargetInvocationException e = Assert.Throws<TargetInvocationException>(() => Utility.DecryptWithKey(cipherText, cipherMD, "testsrv"));
            Assert.Contains(expectedMessage, e.InnerException.Message);
            e = Assert.Throws<TargetInvocationException>(() => Utility.EncryptWithKey(plainText, cipherMD, "testsrv"));
            Assert.Contains(expectedMessage, e.InnerException.Message);
        }
Example #8
0
        public void TestInvalidAlgorithmVersion()
        {
            string expectedMessage = string.Format(SystemDataResourceManager.Instance.TCE_InvalidAlgorithmVersion,
                                                   40, "01");

            byte[] plainText  = Encoding.Unicode.GetBytes("Hello World");
            byte[] cipherText = EncryptDataUsingAED(plainText, CertFixture.cek, CColumnEncryptionType.Deterministic);
            // Put a version number of 0x10
            cipherText[0] = 0x40;
            TargetInvocationException e = Assert.Throws <TargetInvocationException>(() => DecryptDataUsingAED(cipherText, CertFixture.cek, CColumnEncryptionType.Deterministic));

            Assert.Contains(expectedMessage, e.InnerException.Message);
        }
        public static void RethrowInnerException(this TargetInvocationException exception)
        {
            Exception innerException = exception.InnerException;

#if !WINRT
            FieldInfo stackTraceField = typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic);
            stackTraceField.SetValue(innerException, innerException.StackTrace);
#else
            ExceptionDispatchInfo.Capture(innerException).Throw();
#endif

            throw innerException;
        }
Example #10
0
        private string SmartFormatException(Exception exception)
        {
            if (exception is TargetInvocationException)
            {
                TargetInvocationException reflectionException = exception as TargetInvocationException;
                if (reflectionException.InnerException != null)
                {
                    exception = reflectionException.InnerException;
                }
            }

            return(FormatException(exception));
        }
        private static void TryPayload(object payload)
        {
            MemoryStream    ms     = new MemoryStream();
            BinaryFormatter writer = new BinaryFormatter();

            writer.Serialize(ms, payload);
            ms.Position = 0;

            BinaryFormatter           reader = new BinaryFormatter();
            TargetInvocationException tie    = Assert.Throws <TargetInvocationException>(() => reader.Deserialize(ms));

            Assert.IsAssignableFrom(typeof(SerializationException), tie.InnerException);
        }
        public void TestCreateNewUniqueProductId()
        {
            const string   MEMBER_FUNCTION_NAME_CREATE_NEW_UNIQUE_PRODUCT_ID = "CreateNewUniqueProductId";
            List <Product> products = CreateUniqueProductIdQualifiedProducts();

            _target.SetFieldOrProperty(MEMBER_VARIABLE_NAME_PRODUCTS, products);
            Assert.AreEqual(( int )_target.Invoke(MEMBER_FUNCTION_NAME_CREATE_NEW_UNIQUE_PRODUCT_ID), 2);
            products = CreateFromZeroToOneThousandUniqueProductIdQualifiedProducts();
            _target.SetFieldOrProperty(MEMBER_VARIABLE_NAME_PRODUCTS, products);
            TargetInvocationException expectedException = Assert.ThrowsException <TargetInvocationException>(() => _target.Invoke(MEMBER_FUNCTION_NAME_CREATE_NEW_UNIQUE_PRODUCT_ID));

            Assert.IsInstanceOfType(expectedException.InnerException, typeof(ApplicationException));
        }
Example #13
0
        public void ShouldRollbackAndThrowOnExceptionInsideATargetInvotacionExceptionOnTransactionalUnitOfWork()
        {
            persistenceContext.Expect(x => x.CreateTransactionalContext()).Return(transactionalContext).Repeat.Once();
            transactionalContext.Expect(x => x.Commit()).Repeat.Never();
            transactionalContext.Expect(x => x.Begin()).Repeat.Once();
            transactionalContext.Expect(x => x.Rollback()).Repeat.Once();

            mocks.ReplayAll();
            var exception = new TargetInvocationException(new TestException("expected"));

            Assert.Throws <TestException>(
                () => workContext.RunUnitOfWork(() => { throw exception; }, new UnitOfWorkInfo(true)));
        }
Example #14
0
        public void ThrowOnNullToCtor(object sourceObject)
        {
            Type                      type     = sourceObject.GetType();
            Type                      viewType = GetDebugViewType(type);
            ConstructorInfo           ctor     = viewType.GetConstructors().Single();
            TargetInvocationException tie      = Assert.Throws <TargetInvocationException>(() => ctor.Invoke(new object[] { null }));
            ArgumentNullException     ane      = (ArgumentNullException)tie.InnerException;

            if (!PlatformDetection.IsNetNative) // The .NET Native toolchain optimizes away exception ParamNames
            {
                Assert.Equal(ctor.GetParameters()[0].Name, ane.ParamName);
            }
        }
Example #15
0
 public void TestInvalidAuthenticationTag()
 {
     string expectedMessage = @"Specified ciphertext has an invalid authentication tag.\s+\(?Parameter (name: )?'?cipherText('\))?";
     byte[] plainText = Encoding.Unicode.GetBytes("Hello World");
     byte[] cipherText = Utility.EncryptDataUsingAED(plainText, CertFixture.cek, Utility.CColumnEncryptionType.Deterministic);
     // Zero out 4 bytes of authentication tag
     for (int i = 0; i < 4; i++)
     {
         cipherText[i + 1] = 0x00;
     }
     TargetInvocationException e = Assert.Throws<TargetInvocationException>(() => Utility.DecryptDataUsingAED(cipherText, CertFixture.cek, Utility.CColumnEncryptionType.Deterministic));
     Assert.Matches(expectedMessage, e.InnerException.Message);
 }
        private void DoRunScript(object sender, PythonScriptEditor.RunScriptEventArgs e)
        {
            try
            {
                ScriptEngine engine = Python.CreateEngine();

                engine.Runtime.LoadAssembly(Assembly.GetExecutingAssembly());
                engine.Runtime.IO.SetOutput(new MemoryStream(), new ConsoleTextWriter(this, false));
                engine.Runtime.IO.SetErrorOutput(new MemoryStream(), new ConsoleTextWriter(this, true));

                ICollection <string> paths = engine.GetSearchPaths();

                paths.Add(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PythonLib"));

                engine.SetSearchPaths(paths);

                ScriptErrorListener listener = new ScriptErrorListener();
                ScriptSource        source   = engine.CreateScriptSourceFromString(e.ScriptText);

                CompiledCode code = source.Compile(listener);

                if (listener.Errors.Count == 0)
                {
                    // Just create the global scope, don't execute it yet
                    ScriptScope scope = engine.CreateScope();

                    scope.SetVariable("obj", COMUtilities.IsComImport(m_dispType)
                        ? new DynamicComObjectWrapper(m_registry, m_dispType, m_pObject) : m_pObject);
                    scope.SetVariable("disp", m_pObject);

                    dynamic host = new ExpandoObject();

                    host.openobj = new Action <DynamicComObjectWrapper>(o => { OpenObjectViewer(o); });

                    scope.SetVariable("host", host);

                    code.Execute(scope);
                }
            }
            catch (Exception ex)
            {
                TargetInvocationException tex = ex as TargetInvocationException;

                if (tex != null)
                {
                    ex = tex.InnerException;
                }

                AddText(ex.Message + Environment.NewLine);
            }
        }
Example #17
0
            private static T Create__Instance__ <T>(T Instance) where T : Form, new()
            {
                bool flag = Instance == null || Instance.IsDisposed;
                T    result;

                if (flag)
                {
                    bool flag2 = MyProject.MyForms.m_FormBeingCreated != null;
                    if (flag2)
                    {
                        bool flag3 = MyProject.MyForms.m_FormBeingCreated.ContainsKey(typeof(T));
                        if (flag3)
                        {
                            throw new InvalidOperationException(Utils.GetResourceString("WinForms_RecursiveFormCreate", new string[0]));
                        }
                    }
                    else
                    {
                        MyProject.MyForms.m_FormBeingCreated = new Hashtable();
                    }
                    MyProject.MyForms.m_FormBeingCreated.Add(typeof(T), null);
                    try
                    {
                        try
                        {
                            result = Activator.CreateInstance <T>();
                            return(result);
                        }
                        object arg_97_0;
                        TargetInvocationException expr_9C = arg_97_0 as TargetInvocationException;
                        int arg_B9_0;
                        if (expr_9C == null)
                        {
                            arg_B9_0 = 0;
                        }
                        else
                        {
                            TargetInvocationException ex = expr_9C;
                            ProjectData.SetProjectError(expr_9C);
                            arg_B9_0 = (((ex.InnerException != null) > false) ? 1 : 0);
                        }
                        endfilter(arg_B9_0);
                    }
                    finally
                    {
                        MyProject.MyForms.m_FormBeingCreated.Remove(typeof(T));
                    }
                }
                result = Instance;
                return(result);
            }
Example #18
0
        public void TestInvalidEncryptionType()
        {
            Object cipherMD = Utility.GetSqlCipherMetadata(0, 2, null, 3, 0x01);
            Utility.AddEncryptionKeyToCipherMD(cipherMD, CertFixture.encryptedCek, 0, 0, 0, new byte[] { 0x01, 0x02, 0x03 }, CertFixture.certificatePath, "MSSQL_CERTIFICATE_STORE", "RSA_OAEP");
            byte[] plainText = Encoding.Unicode.GetBytes("HelloWorld");
            byte[] cipherText = Utility.EncryptDataUsingAED(plainText, CertFixture.cek, Utility.CColumnEncryptionType.Deterministic);

            string expectedMessage = @"Encryption type '3' specified for the column in the database is either invalid or corrupted. Valid encryption types for algorithm 'AEAD_AES_256_CBC_HMAC_SHA256' are: 'Deterministic', 'Randomized'.\s+\(?Parameter (name: )?'?encryptionType('\))?";
            TargetInvocationException e = Assert.Throws<TargetInvocationException>(() => Utility.DecryptWithKey(cipherText, cipherMD, "testsrv"));
            Assert.Matches(expectedMessage, e.InnerException.Message);

            e = Assert.Throws<TargetInvocationException>(() => Utility.EncryptWithKey(plainText, cipherMD, "testsrv"));
            Assert.Matches(expectedMessage, e.InnerException.Message);
        }
Example #19
0
        public static void VerifyInvokeIsUsingEmit_Constructor()
        {
            ConstructorInfo           ctor = typeof(TestClassThatThrows).GetConstructor(Type.EmptyTypes) !;
            TargetInvocationException ex   = Assert.Throws <TargetInvocationException>(() => ctor.Invoke(null));
            Exception exInner = ex.InnerException;

            Assert.Contains("Here", exInner.ToString());
            Assert.Contains(InterpretedMethodName(), exInner.ToString());
            Assert.DoesNotContain("InvokeStub_TestClassThatThrows", exInner.ToString());

            string InterpretedMethodName() => PlatformDetection.IsMonoRuntime ?
            "System.Reflection.ConstructorInvoker.InterpretedInvoke" :
            "System.RuntimeMethodHandle.InvokeMethod";
        }
Example #20
0
        public void TestInitializeProductTypes()
        {
            const string MEMBER_FUNCTION_NAME_INITIALIZE_PRODUCT_TYPES = "InitializeProductTypes";
            var          arguments = new object[] { null };
            TargetInvocationException expectedException = Assert.ThrowsException <TargetInvocationException>(() => _target.Invoke(MEMBER_FUNCTION_NAME_INITIALIZE_PRODUCT_TYPES, arguments));

            Assert.IsInstanceOfType(expectedException.InnerException, typeof(ArgumentNullException));
            arguments = new object[] { CreateProducts() };
            _target.Invoke(MEMBER_FUNCTION_NAME_INITIALIZE_PRODUCT_TYPES, arguments);
            List <string> expectedProductTypes = (List <string>)_target.GetFieldOrProperty(MEMBER_VARIABLE_NAME_PRODUCT_TYPES);

            Assert.AreEqual(expectedProductTypes[0], "Type A");
            Assert.AreEqual(expectedProductTypes[1], "Type B");
        }
Example #21
0
        public void CanSerializeTargetInvocationException()
        {
            var exc        = new TargetInvocationException(null);
            var serializer = new Hyperion.Serializer();

            using (var stream = new MemoryStream())
            {
                serializer.Serialize(exc, stream);
                stream.Position = 0;
                var deserialized = serializer.Deserialize <TargetInvocationException>(stream);
                Assert.Equal(exc.Message, deserialized.Message);
                Assert.Equal(exc.StackTrace, deserialized.StackTrace);
            }
        }
        public void ThrowOnNullToCtor()
        {
            if (BindingRestrictionsDebugViewType == null)
            {
                return;
            }
            TargetInvocationException tie = Assert.Throws <TargetInvocationException>(() => BindingRestrictionsProxyCtor.Invoke(new object[] { null }));
            ArgumentNullException     ane = (ArgumentNullException)tie.InnerException;

            if (!PlatformDetection.IsNetNative) // The .NET Native toolchain optimizes away exception ParamNames
            {
                Assert.Equal("node", ane.ParamName);
            }
        }
        public void ExtractExchangeRateNegativeRate()
        {
            TargetInvocationException exception = Assert.ThrowsException <TargetInvocationException>(() => _privateType.InvokeStatic("ExtractExchangeRate", "AUD;CHF;-1"));

            Assert.IsInstanceOfType(exception.InnerException, typeof(DataFormatException));

            List <string> messages = new List <string>()
            {
                "The conversion rate (T) is negative",
                "Line = AUD;CHF;-1"
            };

            Assert.AreEqual(exception.InnerException.Message, string.Join("\n", messages));
        }
Example #24
0
        public void TestMethod23()
        {
            CreateUsers23();

            MethodInfo createComputer = controllerType23.GetMethod("CreateComputer");

            object[] param = new object[] { computers23[0] };

            TargetInvocationException ex = Assert.ThrowsException <TargetInvocationException>(() => createComputer.Invoke(controller23, param));

            Assert.AreEqual(typeof(ArgumentException), ex.InnerException.GetType());

            Assert.AreEqual(expectedOutput23, ex.InnerException.Message);
        }
        public void TestUpdateCurrentResizingShape()
        {
            const string MEMBER_FUNCTION_NAME_UPDATE_CURRENT_RESIZING_SHAPE = "UpdateCurrentResizingShape";
            var          arguments = new object[] { null };
            TargetInvocationException expectedException = Assert.ThrowsException <TargetInvocationException>(() => _target.Invoke(MEMBER_FUNCTION_NAME_UPDATE_CURRENT_RESIZING_SHAPE, arguments));

            Assert.IsInstanceOfType(expectedException.InnerException, typeof(ArgumentNullException));
            var mousePosition = new Point();

            arguments = new object[] { mousePosition };
            _target.Invoke(MEMBER_FUNCTION_NAME_UPDATE_CURRENT_RESIZING_SHAPE, arguments);
            Assert.AreSame(_currentResizingShapeShapeDrawer.DrawingEndingPoint, mousePosition);
            Assert.IsTrue(_canvasDrawer.IsCalledNotifyCanvasRefreshDrawRequested);
        }
Example #26
0
            public void Run()
            {
                foreach (ConstructorInfo constructor in TargetType.GetConstructors())
                {
                    ParameterInfo[] parameters = constructor.GetParameters();

                    object?[] parameterValues = parameters
                                                .Select(p => p.ParameterType)
                                                .Select(t =>
                    {
                        if (SpecifiedValues.TryGetValue(t, out object?value))
                        {
                            return(value);
                        }
                        Mock mock = (Mock)Activator.CreateInstance(typeof(Mock <>).MakeGenericType(t)) !;
                        return(mock.Object);
                    })
                                                .ToArray();

                    for (int i = 0; i < parameters.Length; i++)
                    {
                        object?[] values = parameterValues.ToArray();
                        values[i] = null;

                        if (AllowedNullParameters.Contains(parameters[i].ParameterType) ||
                            parameters[i].HasDefaultValue && parameters[i].DefaultValue is null)
                        {
                            //NB: no exception thrown
                            constructor.Invoke(values);
                        }
                        else
                        {
                            string parameterDisplay      = $"'{parameters[i].Name}' ({parameters[i].ParameterType.Name})";
                            TargetInvocationException ex = Assert.ThrowsException <TargetInvocationException>(new Action(() =>
                            {
                                object?rv = constructor.Invoke(values);
                                throw new Exception($"Expected {nameof(ArgumentNullException)} for null parameter {parameterDisplay} but no exception was thrown");
                            }));
                            if (ex.InnerException is ArgumentNullException argumentNullException)
                            {
                                Assert.AreEqual(parameters[i].Name, argumentNullException.ParamName);
                            }
                            else
                            {
                                throw new Exception($"Thrown argument for {parameterDisplay} was '{ex.InnerException?.GetType().Name}' not {nameof(ArgumentNullException)}.", ex.InnerException);
                            }
                        }
                    }
                }
            }
Example #27
0
        public void StripTargetInvocationExceptionAndAggregateException()
        {
            _client.AddWrapperExceptions(typeof(AggregateException));

            OutOfMemoryException      exception2   = new OutOfMemoryException("Ran out of Int64s");
            AggregateException        innerWrapper = new AggregateException(_exception, exception2);
            TargetInvocationException wrapper      = new TargetInvocationException(innerWrapper);

            List <Exception> exceptions = _client.ExposeStripWrapperExceptions(wrapper).ToList();

            Assert.AreEqual(2, exceptions.Count);
            Assert.Contains(_exception, exceptions);
            Assert.Contains(exception2, exceptions);
        }
Example #28
0
        public void ViewTypeThrowsOnNull(object collection)
        {
            Type debugViewType = GetDebugViewType(collection.GetType());

            if (debugViewType == null)
            {
                throw new SkipTestException($"Didn't find DebuggerTypeProxyAttribute on {collection.GetType()}.");
            }
            ConstructorInfo           constructor = debugViewType.GetConstructors().Single();
            TargetInvocationException tie         = Assert.Throws <TargetInvocationException>(() => constructor.Invoke(new object[] { null }));
            var ane = (ArgumentNullException)tie.InnerException;

            Assert.Equal("collection", ane.ParamName);
        }
Example #29
0
        private static T smethod_0 <T>(T Instance) where T : Form, new()
        {
            if (Instance != null && !Instance.IsDisposed)
            {
                return(Instance);
            }
            if (Class1.Class2.hashtable_0 != null)
            {
                if (Class1.Class2.hashtable_0.ContainsKey(typeof(T)))
                {
                    throw new InvalidOperationException(Utils.GetResourceString("WinForms_RecursiveFormCreate", new string[0]));
                }
            }
            else
            {
                Class1.Class2.hashtable_0 = new Hashtable();
            }
            Class1.Class2.hashtable_0.Add(typeof(T), null);
            T result;

            try
            {
                try
                {
                    result = Activator.CreateInstance <T>();
                    return(result);
                }
                finally { }
                object arg_73_0;
                TargetInvocationException expr_78 = arg_73_0 as TargetInvocationException;
                int arg_95_0;
                if (expr_78 == null)
                {
                    arg_95_0 = 0;
                }
                else
                {
                    TargetInvocationException ex = expr_78;
                    ProjectData.SetProjectError(expr_78);
                    //arg_95_0 = (((ex.InnerException != null) > false) ? 1 : 0);
                }
                //endfilter(arg_95_0);
            }
            finally
            {
                Class1.Class2.hashtable_0.Remove(typeof(T));
            }
            return(result);
        }
Example #30
0
        public static void Throws <TException>(Action act, Predicate <TException> checker) where TException : Exception
        {
            bool matched = false;
            bool thrown  = false;

            try
            {
                act();
            }
            catch (Exception ex)
            {
                TException tex = ex as TException;
                if (tex == null)
                {
                    if (typeof(TException) == typeof(TargetInvocationException))
                    {
                        // The only place we do special processing is TargetInvocationException, but if that's
                        // what the user expected, we don't do anything
                        throw;
                    }

                    TargetInvocationException tiex = tex as TargetInvocationException;
                    if (tiex == null)
                    {
                        throw;
                    }
                    tex = tiex.InnerException as TException;
                    if (tex == null)
                    {
                        throw;
                    }
                }
                thrown  = true;
                matched = checker(tex);
                if (!matched)
                {
                    throw;
                }
            }

            if (!thrown)
            {
                throw new AssertionException(String.Format("Expected exception of type '{0}' was not thrown", typeof(TException).FullName));
            }
            else if (!matched)
            {
                throw new AssertionException(String.Format("Expected exception of type '{0}' was thrown but did not match the configured criteria", typeof(TException).FullName));
            }
        }
Example #31
0
        /// <summary>
        /// Extracts the first inner exception of type <typeparamref name="TPreferredException"/>
        /// from the <see cref="AggregateException"/> if one is present.
        /// </summary>
        /// <remarks>
        /// If no <typeparamref name="TPreferredException"/> inner exception is present, this
        /// method returns the first inner exception.   All inner exceptions will be traced,
        /// including the one returned.   The containing <paramref name="aggregateException"/>
        /// will not be traced unless there are no inner exceptions.
        /// </remarks>
        /// <typeparam name="TPreferredException">The preferred type of inner exception to extract.
        /// Use <c>typeof(Exception)</c> to extract the first exception regardless of type.</typeparam>
        /// <param name="aggregateException">The <see cref="AggregateException"/> to examine.</param>
        /// <param name="eventSource">The event source to trace.</param>
        /// <returns>The extracted exception.  It will not be <c>null</c>
        /// but it may not be of type <typeparamref name="TPreferredException"/>.</returns>
        public Exception AsError <TPreferredException>(AggregateException aggregateException, string eventSource)
        {
            Fx.Assert(aggregateException != null, "aggregateException cannot be null.");

            // If aggregateException contains any fatal exceptions, return it directly
            // without tracing it or any inner exceptions.
            if (Fx.IsFatal(aggregateException))
            {
                return(aggregateException);
            }

            // Collapse possibly nested graph into a flat list.
            // Empty inner exception list is unlikely but possible via public api.
            ReadOnlyCollection <Exception> innerExceptions = aggregateException.Flatten().InnerExceptions;

            if (innerExceptions.Count == 0)
            {
                return(TraceException(aggregateException, eventSource));
            }

            // Find the first inner exception, giving precedence to TPreferredException
            Exception favoredException = null;

            foreach (Exception nextInnerException in innerExceptions)
            {
                // AggregateException may wrap TargetInvocationException, so unwrap those as well
                TargetInvocationException targetInvocationException = nextInnerException as TargetInvocationException;

                Exception innerException = (targetInvocationException != null && targetInvocationException.InnerException != null)
                                                ? targetInvocationException.InnerException
                                                : nextInnerException;

                if (innerException is TPreferredException && favoredException == null)
                {
                    favoredException = innerException;
                }

                // All inner exceptions are traced
                TraceException <Exception>(innerException, eventSource);
            }

            if (favoredException == null)
            {
                Fx.Assert(innerExceptions.Count > 0, "InnerException.Count is known to be > 0 here.");
                favoredException = innerExceptions[0];
            }

            return(favoredException);
        }
        public void ThrowOnNullToCtor(object sourceObject)
        {
            Type type     = sourceObject.GetType();
            Type viewType = GetDebugViewType(type);

            if (viewType == null)
            {
                throw new SkipTestException($"Didn't find DebuggerTypeProxyAttribute on {type}.");
            }
            ConstructorInfo           ctor = viewType.GetConstructors().Single();
            TargetInvocationException tie  = Assert.Throws <TargetInvocationException>(() => ctor.Invoke(new object[] { null }));
            ArgumentNullException     ane  = (ArgumentNullException)tie.InnerException;

            Assert.Equal(ctor.GetParameters()[0].Name, ane.ParamName);
        }
    public bool PosTest3()
    {
        bool retVal = true;

        const string c_TEST_ID = "P003";
        string c_TEST_DESC = "PosTest3: initialize an instance of type TargetInvocationException using a null reference";
        string errorDesc;

        string message = null;
        Exception innerException = new Exception();

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
        try
        {
            TargetInvocationException e = new TargetInvocationException(message, innerException);
            if (null == e)
            {
                errorDesc = "Failed to initialize an instance of type TargetInvocationException.";
                errorDesc += "\nInput message is a null reference.";
                errorDesc += "\nInner exception is " + innerException;
                TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            errorDesc = "Unexpected exception: " + e;
            errorDesc += "\nInput message is a null reference.";
            errorDesc += "\nInner exception is " + innerException;
            TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc);
            retVal = false;
        }

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

        const string c_TEST_ID = "P002";
        string c_TEST_DESC = "PosTest2: initialize an instance of type TargetInvocationException using a string containing special character";
        string errorDesc;

        string message = "Not supported exception occurs here \n\r\0\t\v";
        Exception innerException = new Exception();

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
        try
        {
            TargetInvocationException e = new TargetInvocationException(message, innerException);
            if (null == e || e.Message != message || e.InnerException != innerException)
            {
                errorDesc = "Failed to initialize an instance of type TargetInvocationException.";
                errorDesc += "\nInput message is \"" + message + "\"";
                errorDesc += "\nInner exception is " + innerException;
                TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            errorDesc = "Unexpected exception: " + e;
            errorDesc += "\nInput message is \"" + message + "\"";
            errorDesc += "\nInner exception is " + innerException;
            TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc);
            retVal = false;
        }

        return retVal;
    }