public void First_exception_fails_operation_without_executing_remaining_calls()
        {
            Queue <TaskCompletionSource <bool> > pending = new Queue <TaskCompletionSource <bool> >();
            Func <Task> doAsync = delegate
            {
                TaskCompletionSource <bool> tcs = new TaskCompletionSource <bool>();
                pending.Enqueue(tcs);
                return(tcs.Task);
            };

            OperationManager manager = new OperationManager(1, doAsync);
            Task             task    = manager.RunAsync(3);

            Assert.False(task.IsCompleted);
            Assert.Equal(1, pending.Count);

            TaskCompletionSource <bool> current   = pending.Dequeue();
            InvalidProgramException     exception = new InvalidProgramException("expected");

            current.SetException(exception);

            Assert.False(task.IsCompleted);
            Assert.Equal(1, pending.Count);

            current = pending.Dequeue();
            current.SetResult(false);

            Assert.True(task.IsCompleted);
            Assert.True(task.IsFaulted);
            Assert.NotNull(task.Exception);
            AggregateException ae = Assert.IsType <AggregateException>(task.Exception).Flatten();

            Assert.Equal(1, ae.InnerExceptions.Count);
            Assert.Same(exception, ae.InnerExceptions[0]);
        }
        public static void Ctor_String()
        {
            string message   = "bad program";
            var    exception = new InvalidProgramException(message);

            ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_INVALIDPROGRAM, message: message);
        }
示例#3
0
        public virtual void Construct_MessageAndInnerException_NullMessage()
        {
            var innerException = new InvalidProgramException();
            var exception      = Create(null as string, innerException);

            exception.Message.Should().NotBeNullOrWhiteSpace();
            exception.InnerException.Should().BeSameAs(innerException);
        }
示例#4
0
        public virtual void Construct_MessageAndInnerException_NullInnerException()
        {
            var innerException = new InvalidProgramException();
            var exception      = Create(ArcaneMessage, null as Exception);

            exception.Message.Should().BeSameAs(ArcaneMessage);
            exception.InnerException.Should().BeNull();
        }
        public static void Ctor_String_Exception()
        {
            string message        = "bad program";
            var    innerException = new Exception("Inner exception");
            var    exception      = new InvalidProgramException(message, innerException);

            ExceptionUtility.ValidateExceptionProperties(exception, hResult: COR_E_INVALIDPROGRAM, innerException: innerException, message: message);
        }
示例#6
0
        public void TestIsOdd()
        {
            bool result3 = InvalidProgramException.IsOdd(3);

            Assert.AreEqual(true, result3);

            bool result4 = InvalidProgramException.IsOdd(4);

            Assert.AreEqual(false, result4);
        }
示例#7
0
        public virtual void SerializeThenDeserialize() // tests protected serialization constructor
        {
            var innerException = new InvalidProgramException();
            var exception      = Create(ArcaneMessage, innerException);

            var deserialized = Roundtrip(exception);

            deserialized.Should().NotBeNull();
            deserialized.Message.Should().Be(ArcaneMessage);
            deserialized.InnerException.Should().BeOfType <InvalidProgramException>();
        }
示例#8
0
        public void RunSyncronously_FunctionThrowsException_ExceptionIsCaughtAndLogged()
        {
            // Arrange
            var         errorMessage            = "Something bad happened";
            var         invalidProgramException = new InvalidProgramException(errorMessage);
            Func <Task> badFunction             = () => throw invalidProgramException;

            // Act
            test.Instance.RunSyncronously(badFunction);

            // Assert
            test.GetMockFor <ILogger>().Verify(logger => logger.LogError(errorMessage, invalidProgramException, It.IsAny <string>()), Times.Once());
        }
示例#9
0
        protected internal virtual Task RunAsync()
        {
            var pipeStates = BeforeInvoke();

            var runTask = _invoker.InvokeMessageHandlerAsync(this);

            if (runTask.Status == TaskStatus.Created)
            {
                var exception = new InvalidProgramException($"{Invoker.MessageHandlerType.Name}.Handle({Invoker.MessageType.Name}) did not start the returned task");
                runTask = Task.FromException(exception);
            }

            runTask.ContinueWith(task => AfterInvoke(pipeStates, task.IsFaulted, task.Exception), TaskContinuationOptions.ExecuteSynchronously);

            return(runTask);
        }
        private static void VerifySetsAndRestoresActivityIdOnSyncError(Func <ICalculatorClientAsync, Task <double> > doAsync)
        {
            ClientEventSource            eventSource       = ClientEventSource.Instance;
            InvalidProgramException      expectedException = new InvalidProgramException("Expected.");
            CalculatorClientWithActivity client            = new CalculatorClientWithActivity(new CalculatorClientStub(() => Throw(expectedException)), eventSource, Guid.Empty);

            using (ClientEventListener listener = new ClientEventListener(eventSource, EventLevel.Informational, ClientEventSource.Keywords.Request))
            {
                Guid originalActivityId = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
                EventProvider.SetActivityId(ref originalActivityId);
                listener.EventWritten += (o, e) => Assert.NotEqual(originalActivityId, Trace.CorrelationManager.ActivityId);

                InvalidProgramException ipe = Assert.Throws <InvalidProgramException>(() => doAsync(client));
                Assert.Same(expectedException, ipe);

                Assert.Equal(originalActivityId, Trace.CorrelationManager.ActivityId);
            }
        }
示例#11
0
        public override async Task HandleAsync(ThrowAggregateExceptionAction action, IDispatcher dispatcher)
        {
            var exception1 = new InvalidOperationException("First embedded exception");
            var exception2 = new InvalidCastException("Second embedded exception");
            var exception3 = new InvalidProgramException("Third embedded exception");

            await Task.Delay(100);

            try
            {
                throw new AggregateException(
                          exception1,
                          new AggregateException(exception2, exception3));
            }
            finally
            {
                action.TriggerHasFinished.Set();
            }
        }
 public bool PosTest1()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest1:Initialize the InvalidProgramException instance");
     try
     {
         InvalidProgramException myException = new InvalidProgramException();
         if (myException == null)
         {
             TestLibrary.TestFramework.LogError("001", "the InvalidProgramException instance creating failed");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
         retVal = false;
     }
     return retVal;
 }
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1:Initialize the InvalidProgramException instance");
        try
        {
            InvalidProgramException myException = new InvalidProgramException();
            if (myException == null)
            {
                TestLibrary.TestFramework.LogError("001", "the InvalidProgramException instance creating failed");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
            retVal = false;
        }
        return(retVal);
    }
 public bool PosTest1()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest1:Initialize the InvalidProgramException instance with message 1");
     try
     {
         string message = "HelloWorld";
         InvalidProgramException myException = new InvalidProgramException(message);
         if (myException == null || myException.Message != message)
         {
             TestLibrary.TestFramework.LogError("001", "the InvalidProgramException with message instance creating failed");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
         retVal = false;
     }
     return retVal;
 }
 public bool PosTest2()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest2:Initialize the InvalidProgramException instance with message 2");
     try
     {
         string message = null;
         InvalidProgramException myException = new InvalidProgramException(message);
         if (myException == null || myException.Message == null)
         {
             TestLibrary.TestFramework.LogError("003", "Initialize the InvalidProgramException instance with null message not create");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
         retVal = false;
     }
     return retVal;
 }
 public bool PosTest3()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest3:Initialize the InvalidProgramException instance with message and InnerException 3");
     try
     {
         string message = null;
         InvalidProgramException myException = new InvalidProgramException(message, null);
         if (myException == null || myException.Message == null || myException.InnerException != null)
         {
             TestLibrary.TestFramework.LogError("005", "Initialize the InvalidProgramException instance with null message and null InnerException not succeed");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
         retVal = false;
     }
     return retVal;
 }
        public void Test_ConnectionScope_GetDefaultDbConext()
        {
            bool currentValue = ClownFish.Data.Initializer.Instance.IsAutoCreateOneOffDbContext;

            // 设置  IsAutoCreateOneOffDbContext = true;
            ClownFish.Data.Initializer.Instance.AllowCreateOneOffDbContext();

            using (DbContext db = ConnectionScope.GetDefaultDbConext()) {
                Assert.IsNotNull(db);
                Assert.AreEqual(true, db.AutoDisposable);
            }


            // 设置  IsAutoCreateOneOffDbContext = false;
            typeof(ClownFish.Data.Initializer).InvokeMember(
                "IsAutoCreateOneOffDbContext",
                BindingFlags.SetProperty | BindingFlags.NonPublic | BindingFlags.Instance,
                null, ClownFish.Data.Initializer.Instance,
                new object[] { false });


            InvalidProgramException exception = null;

            try {
                DbContext db = ConnectionScope.GetDefaultDbConext();
            }
            catch (InvalidProgramException ex) {
                exception = ex;
            }

            Assert.IsNotNull(exception);


            // 恢复  IsAutoCreateOneOffDbContext
            typeof(ClownFish.Data.Initializer).InvokeMember(
                "IsAutoCreateOneOffDbContext",
                BindingFlags.SetProperty | BindingFlags.NonPublic | BindingFlags.Instance,
                null, ClownFish.Data.Initializer.Instance,
                new object[] { currentValue });
        }
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1:Initialize the InvalidProgramException instance with message 1");
        try
        {
            string message = "HelloWorld";
            InvalidProgramException myException = new InvalidProgramException(message);
            if (myException == null || myException.Message != message)
            {
                TestLibrary.TestFramework.LogError("001", "the InvalidProgramException with message instance creating failed");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
            retVal = false;
        }
        return(retVal);
    }
 public bool PosTest2()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest2:Initialize the InvalidProgramException instance with message and InnerException 2");
     try
     {
         string message = null;
         ArgumentException innerException = new ArgumentException();
         InvalidProgramException myException = new InvalidProgramException(message, innerException);
         if (myException == null || myException.Message == null || !myException.InnerException.Equals(innerException))
         {
             TestLibrary.TestFramework.LogError("003", "Initialize the InvalidProgramException instance with null message not succeed");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
         retVal = false;
     }
     return retVal;
 }
示例#20
0
        private void DispatchAsync(PipeInvocation invocation, MessageDispatch dispatch)
        {
            var invocationTask = invocation.RunAsync();

            invocationTask.ContinueWith(task => dispatch.SetHandled(invocation.Invoker, GetException(task)), TaskContinuationOptions.ExecuteSynchronously);

            if (invocationTask.Status != TaskStatus.Created)
            {
                return;
            }

            if (invocation.Invoker.ShouldCreateStartedTasks)
            {
                var exception = new InvalidProgramException($"{invocation.Invoker.MessageHandlerType.Name}.Handle({invocation.Invoker.MessageType.Name}) did not start the returned task");
                dispatch.SetHandled(invocation.Invoker, exception);
                return;
            }

            var taskScheduler = GetTaskScheduler(invocation.Invoker.DispatchQueueName);

            invocationTask.Start(taskScheduler);
        }
    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2:Initialize the InvalidProgramException instance with message 2");
        try
        {
            string message = null;
            InvalidProgramException myException = new InvalidProgramException(message);
            if (myException == null || myException.Message == null)
            {
                TestLibrary.TestFramework.LogError("003", "Initialize the InvalidProgramException instance with null message not create");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
            retVal = false;
        }
        return(retVal);
    }
示例#22
0
    public bool PosTest3()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest3:Initialize the InvalidProgramException instance with message and InnerException 3");
        try
        {
            string message = null;
            InvalidProgramException myException = new InvalidProgramException(message, null);
            if (myException == null || myException.Message == null || myException.InnerException != null)
            {
                TestLibrary.TestFramework.LogError("005", "Initialize the InvalidProgramException instance with null message and null InnerException not succeed");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
            retVal = false;
        }
        return(retVal);
    }
示例#23
0
        public void Enqueue_with_events_traces_event_on_error()
        {
            InputQueueStub <string> inner       = new InputQueueStub <string>();
            QueueEventSource        eventSource = QueueEventSource.Instance;
            Guid id = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
            InputQueueWithEvents <string> queue = new InputQueueWithEvents <string>(inner, id, eventSource);

            using (QueueEventListener listener = new QueueEventListener(eventSource, EventLevel.Informational, EventKeywords.None))
            {
                InvalidProgramException expectedException = new InvalidProgramException("Expected.");
                inner.Enqueued += delegate(object sender, EventArgs e)
                {
                    listener.VerifyEvent(QueueEventId.Enqueue, EventLevel.Informational, EventKeywords.None, id);
                    listener.Events.Clear();
                    throw expectedException;
                };

                InvalidProgramException ipe = Assert.Throws <InvalidProgramException>(() => queue.Enqueue("a"));
                Assert.Same(expectedException, ipe);

                listener.VerifyEvent(QueueEventId.EnqueueCompleted, EventLevel.Informational, EventKeywords.None, id);
            }
        }
示例#24
0
    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2:Initialize the InvalidProgramException instance with message and InnerException 2");
        try
        {
            string                  message        = null;
            ArgumentException       innerException = new ArgumentException();
            InvalidProgramException myException    = new InvalidProgramException(message, innerException);
            if (myException == null || myException.Message == null || !myException.InnerException.Equals(innerException))
            {
                TestLibrary.TestFramework.LogError("003", "Initialize the InvalidProgramException instance with null message not succeed");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
            retVal = false;
        }
        return(retVal);
    }
示例#25
0
        public void Should_execute_all_cleanup_steps_despite_async_exceptions_in_run_and_cleanup_and_complete_with_all_exceptions()
        {
            CleanupGuard           guard       = new CleanupGuard();
            List <int>             steps       = new List <int>();
            Func <int, Task, Task> doStepAsync = delegate(int i, Task t)
            {
                steps.Add(i);
                return(t);
            };

            TaskCompletionSource <bool> cleanupTcs = new TaskCompletionSource <bool>();

            guard.Register(() => doStepAsync(1, Task.FromResult(false)));
            guard.Register(() => doStepAsync(2, cleanupTcs.Task));

            TaskCompletionSource <bool> runTcs = new TaskCompletionSource <bool>();
            Task task = guard.RunAsync(g => runTcs.Task);

            Assert.False(task.IsCompleted);

            InvalidProgramException expectedRunException = new InvalidProgramException("Expected (run).");

            runTcs.SetException(expectedRunException);

            InvalidTimeZoneException expectedCleanupException = new InvalidTimeZoneException("Expected (cleanup).");

            cleanupTcs.SetException(expectedCleanupException);

            Assert.Equal(TaskStatus.Faulted, task.Status);
            Assert.NotNull(task.Exception);
            AggregateException ae = Assert.IsType <AggregateException>(task.Exception).Flatten();

            Assert.Equal(2, ae.InnerExceptions.Count);
            Assert.Same(expectedRunException, ae.InnerExceptions[0]);
            Assert.Same(expectedCleanupException, ae.InnerExceptions[1]);
            Assert.Equal(new int[] { 2, 1 }, steps.ToArray());
        }
示例#26
0
        public void Test()
        {
            //string path = Path.GetTempFileName();
            string path = @"D:\Users\jwood\Desktop\LogFile.txt";

            LogFile logFile = new LogFile(path);

            //logFile.LogLevel = LogLevel.None;

            logFile.LogInfo("An information-level log entry");
            logFile.LogWarning("A warning-level log entry");
            logFile.LogError("An error-level log entry");
            logFile.LogCritical("A critical-level log entry");

            logFile.LogDivider();

            Exception ex = new ArgumentNullException("parameterName");

            ex = new InvalidOperationException("Unable to do that", ex);
            ex = new InvalidDataException("Unable to do this", ex);
            ex = new InvalidProgramException("There was a problem!", ex);

            logFile.LogError("Text and an exception (not logging inner exceptions)", ex);

            logFile.LogInnerExceptions = true;
            logFile.LogError("Text and an exception (logging inner exceptions)", ex);
            logFile.LogInnerExceptions = false;

            logFile.LogDivider();

            logFile.LogInfo("I finished the first thing", "I did the second thing", "I breezed through the third thing", ex);

            logFile.LogFormat(LogLevel.Info, "Formatted log entry : {0}:{1}:{2}", 123, 456, 789);

            //File.Delete(path);
        }
示例#27
0
        /// <summary>   Gets the 7zip library path.</summary>
        /// <exception cref="TimeoutException"> Thrown when a Timeout error condition occurs.</exception>
        /// <returns>   The library path.</returns>
        /// <remarks> In WindowsCE, a file called 7z.dll in the same directory as this assembly.  If it does not exist,
        ///           an Embedded resource is extracted to this directory and used.  All other platforms use the following
        ///           logic:
        ///           1. [All] The value provided to a previous call to SetLibraryPath() is used.
        ///           2. [Full Framework] app.config AppSetting '7zLocation' which must be path to the proper bit 7z.dll
        ///           3. [All] Embedded resource is extracted to %TEMP% and used. (assuming build with embedded 7z.dll is used)
        ///           4. [All] 7z.dll from a x86 or x64 subdirectory of this assembly's directory.
        ///           5. [All] 7za.dll from a x86 or x64 subdirectory of this assembly's directory.
        ///           6. [All] 7z86.dll or 7z64.dll in the same directory as this assembly.
        ///           7. [All] 7za86.dll or 7za64.dll in the same directory as this assembly.
        ///           8. [All] A file called 7z.dll in the same directory as this assembly.
        ///           9. [All] A file called 7za.dll in the same directory as this assembly.
        ///           If not found, we give up and fail.
        /// </remarks>
        private static string GetLibraryPath()
        {
            if (_libraryFileName != null && (_modulePtr != IntPtr.Zero || File.Exists(_libraryFileName)))
            {
                return(_libraryFileName);
            }

            string default7zPath = null;

#if !WINCE && !MONO
            var sevenZipLocation = ConfigurationManager.AppSettings["7zLocation"];
            if (!string.IsNullOrEmpty(sevenZipLocation) && File.Exists(sevenZipLocation))
            {
                _libraryFileName = sevenZipLocation;
                return(_libraryFileName);
            }
            default7zPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
#endif
#if WINCE
            default7zPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
            var sevenZipLocation = Path.Combine(default7zPath, "7z.dll");
            if (File.Exists(sevenZipLocation))
            {
                _libraryFileName = sevenZipLocation;
                return(_libraryFileName);
            }
            var bitness = "arm";
#else
            var bitness = IntPtr.Size == 4 ? "x86" : "x64";
#endif
            var thisType = typeof(SevenZipLibraryManager);
#if WINCE
            _libraryFileName = sevenZipLocation;
#else
            var version = thisType.Assembly.GetName().Version.ToString(3);
            _libraryFileName = Path.Combine(Path.GetTempPath(), String.Join(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture), new string[] { "SevenZipSharp", version, bitness, "7z.dll" }));
#endif
            if (File.Exists(_libraryFileName))
            {
                return(_libraryFileName);
            }

            //NOTE: This is the approach used in https://github.com/jacobslusser/ScintillaNET for handling the native component.
            //      I liked it, so I added it to this project.  We could have a build configuration that doesn't embed the dlls
            //      to make our assembly smaller and future proof, but you'd need to handle distributing and setting the dll yourself.
            // Extract the embedded DLL http://stackoverflow.com/a/768429/2073621
            // Synchronize access to the file across processes http://stackoverflow.com/a/229567/2073621
            var guid = ((GuidAttribute)thisType.Assembly.GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(CultureInfo.InvariantCulture);
            var name = string.Format(CultureInfo.InvariantCulture, "Global\\{{{0}}}", guid);
            using (var mutex = new Mutex(false, name))
            {
#if !WINCE
                var access   = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var security = new MutexSecurity();
                security.AddAccessRule(access);
                mutex.SetAccessControl(security);
#endif
                var ownsHandle = false;
                try
                {
                    try
                    {
                        ownsHandle = mutex.WaitOne(5000, false); // 5 sec
                        if (!ownsHandle)
                        {
                            var timeoutMessage = string.Format(CultureInfo.InvariantCulture, "Timeout waiting for exclusive access to '{0}'.", _libraryFileName);
                            throw new TimeoutException(timeoutMessage);
                        }
                    }
#if WINCE
                    catch
#else
                    catch (AbandonedMutexException)
#endif
                    {
                        // Previous process terminated abnormally
                        ownsHandle = true;
                    }

                    // Double-checked (process) lock
                    if (File.Exists(_libraryFileName))
                    {
                        return(_libraryFileName);
                    }

                    // Write the embedded file to disk
                    var directory = Path.GetDirectoryName(_libraryFileName);
                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    Exception ex = null;
                    try
                    {
#if WINCE
                        var resource = string.Format(CultureInfo.InvariantCulture, "{0}.{1}.7z.dll.gz", thisType.Assembly.GetName().Name, bitness); //packing of resources differ
#else
                        var resource = string.Format(CultureInfo.InvariantCulture, "{0}.{1}.7z.dll.gz", thisType.Namespace, bitness);               //packing of resources differ
#endif
                        var resourceStream = thisType.Assembly.GetManifestResourceStream(resource);
                        if (resourceStream == null)
                        {
                            ex = new InvalidProgramException(string.Format("Could not extract resource named '{0}' from assembly '{1}'", resource, thisType.Assembly.FullName));
                        }
                        else
                        {
                            using (var gzipStream = new GZipStream(resourceStream, System.IO.Compression.CompressionMode.Decompress))
                            {
                                using (var fileStream = File.Create(_libraryFileName))
                                {
                                    //Would normally use gzipStream.CopyTo(fileStream) but this is .NET 2.0 compliant.
                                    var buffer = new byte[4096];
                                    int count;
                                    while ((count = gzipStream.Read(buffer, 0, buffer.Length)) != 0)
                                    {
                                        fileStream.Write(buffer, 0, count);
                                    }
                                    return(_libraryFileName);
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        ex = e;
                        if (File.Exists(_libraryFileName))
                        {
                            File.Delete(_libraryFileName);
                        }
                    }
#if !WINCE
                    if (default7zPath != null)
                    {
                        var testPath = Path.Combine(default7zPath, String.Concat(bitness, Path.DirectorySeparatorChar, "7z.dll"));
                        if (File.Exists(testPath))
                        {
                            return(_libraryFileName = testPath);
                        }
                        testPath = Path.Combine(default7zPath, String.Concat(bitness, Path.DirectorySeparatorChar, "7za.dll"));
                        if (File.Exists(testPath))
                        {
                            return(_libraryFileName = testPath);
                        }
                        var bitnessSansX           = IntPtr.Size == 4 ? "86" : "64";
                        var sevenZipWithBitDllName = string.Format(CultureInfo.InvariantCulture, "7z{0}.dll", bitnessSansX);
                        testPath = Path.Combine(default7zPath, sevenZipWithBitDllName);
                        if (File.Exists(testPath))
                        {
                            return(_libraryFileName = testPath);
                        }
                        var sevenZipAWithBitDllName = string.Format(CultureInfo.InvariantCulture, "7za{0}.dll", bitnessSansX);
                        testPath = Path.Combine(default7zPath, sevenZipAWithBitDllName);
                        if (File.Exists(testPath))
                        {
                            return(_libraryFileName = testPath);
                        }
                        testPath = Path.Combine(default7zPath, "7z.dll");
                        if (File.Exists(testPath))
                        {
                            return(_libraryFileName = testPath);
                        }
                        testPath = Path.Combine(default7zPath, "7za.dll");
                        if (File.Exists(testPath))
                        {
                            return(_libraryFileName = testPath);
                        }
                    }
#endif
                    _libraryFileName = null;
                    throw new SevenZipLibraryException("Unable to locate the 7z.dll. Please call SetLibraryPath() or set app.config AppSetting '7zLocation' " +
                                                       "which must be path to the proper bit 7z.dll", ex);
                }
        public static void Ctor_Empty()
        {
            var exception = new InvalidProgramException();

            ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_INVALIDPROGRAM, validateMessage: false);
        }
        public void Extensions_InvalidProgramExceptionIsCriticalTest()
        {
            var ex = new InvalidProgramException();

            Assert.IsTrue(ex.IsCritical());
        }
示例#30
0
 public JitHitInternalLimitsOnIndexingFunction(InvalidProgramException e)
     : base(ErrorMessage, e)
 {
 }
示例#31
0
        internal void Answer(Packet packet)
        {
            if (packet.Command == 0xFF)
            {
                Exception exception;

                switch (packet.Helper)
                {
                case 0x01:
                    exception = new UniverseServerUnhandledException();
                    break;

                case 0x02:
                    exception = new InvalidParameterException();
                    break;

                case 0x03:
                    exception = new AccountDoesntExistException();
                    break;

                case 0x04:
                    exception = new OperationRequiresAdminStatusException();
                    break;

                case 0x05:
                    exception = new PermissionDeniedException(packet.SubAddress);
                    break;

                case 0x06:
                    exception = new IllegalNameException();
                    break;

                case 0x07:
                    exception = new UnitDoesntExistException();
                    break;

                case 0x08:
                    exception = new NoUniverseAssignmentException();
                    break;

                case 0x09:
                    exception = new WrongStateException();
                    break;

                case 0x0A:
                    exception = new TooManyEntriesException();
                    break;

                case 0x10:
                    exception = new JoinRefusedException(packet.SubAddress);
                    break;

                case 0x11:
                    exception = new PartException(packet.SubAddress);
                    break;

                case 0x20:
                    exception = new UniverseDoesntExistException();
                    break;

                case 0x21:
                    exception = new UniverseOfflineException();
                    break;

                case 0x22:
                    exception = new UniverseGoneWhileExecutingRequestException();
                    break;

                case 0x23:
                    exception = new NoUniverseAvailableException();
                    break;

                case 0x24:
                    exception = new GalaxyDoesntExistException();
                    break;

                case 0x60:
                    exception = new NonEditableUnitException();
                    break;

                case 0x61:
                    exception = new AmbiguousXmlDataException();
                    break;

                case 0xFB:
                {
                    BinaryMemoryReader tmpReader = packet.Read();

                    string message   = tmpReader.ReadString();
                    string parameter = tmpReader.ReadString();

                    exception = new ArgumentException(message, parameter);
                }
                break;

                case 0xFC:
                {
                    BinaryMemoryReader tmpReader = packet.Read();

                    string message   = tmpReader.ReadString();
                    string parameter = tmpReader.ReadString();

                    exception = new ArgumentNullException(parameter, message);
                }
                break;

                case 0xFD:
                {
                    string message = packet.Read().ReadString();

                    exception = new InvalidOperationException(message);
                }
                break;

                case 0xFE:
                    exception = new Exception("This exception will be replaced with an generic exception.");
                    break;

                case 0xFF:
                    BinaryMemoryReader reader = packet.Read();
                    exception = new InvalidProgramException($"!!! INVALID EXCEPTION COUGHT BY SERVER !!!\n\nThe server has cought a \"{reader.ReadString()}\" and did just forward this to the client (you). The exception has the following message:\n\n{reader.ReadString()}\n\nAnd the following stack trace:\n\n{reader.ReadString()}\n\nIf you are in the C# course of the HS-Esslingen: Contact your teacher.");
                    break;

                default:
                    exception = new Exception($"Unknown Exception Code: 0x{packet.Helper.ToString()}.");
                    break;
                }

                ThreadPool.QueueUserWorkItem(delegate { tcs.SetException(exception); });

                return;
            }

            ThreadPool.QueueUserWorkItem(delegate { tcs.SetResult(packet); });
        }
示例#32
0
        /// <summary>
        /// Run fuzzer
        /// </summary>
        /// <param name="action">Action</param>
        /// <param name="args">Arguments</param>
        public static void Run(Action <Stream> action, FuzzerRunArgs args = null)
        {
            CoverageHelper.CreateCoverageListener();

            if (action == null)
            {
                throw new NullReferenceException(nameof(action));
            }

            // Check supervisor

            Mutex mutex;
            var   supervisor = FuzzerRunArgs.SupervisorType.None;

            if (args != null && args.Supervisor != FuzzerRunArgs.SupervisorType.None)
            {
                // Check if is the listener or the task with mutex

                mutex = new Mutex(false, "TuringMachine.Supervisor." + Client.PublicName, out var isNew);

                if (!isNew)
                {
                    Client.PublicName += $".{Process.GetCurrentProcess().Id}:{args.TaskId}";
                }
                else
                {
                    Client.PublicName += ".Supervisor";
                    supervisor         = args.Supervisor;
                }
            }
            else
            {
                mutex = null;
            }

            if (!Client.IsStarted)
            {
                // If you want other connection you must call this method before Run

                Client.Start(CommandLineOptions.Parse().GetConnection());
            }

            // Send current files

            Client.SendCurrentFiles(new OperationCanceledException(), null, true);

            // Fuzz

            var cancel  = new CancelEventArgs();
            var handler = new ConsoleCancelEventHandler((o, s) =>
            {
                cancel.Cancel = true;
                s.Cancel      = true;
            });

            Console.CancelKeyPress += handler;

            // Ensure data

            while (Client.GetInput() == null || Client.GetConfig() == null)
            {
                Thread.Sleep(50);
            }

            switch (supervisor)
            {
            case FuzzerRunArgs.SupervisorType.RegularSupervisor:
            {
                var pi = new ProcessStartInfoEx()
                {
                    FileName               = "dotnet",
                    Arguments              = string.Join(" ", Environment.GetCommandLineArgs().Select(u => u)),
                    WindowStyle            = ProcessWindowStyle.Normal,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    UseShellExecute        = false,
                    CreateNoWindow         = false,
                };

                while (!cancel.Cancel)
                {
                    using (var pr = new ProcessEx(pi))
                    {
                        pr.WaitForExit();

                        Exception exception;

                        switch (pr.ExitCode)
                        {
                        case StackOverflowExceptionCode:
                        {
                            exception = new StackOverflowException($"Unhandled exception: {pr.ExitCode}");
                            break;
                        }

                        default:
                        {
                            exception = new InvalidProgramException($"Unhandled exception: {pr.ExitCode}");
                            break;
                        }
                        }

                        if (Client.SendCurrentFiles(exception, pr.Output, true) == 0)
                        {
                            Client.SendLog(new FuzzerLog()
                                {
                                    Coverage = CoverageHelper.CurrentCoverage,
                                    InputId  = Guid.Empty,
                                    ConfigId = Guid.Empty,
                                });
                        }
                    }
                }
                break;
            }

            case FuzzerRunArgs.SupervisorType.None:
            {
                while (!cancel.Cancel)
                {
                    var input  = Client.GetInput();
                    var config = Client.GetConfig();

                    string     currentStreamPath  = null;
                    FileStream storeCurrentStream = null;

                    if (args?.StoreCurrent == true)
                    {
                        // Free current stream

                        currentStreamPath  = $"{input.Id}.{config.Id}.{Process.GetCurrentProcess().Id}.{args.TaskId}.current";
                        storeCurrentStream = new FileStream(currentStreamPath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
                    }

                    using (var stream = new FuzzingStream(config, input, storeCurrentStream)
                        {
                            ExtraLogInformation = "TaskId: " + args.TaskId
                        })
                    {
                        var log = Client.Execute(action, stream);

                        if (log != null)
                        {
                            Client.SendLog(log);
                            args?.OnLog?.Invoke(log, cancel);
                        }
                    }

                    if (storeCurrentStream != null)
                    {
                        // Delete current stream

                        storeCurrentStream.Close();
                        storeCurrentStream.Dispose();
                        File.Delete(currentStreamPath);
                    }
                }
                break;
            }
            }

            Console.CancelKeyPress -= handler;
            mutex?.Dispose();
        }
示例#33
0
        protected override object InvokeMethod(HookMethod method, object[] args)
        {
            object obj;
            object obj1;
            bool   compiledAssembly;

            if (!this.hookDispatchFallback && !method.IsBaseHook)
            {
                if (args != null && args.Length != 0)
                {
                    ParameterInfo[] parameters = method.Parameters;
                    for (int i = 0; i < (int)args.Length; i++)
                    {
                        object obj2 = args[i];
                        if (obj2 != null)
                        {
                            Type parameterType = parameters[i].ParameterType;
                            if (parameterType.IsValueType)
                            {
                                Type type = obj2.GetType();
                                if (parameterType != typeof(object) && type != parameterType)
                                {
                                    args[i] = Convert.ChangeType(obj2, parameterType);
                                }
                            }
                        }
                    }
                }
                try
                {
                    if (!this.DirectCallHook(method.Name, out obj, args))
                    {
                        this.PrintWarning(string.Concat("Unable to call hook directly: ", method.Name), Array.Empty <object>());
                        return(method.Method.Invoke(this, args));
                    }
                    else
                    {
                        obj1 = obj;
                    }
                }
                catch (InvalidProgramException invalidProgramException1)
                {
                    InvalidProgramException invalidProgramException = invalidProgramException1;
                    Interface.Oxide.LogError(string.Concat("Hook dispatch failure detected, falling back to reflection based dispatch. ", invalidProgramException), Array.Empty <object>());
                    CompilablePlugin compilablePlugin = CSharpPluginLoader.GetCompilablePlugin(Interface.Oxide.PluginDirectory, base.Name);
                    if (compilablePlugin != null)
                    {
                        compiledAssembly = compilablePlugin.CompiledAssembly;
                    }
                    else
                    {
                        compiledAssembly = false;
                    }
                    if (compiledAssembly)
                    {
                        File.WriteAllBytes(string.Concat(Interface.Oxide.PluginDirectory, "\\", base.Name, ".dump"), compilablePlugin.CompiledAssembly.PatchedAssembly);
                        Interface.Oxide.LogWarning(string.Concat("The invalid raw assembly has been dumped to Plugins/", base.Name, ".dump"), Array.Empty <object>());
                    }
                    this.hookDispatchFallback = true;
                    return(method.Method.Invoke(this, args));
                }
                return(obj1);
            }
            return(method.Method.Invoke(this, args));
        }