public async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options) { try { await _webSocket.ConnectAsync(uri, cancellationToken, options).ConfigureAwait(false); } catch (Exception ex) { WebErrorStatus status = RTWebSocketError.GetStatus(ex.HResult); var inner = new Exception(status.ToString(), ex); WebSocketException wex = new WebSocketException(SR.net_webstatus_ConnectFailure, inner); if (NetEventSource.IsEnabled) NetEventSource.Error(_webSocket, wex); throw wex; } }
public async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options) { try { await _webSocket.ConnectAsync(uri, cancellationToken, options).ConfigureAwait(false); } catch (Win32Exception ex) { WebSocketException wex = new WebSocketException(SR.net_webstatus_ConnectFailure, ex); if (Logging.On) { Logging.Exception(Logging.WebSockets, this, "ConnectAsync", wex); } throw wex; } }
public async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options) { try { await _webSocket.ConnectAsync(uri, cancellationToken, options).ConfigureAwait(false); } catch (Win32Exception ex) { WebSocketException wex = new WebSocketException(SR.net_webstatus_ConnectFailure, ex); if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exception(NetEventSource.ComponentType.WebSocket, this, "ConnectAsync", wex); } throw wex; } }
public async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options) { try { await _webSocket.ConnectAsync(uri, cancellationToken, options).ConfigureAwait(false); } catch (Exception ex) { WebErrorStatus status = RTWebSocketError.GetStatus(ex.HResult); var inner = new Exception(status.ToString(), ex); WebSocketException wex = new WebSocketException(SR.net_webstatus_ConnectFailure, inner); if (Logging.On) { Logging.Exception(Logging.WebSockets, this, "ConnectAsync", wex); } throw wex; } }
public async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options) { try { await _webSocket.ConnectAsync(uri, cancellationToken, options).ConfigureAwait(false); } catch (Exception ex) { // TODO #4143: ** TFS BUILD IS BROKEN ** // This doesn't compile right now due to missing types 'WebErrorStatus' and 'RTWebSocketError' // Commenting out for now to allow the build to resume. //WebErrorStatus status = RTWebSocketError.GetStatus(ex.HResult); //var inner = new Exception(status.ToString(), ex); var inner = ex; WebSocketException wex = new WebSocketException(SR.net_webstatus_ConnectFailure, inner); if (Logging.On) { Logging.Exception(Logging.WebSockets, this, "ConnectAsync", wex); } throw wex; } }
private async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken) { HttpWebResponse response = null; CancellationTokenRegistration connectCancellation = new CancellationTokenRegistration(); // Any errors from here on out are fatal and this instance will be disposed. try { HttpWebRequest request = CreateAndConfigureRequest(uri); if (Logging.On) Logging.Associate(Logging.WebSockets, this, request); connectCancellation = cancellationToken.Register(AbortRequest, request, false); response = await request.GetResponseAsync().SuppressContextFlow() as HttpWebResponse; Contract.Assert(response != null, "Not an HttpWebResponse"); if (Logging.On) Logging.Associate(Logging.WebSockets, this, response); string subprotocol = ValidateResponse(request, response); innerWebSocket = WebSocket.CreateClientWebSocket(response.GetResponseStream(), subprotocol, options.ReceiveBufferSize, options.SendBufferSize, options.KeepAliveInterval, false, options.GetOrCreateBuffer()); if (Logging.On) Logging.Associate(Logging.WebSockets, this, innerWebSocket); // Change internal state to 'connected' to enable the other methods if (Interlocked.CompareExchange(ref state, connected, connecting) != connecting) { // Aborted/Disposed during connect. throw new ObjectDisposedException(GetType().FullName); } } catch (WebException ex) { ConnectExceptionCleanup(response); WebSocketException wex = new WebSocketException(SR.GetString(SR.net_webstatus_ConnectFailure), ex); if (Logging.On) Logging.Exception(Logging.WebSockets, this, "ConnectAsync", wex); throw wex; } catch (Exception ex) { ConnectExceptionCleanup(response); if (Logging.On) Logging.Exception(Logging.WebSockets, this, "ConnectAsync", ex); throw; } finally { // We successfully connected (or failed trying), disengage from this token. // Otherwise any timeout/cancellation would apply to the full session. // In the failure case we need to release the reference to HWR. connectCancellation.Dispose(); } }
public async Task WhenBlobTransferCompleteEventIsRaisedAndAnErrorOcurredThenErrorCallbackIsCalled() { EventHandler<BlobTransferCompleteEventArgs> blobTransferCompletedHandler = null; var stubAsset = new StubIAsset { IdGet = () => "myId", NameGet = () => "test" }; var stubAssetFile = new StubIAssetFile(); var stubAccessPolicy = new StubIAccessPolicy(); var stubLocator = new StubILocator() { AccessPolicyGet = () => stubAccessPolicy }; Exception providedError = null; using (ShimsContext.Create()) { var stubAssets = new StubAssetBaseCollection { CreateAsyncStringAssetCreationOptionsCancellationToken = (name, options, cancellationToken) => Task.FromResult((IAsset)stubAsset) }; var stubAssetsFiles = new StubAssetFileBaseCollection { CreateAsyncStringCancellationToken = (path, cancellationToken) => Task.FromResult((IAssetFile)stubAssetFile) }; stubAsset.AssetFilesGet = () => stubAssetsFiles; var accessPolicies = new ShimAccessPolicyBaseCollection { CreateAsyncStringTimeSpanAccessPermissions = (name, timesSpan, accessPermissions) => Task.FromResult((IAccessPolicy)stubAccessPolicy) }; var locators = new ShimLocatorBaseCollection { CreateSasLocatorAsyncIAssetIAccessPolicy = (asset, acccessPolicy) => Task.FromResult((ILocator)stubLocator) }; ShimPath.GetFileNameString = fileName => string.Empty; ShimBlobTransferClient.Constructor = client => { }; stubAssetFile.UploadAsyncStringBlobTransferClientILocatorCancellationToken = (filePath, blobTransferClient, locator, cancellationToken) => Task.Delay(0); var context = new ShimCloudMediaContext { AssetsGet = () => stubAssets, AccessPoliciesGet = () => accessPolicies, LocatorsGet = () => locators, }; Func<CloudMediaContext> createContext = () => context; ShimBlobTransferClient.AllInstances.TransferCompletedAddEventHandlerOfBlobTransferCompleteEventArgs = (client, handler) => { blobTransferCompletedHandler = handler; }; var uploader = new AzureMediaServicesUploader("myVideo", @"C:\videos\myvideo.mp4", createContext); Action<Exception> onError = error => { providedError = error; }; uploader.On(error: onError); await uploader.Start(); } var sampleError = new WebSocketException(WebSocketError.ConnectionClosedPrematurely); var args = new BlobTransferCompleteEventArgs(sampleError, true, null, @"C:\videos\myvideo.mp4", new Uri("http://myvideo"), BlobTransferType.Upload); blobTransferCompletedHandler.Invoke(null, args); Assert.AreSame(sampleError, providedError); }
// We only want to throw an OperationCanceledException if the CancellationToken passed // down from the caller is canceled - not when Abort is called on another thread and // the linkedCancellationToken is canceled. private void ThrowIfConvertibleException(string methodName, Exception exception, CancellationToken cancellationToken, bool aborted) { Debug.Assert(exception != null, "'exception' MUST NOT be NULL."); if (NetEventSource.IsEnabled && !string.IsNullOrEmpty(methodName)) { NetEventSource.Error(this, $"methodName: {methodName}, exception: {exception}"); } OperationCanceledException operationCanceledException = exception as OperationCanceledException; if (operationCanceledException != null) { if (cancellationToken.IsCancellationRequested || !aborted) { return; } ThrowIfAborted(aborted, exception); } WebSocketException convertedException = exception as WebSocketException; if (convertedException != null) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfAborted(aborted, convertedException); return; } SocketException socketException = exception as SocketException; if (socketException != null) { convertedException = new WebSocketException(socketException.NativeErrorCode, socketException); } HttpListenerException httpListenerException = exception as HttpListenerException; if (httpListenerException != null) { convertedException = new WebSocketException(httpListenerException.ErrorCode, httpListenerException); } IOException ioException = exception as IOException; if (ioException != null) { socketException = exception.InnerException as SocketException; if (socketException != null) { convertedException = new WebSocketException(socketException.NativeErrorCode, ioException); } } if (convertedException != null) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfAborted(aborted, convertedException); throw convertedException; } AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { // Collapse possibly nested graph into a flat list. // Empty inner exception list is unlikely but possible via public api. ReadOnlyCollection<Exception> unwrappedExceptions = aggregateException.Flatten().InnerExceptions; if (unwrappedExceptions.Count == 0) { return; } foreach (Exception unwrappedException in unwrappedExceptions) { ThrowIfConvertibleException(null, unwrappedException, cancellationToken, aborted); } } }
static void TryConvertAndThrow(WebSocketException ex) { switch (ex.WebSocketErrorCode) { //case WebSocketError.Success: //case WebSocketError.InvalidMessageType: //case WebSocketError.Faulted: //case WebSocketError.NativeError: //case WebSocketError.NotAWebSocket: case WebSocketError.UnsupportedVersion: throw FxTrace.Exception.AsError(new CommunicationException(SR.Format(SR.WebSocketVersionMismatchFromServer, ""), ex)); case WebSocketError.UnsupportedProtocol: throw FxTrace.Exception.AsError(new CommunicationException(SR.Format(SR.WebSocketSubProtocolMismatchFromServer, ""), ex)); //case WebSocketError.HeaderError: //case WebSocketError.ConnectionClosedPrematurely: //case WebSocketError.InvalidState: default: throw FxTrace.Exception.AsError(new CommunicationException(ex.Message, ex)); } }
private void CancelAllOperations() { if (_operation.TcsClose != null) { var exception = new WebSocketException( WebSocketError.InvalidState, SR.Format( SR.net_WebSockets_InvalidState_ClosedOrAborted, "System.Net.WebSockets.InternalClientWebSocket", "Aborted")); _operation.TcsClose.TrySetException(exception); } if (_operation.TcsCloseOutput != null) { var exception = new WebSocketException( WebSocketError.InvalidState, SR.Format( SR.net_WebSockets_InvalidState_ClosedOrAborted, "System.Net.WebSockets.InternalClientWebSocket", "Aborted")); _operation.TcsCloseOutput.TrySetException(exception); } if (_operation.TcsReceive != null) { var exception = new WebSocketException( WebSocketError.InvalidState, SR.Format( SR.net_WebSockets_InvalidState_ClosedOrAborted, "System.Net.WebSockets.InternalClientWebSocket", "Aborted")); _operation.TcsReceive.TrySetException(exception); } if (_operation.TcsSend != null) { var exception = new OperationCanceledException(); _operation.TcsSend.TrySetException(exception); } if (_operation.TcsUpgrade != null) { var exception = new WebSocketException(SR.net_webstatus_ConnectFailure); _operation.TcsUpgrade.TrySetException(exception); } }
private void OnMessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) { // GetDataReader() throws an exception when either: // (1) The underlying TCP connection is closed prematurely (e.g., FIN/RST received without sending/receiving a WebSocket Close frame). // (2) The server sends invalid data (e.g., corrupt HTTP headers or a message exceeding the MaxMessageSize). // // In both cases, the appropriate thing to do is to close the socket, as we have reached an unexpected state in // the WebSocket protocol. try { using (DataReader reader = args.GetDataReader()) { uint dataAvailable; while ((dataAvailable = reader.UnconsumedBufferLength) > 0) { ArraySegment <byte> buffer; try { buffer = _receiveAsyncBufferTcs.Task.GetAwaiter().GetResult(); } catch (OperationCanceledException) // Caused by Abort call on WebSocket { return; } _receiveAsyncBufferTcs = new TaskCompletionSource <ArraySegment <byte> >(); WebSocketMessageType messageType; if (args.MessageType == SocketMessageType.Binary) { messageType = WebSocketMessageType.Binary; } else { messageType = WebSocketMessageType.Text; } bool endOfMessage = false; uint readCount = Math.Min(dataAvailable, (uint)buffer.Count); var dataBuffer = reader.ReadBuffer(readCount); // Safe to cast readCount to int as the maximum value that readCount can be is buffer.Count. dataBuffer.CopyTo(0, buffer.Array, buffer.Offset, (int)readCount); if (dataAvailable == readCount) { endOfMessage = !IsPartialMessageEvent(args); } WebSocketReceiveResult recvResult = new WebSocketReceiveResult((int)readCount, messageType, endOfMessage); _webSocketReceiveResultTcs.TrySetResult(recvResult); } } } catch (Exception exc) { // WinRT WebSockets always throw exceptions of type System.Exception. However, we can determine whether // or not we're dealing with a known error by using WinRT's WebSocketError.GetStatus method. WebErrorStatus status = RTWebSocketError.GetStatus(exc.HResult); WebSocketError actualError = WebSocketError.Faulted; switch (status) { case WebErrorStatus.ConnectionAborted: case WebErrorStatus.ConnectionReset: case WebErrorStatus.Disconnected: actualError = WebSocketError.ConnectionClosedPrematurely; break; } // Propagate a custom exception to any pending ReceiveAsync/CloseAsync operations and close the socket. WebSocketException customException = new WebSocketException(actualError, exc); AbortInternal(customException); } }
private static void OnWebSocketError( WinHttpWebSocketState state, Interop.WinHttp.WINHTTP_WEB_SOCKET_ASYNC_RESULT asyncResult) { Debug.Assert(state != null, "OnWebSocketError: state is null"); var innerException = WinHttpException.CreateExceptionUsingError((int)(asyncResult.AsyncResult.dwError)); if (asyncResult.AsyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED) { var exception = new WebSocketException( WebSocketError.InvalidState, SR.Format( SR.net_WebSockets_InvalidState_ClosedOrAborted, "System.Net.WebSockets.InternalClientWebSocket", "Aborted"), innerException); state.UpdateState(WebSocketState.Aborted); if (state.TcsReceive != null) { state.TcsReceive.TrySetException(exception); } if (state.TcsSend != null) { state.TcsSend.TrySetException(exception); } return; } switch (asyncResult.Operation) { case Interop.WinHttp.WINHTTP_WEB_SOCKET_OPERATION.WINHTTP_WEB_SOCKET_SEND_OPERATION: state.PendingWriteOperation = false; state.TcsSend.TrySetException(innerException); break; case Interop.WinHttp.WINHTTP_WEB_SOCKET_OPERATION.WINHTTP_WEB_SOCKET_RECEIVE_OPERATION: state.PendingReadOperation = false; state.TcsReceive.TrySetException(innerException); break; case Interop.WinHttp.WINHTTP_WEB_SOCKET_OPERATION.WINHTTP_WEB_SOCKET_CLOSE_OPERATION: state.TcsClose.TrySetException(innerException); break; case Interop.WinHttp.WINHTTP_WEB_SOCKET_OPERATION.WINHTTP_WEB_SOCKET_SHUTDOWN_OPERATION: state.TcsCloseOutput.TrySetException(innerException); break; default: Debug.Fail( "OnWebSocketError: Operation (" + asyncResult.Operation + ") is not expected.", "Error code: " + asyncResult.AsyncResult.dwError + " (" + innerException.Message + ")"); break; } }
private static void OnWebSocketSecureFailure(WinHttpWebSocketState state, uint flags) { Debug.Assert(state != null, "OnWebSocketSecureFailure: state is null"); var innerException = WinHttpException.CreateExceptionUsingError((int)Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE); var exception = new WebSocketException(WebSocketError.ConnectionClosedPrematurely, innerException); // TODO (Issue 2509): handle SSL related exceptions. state.UpdateState(WebSocketState.Aborted); // TODO (Issue 2509): Create exception from WINHTTP_CALLBACK_STATUS_SECURE_FAILURE flags. state.TcsUpgrade.TrySetException(exception); }
private static void OnRequestSecureFailure(WinHttpWebSocketState state, uint flags) { Debug.Assert(state != null, "OnRequestSecureFailure: state is null"); var innerException = WinHttpException.CreateExceptionUsingError((int)Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE); var exception = new WebSocketException( WebSocketError.Success, SR.net_webstatus_ConnectFailure, innerException); // TODO: handle SSL related exceptions. state.UpdateState(WebSocketState.Closed); // TODO: Create exception from WINHTTP_CALLBACK_STATUS_SECURE_FAILURE flags. state.TcsUpgrade.TrySetException(exception); }
private static void OnRequestError( WinHttpWebSocketState state, Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult) { Debug.Assert(state != null, "OnRequestError: state is null"); var innerException = WinHttpException.CreateExceptionUsingError((int)asyncResult.dwError); switch ((uint)asyncResult.dwResult.ToInt32()) { case Interop.WinHttp.API_SEND_REQUEST: case Interop.WinHttp.API_RECEIVE_RESPONSE: { var exception = new WebSocketException(SR.net_webstatus_ConnectFailure, innerException); state.UpdateState(WebSocketState.Closed); state.TcsUpgrade.TrySetException(exception); } break; default: { Debug.Fail( "OnRequestError: Result (" + asyncResult.dwResult + ") is not expected.", "Error code: " + asyncResult.dwError + " (" + innerException.Message + ")"); } break; } }
private Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken) { _innerWebSocket = new WinHttpWebSocket(); try { // Change internal state to 'connected' to enable the other methods if ((InternalState)Interlocked.CompareExchange(ref _state, (int)InternalState.Connected, (int)InternalState.Connecting) != InternalState.Connecting) { // Aborted/Disposed during connect. throw new ObjectDisposedException(GetType().FullName); } return _innerWebSocket.ConnectAsync(uri, cancellationToken, _options); } catch (Win32Exception ex) { WebSocketException wex = new WebSocketException(SR.net_webstatus_ConnectFailure, ex); if (Logging.On) { Logging.Exception(Logging.WebSockets, this, "ConnectAsync", wex); } throw wex; } catch (Exception ex) { if (Logging.On) { Logging.Exception(Logging.WebSockets, this, "ConnectAsync", ex); } throw; } }
private void CancelAllOperations() { if (_receiveAsyncBufferTcs != null) { // This exception will be received by OnMessageReceived and won't be exposed // to user code. var exception = new OperationCanceledException("Aborted"); _receiveAsyncBufferTcs.TrySetException(exception); } if (_webSocketReceiveResultTcs != null) { var exception = new WebSocketException( WebSocketError.InvalidState, SR.Format( SR.net_WebSockets_InvalidState_ClosedOrAborted, "System.Net.WebSockets.InternalClientWebSocket", "Aborted")); _webSocketReceiveResultTcs.TrySetException(exception); } if (_closeWebSocketReceiveResultTcs != null) { var exception = new WebSocketException( WebSocketError.InvalidState, SR.Format( SR.net_WebSockets_InvalidState_ClosedOrAborted, "System.Net.WebSockets.InternalClientWebSocket", "Aborted")); _closeWebSocketReceiveResultTcs.TrySetException(exception); } }
public async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options) { try { await _webSocket.ConnectAsync(uri, cancellationToken, options).ConfigureAwait(false); } catch (Win32Exception ex) { var wex = new WebSocketException(SR.net_webstatus_ConnectFailure, ex); if (NetEventSource.IsEnabled) NetEventSource.Error(_webSocket, wex); throw wex; } }