private void buttonStart_Click(object sender, System.EventArgs e) { try { if (this.GenuineTcpChannel == null) { Hashtable properties = new Hashtable(); properties["port"] = this.numericUpDownPort.Value.ToString(); properties["port"] = this.numericUpDownPort.Value.ToString(); this.GenuineTcpChannel = new GenuineTcpChannel(properties, null, null); ChannelServices.RegisterChannel(this.GenuineTcpChannel); } else { this.GenuineTcpChannel["port"] = this.numericUpDownPort.Value.ToString(); this.GenuineTcpChannel.StartListening(null); } this.UpdateLog("Server has been successfully started."); this.buttonStartEnabled = false; } catch (Exception ex) { if (ex is OperationException) { OperationException operationException = (OperationException)ex; MessageBox.Show(this, operationException.OperationErrorMessage.UserFriendlyMessage, operationException.OperationErrorMessage.ErrorIdentifier, MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show(this, ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
// Write request callback from libuv thread void INativeUnsafe.FinishWrite(int bytesWritten, OperationException error) { var ch = (NativeChannel)this.channel; bool resetWritePending = ch.TryResetState(StateFlags.WriteScheduled); Debug.Assert(resetWritePending); try { ChannelOutboundBuffer input = this.OutboundBuffer; if (error != null) { input.FailFlushed(error, true); CloseSafe(ch, this.CloseAsync(new ChannelException("Failed to write", error), false)); } else { if (bytesWritten > 0) { input.RemoveBytes(bytesWritten); } } } catch (Exception ex) { CloseSafe(ch, this.CloseAsync(new ClosedChannelException("Failed to write", ex), false)); } this.Flush0(); }
private void OnFSEventCallback(string fileName, int events, int status) { #if DEBUG if (Log.TraceEnabled) { Log.Trace("{} {} callback", HandleType, InternalHandle); } #endif try { OperationException error = null; if ((uint)status > SharedConstants.TooBigOrNegative) { error = NativeMethods.CreateError((uv_err_code)status); } var fileSystemEvent = new FileSystemEvent(fileName, (FSEventType)events, error); _eventCallback?.Invoke(this, fileSystemEvent); } catch (Exception exception) { Log.Handle_callback_error(HandleType, InternalHandle, exception); throw; } }
/// <summary> /// Sends the content to the specified remote host and returns a response sent by the remote /// host in reply. /// </summary> /// <param name="destination">The remote host.</param> /// <param name="serviceName">The name of the service.</param> /// <param name="content">The content.</param> /// <returns>The response.</returns> public Stream SendSync(HostInformation destination, string serviceName, Stream content) { // create the message Message message = new Message(this.ITransportContext, destination, 0, new TransportHeaders(), content); message.IsSynchronous = true; message.GenuineMessageType = GenuineMessageType.ExternalStreamConsumer; message.DestinationMarshalByRef = serviceName; // register the response catcher SyncResponseProcessorWithEvent syncResponseProcessorWithEvent = new SyncResponseProcessorWithEvent(message); this.ITransportContext.IIncomingStreamHandler.RegisterResponseProcessor(message.MessageId, syncResponseProcessorWithEvent); // and send the message this.ITransportContext.ConnectionManager.Send(message); int timeSpanInMilliseconds = GenuineUtility.GetMillisecondsLeft(message.FinishTime); if (timeSpanInMilliseconds <= 0) { throw GenuineExceptions.Get_Send_ServerDidNotReply(); } if (!syncResponseProcessorWithEvent.IsReceivedEvent.WaitOne(timeSpanInMilliseconds, false)) { throw GenuineExceptions.Get_Send_ServerDidNotReply(); } if (syncResponseProcessorWithEvent.DispatchedException != null) { throw OperationException.WrapException(syncResponseProcessorWithEvent.DispatchedException); } return(syncResponseProcessorWithEvent.Response.Stream); }
void OnFSPollCallback(int status, ref uv_stat_t prev, ref uv_stat_t curr) { Log.TraceFormat("{0} {1} callback", this.HandleType, this.InternalHandle); try { FileStatus previous = null; FileStatus current = null; OperationException error = null; if (status < 0) { error = NativeMethods.CreateError((uv_err_code)status); } else { previous = (FileStatus)prev; current = (FileStatus)curr; } this.pollCallback?.Invoke(this, new FSPollStatus(previous, current, error)); } catch (Exception exception) { Log.Error($"{this.HandleType} {this.InternalHandle} callback error.", exception); throw; } }
private void OnFSPollCallback(int status, ref uv_stat_t prev, ref uv_stat_t curr) { #if DEBUG if (Log.TraceEnabled) { Log.Trace("{} {} callback", HandleType, InternalHandle); } #endif try { FileStatus previous = null; FileStatus current = null; OperationException error = null; if ((uint)status > SharedConstants.TooBigOrNegative) // < 0 { error = NativeMethods.CreateError((uv_err_code)status); } else { previous = (FileStatus)prev; current = (FileStatus)curr; } _pollCallback?.Invoke(this, new FSPollStatus(previous, current, error)); } catch (Exception exception) { Log.Handle_callback_error(HandleType, InternalHandle, exception); throw; } }
private async void OnSendMail() { if (!CanSendMail()) { return; } try { IsBusy = true; await SendMailAsync(); Close(); } catch (Exception ex) { Close(); var mailex = new OperationException(BugReportResources.UnableSendEmailToSupport, ex); _log.Debug(mailex); ShowError(message: null, ex: mailex, additionalParams: null, attachments: null, isBtnSandMailEnable: false); } finally { IsBtnSandMailEnable = false; IsBusy = false; } }
void OnPollCallback(int status, int events) { if (Log.IsTraceEnabled) { Log.TraceFormat("{0} {1} callback", this.HandleType, this.InternalHandle); } try { OperationException error = null; var mask = PollMask.None; if (status < 0) { error = NativeMethods.CreateError((uv_err_code)status); } else { mask = (PollMask)events; } this.pollCallback?.Invoke(this, new PollStatus(mask, error)); } catch (Exception exception) { Log.Error($"{this.HandleType} {this.InternalHandle} callback error.", exception); throw; } }
public static ISnmpMessage EndGetResponse(this ISnmpMessage request, IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } if (request == null) { throw new ArgumentNullException(nameof(request)); } var ar = (SnmpMessageAsyncResult)asyncResult; var s = ar.WorkSocket; var count = s.EndReceive(ar.Inner); // Passing 'count' is not necessary because ParseMessages should ignore it, but it offer extra safety (and would avoid an issue if parsing >1 response). var response = MessageFactory.ParseMessages(ar.GetBuffer(), 0, count, ar.Users)[0]; var responseCode = response.TypeCode(); if (responseCode == SnmpType.ResponsePdu || responseCode == SnmpType.ReportPdu) { var requestId = request.MessageId(); var responseId = response.MessageId(); if (responseId != requestId) { throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response sequence: expected {0}, received {1}", requestId, responseId), ar.Receiver.Address); } return(response); } throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response type: {0}", responseCode), ar.Receiver.Address); }
/// <summary> /// Renews the Security Session life time. /// The first call of this method is always reset the lifetime value to the specified value. /// </summary> /// <param name="timeSpan">A time period to renew all host-related information.</param> /// <param name="canMakeShorter">Indicates whether this call may reduce the host expiration time.</param> public void Renew(int timeSpan, bool canMakeShorter) { if (this._firstRenewing) { this._firstRenewing = false; canMakeShorter = true; } lock (this.DisposeLock) { if (this.IsDisposed) { throw OperationException.WrapException(this.DisposeReason); } lock (this._accessToLocalMembers) { int proposedTime = GenuineUtility.GetTimeout(timeSpan); if (canMakeShorter || GenuineUtility.IsTimeoutExpired(this._expireTime, proposedTime)) { this._expireTime = proposedTime; } } } }
/// <summary> /// Gets a Security Session. /// </summary> /// <param name="securitySessionName">The name of the Security Session.</param> /// <param name="keyStore">The store of all keys.</param> /// <returns>An object implementing ISecuritySession interface.</returns> public SecuritySession GetSecuritySession(string securitySessionName, IKeyStore keyStore) { lock (this.DisposeLock) { if (this.IsDisposed) { throw OperationException.WrapException(this.DisposeReason); } lock (_securitySessions) { SecuritySession iSecuritySession = _securitySessions[securitySessionName] as SecuritySession; if (iSecuritySession == null) { IKeyProvider iKeyProvider = keyStore.GetKey(securitySessionName); if (iKeyProvider == null) { throw GenuineExceptions.Get_Security_ContextNotFound(securitySessionName); } iSecuritySession = iKeyProvider.CreateSecuritySession(securitySessionName, this); _securitySessions[securitySessionName] = iSecuritySession; } return(iSecuritySession); } } }
private void OnPollCallback(int status, int events) { #if DEBUG if (Log.TraceEnabled) { Log.Trace("{} {} callback", HandleType, InternalHandle); } #endif try { OperationException error = null; var mask = PollMask.None; if ((uint)status > SharedConstants.TooBigOrNegative) // < 0 { error = NativeMethods.CreateError((uv_err_code)status); } else { mask = (PollMask)events; } _pollCallback?.Invoke(this, new PollStatus(mask, error)); } catch (Exception exception) { Log.Handle_callback_error(HandleType, InternalHandle, exception); throw; } }
// Write request callback from libuv thread void INativeUnsafe.FinishWrite(int bytesWritten, OperationException error) { var ch = _channel; bool resetWritePending = ch.TryResetState(StateFlags.WriteScheduled); Debug.Assert(resetWritePending); try { ChannelOutboundBuffer input = OutboundBuffer; if (error is object) { input.FailFlushed(error, true); _ = ch.Pipeline.FireExceptionCaught(error); Close(VoidPromise(), ThrowHelper.GetChannelException_FailedToWrite(error), WriteClosedChannelException, false); } else { if (bytesWritten > 0) { input.RemoveBytes(bytesWritten); } } } catch (Exception ex) { Close(VoidPromise(), ThrowHelper.GetClosedChannelException_FailedToWrite(ex), WriteClosedChannelException, false); } Flush0(); }
/// <summary> /// Creates shared memory object. /// </summary> public void LowLevel_CreateSharedMemory() { if (WindowsAPI.FailureReason != null) { throw OperationException.WrapException(WindowsAPI.FailureReason); } IParameterProvider parameters = this.ITransportContext.IParameterProvider; string fileMappingName = GenuineSharedMemoryChannel.ConstructSharedObjectName( this.ShareName, parameters); this._mapHandle = WindowsAPI.CreateFileMapping((IntPtr)(int)-1, WindowsAPI.AttributesWithNullDACL, WindowsAPI.PAGE_READWRITE, 0, (uint)this._shareSize, fileMappingName); if (this._mapHandle == IntPtr.Zero) { throw GenuineExceptions.Get_Windows_CanNotCreateOrOpenSharedMemory(Marshal.GetLastWin32Error()); } this._pointer = WindowsAPI.MapViewOfFile(this._mapHandle, WindowsAPI.SECTION_MAP_READ | WindowsAPI.SECTION_MAP_WRITE, 0, 0, 0); if (this._pointer == IntPtr.Zero) { int lastWinError = Marshal.GetLastWin32Error(); WindowsAPI.CloseHandle(this._mapHandle); throw GenuineExceptions.Get_Windows_SharedMemoryError(lastWinError); } }
/// <summary> /// Raise the proper DomainDataServiceException if we encounter an error during execution of the DomainService operation. /// </summary> /// <param name="validationErrors">ValidationResults from a DomainService operation execution.</param> internal static void HandleValidationErrors(IEnumerable <ValidationResult> validationErrors) { if (validationErrors != null && validationErrors.Any()) { IEnumerable <ValidationResultInfo> operationErrors = validationErrors.Select(ve => new ValidationResultInfo(ve.ErrorMessage, ve.MemberNames)); OperationException oe = new OperationException(Resource.DomainDataService_OperationError, operationErrors); throw new DomainDataServiceException(Resource.DomainDataService_General_Error, oe); } }
public void OperationException_exposes_public_string_and_inner_exception_constructor() { var inner = new Exception(); var ex = new OperationException("Foo", inner); Assert.Equal("Foo", ex.Message); Assert.Same(inner, ex.InnerException); }
private void OnWrappedCompleted(AsyncOperationHandle <TObject> x) { OperationException ex = null; if (x.Status == AsyncOperationStatus.Failed) { ex = new OperationException($"ChainOperation failed because dependent operation failed", x.OperationException); } Complete(m_WrappedOp.Result, x.Status == AsyncOperationStatus.Succeeded, ex, m_ReleaseDependenciesOnFailure); }
protected virtual bool ExceptionHandler(Exception ex, string message) { if (ex == null) { return(true); } var result = new OperationException(message, ex); return(ExceptionPolicy.Instance.HandleException(result, "PL")); }
// Read callback from libuv thread void INativeUnsafe.FinishRead(ReadOperation operation) { var ch = (NativeChannel)this.channel; IChannelConfiguration config = ch.Configuration; IChannelPipeline pipeline = ch.Pipeline; OperationException error = operation.Error; bool close = error != null || operation.EndOfStream; IRecvByteBufAllocatorHandle allocHandle = this.RecvBufAllocHandle; allocHandle.Reset(config); IByteBuffer buffer = operation.Buffer; Debug.Assert(buffer != null); allocHandle.LastBytesRead = operation.Status; if (allocHandle.LastBytesRead <= 0) { // nothing was read -> release the buffer. buffer.Release(); } else { buffer.SetWriterIndex(buffer.WriterIndex + operation.Status); allocHandle.IncMessagesRead(1); ch.ReadPending = false; pipeline.FireChannelRead(buffer); } allocHandle.ReadComplete(); pipeline.FireChannelReadComplete(); if (close) { if (error != null) { pipeline.FireExceptionCaught(new ChannelException(error)); } this.CloseSafe(); } else { // If read is called from channel read or read complete // do not stop reading if (!ch.ReadPending && !config.AutoRead) { ch.DoStopRead(); } } }
/// <summary> /// Sends an <see cref="ISnmpMessage"/> and handles the response from agent. /// </summary> /// <param name="request">The <see cref="ISnmpMessage"/>.</param> /// <param name="connectionTimeout">The time-out value, in milliseconds for how long to wait for a connection</param> /// <param name="responseTimeout">The time-out value, in milliseconds for how long to wait for a response. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param> /// <param name="receiver">Agent.</param> /// <param name="client">The DTLS client</param> /// <param name="registry">The user registry.</param> /// <returns></returns> public static async Task <ISnmpMessage> GetSecureResponseAsync(this ISnmpMessage request, TimeSpan connectionTimeout, TimeSpan responseTimeout, IPEndPoint receiver, Client client, UserRegistry registry) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (receiver == null) { throw new ArgumentNullException(nameof(receiver)); } if (client is null) { throw new ArgumentNullException(nameof(client)); } if (registry == null) { throw new ArgumentNullException(nameof(registry)); } var requestCode = request.TypeCode(); if (requestCode == SnmpType.TrapV1Pdu || requestCode == SnmpType.TrapV2Pdu || requestCode == SnmpType.ReportPdu) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", requestCode)); } var bytes = request.ToBytes(); await client.ConnectToServerAsync(receiver, responseTimeout, connectionTimeout).ConfigureAwait(false); var reply = await client.SendAndGetResponseAsync(bytes, responseTimeout).ConfigureAwait(false); // Passing 'count' is not necessary because ParseMessages should ignore it, but it offer extra safety (and would avoid an issue if parsing >1 response). var response = MessageFactory.ParseMessages(reply, 0, reply.Length, registry)[0]; var responseCode = response.TypeCode(); if (responseCode == SnmpType.ResponsePdu || responseCode == SnmpType.ReportPdu) { var requestId = request.MessageId(); var responseId = response.MessageId(); if (responseId != requestId) { throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response sequence: expected {0}, received {1}", requestId, responseId), receiver.Address); } return(response); } throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response type: {0}", responseCode), receiver.Address); }
void OnNameInfoCallback(int status, string hostname, string service) { OperationException error = null; if (status < 0) { error = NativeMethods.CreateError((uv_err_code)status); } var nameInfo = new NameInfo(hostname, service, error); this.requestCallback?.Invoke(this, nameInfo); }
private void OnNameInfoCallback(int status, string hostname, string service) { OperationException error = null; if ((uint)status > SharedConstants.TooBigOrNegative) // < 0 { error = NativeMethods.CreateError((uv_err_code)status); } var nameInfo = new NameInfo(hostname, service, error); _requestCallback?.Invoke(this, nameInfo); }
// Connect request callback from libuv thread void INativeUnsafe.FinishConnect(ConnectRequest request) { var ch = (NativeChannel)this.channel; ch.connectCancellationTask?.Cancel(); TaskCompletionSource promise = ch.connectPromise; bool success = false; try { if (promise != null) // Not cancelled from timed out { OperationException error = request.Error; if (error != null) { if (error.ErrorCode == ErrorCode.ETIMEDOUT) { // Connection timed out should use the standard ConnectTimeoutException promise.TrySetException(new ConnectTimeoutException(error.ToString())); } else { promise.TrySetException(new ChannelException(error)); } } else { bool wasActive = ch.Active; ch.DoFinishConnect(); success = promise.TryComplete(); // Regardless if the connection attempt was cancelled, channelActive() // event should be triggered, because what happened is what happened. if (!wasActive && ch.Active) { ch.Pipeline.FireChannelActive(); } } } } finally { request.Dispose(); ch.connectPromise = null; if (!success) { this.CloseSafe(); } } }
// Connect request callback from libuv thread void INativeUnsafe.FinishConnect(ConnectRequest request) { var ch = _channel; _ = (ch._connectCancellationTask?.Cancel()); var promise = ch._connectPromise; bool success = false; try { if (promise is object) // Not cancelled from timed out { OperationException error = request.Error; if (error is object) { if (error.ErrorCode == ErrorCode.ETIMEDOUT) { // Connection timed out should use the standard ConnectTimeoutException _ = promise.TrySetException(ThrowHelper.GetConnectTimeoutException(error)); } else { _ = promise.TrySetException(ThrowHelper.GetChannelException(error)); } } else { bool wasActive = ch.Active; ch.DoFinishConnect(); success = promise.TryComplete(); // Regardless if the connection attempt was cancelled, channelActive() // event should be triggered, because what happened is what happened. if (!wasActive && ch.Active) { _ = ch.Pipeline.FireChannelActive(); } } } } finally { request.Dispose(); ch._connectPromise = null; if (!success) { CloseSafe(); } } }
void OnWriteCallback(int status) { OperationException error = null; if (status < 0) { error = NativeMethods.CreateError((uv_err_code)status); } Action <WriteBufferRequest, Exception> callback = this.completion; this.Release(); callback?.Invoke(this, error); }
/// <summary> /// Determines whether the exception is critical and the connection is subject to be destroyed. /// </summary> /// <param name="operationException">The instance of the OperationException class or a null reference.</param> /// <returns>True if the exception is critical and the connection is subject to be destroyed.</returns> internal static bool IsExceptionCritical(OperationException operationException) { if (operationException == null) { return(false); } return(operationException is GenuineExceptions.QueueIsOverloaded || operationException is GenuineExceptions.ChannelClosed || operationException is GenuineExceptions.ServerHasBeenRestarted || operationException is GenuineExceptions.ClientDidNotReconnectWithinTimeOut || operationException is GenuineExceptions.ConnectionClosed || operationException is GenuineExceptions.ChannelDesynchronization || operationException is GenuineExceptions.ConnectionShutDown || operationException is GenuineExceptions.ConnectionClosedAfterTimeout); }
protected virtual void ExceptionHandler(Exception ex, string message) { if (string.IsNullOrEmpty(message)) { throw new ArgumentNullException("message"); } if (ex == null) { return; } var result = new OperationException(message, ex); ExceptionPolicy.Instance.HandleException(result, PolicyName); }
/// <summary> /// Creates named event object. /// </summary> /// <param name="name">The name of the event object.</param> /// <param name="initialState">If this parameter is TRUE, the initial state of the event object is signaled; otherwise, it is nonsignaled.</param> /// <param name="manualReset">If this parameter is FALSE, the function creates an auto-reset event object, and system automatically resets the state to nonsignaled after a single waiting thread has been released.</param> /// <returns>Created event object.</returns> public static NamedEvent CreateNamedEvent(string name, bool initialState, bool manualReset) { if (WindowsAPI.FailureReason != null) { throw OperationException.WrapException(WindowsAPI.FailureReason); } IntPtr handler = WindowsAPI.CreateEvent(WindowsAPI.AttributesWithNullDACL, manualReset ? 1 : 0, (initialState ? 1 : 0), name); if (handler == IntPtr.Zero) { throw GenuineExceptions.Get_Windows_CanNotCreateOrOpenNamedEvent(Marshal.GetLastWin32Error()); } return(new NamedEvent(handler)); }
void OnRead(Pipe handle, int status) { if (status < 0) { handle.CloseHandle(); if (status != NativeMethods.EOF) { OperationException error = NativeMethods.CreateError((uv_err_code)status); Logger.Warn("IPC Pipe read error", error); } } else { Tcp tcp = handle.GetPendingHandle(); ((WorkerEventLoopGroup)this.Parent).Accept(tcp); } }
private static void OnWatcherCallback(IntPtr handle, int status) { if (handle == IntPtr.Zero) { return; } var request = RequestContext.GetTarget <WatcherRequest>(handle); OperationException error = null; if ((uint)status > SharedConstants.TooBigOrNegative) // < 0 { error = NativeMethods.CreateError((uv_err_code)status); } request?.OnWatcherCallback(error); }
public void Constructor_SetState() { ValidationResultInfo error = new ValidationResultInfo(); ValidationResultInfo[] errors = new[] { error }; OperationException exception; exception = new OperationException("message", error); Assert.AreEqual("message", exception.Message); Assert.AreEqual(1, exception.OperationErrors.Count()); Assert.AreSame(error, exception.OperationErrors.Single()); exception = new OperationException("message", errors); Assert.AreEqual("message", exception.Message); Assert.AreEqual(1, exception.OperationErrors.Count()); Assert.AreSame(error, exception.OperationErrors.Single()); }
/// <summary> /// Determines whether the exception is critical and the connection is subject to be destroyed. /// </summary> /// <param name="operationException">The instance of the OperationException class or a null reference.</param> /// <returns>True if the exception is critical and the connection is subject to be destroyed.</returns> internal static bool IsExceptionCritical(OperationException operationException) { if (operationException == null) return false; return operationException is GenuineExceptions.QueueIsOverloaded || operationException is GenuineExceptions.ChannelClosed || operationException is GenuineExceptions.ServerHasBeenRestarted || operationException is GenuineExceptions.ClientDidNotReconnectWithinTimeOut || operationException is GenuineExceptions.ConnectionClosed || operationException is GenuineExceptions.ChannelDesynchronization || operationException is GenuineExceptions.ConnectionShutDown || operationException is GenuineExceptions.ConnectionClosedAfterTimeout; }