Exemple #1
0
        public void Exceptions_are_made_available_as_messages()
        {
            var evt = new ManualResetEvent(false);
            ExceptionOccurred capturedMessage = null;
            var bus = BusSetup.StartWith <AsyncConfiguration>().Construct();

            bus.Subscribe <MessageB>(msg =>
            {
                throw new ArgumentException("Bad message");
            });
            bus.Subscribe <ExceptionOccurred>(x =>
            {
                capturedMessage = x;
                evt.Set();
            });

            bus.Publish(new MessageB());
            var signaled = evt.WaitOne(TimeSpan.FromSeconds(2));

            if (!signaled)
            {
                Assert.Fail("Exception was never captured!");
            }

            capturedMessage.Exception.ShouldBeOfType <AggregateException>();
            var xes = ((AggregateException)capturedMessage.Exception).InnerExceptions;

            xes[0].ShouldBeOfType <ArgumentException>();
            xes[0].Message.ShouldBeEqualTo("Bad message");
        }
        public JniNativeMethods(IntPtr env)
        {
            JniNativeInterface javaNativeInterface = **(JniNativeInterface **)env;

            // Class delegates
            findClass       = (FindClass)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.FindClass, typeof(FindClass));
            newGlobalRef    = (NewGlobalRef)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.NewGlobalRef, typeof(NewGlobalRef));
            deleteLocalRef  = (DeleteLocalRef)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.DeleteLocalRef, typeof(DeleteLocalRef));
            deleteGlobalRef = (DeleteGlobalRef)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.DeleteGlobalRef, typeof(DeleteGlobalRef));
            getObjectClass  = (GetObjectClass)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.GetObjectClass, typeof(GetObjectClass));
            newObject       = (NewObjectA)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.NewObjectA, typeof(NewObjectA));

            // String conversion delegates
            newStringUTF          = (NewStringUTF)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.NewStringUTF, typeof(NewStringUTF));
            getStringChars        = (GetStringChars)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.GetStringChars, typeof(GetStringChars));
            releaseStringChars    = (ReleaseStringChars)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.ReleaseStringChars, typeof(ReleaseStringChars));
            getStringUTFChars     = (GetStringUTFChars)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.GetStringUTFChars, typeof(GetStringUTFChars));
            releaseStringUTFChars = (ReleaseStringUTFChars)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.ReleaseStringUTFChars, typeof(ReleaseStringUTFChars));
            getStringUTFLength    = (GetStringUTFLength)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.GetStringUTFLength, typeof(GetStringUTFLength));

            // Method delegates
            registerNatives      = (RegisterNatives)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.RegisterNatives, typeof(RegisterNatives));
            getStaticMethodId    = (GetStaticMethodId)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.GetStaticMethodID, typeof(GetStaticMethodId));
            getMethodID          = (GetMethodID)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.GetMethodID, typeof(GetMethodID));
            callStaticVoidMethod = (CallStaticVoidMethod)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.CallStaticVoidMethod, typeof(CallStaticVoidMethod));
            callVoidMethod       = (CallVoidMethodA)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.CallVoidMethodA, typeof(CallVoidMethodA));

            // Exception delegates
            exceptionCheck    = (ExceptionCheck)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.ExceptionCheck, typeof(ExceptionCheck));
            exceptionOccurred = (ExceptionOccurred)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.ExceptionOccurred, typeof(ExceptionOccurred));
            exceptionClear    = (ExceptionClear)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.ExceptionClear, typeof(ExceptionClear));
            exceptionDescribe = (ExceptionDescribe)Marshal.GetDelegateForFunctionPointer(javaNativeInterface.ExceptionDescribe, typeof(ExceptionDescribe));
        }
        /// <summary>
        /// Tries to convert a given memory stream to the UTF16 encoding by adding an UTF16 BOM to the stream.
        /// </summary>
        /// <param name="stream">The stream to try to convert to.</param>
        /// <param name="encoding">The encoding successfully used with the stream data.</param>
        /// <param name="bigEndian"><c>true</c> to use the big endian byte order (most significant byte first); <c>false</c> to use the little endian byte order (least significant byte first).</param>
        /// <param name="noBom">A value indicating whether the detected unicode file contains a byte-order-mark.</param>
        /// <returns>A string converted into the UTF16 encoding if successful; otherwise null.</returns>
        public static string TryUtf16Encoding(MemoryStream stream, bool bigEndian, out Encoding encoding, out bool noBom)
        {
            noBom = false;

            if (!FormSettings.Settings.SkipUnicodeDetectLe && !bigEndian &&
                ByteMatch(GetEncodingComparisonBytes(stream), Utf16LittleEndianBom) ||
                !FormSettings.Settings.SkipUnicodeDetectBe && bigEndian &&
                ByteMatch(GetEncodingComparisonBytes(stream), Utf16BigEndianBom))
            {
                try
                {
                    encoding = new UnicodeEncoding(bigEndian, true, true);
                    return(encoding.GetString(stream.ToArray()));
                }
                catch (Exception ex)
                {
                    ExceptionOccurred?.Invoke("TryUtf16Encoding", new EncodingExceptionEventArgs {
                        Exception = ex
                    });

                    // failed..
                    encoding = null;
                    return(null);
                }
            }

            // the user doesn't want this detection..
            if (FormSettings.Settings.SkipUnicodeDetectLe && !bigEndian ||
                FormSettings.Settings.SkipUnicodeDetectBe && bigEndian)
            {
                // so just return..
                encoding = null;
                return(null);
            }

            try // there is no BOM..
            {
                // get the contents of the memory stream into a list of bytes..
                List <byte> bytes = new List <byte>(stream.ToArray());

                // insert the BOM..
//                bytes.InsertRange(0, bigEndian ? Utf16BigEndianBom : Utf16LittleEndianBom);

                // try the UTF16 encoding with the BOM..
                encoding = new UnicodeEncoding(bigEndian, false, true);
                noBom    = true;
                return(encoding.GetString(bytes.ToArray()));
            }
            catch (Exception ex)
            {
                ExceptionOccurred?.Invoke("TryUtf16Encoding", new EncodingExceptionEventArgs {
                    Exception = ex
                });

                // failed..
                encoding = null;
                return(null);
            }
        }
Exemple #4
0
        private void PacketReceivingThread()
        {
            try
            {
                while (_running)
                {
                    var datapacket = new DataPacket(DefaultCodec);

                    datapacket.ReadFromStream(_rawReadCodec, RemoteBoundTo, () => CompressThreshold, () => State);

                    if (!PacketProvider.TryCreatePacket(datapacket.PacketId, datapacket.BoundTo, datapacket.State, out var packet) &&
                        ((packet = OnUnknownPacketReceived(datapacket)) is DataPacket ||
                         packet is null))
                    {
                        _logger.Warn($"Unknown packet 0x{datapacket.PacketId:X2}");
                        continue;
                    }

                    packet.ReadFromStream(datapacket.Content);

                    if (!OnPacketReceived(packet))
                    {
                        continue;
                    }

                    lock (_receivePacketQueue)
                    {
                        _receivePacketQueue.Enqueue(packet);

                        if (_waitReceiveCount != 0)
                        {
                            Monitor.Pulse(_receivePacketQueue);
                        }
                    }
                }
            }
            catch (EndOfStreamException)
            {
                _receivePacketQueue.Enqueue(null);
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                ExceptionOccurred?.Invoke(this, ex);
            }
            finally
            {
                lock (_receivePacketQueue)
                {
                    if (_waitReceiveCount != 0)
                    {
                        Monitor.PulseAll(_receivePacketQueue);
                    }
                }
                _running = false;
                State    = ProtocolState.Closed;
            }
        }
Exemple #5
0
        /// <summary>
        /// Begin a task reading data from the Fanuc Device
        /// </summary>
        public void WriteOut(string data, FanucSocketOptions options)
        {
            if (SafeToProceed())
            {
                ns.Flush(); // Removes extra data that is stuck in the socket

                cancelSource  = new CancellationTokenSource();
                opCancelToken = cancelSource.Token;

                // Main read task
                operation = new Task(
                    cancellationToken: cancelSource.Token,
                    creationOptions: TaskCreationOptions.LongRunning,
                    action: () =>
                {
                    this.WriteOut_Main(data, options);
                }
                    );

                // If sending completes fully, fire event and dispose
                operation.ContinueWith(
                    continuationOptions: TaskContinuationOptions.ExecuteSynchronously,
                    continuationAction: (t) =>
                {
                    if (t.IsCompleted && !t.IsCanceled)
                    {
                        if (SendOperationCompleted != null)
                        {
                            SendOperationCompleted.Invoke(this, null);
                        }
                    }
                    else if (t.IsFaulted)
                    {
                        if (ExceptionOccurred != null)
                        {
                            ExceptionOccurred.Invoke(this, t.Exception);
                        }
                    }

                    cancelSource.Dispose();
                    cancelSource = null;

                    operation.Dispose();
                    operation = null;

                    ChangeState(FanucSocketState.Idle);
                }
                    );

                operation.Start();
            }

            else
            {
                throw new FanucException("Operation in progress!");
            }
        }
Exemple #6
0
        public ThreadGun <T> FillingMagazine(int magazineCount)
        {
            if (_action == null)
            {
                return(this);
            }

            void Action()
            {
                if (ExceptionOccurred == null)
                {
                    _action();
                }
                else
                {
                    try
                    {
                        _action();
                    }
                    catch (Exception ex)
                    {
                        ExceptionOccurred?.Invoke(this, null, null, ex);
                    }
                }

                if (_waitingPeriod != 0)
                {
                    Thread.Sleep(_waitingPeriod);
                    _waitingPeriod = 0;
                    _waitingCompletedAction?.Invoke();
                }

                try
                {
                    _magazine.TryPop(out var action);
                    action.Invoke();
                }
                catch (NullReferenceException)
                {
                    _completed = 1;
                }
            }

            for (var i = 0; i < magazineCount; i++)
            {
                _magazine.Push(Action);
            }

            return(this);
        }
Exemple #7
0
        public TItem Retry <TItem>(Func <TItem> action, RetryPolicy retryPolicy = RetryPolicy.ThrowException, int numberOfRetries = 3)
        {
            Guard.ThrowIfNull("action", action);
            Guard.EnsureIsValid("retryPolicy", r => r > 0, retryPolicy);
            Guard.EnsureIsValid("numberOfRetries", i => i > 0, numberOfRetries);

            var       numberOfExecutions = 0;
            Exception caughtException    = null;
            var       value = default(TItem);

            while (numberOfExecutions < numberOfRetries)
            {
                try
                {
                    value = action();
                }
                catch (Exception exception)
                {
                    if (numberOfExecutions != (numberOfRetries - 1))
                    {
                        continue;
                    }

                    if (retryPolicy == RetryPolicy.ThrowException)
                    {
                        throw;
                    }

                    caughtException = exception;
                }
                finally
                {
                    numberOfExecutions++;
                }
            }

            if (caughtException.IsNull() || retryPolicy == RetryPolicy.SwallowAllExceptions)
            {
                return(value);
            }

            if (ExceptionOccurred.IsNotNull())
            {
                ExceptionOccurred(this, new ExceptionEventArgs(caughtException));
            }

            return(value);
        }
        /// <summary>
        /// Tries to convert a given memory stream to the UTF8 encoding by adding an UTF8 BOM to the stream.
        /// </summary>
        /// <param name="stream">The stream to try to convert to.</param>
        /// <param name="encoding">The encoding successfully used with the stream data.</param>
        /// <param name="noBom">A value indicating whether the detected unicode file contains a byte-order-mark.</param>
        /// <returns>A string converted into the UTF8 encoding if successful; otherwise null.</returns>
        public static string TryUtf8Encoding(MemoryStream stream, out Encoding encoding, out bool noBom)
        {
            noBom = false;
            if (ByteMatch(GetEncodingComparisonBytes(stream), Utf8Bom))
            {
                try
                {
                    encoding = new UTF8Encoding(true, true);
                    return(encoding.GetString(stream.ToArray()));
                }
                catch (Exception ex)
                {
                    ExceptionOccurred?.Invoke("TryUtf8Encoding", new EncodingExceptionEventArgs {
                        Exception = ex
                    });

                    // failed..
                    encoding = null;
                    return(null);
                }
            }

            try // there is no BOM..
            {
                // get the contents of the memory stream into a list of bytes..
                List <byte> bytes = new List <byte>(stream.ToArray());

                // insert the BOM..
                bytes.InsertRange(0, Utf8Bom);

                // try the UTF8 encoding with the BOM..
                encoding = new UTF8Encoding(false, true);
                noBom    = true;
                return(encoding.GetString(bytes.ToArray()));
            }
            catch (Exception ex)
            {
                ExceptionOccurred?.Invoke("TryUtf8Encoding", new EncodingExceptionEventArgs {
                    Exception = ex
                });

                // failed..
                encoding = null;
                return(null);
            }
        }
Exemple #9
0
        public ThreadGun <T> FillingMagazine(int magazineCount)
        {
            if (_action == null)
            {
                return(this);
            }

            void Action()
            {
                if (ExceptionOccurred == null)
                {
                    _action();
                }
                else
                {
                    try
                    {
                        _action();
                    }
                    catch (Exception ex)
                    {
                        ExceptionOccurred?.Invoke(this, null, null, ex);
                    }
                }

                Wait();

                try
                {
                    _magazine.TryPop(out var action);
                    action.Invoke();
                }
                catch (NullReferenceException)
                {
                    IsCompleted = true;
                }
            }

            for (var i = 0; i < magazineCount; i++)
            {
                _magazine.Push(Action);
            }

            return(this);
        }
        public static void Shutdown(string message, Exception e)
        {
            if (hasShutdown)
            {
                // Shutdown already in progress
                return;
            }

            hasShutdown = true;

            Log.Exception(e, message);

            if (isDispatcherInitialized)
            {
                var dispatcher = GetApplicationDispatcher();
                if (dispatcher.CheckAccess())
                {
                    ShowExceptionDialog(e);
                }
                else
                {
                    dispatcher.Invoke(() => ShowExceptionDialog(e));
                }
            }

            if (Debugger.IsAttached)
            {
                Debugger.Break();
            }

            if (DateTime.Now - StartTime >= MinTimeBeforeAutoRestart)
            {
                ExceptionOccurred?.Invoke(null, EventArgs.Empty);
            }

            if (isDispatcherInitialized)
            {
                Application.Current.Shutdown(0);
            }
            else
            {
                throw new Exception($"Unhandled exception {message}", e);
            }
        }
Exemple #11
0
        public ThreadGun <T> FillingMagazine(Action <T> action, T input)
        {
            void Action()
            {
                if (ExceptionOccurred == null)
                {
                    _actionT(input);
                }
                else
                {
                    try
                    {
                        _actionT(input);
                    }
                    catch (Exception ex)
                    {
                        ExceptionOccurred?.Invoke(this, _inputs, input, ex);
                    }
                }

                if (_waitingPeriod != 0)
                {
                    Thread.Sleep(_waitingPeriod);
                    _waitingPeriod = 0;
                    _waitingCompletedAction?.Invoke();
                }

                try
                {
                    _magazine.TryPop(out var act);
                    act.Invoke();
                }
                catch (NullReferenceException)
                {
                    _completed = 1;
                }
            }

            if (ExceptionOccurred == null)
            {
                _magazine.Push(Action);
            }
            return(this);
        }
Exemple #12
0
        private void ClientAcceptedCallback(IAsyncResult ar)
        {
            Task.Run(() =>
            {
                try
                {
                    using (var connectedClient = new IdentifiedClient(_listener.EndAcceptTcpClient(ar)))
                    {
                        _connectedClients.Add(connectedClient);

                        using (var stream = connectedClient.TcpClient.GetStream())
                        {
                            while (connectedClient.TcpClient.Connected)
                            {
                                var data = _dataProvider.ReceiveData(stream);

                                try
                                {
                                    var m = UnpackResponse(data, connectedClient);

                                    if (m != null)
                                    {
                                        M.SendAsync(m);
                                    }
                                }
                                catch (Exception e)
                                {
                                    L.Error("Exception in TcpServer: " + e.Message);
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    ExceptionOccurred?.Invoke(this, e);
                }
            });

            Log("Client connected");
            WaitForClient();
        }
Exemple #13
0
        /// <summary>
        ///     Queues an invocation to the pool.
        /// </summary>
        /// <param name="invocation">Invocation to execute.</param>
        /// <exception cref="InvalidOperationException">Thrown when the pool size is 0.</exception>
        public void Enqueue(AsyncReferenceInvocation invocation)
        {
            // dispatch method used to wrap invocations
            // this allows us to observe cancellations, wait on the semaphore, and
            // generally control internal state before and after invocation execution.
            async Task DispatchImpl()
            {
                try
                {
                    if (_CancellationTokenSource.IsCancellationRequested)
                    {
                        return;
                    }

                    await _Semaphore.WaitAsync(CancellationToken).ConfigureAwait(false);

                    await invocation.Invoke(CancellationToken).ConfigureAwait(false);

                    _Semaphore.Release(1);
                }
                catch (Exception exception) when(exception is not OperationCanceledException)
                {
                    // invoke exception event to propagate swallowed errors
                    ExceptionOccurred?.Invoke(this, exception);
                }
            }

            // ensure the pool size isn't being modified
            _ModifyPoolReset.Wait(CancellationToken);

            // ensure the pool is actually accepting invocations and dispatch
            if (Size == 0)
            {
                ThrowHelper.ThrowInvalidOperationException($"Pool is empty. Call {nameof(DefaultPoolSize)}() or {nameof(ModifyPoolSize)}().");
            }
            else
            {
                Task.Factory.StartNew(DispatchImpl, CancellationToken);
            }
        }
        public async void Start()
        {
            if (_isRunning)
            {
                return;
            }

            _isRunning = true;

            while (_isRunning)
            {
                try
                {
                    var typing = await _keyboard.FetchTextAsync();

                    if (typing.Enter)
                    {
                        _lastTyping = typing;
                        Confirmed?.Invoke(this, new TypingTextEventArgs(typing));
                    }
                    else
                    {
                        var isEqual = _lastTyping != null && _lastTyping.Text == typing.Text &&
                                      _lastTyping.CaretStartIndex == typing.CaretStartIndex &&
                                      _lastTyping.CaretEndIndex == typing.CaretEndIndex;
                        _lastTyping = typing;
                        if (!isEqual)
                        {
                            Typing?.Invoke(this, new TypingTextEventArgs(typing));
                        }
                    }
                }
                catch (Exception ex)
                {
                    ExceptionOccurred?.Invoke(this, new ExceptionEventArgs(ex));
                }

                await Task.Delay(20);
            }
        }
Exemple #15
0
        public ThreadGun <T> FillingMagazine(Action <T> action, T input)
        {
            void Action()
            {
                if (ExceptionOccurred == null)
                {
                    _actionT(input);
                }
                else
                {
                    try
                    {
                        _actionT(input);
                    }
                    catch (Exception ex)
                    {
                        ExceptionOccurred?.Invoke(this, _inputs, input, ex);
                    }
                }

                Wait();

                try
                {
                    _magazine.TryPop(out var act);
                    act.Invoke();
                }
                catch (NullReferenceException)
                {
                    IsCompleted = true;
                }
            }

            if (ExceptionOccurred == null)
            {
                _magazine.Push(Action);
            }
            return(this);
        }
        protected async Task EvaluateRuleAndExecuteActionsAsync()
        {
            try
            {
                //_logger?.Here(ClassType, Description).Debug("Started");

                var result = await PerformEvaluateRuleAsync();

                var(RuleIsMet, HasRuleIsMetChanged, data) = result;

                var tasks = new List <Task>();

                foreach (var ruleAction in ruleActions)
                {
                    tasks.Add(ruleAction.ExecuteAsync(RuleIsMet, HasRuleIsMetChanged, data));
                }
                await Task.WhenAll(tasks.ToArray());
            }
            catch (Exception ex)
            {
                if (ExceptionOccurred is null)
                {
                    if (!_ThrowOnExceptions)
                    {
                        _logger?.Here(ClassType, Description).Warning(ex, "Unknown Exception was thrown during evaluation. No Exception EventHandler is subscribed, Exception Was ignored.");
                    }
                    else
                    {
                        _logger?.Here(ClassType, Description).Error(ex, "Unknown Exception was thrown during evaluation. No Exception EventHandler is subscribed. Re-throwing");
                        throw;
                    }
                }
                else
                {
                    _logger?.Here(ClassType, Description).Debug("Invoking Exception event handler");
                    ExceptionOccurred.Invoke(this, new ExceptionOccurredEventArgs(ex));
                }
            }
        }
        public void StartMonitoringLoop()
        {
            try
            {
                if (CToken.IsCancellationRequested)
                {
                    CTokenSource = new CancellationTokenSource();
                }

                using (SerialPort serial = new SerialPort(this.SerialPortName, this.SerialPortBaudrate))
                {
                    serial.Open();

                    StartAllWorkers();

                    while (!CToken.IsCancellationRequested)
                    {
                        string newLine = serial.ReadLine();

                        string message = ReadMessage(newLine);

                        SPClass serialPortClassWhichMessageHasBeenSentTo = ReadPrefixAndChooseClass(newLine);

                        SendMessageToWorker(serialPortClassWhichMessageHasBeenSentTo, message);

                        Thread.Sleep(100);

                        Helper.NLogger.Debug("\n\n");
                    }
                }
            }
            catch (Exception ex)
            {
                Helper.NLogger.Error($"\n{ex.Message} \n{ex.InnerException}\n{ex.StackTrace}\n");
                ExceptionOccurred?.Invoke(this, new EventArgs());
            }
        }
Exemple #18
0
 /// <summary>
 /// Updates the and render.
 /// </summary>
 public void UpdateAndRender()
 {
     if (CanRender())
     {
         IsBusy = true;
         var t0 = TimeSpan.FromSeconds((double)Stopwatch.GetTimestamp() / Stopwatch.Frequency);
         RenderStatistics.FPSStatistics.Push((t0 - lastRenderTime).TotalMilliseconds);
         RenderStatistics.Camera = viewport.CameraCore;
         lastRenderTime          = t0;
         UpdateRequested         = false;
         ++updateCounter;
         renderContext.AutoUpdateOctree      = RenderConfiguration.AutoUpdateOctree;
         renderContext.EnableBoundingFrustum = EnableRenderFrustum;
         if (RenderConfiguration.UpdatePerFrameData)
         {
             viewport.Update(t0);
             renderContext.TimeStamp           = t0;
             renderContext.Camera              = viewport.CameraCore;
             renderContext.WorldMatrix         = viewport.WorldMatrix;
             renderContext.OITWeightPower      = RenderConfiguration.OITWeightPower;
             renderContext.OITWeightDepthSlope = RenderConfiguration.OITWeightDepthSlope;
             renderContext.OITWeightMode       = RenderConfiguration.OITWeightMode;
         }
         PreRender();
         UpdateSceneGraphRequested = false;
         try
         {
             if (renderBuffer.BeginDraw())
             {
                 OnRender(t0);
                 renderBuffer.EndDraw();
             }
             if (RenderConfiguration.RenderD2D && D2DTarget.D2DTarget != null)
             {
                 OnRender2D(t0);
             }
             renderBuffer.Present();
         }
         catch (SharpDXException ex)
         {
             var desc = ResultDescriptor.Find(ex.ResultCode);
             if (desc == global::SharpDX.DXGI.ResultCode.DeviceRemoved || desc == global::SharpDX.DXGI.ResultCode.DeviceReset ||
                 desc == global::SharpDX.DXGI.ResultCode.DeviceHung || desc == global::SharpDX.Direct2D1.ResultCode.RecreateTarget ||
                 desc == global::SharpDX.DXGI.ResultCode.AccessLost)
             {
                 Log(LogLevel.Warning, $"Device Lost, code = {desc.Code}");
                 RenderBuffer_OnDeviceLost(RenderBuffer, EventArgs.Empty);
             }
             else
             {
                 Log(LogLevel.Error, ex);
                 EndD3D();
                 ExceptionOccurred?.Invoke(this, new RelayExceptionEventArgs(ex));
             }
         }
         catch (Exception ex)
         {
             Log(LogLevel.Error, ex);
             EndD3D();
             ExceptionOccurred?.Invoke(this, new RelayExceptionEventArgs(ex));
         }
         finally
         {
             PostRender();
             IsBusy = false;
         }
         lastRenderingDuration = TimeSpan.FromSeconds((double)Stopwatch.GetTimestamp() / Stopwatch.Frequency) - t0;
         RenderStatistics.LatencyStatistics.Push(lastRenderingDuration.TotalMilliseconds);
         OnRendered?.Invoke(this, EventArgs.Empty);
     }
 }
Exemple #19
0
 protected virtual void OnExceptionOccurred(DebuggeeExceptionEventArgs e)
 {
     ExceptionOccurred?.Invoke(this, e);
 }
Exemple #20
0
 private void OnExceptionOccurred(Exception value)
 {
     ExceptionOccurred?.Invoke(this, value);
 }
Exemple #21
0
 /// <summary>
 /// Invokes the ExceptionOccurred event.
 /// </summary>
 protected virtual void OnExceptionOccured()
 {
     ExceptionOccurred?.Invoke(this, EventArgs.Empty);
 }
Exemple #22
0
        public ThreadGun <T> FillingMagazine()
        {
            _magazine = new ConcurrentStack <Action>();
            if (_actionT != null)
            {
                foreach (var input in _inputs)
                {
                    void Action()
                    {
                        if (ExceptionOccurred == null)
                        {
                            _actionT(input);
                        }
                        else
                        {
                            try
                            {
                                _actionT(input);
                            }
                            catch (Exception ex)
                            {
                                ExceptionOccurred?.Invoke(this, _inputs, input, ex);
                            }
                        }

                        if (_waitingPeriod != 0)
                        {
                            Thread.Sleep(_waitingPeriod);
                            _waitingPeriod = 0;
                            _waitingCompletedAction?.Invoke();
                        }

                        try
                        {
                            _magazine.TryPop(out var action);
                            action.Invoke();
                        }
                        catch (NullReferenceException)
                        {
                            _completed = 1;
                        }
                    }

                    _magazine.Push(Action);
                }
            }
            else if (_action != null)
            {
                void Action()
                {
                    if (ExceptionOccurred == null)
                    {
                        _action();
                    }
                    else
                    {
                        try
                        {
                            _action();
                        }
                        catch (Exception ex)
                        {
                            ExceptionOccurred?.Invoke(this, null, null, ex);
                        }
                    }

                    if (_waitingPeriod != 0)
                    {
                        Thread.Sleep(_waitingPeriod);
                        _waitingPeriod = 0;
                        _waitingCompletedAction?.Invoke();
                    }

                    try
                    {
                        _magazine.TryPop(out var action);
                        action.Invoke();
                    }
                    catch (NullReferenceException)
                    {
                        _completed = 1;
                    }
                }

                for (var i = 0; i < _magazineCount; i++)
                {
                    _magazine.Push(Action);
                }
            }
            else if (_func != null)
            {
                foreach (var input in _inputs)
                {
                    async void AsyncAction()
                    {
                        var task = Task.Run(async() => await _func(input));

                        AddActiveTask(task);
                        if (ExceptionOccurred == null)
                        {
                            await task;
                        }
                        else
                        {
                            try
                            {
                                await task;
                            }
                            catch (Exception ex)
                            {
                                ExceptionOccurred?.Invoke(this, _inputs, input, ex);
                            }
                        }

                        if (_waitingPeriod != 0)
                        {
                            Thread.Sleep(_waitingPeriod);
                            _waitingPeriod = 0;
                            _waitingCompletedAction?.Invoke();
                        }

                        try
                        {
                            _magazine.TryPop(out var action);
                            action.Invoke();
                        }
                        catch (NullReferenceException)
                        {
                            _completed = 1;
                        }
                    }

                    _magazine.Push(AsyncAction);
                }
            }

            return(this);
        }
Exemple #23
0
 protected void OnExceptionOccurred(Exception ex)
 {
     Debug.Fail("exception occurred while executing sql statements", ex.Message);
     ExceptionOccurred?.Invoke(this, ex);
 }
Exemple #24
0
 private void OnExceptionOccurred(Exception value)
 {
     ExceptionOccurred?.Invoke(this, value, PushToThreadPool);
 }
Exemple #25
0
 private void OnExceptionOccurred(Exception exception)
 {
     ExceptionOccurred?.Invoke(this, new ExceptionEventArgs(exception));
 }
Exemple #26
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="value"></param>
 protected void OnExceptionOccurred(Exception value)
 {
     ExceptionOccurred?.Invoke(this, value);
 }
Exemple #27
0
 private void OnExceptionOccurred(Exception exception)
 {
     ExceptionOccurred?.Invoke(this, exception);
 }
        /// <summary>
        /// Tries different unicode encodings for a given file (with or without a BOM).
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="encoding">The detected encoding if any.</param>
        /// <param name="bigEndian">A value indicating whether the detected encoding is big-endian.</param>
        /// <param name="noBom">A value indicating whether the detected unicode file contains a byte-order-mark.</param>
        /// <returns>The contents of the file as a string if an unicode encoding variant was found for it.</returns>
        public static string TryEncodings(string fileName, out Encoding encoding, out bool bigEndian, out bool noBom)
        {
            noBom     = false;
            bigEndian = false;
            try
            {
                using FileStream fileStream     = File.OpenRead(fileName);
                using MemoryStream memoryStream = new MemoryStream();
                fileStream.CopyTo(memoryStream);

                // try the UTF8 encoding..
                var result = TryUtf8Encoding(memoryStream, out encoding, out noBom);

                if (result != null)
                {
                    bigEndian = false;
                    return(result);
                }

                // try the UTF16 encoding with LittleEndian..
                result = TryUtf16Encoding(memoryStream, false, out encoding, out noBom);

                if (result != null)
                {
                    bigEndian = false;
                    return(result);
                }

                // try the UTF16 encoding with BigEndian..
                result = TryUtf16Encoding(memoryStream, true, out encoding, out noBom);

                if (result != null)
                {
                    bigEndian = true;
                    return(result);
                }

                // try the UTF32 encoding with LittleEndian..
                result = TryUtf32Encoding(memoryStream, false, out encoding, out noBom);

                if (result != null)
                {
                    bigEndian = false;
                    return(result);
                }

                // try the UTF32 encoding with BigEndian..
                result = TryUtf32Encoding(memoryStream, true, out encoding, out noBom);

                if (result != null)
                {
                    bigEndian = true;
                    return(result);
                }
            }
            catch (Exception ex)
            {
                ExceptionOccurred?.Invoke("TryEncodings", new EncodingExceptionEventArgs {
                    Exception = ex
                });

                // failed..
                encoding = null;
                return(null);
            }

            return(null);
        }
Exemple #29
0
 private void OnExceptionOccurred(Exception exception)
 {
     ExceptionOccurred?.Invoke(this, new ConnectionExceptionEventArgs <T>(this, exception));
 }
Exemple #30
0
 public void OnExceptionOccurred(Exception ex) =>
 ExceptionOccurred?.Invoke(ex.Message);