public void CanBeSerializedAndDeserializedTest() { var message = Guid.NewGuid().ToString(); var targetType = typeof(Person); var referenceName = Guid.NewGuid().ToString(); var context = new Company(); var buildLog = Guid.NewGuid().ToString(); var inner = new TimeoutException(); var formatter = new BinaryFormatter(); var target = new BuildException(message, targetType, referenceName, context, buildLog, inner); using (var ms = new MemoryStream()) { formatter.Serialize(ms, target); ms.Seek(0, SeekOrigin.Begin); var outputException = formatter.Deserialize(ms) as BuildException; outputException.Message.Should().Be(message); outputException.TargetType.Should().Be(targetType); outputException.ReferenceName.Should().Be(referenceName); outputException.Context.Should().BeNull(); outputException.BuildLog.Should().Be(buildLog); outputException.InnerException.Message.ShouldBeEquivalentTo(inner.Message); } }
static async Task WaitForPulsar(TimeSpan timeout) { var sw = Stopwatch.StartNew(); Exception timeoutEx = new System.TimeoutException("Timeout waiting for Pulsar"); while (sw.Elapsed < timeout) { try { var response = await $"http://pulsar:8080/admin/v2/namespaces/public/default" .AllowAnyHttpStatus() .GetAsync(); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync()); return; } catch (Exception ex) { timeoutEx = new System.TimeoutException("Timeout waiting for Pulsar", ex); await Task.Delay(TimeSpan.FromSeconds(5)); } } throw timeoutEx; }
internal override void Timeout(InternalTransaction tx) { if (DiagnosticTrace.Warning) { TransactionTimeoutTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceLtm"), tx.TransactionTraceId); } TimeoutException e = new TimeoutException(System.Transactions.SR.GetString("TraceTransactionTimeout")); this.Rollback(tx, e); }
static StackObject *Ctor_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *__ret = ILIntepreter.Minus(__esp, 0); var result_of_this_method = new System.TimeoutException(); return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
public void TimeoutIsTransient() { // Arrange var exception = new TimeoutException(); // Act var result = SqlTransientStrategy.IsTransient(exception); // Assert Assert.True(result); }
static StaticData() { // Exception created but is not thrown TestCreatedException = new SystemException("System Test Exception"); // Traditional created and throw exception try { throw new RankException("Rank Test"); } catch (RankException e) { TestThrowException = e; } // Exception containing inner exceptions try { try { try { throw new TypeAccessException("Test Type Exception"); } catch (TypeAccessException exp1) { throw new DivideByZeroException("Divide By Zero Test", exp1); } } catch (DivideByZeroException exp2) { throw new ArithmeticException("Inner Exception Test", exp2); } } catch (ArithmeticException exp3) { TestInnerException = exp3; } // Exception with a defined stack trace var callClass = new TestNamespace.ClassAlpha(); try { callClass.ThrowException(); } catch (TimeoutException exp) { TestCallStackException = exp; } }
internal virtual bool ContinueSearch(int timeout, DateTime startTime) { bool result = false; if (0 == timeout) return result; if ((null == ResultCollection || 0 == ResultCollection.Count) && (DateTime.Now - startTime).TotalSeconds <= timeout / 1000) return true; //if (null == ResultCollection) { // var eTimeoutException = new TimeoutException(TimeoutExpirationInformation); // throw(eTimeoutException); //} if (null != ResultCollection) return result; var eTimeoutException = new TimeoutException(TimeoutExpirationInformation); throw (eTimeoutException); }
public void CanCreateWithBuildInformationAndInnerExceptionTest() { var message = Guid.NewGuid().ToString(); var targetType = typeof(Person); var referenceName = Guid.NewGuid().ToString(); var context = new Company(); var buildLog = Guid.NewGuid().ToString(); var inner = new TimeoutException(); var target = new BuildException(message, targetType, referenceName, context, buildLog, inner); target.Message.Should().Be(message); target.TargetType.Should().Be(targetType); target.ReferenceName.Should().Be(referenceName); target.Context.Should().Be(context); target.BuildLog.Should().Be(buildLog); target.InnerException.Should().Be(inner); }
/// <summary> /// 提取异常信息 /// </summary> /// <param name="ex"></param> private static string GetExceptionMessage(Exception ex) { string faultMessage = "未知错误,请查看ERP日志!"; System.TimeoutException timeoutEx = ex as System.TimeoutException; if (timeoutEx != null) { faultMessage = "因第一次访问ERP服务,访问超时,如避免此错误,请先启动ERP系统!"; } else { FaultException <ServiceException> faultEx = ex as FaultException <ServiceException>; if (faultEx == null) { faultMessage = ex.Message; } else { ServiceException serviceEx = faultEx.Detail; if (serviceEx != null && !string.IsNullOrEmpty(serviceEx.Message) && !serviceEx.Message.Equals("fault", StringComparison.OrdinalIgnoreCase)) { // 错误信息在faultEx.Message中,请提取, // 格式为"Fault:料品不能为空,请录入\n 在....." int startIndex = serviceEx.Message.IndexOf(":"); int endIndex = serviceEx.Message.IndexOf("\n"); if (endIndex == -1) { endIndex = serviceEx.Message.Length; } if (endIndex > 0 && endIndex > startIndex + 1) { faultMessage = serviceEx.Message.Substring(startIndex + 1, endIndex - startIndex - 1); } else { faultMessage = serviceEx.Message; } } } } return(faultMessage); }
internal virtual bool ContinueSearch(int timeout, DateTime startTime) { bool result = false; if (0 == timeout) return result; if ((null == ResultCollection || 0 == ResultCollection.Count) && (System.DateTime.Now - startTime).TotalSeconds <= timeout / 1000) return true; if (null == ResultCollection) { var eTimeoutException = new TimeoutException( TimeoutExpirationInformation); throw(eTimeoutException); } else { // no action currently } return result; }
/// <summary> /// Polls aPolledCondition until it returns true or until timeout occurs. /// /// If the condition is reached before the timeout then the OnSuccessAction is called. /// If a timeout occurs then OnTimeout is called /// </summary> /// <param name="aPolledCondition">The condition to poll, function should return true when the condition is reached, or false otherwise</param> /// <param name="aOnTimeoutAction">An action to perform should the poll times out, Return true [default] if an exception is to be thrown, false otherwise signals the condition was handled and no exceptions will be thrown</param> /// <param name="aOnSuccessAction">An Action to perform should the poll succeed before the timeout period</param> /// <param name="aTimeout">An Time to wait before timing out</param> /// <param name="aHeartbeatInterval">An interval at which polling should occur</param> /// <param name="aTimeoutMessage">Timout message</param> /// <param name="aActionName">Name for the action to put in the logs</param> /// <param name="aCancelPollingEvent">a ManualResetEvent to signal should we want to cancel the polling loop</param> public static void PollWithTimeout(this Func<bool> aPolledCondition, Func<bool> aOnTimeoutAction = null, Action aOnSuccessAction = null, TimeSpan? aTimeout = null, TimeSpan? aHeartbeatInterval = null, string aTimeoutMessage = null, string aActionName = null, ManualResetEvent aCancelPollingEvent = null) { if (aTimeoutMessage == null) aTimeoutMessage = "Timeout occured while waiting for action to complete"; if (aPolledCondition == null) throw new ArgumentNullException("aPolledCondition"); bool waitInfinitely = !aTimeout.HasValue; bool conditionReached = false; TimeSpan heartbeatTimeSpan = aHeartbeatInterval.HasValue ? aHeartbeatInterval.Value : TimeSpan.FromSeconds(5); if (!waitInfinitely) { heartbeatTimeSpan = aTimeout > heartbeatTimeSpan ? heartbeatTimeSpan : TimeSpan.FromMilliseconds(aTimeout.Value.Milliseconds / 10.0); aPolledCondition.Log().Info("heartbeat for polling set to {0}", heartbeatTimeSpan); } DateTime actionStartedDateTime = DateTime.Now; DateTime lastMessageHeartbeat = DateTime.Now; TimeoutException ex = null; IAsyncResult result = null; bool finished = false; bool cancelled = false; do { if (result == null || (!conditionReached && result.IsCompleted)) { result = aPolledCondition.BeginInvoke(ar => { conditionReached = aPolledCondition.EndInvoke(ar); }, null); } //We give up to the Heartbeat for the polling condition to be evaluated result.AsyncWaitHandle.WaitOne(heartbeatTimeSpan); if (result.IsCompleted && conditionReached) { finished = true; } else { DateTime nowDateTime = DateTime.Now; if (!waitInfinitely && (nowDateTime - actionStartedDateTime >= aTimeout)) { finished = true; ex = new TimeoutException(String.Format("{0}, total time waited [{1}]", aTimeoutMessage, nowDateTime - actionStartedDateTime)); } else { if (DateTime.Now - lastMessageHeartbeat >= heartbeatTimeSpan) { lastMessageHeartbeat = DateTime.Now; } if (result.IsCompleted) { //this wait is needed sicne the waitOne above will typically take very short time to complete //it is there only to prevent blockage in the evaluation of the condition //Here we wait 5 seconds before we evaluate the condition again //or the heartbeat timeout whichever one is fastest if (heartbeatTimeSpan > TimeSpan.FromSeconds(5)) { Thread.Sleep(TimeSpan.FromSeconds(5)); } else { Thread.Sleep(heartbeatTimeSpan); } } } } if (aCancelPollingEvent != null) { cancelled = aCancelPollingEvent.WaitOne(0); } } while (!finished && !cancelled); if (!cancelled) { //Ok.. we got out of the loop... if (conditionReached) { if (aOnSuccessAction != null) { aOnSuccessAction.Invoke(); } } else { bool throwException = true; if (aOnTimeoutAction != null) { throwException = aOnTimeoutAction.Invoke(); } if (throwException && ex != null) { throw ex; } } } }
internal void SetTimedOut() { Exception = new TimeoutException("Beim Warten auf die Endsequenz eines Packets wurde der TimeOut überschritten."); State = States.TimedOut; }
static void OnAsyncWaiterSignaled(object state, TimeoutException asyncException) { AsyncWaiterData asyncWaiter = (AsyncWaiterData)state; Exception completionException = asyncException; if (asyncException != null) { lock (asyncWaiter.Owner.ThisLock) { if (!asyncWaiter.Owner.waiters.Remove(asyncWaiter.Token)) { // We ----d between timing out and getting signaled. // We'll take the signal which means we now own the lock completionException = null; } } } // Callers of EnterAsync take a null value for the exception to mean // that they own the lock. Either we were signaled (asyncException was // null), we got the lock in a ----y way (we nulled the exception when // we found we weren't in the list), or we don't have the lock (asyncException // is non-null and we are passing it along). asyncWaiter.Callback(asyncWaiter.State, completionException); }
static void OnWaitEvent(object state, TimeoutException asyncException) { WaitForCanPersistAsyncResult thisPtr = (WaitForCanPersistAsyncResult)state; if (asyncException != null) { thisPtr.Complete(false, asyncException); return; } bool completeSelf = true; Exception completionException = null; try { completeSelf = thisPtr.HandleWaitEvent(); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } completionException = exception; } if (completeSelf) { thisPtr.Complete(false, completionException); } }
static void OnIdleReceived(object state, TimeoutException asyncException) { AcquireLockOnIdleAsyncResult thisPtr = (AcquireLockOnIdleAsyncResult)state; if (asyncException != null) { if (thisPtr.instance.CleanupIdleWaiter(thisPtr.idleEvent, asyncException, ref thisPtr.acquiredLockAsynchronously)) { Fx.Assert(!thisPtr.acquiredLockAsynchronously, "We shouldn't own the lock if we're rethrowing"); thisPtr.Complete(false, asyncException); return; } Fx.Assert(thisPtr.acquiredLockAsynchronously, "We should own the lock if we're ----ing"); } thisPtr.acquiredLockAsynchronously = true; thisPtr.Complete(false, null); }
static void OnNextIdle(object state, TimeoutException asyncException) { ResumeProtocolBookmarkAsyncResult thisPtr = (ResumeProtocolBookmarkAsyncResult)state; if (asyncException != null) { lock (thisPtr.instance.activeOperationsLock) { // If the waitHandle is not in either of these lists then it must have // been removed by the Set() path - that means we've got the lock, so let's // just run with it (IE - ---- the exception). if (thisPtr.instance.nextIdleWaiters.Remove(thisPtr.waitHandle) || thisPtr.instance.idleWaiters.Remove(thisPtr.waitHandle)) { thisPtr.Complete(false, asyncException); return; } } } thisPtr.ownsLock = true; bool completeSelf = true; Exception completionException = null; try { completeSelf = thisPtr.PerformResumption(); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } completionException = e; } finally { if (completeSelf) { thisPtr.instance.ReleaseLock(ref thisPtr.ownsLock); } } if (completeSelf) { thisPtr.Complete(false, completionException); } }
public bool RecivePacket(ref byte[] packet) { if (_comPort.IsOpen == false) { StatusString = "Error in RecivePacket: port not opened"; return false; } try { int bytesTotallyRecieved = 0; bool smthRead = false; int sleepTime = (SilentInterval / 3 == 0) ? 1 : SilentInterval / 3; int stepsCount = _comPort.ReadTimeout / sleepTime; int silenceTime = 0; for (int i = 0; i < stepsCount; i++) { int bytesRecieved = _comPort.BytesToRead; if (bytesRecieved > 0) { silenceTime = 0; smthRead = true; Array.Resize<Byte>(ref packet, bytesTotallyRecieved + bytesRecieved); _comPort.Read(packet, bytesTotallyRecieved, bytesRecieved); bytesTotallyRecieved += bytesRecieved; continue; } else { silenceTime += sleepTime; if (smthRead && silenceTime > SilentInterval) { break; } } Thread.Sleep(sleepTime); } if (smthRead == false) { TimeoutException ex = new TimeoutException(); throw(ex); } StatusString = "OK"; return true; } catch (TimeoutException) { throw; } catch (Exception error) { if (LogExceptionRsp != null) LogExceptionRsp(error); return false; } }
public void StorageTransientErrorDetectionStrategyTestTimeoutException() { var exception = new TimeoutException(); bool actual = new StorageTransientErrorDetectionStrategy().IsTransient(exception); Assert.IsTrue(actual); }
internal void CreateTimeoutTimer() { if (Request.ConnectionTimeout > 0) { timer = new Timer(s => { timer.Dispose(); if (IsPending && !IsConnected) { Exception = new TimeoutException("The connection timed out."); Abort(); } }, null, Request.ConnectionTimeout * 1000, Timeout.Infinite); } }
public void CanCreateWithMessageAndExceptionTest() { var message = Guid.NewGuid().ToString(); var inner = new TimeoutException(); var target = new BuildException(message, inner); target.Message.Should().Be(message); target.InnerException.Should().Be(inner); }
private void OnConnectionModeKnownCore(ConnectionModeReader modeReader, bool isCached) { lock (this.ThisLock) { if (this.isDisposed) { return; } this.connectionReaders.Remove(modeReader); } bool flag = true; try { FramingMode connectionMode; try { connectionMode = modeReader.GetConnectionMode(); } catch (CommunicationException exception) { TraceEventType exceptionEventType = modeReader.Connection.ExceptionEventType; if (DiagnosticUtility.ShouldTrace(exceptionEventType)) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, exceptionEventType); } return; } catch (TimeoutException exception2) { if (!isCached) { exception2 = new TimeoutException(System.ServiceModel.SR.GetString("ChannelInitializationTimeout", new object[] { this.channelInitializationTimeout }), exception2); ErrorBehavior.ThrowAndCatch(exception2); } TraceEventType type = modeReader.Connection.ExceptionEventType; if (DiagnosticUtility.ShouldTrace(type)) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, type); } return; } switch (connectionMode) { case FramingMode.Singleton: this.OnSingletonConnection(modeReader.Connection, modeReader.ConnectionDequeuedCallback, modeReader.StreamPosition, modeReader.BufferOffset, modeReader.BufferSize, modeReader.GetRemainingTimeout()); break; case FramingMode.Duplex: this.OnDuplexConnection(modeReader.Connection, modeReader.ConnectionDequeuedCallback, modeReader.StreamPosition, modeReader.BufferOffset, modeReader.BufferSize, modeReader.GetRemainingTimeout()); break; default: { Exception innerException = new InvalidDataException(System.ServiceModel.SR.GetString("FramingModeNotSupported", new object[] { connectionMode })); Exception exception4 = new ProtocolException(innerException.Message, innerException); FramingEncodingString.AddFaultString(exception4, "http://schemas.microsoft.com/ws/2006/05/framing/faults/UnsupportedMode"); ErrorBehavior.ThrowAndCatch(exception4); return; } } flag = false; } catch (Exception exception5) { if (Fx.IsFatal(exception5)) { throw; } if (!System.ServiceModel.Dispatcher.ExceptionHandler.HandleTransportExceptionHelper(exception5)) { throw; } } finally { if (flag) { modeReader.Dispose(); } } }
public override void DoAction(Action action) { //LogFactory.LogInstance.WriteLog(LogInterface.LogLevel.DEBUG, GetMessage("Enter timeout operator.")); AutoResetEvent ev = null; Exception exception = null; try { ev = new AutoResetEvent(false); ThreadPool.QueueUserWorkItem((args) => { try { base.DoAction(action); } catch (Exception ex) { exception = ex; } if (ev != null) ev.Set(); }, null); if (!ev.WaitOne(TimeOut)) { exception = new TimeoutException(); LogFactory.LogInstance.WriteException(LogInterface.LogLevel.ERR, GetMessage("time out"), exception, "time out"); } } finally { //LogFactory.LogInstance.WriteLog(LogInterface.LogLevel.DEBUG, GetMessage("Exit timeout operator.")); if (ev != null) { ev.Dispose(); ev = null; } } if (exception != null) { LogFactory.LogInstance.WriteException(LogInterface.LogLevel.ERR, GetMessage("throw exception in timeout operator"), exception, exception.Message); throw exception; } }
/// <summary> /// Выполняет одноразовую операцию получения и отправки пакетов. /// </summary> public override void Process() { // Flush send buffer OSCARQueueEntity toSend; while (!m_sendBuffer.IsEmpty) if (m_sendBuffer.TryDequeue(out toSend)) sendPacket(toSend.Host, ref toSend.FLAP, toSend.Data); else break; // Receive packets byte[] data; EndPoint from; while (this.readPacket(ref m_svcFlap, out data, out from)) HandlePacket(ref m_svcFlap, data, (IPEndPoint)from); // Check connect attempt if (m_connReq != null) // IsConnecting { // Did connection attempt failed (No response?) if ((Environment.TickCount - m_connReq.LastSent) >= ConnReq.Timeout) { // Did we reached fail limit? if (m_connReq.AttemptsTaken >= ConnReq.AttemptsLimit) { var host = m_connReq.Host; var error = new TimeoutException("OSCARUdp connection attempt timed out, response was not received."); m_connReq = null; m_events.ConnectFailed(this, new HostErrorEventArgs(host, error)); } else { // Re-send m_connReq.Send(this, ref m_svcFlap); } } } }
internal void HandleTimeout(TimeoutException tex) { bool isFatal = false; if (abortOnTimeout) { // Special connection started to cancel a query. // Timeout handler is disabled to prevent recursive connection // spawning when original query and KILL time out. Abort(); throw new MySqlException(Resources.Timeout, true , tex); } try { // Do a fast cancel.The reason behind small values for connection // and command timeout is that we do not want user to wait longer // after command has already expired. // Microsoft's SqlClient seems to be using 5 seconds timeouts // here as well. // Read the error packet with "interrupted" message. CancelQuery(5); driver.ResetTimeout(5000); if (Reader != null) { Reader.Close(); Reader = null; } } catch (Exception ex) { MySqlTrace.LogWarning(ServerThread, "Could not kill query in timeout handler, " + " aborting connection. Exception was " + ex.Message); Abort(); isFatal = true; } throw new MySqlException(Resources.Timeout, isFatal, tex); }
protected override TimeoutException CreateNewConnectionTimeoutException(TimeSpan timeout, TimeoutException innerException) { return new TimeoutException(System.ServiceModel.SR.GetString("RequestTimedOutEstablishingTransportSession", new object[] { timeout, this.channel.Via.AbsoluteUri }), innerException); }
/// <summary> /// Handles Timeout exception during publishing /// </summary> /// <param name="TimeoutException"></param> private void FinishWithTimeoutException(TimeoutException te) { boolError = true; string statusMessage = "A Timeout error occurred while trying to publish the survey."; AddStatusMessage(statusMessage); txtStatusSummary.Text = statusMessage; txtStatus.AppendText(te.ToString()); btnShowLog.Enabled = true; btnDetails.Visible = true; this.progressBar.Visible = false; this.Cursor = Cursors.Default; panel2.Visible = false; lblSuccessNotice.Text = "A Timeout error occurred while trying to publish the survey."; lblSuccessNotice.BackColor = Color.FromArgb(243, 217, 217); panel3.Visible = true; lblSuccessNotice2.Visible = false; btnPublishForm.Enabled = false; }
internal static StorageException GenerateTimeoutException(RequestResult res, Exception inner) { if (res != null) { res.HttpStatusCode = 408; // RequestTimeout } TimeoutException timeoutEx = new TimeoutException(SR.TimeoutExceptionMessage, inner); return new StorageException(res, timeoutEx.Message, timeoutEx) { IsRetryable = false }; }
protected abstract TimeoutException CreateNewConnectionTimeoutException(TimeSpan timeout, TimeoutException innerException);
internal static Exception Timeout(bool includeDetail, string errorMessage, Message message, ServerEndPoint server) { var ex = new TimeoutException(errorMessage); if (includeDetail) AddDetail(ex, message, server, null); return ex; }
private static void OnHostTransaction(object state, TimeoutException timeoutException) { InstanceHandle.AcquireContextAsyncResult result = (InstanceHandle.AcquireContextAsyncResult) state; Exception exception = timeoutException; bool flag = exception != null; if (!flag) { try { if (result.DoAfterTransaction()) { flag = true; } } catch (Exception exception2) { if (Fx.IsFatal(exception2)) { throw; } exception = exception2; flag = true; } } if (flag) { if (exception != null) { result.handle.FinishOperation(); } result.Complete(false, exception); } }
static void HandleEndWait(object state, TimeoutException e) { PendingOperationAsyncResult thisPtr = (PendingOperationAsyncResult)state; thisPtr.Complete(false, e); }
private static void OnEnteredAsync(object state, TimeoutException exception) { EnterAsyncData data = (EnterAsyncData) state; ThreadNeutralSemaphore semaphore = data.Semaphore; Exception asyncException = exception; if ((exception != null) && !semaphore.RemoveWaiter(data.Waiter)) { asyncException = null; } if (semaphore.aborted) { asyncException = semaphore.CreateObjectAbortedException(); } data.Callback(data.State, asyncException); }
static void OnSignaled(object state, TimeoutException exception) { ResumeProtocolBookmarkAsyncResult thisPtr = (ResumeProtocolBookmarkAsyncResult)state; if (exception != null) { thisPtr.Complete(false, exception); return; } bool completeSelf = false; Exception completionException = null; try { completeSelf = thisPtr.DoResumeBookmark(); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } completionException = e; } finally { if (completionException != null) { thisPtr.Complete(false, completionException); } } if (completeSelf) { thisPtr.Complete(false); } }