コード例 #1
0
 static void SetCurrentThreadActivityId(TrackingContext trackingContext)
 {
     if (trackingContext != null)
     {
         SetCurrentThreadActivityId(trackingContext.ActivityId);
     }
 }
コード例 #2
0
        Task OnAcceptClientCommandAsync(ListenerCommand.AcceptCommand acceptCommand)
        {
            string id = acceptCommand.Id;
            var    trackingContext = TrackingContext.Create(id, this.Address);

#if DEBUG
            // TestHook: In DEBUG builds if the trackingId is Guid.Empty don't accept the rendezvous
            if (trackingContext.TrackingId.StartsWith(Guid.Empty.ToString(), StringComparison.Ordinal))
            {
                return(TaskEx.CompletedTask);
            }
#endif

            RelayEventSource.Log.RelayListenerRendezvousStart(this.ToString(), trackingContext.TrackingId, acceptCommand.Address);

            DataConnection clientConnection;
            lock (this.ThisLock)
            {
                if (this.closeCalled)
                {
                    RelayEventSource.Log.RelayListenerRendezvousFailed(this.ToString(), trackingContext.TrackingId, SR.ObjectClosedOrAborted);
                    return(TaskEx.CompletedTask);
                }
                else if (this.clientConnections.ContainsKey(id))
                {
                    RelayEventSource.Log.RelayListenerRendezvousFailed(this.ToString(), trackingContext.TrackingId, SR.DuplicateConnectionId);
                    return(TaskEx.CompletedTask);
                }

                clientConnection = new DataConnection(this, acceptCommand, trackingContext);
                this.clientConnections.Add(id, clientConnection);
            }

            return(clientConnection.AcceptConnectionAsync());
        }
コード例 #3
0
 public WebSocketStream(WebSocket webSocket, TrackingContext trackingContext)
 {
     this.webSocket       = webSocket;
     this.TrackingContext = trackingContext;
     this.ReadTimeout     = Timeout.Infinite;
     this.WriteTimeout    = Timeout.Infinite;
 }
コード例 #4
0
        TrackingContext GetTrackingContext()
        {
            var    queryParameters = HybridConnectionUtility.ParseQueryString(this.rendezvousAddress.Query);
            string trackingId      = queryParameters[HybridConnectionConstants.Id];

            return(TrackingContext.Create(trackingId, this.rendezvousAddress));
        }
コード例 #5
0
        /// <summary>
        /// Establishes a new send-side HybridConnection and returns the Stream.
        /// </summary>
        public async Task <HybridConnectionStream> CreateConnectionAsync(IDictionary <string, string> requestHeaders)
        {
            TrackingContext trackingContext = CreateTrackingContext(this.Address);
            string          traceSource     = nameof(HybridConnectionClient) + "(" + trackingContext + ")";
            // todo - Check if timeout helper needs to be started here.
            var timeoutHelper = TimeoutHelper.CreateOnly(this.OperationTimeout);

            RelayEventSource.Log.ObjectConnecting(traceSource, trackingContext);
            var webSocket = this.ClientWebSocketFactory.Create();

            try
            {
                DefaultWebProxy.ConfigureProxy(webSocket.Options, this.Proxy);
                webSocket.Options.KeepAliveInterval = this.KeepAliveInterval;
                webSocket.Options.SetBuffer(this.ConnectionBufferSize, this.ConnectionBufferSize);
                webSocket.Options.SetRequestHeader(HybridConnectionConstants.Headers.RelayUserAgent, HybridConnectionConstants.ClientAgent);

                if (this.TokenProvider != null)
                {
                    RelayEventSource.Log.GetTokenStart(traceSource);
                    string audience = this.Address.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped);
                    var    token    = await this.TokenProvider.GetTokenAsync(audience, TokenProvider.DefaultTokenTimeout).ConfigureAwait(false);

                    RelayEventSource.Log.GetTokenStop(traceSource, token.ExpiresAtUtc);
                    webSocket.Options.SetRequestHeader(RelayConstants.ServiceBusAuthorizationHeaderName, token.TokenString);
                }

                if (requestHeaders != null)
                {
                    foreach (KeyValuePair <string, string> header in requestHeaders)
                    {
                        webSocket.Options.SetRequestHeader(header.Key, header.Value);
                    }
                }

                // Build the websocket uri, e.g. "wss://contoso.servicebus.windows.net:443/$hc/endpoint1?sb-hc-action=connect&sb-hc-id=E2E_TRACKING_ID"
                Uri webSocketUri = HybridConnectionUtility.BuildUri(
                    this.Address.Host,
                    this.Address.Port,
                    this.Address.AbsolutePath,
                    this.Address.Query,
                    HybridConnectionConstants.Actions.Connect,
                    trackingContext.TrackingId);

                using (var cancelSource = new CancellationTokenSource(timeoutHelper.RemainingTime()))
                {
                    await webSocket.ConnectAsync(webSocketUri, cancelSource.Token).ConfigureAwait(false);
                }

                RelayEventSource.Log.ObjectConnected(traceSource, trackingContext);
                return(new WebSocketStream(webSocket.WebSocket, trackingContext));
            }
            catch (Exception exception) when(!WebSocketExceptionHelper.IsRelayContract(exception))
            {
                throw RelayEventSource.Log.ThrowingException(
                          WebSocketExceptionHelper.ConvertToRelayContract(exception, trackingContext, webSocket.Response, isListener: false),
                          traceSource);
            }
        }
コード例 #6
0
        /// <summary>
        /// Establishes a new send-side HybridConnection and returns the Stream.
        /// </summary>
        public async Task <HybridConnectionStream> CreateConnectionAsync()
        {
            TrackingContext trackingContext = CreateTrackingContext(this.Address);
            string          traceSource     = nameof(HybridConnectionClient) + "(" + trackingContext.ToString() + ")";
            var             timeoutHelper   = new TimeoutHelper(this.OperationTimeout);

            RelayEventSource.Log.RelayClientConnectStart(traceSource);
            try
            {
                var webSocket = new ClientWebSocket();
                webSocket.Options.Proxy             = this.Proxy;
                webSocket.Options.KeepAliveInterval = HybridConnectionConstants.KeepAliveInterval;
                webSocket.Options.SetBuffer(this.ConnectionBufferSize, this.ConnectionBufferSize);

                if (this.TokenProvider != null)
                {
                    RelayEventSource.Log.GetTokenStart(traceSource);
                    string audience = this.Address.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped);
                    var    token    = await this.TokenProvider.GetTokenAsync(audience, TokenProvider.DefaultTokenTimeout).ConfigureAwait(false);

                    RelayEventSource.Log.GetTokenStop(token.ExpiresAtUtc);
                    webSocket.Options.SetRequestHeader(RelayConstants.ServiceBusAuthorizationHeaderName, token.TokenString);
                }

                // Build the websocket uri, e.g. "wss://contoso.servicebus.windows.net:443/$hc/endpoint1?sb-hc-action=connect&sb-hc-id=E2E_TRACKING_ID"
                Uri webSocketUri = HybridConnectionUtility.BuildUri(
                    this.Address.Host,
                    this.Address.Port,
                    this.Address.AbsolutePath,
                    this.Address.Query,
                    HybridConnectionConstants.Actions.Connect,
                    trackingContext.TrackingId);

                using (var cancelSource = new CancellationTokenSource(timeoutHelper.RemainingTime()))
                {
                    await webSocket.ConnectAsync(webSocketUri, cancelSource.Token).ConfigureAwait(false);
                }

#if NET45 // TODO: Flow Response Headers in NETSTANDARD ClientWebSocket
                var trackingId = webSocket.ResponseHeaders[TrackingContext.TrackingIdName];
                if (!string.IsNullOrEmpty(trackingId))
                {
                    // Update to the flown trackingId (which has _GX suffix)
                    trackingContext = TrackingContext.Create(trackingId, trackingContext.SubsystemId);
                    traceSource     = nameof(HybridConnectionClient) + "(" + trackingContext.ToString() + ")";
                }
#endif

                return(new WebSocketStream(webSocket, trackingContext));
            }
            catch (WebSocketException wsException)
            {
                throw RelayEventSource.Log.ThrowingException(WebSocketExceptionHelper.ConvertToRelayContract(wsException), traceSource);
            }
            finally
            {
                RelayEventSource.Log.RelayClientConnectStop();
            }
        }
コード例 #7
0
 public void RelayListenerRendezvousRejected(TrackingContext trackingContext, HttpStatusCode statusCode, string statusDescription)
 {
     if (this.IsEnabled())
     {
         SetCurrentThreadActivityId(trackingContext);
         this.RelayListenerRendezvousRejected(trackingContext.ToString(), (int)statusCode, statusDescription);
     }
 }
コード例 #8
0
 public void HybridHttpCreatingRendezvousConnection(TrackingContext trackingContext)
 {
     if (this.IsEnabled(EventLevel.Informational, EventKeywords.None))
     {
         SetCurrentThreadActivityId(trackingContext);
         this.HybridHttpCreatingRendezvousConnection();
     }
 }
コード例 #9
0
 public void HybridHttpConnectionSendResponse(TrackingContext trackingContext, string connection, int status)
 {
     if (this.IsEnabled(EventLevel.Informational, EventKeywords.None))
     {
         SetCurrentThreadActivityId(trackingContext);
         this.HybridHttpConnectionSendResponse(connection, status);
     }
 }
コード例 #10
0
 public void Info(string source, TrackingContext trackingContext, string message)
 {
     if (this.IsEnabled())
     {
         SetCurrentThreadActivityId(trackingContext);
         this.Info(source, message);
     }
 }
コード例 #11
0
 public void HybridHttpConnectionSendBytes(TrackingContext trackingContext, int count)
 {
     if (this.IsEnabled(EventLevel.Verbose, EventKeywords.None))
     {
         SetCurrentThreadActivityId(trackingContext);
         this.HybridHttpConnectionSendBytes(count);
     }
 }
コード例 #12
0
 public void HybridHttpResponseStreamWrite(TrackingContext trackingContext, int count)
 {
     if (this.IsEnabled(EventLevel.Verbose, EventKeywords.None))
     {
         SetCurrentThreadActivityId(trackingContext);
         this.HybridHttpResponseStreamWrite(count);
     }
 }
コード例 #13
0
 public void ObjectConnected(string source, TrackingContext trackingContext)
 {
     if (this.IsEnabled(EventLevel.Informational, EventKeywords.None))
     {
         SetCurrentThreadActivityId(trackingContext);
         this.ObjectConnected(source);
     }
 }
コード例 #14
0
 public void HybridHttpRequestReceived(TrackingContext trackingContext, string method)
 {
     if (this.IsEnabled(EventLevel.Informational, EventKeywords.None))
     {
         SetCurrentThreadActivityId(trackingContext);
         this.HybridHttpRequestReceived(method, trackingContext?.Address ?? string.Empty);
     }
 }
コード例 #15
0
 public void HybridHttpRequestStarting(TrackingContext trackingContext)
 {
     if (this.IsEnabled(EventLevel.Informational, EventKeywords.None))
     {
         SetCurrentThreadActivityId(trackingContext);
         this.HybridHttpRequestStarting(trackingContext?.ToString() ?? string.Empty);
     }
 }
コード例 #16
0
 public void HybridHttpResponseStreamFlush(TrackingContext trackingContext, string reason)
 {
     if (this.IsEnabled(EventLevel.Verbose, EventKeywords.None))
     {
         SetCurrentThreadActivityId(trackingContext);
         this.HybridHttpResponseStreamFlush(reason);
     }
 }
コード例 #17
0
        internal RelayedHttpListenerContext(HybridConnectionListener listener, Uri requestUri, string trackingId, string method, IDictionary <string, string> requestHeaders)
        {
            this.Listener        = listener;
            this.TrackingContext = TrackingContext.Create(trackingId, requestUri);
            this.Request         = new RelayedHttpListenerRequest(requestUri, method, requestHeaders);
            this.Response        = new RelayedHttpListenerResponse(this);

            this.FlowSubProtocol();
        }
コード例 #18
0
            async Task <WebSocket> ConnectAsync(CancellationToken cancellationToken)
            {
                Fx.Assert(!this.closeCalled, "Shouldn't call ConnectWebSocketAsync if CloseAsync was called.");
                try
                {
                    var connectDelay = ConnectDelayIntervals[this.connectDelayIndex];
                    if (connectDelay != TimeSpan.Zero)
                    {
                        await Task.Delay(connectDelay, cancellationToken).ConfigureAwait(false);
                    }

                    RelayEventSource.Log.RelayClientConnectStart(this.listener);
                    var webSocket = new ClientWebSocket();
                    webSocket.Options.SetBuffer(this.bufferSize, this.bufferSize);
                    webSocket.Options.Proxy             = this.listener.Proxy;
                    webSocket.Options.KeepAliveInterval = HybridConnectionConstants.KeepAliveInterval;
                    webSocket.Options.SetRequestHeader("User-Agent", "ServiceBus/" + ClientAgentFileVersion);

                    var token = await this.tokenRenewer.GetTokenAsync().ConfigureAwait(false);

                    webSocket.Options.SetRequestHeader(RelayConstants.ServiceBusAuthorizationHeaderName, token.TokenString);

                    // When we reconnect we need to remove the "_GXX" suffix otherwise trackingId gets longer after each reconnect
                    string trackingId = TrackingContext.RemoveSuffix(this.listener.TrackingContext.TrackingId);

                    // Build the websocket uri, e.g. "wss://contoso.servicebus.windows.net:443/$hc/endpoint1?sb-hc-action=listen&sb-hc-id=E2E_TRACKING_ID"
                    var webSocketUri = HybridConnectionUtility.BuildUri(
                        this.address.Host,
                        this.address.Port,
                        this.address.AbsolutePath,
                        this.address.Query,
                        HybridConnectionConstants.Actions.Listen,
                        trackingId);

                    await webSocket.ConnectAsync(webSocketUri, cancellationToken).ConfigureAwait(false);

#if NET45 // TODO: Flow Response Headers in NETSTANDARD ClientWebSocket
                    trackingId = webSocket.ResponseHeaders[TrackingContext.TrackingIdName];
                    if (!string.IsNullOrEmpty(trackingId))
                    {
                        // Update to the flown trackingId (which has _GX suffix)
                        this.listener.TrackingContext = TrackingContext.Create(trackingId, this.listener.TrackingContext.SubsystemId);
                    }
#endif

                    this.OnOnline();
                    return(webSocket);
                }
                catch (WebSocketException wsException)
                {
                    throw RelayEventSource.Log.ThrowingException(WebSocketExceptionHelper.ConvertToRelayContract(wsException), this.listener);
                }
                finally
                {
                    RelayEventSource.Log.RelayClientConnectStop();
                }
            }
コード例 #19
0
        static string ExceptionToString(Exception exception, TrackingContext trackingContext = null)
        {
            string exceptionString = exception?.ToString() ?? string.Empty;

            if (trackingContext != null)
            {
                exceptionString = $"{trackingContext}: {exceptionString}";
            }

            return(exceptionString);
        }
コード例 #20
0
        internal RelayedHttpListenerContext(HybridConnectionListener listener, ListenerCommand.AcceptCommand acceptCommand)
        {
            this.Listener             = listener;
            this.wssRendezvousAddress = new Uri(acceptCommand.Address);
            Uri requestUri = this.GenerateRequestUri();

            this.TrackingContext = TrackingContext.Create(acceptCommand.Id, requestUri);
            this.Request         = new RelayedHttpListenerRequest(requestUri, acceptCommand);
            this.Response        = new RelayedHttpListenerResponse(this);

            this.FlowSubProtocol();
        }
コード例 #21
0
        // This private .ctor handles both of the public overloads which take connectionString
        HybridConnectionListener(string connectionString, string path, bool pathFromConnectionString)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw RelayEventSource.Log.ArgumentNull(nameof(connectionString), this);
            }

            var builder = new RelayConnectionStringBuilder(connectionString);

            builder.Validate();

            if (pathFromConnectionString)
            {
                if (string.IsNullOrWhiteSpace(builder.EntityPath))
                {
                    // connectionString did not have required EntityPath
                    throw RelayEventSource.Log.Argument(nameof(connectionString), SR.GetString(SR.ConnectionStringMustIncludeEntityPath, nameof(HybridConnectionClient)), this);
                }
            }
            else
            {
                if (string.IsNullOrWhiteSpace(path))
                {
                    // path parameter is required
                    throw RelayEventSource.Log.ArgumentNull(nameof(path), this);
                }
                else if (!string.IsNullOrWhiteSpace(builder.EntityPath))
                {
                    // EntityPath must not appear in connectionString
                    throw RelayEventSource.Log.Argument(nameof(connectionString), SR.GetString(SR.ConnectionStringMustNotIncludeEntityPath, nameof(HybridConnectionListener)), this);
                }

                builder.EntityPath = path;
            }

            this.Address = new Uri(builder.Endpoint, builder.EntityPath);
            this.ConnectionBufferSize = DefaultConnectionBufferSize;
            this.OperationTimeout     = builder.OperationTimeout;
            this.proxy                     = DefaultWebProxy.Instance;
            this.TrackingContext           = TrackingContext.Create(this.Address);
            this.connectionInputQueue      = new InputQueue <HybridConnectionStream>();
            this.controlConnection         = new ControlConnection(this);
            this.useBuiltInClientWebSocket = HybridConnectionConstants.DefaultUseBuiltInClientWebSocket;
            this.ClientWebSocketFactory    = Microsoft.Azure.Relay.ClientWebSocketFactory.Default;
            this.KeepAliveInterval         = HybridConnectionConstants.KeepAliveInterval;

            this.TokenProvider = builder.CreateTokenProvider();
            if (this.TokenProvider == null)
            {
                throw RelayEventSource.Log.Argument(nameof(connectionString), SR.CannotCreateTokenProviderFromConnectionString, this);
            }
        }
コード例 #22
0
        public static Exception ConvertToRelayContract(Exception exception, TrackingContext trackingContext, HttpResponseMessage httpResponseMessage = null, bool isListener = true)
        {
            string message = exception.Message;

            if (IsRelayContract(exception))
            {
                return(exception);
            }
            else if (exception is WebSocketException)
            {
                WebException    innerWebException;
                IOException     innerIOException;
                SocketException socketException;
                if ((innerWebException = exception.InnerException as WebException) != null)
                {
                    HttpWebResponse httpWebResponse;
                    if ((httpWebResponse = innerWebException.Response as HttpWebResponse) != null)
                    {
                        return(CreateExceptionForStatus(httpWebResponse.StatusCode, httpWebResponse.StatusDescription, exception, trackingContext, isListener));
                    }
                    else if (innerWebException.Status == WebExceptionStatus.NameResolutionFailure)
                    {
                        message = innerWebException.Message;
                    }
                }
                else if ((innerIOException = exception.InnerException as IOException) != null)
                {
                    message = innerIOException.Message;
                }
                else if ((socketException = exception.InnerException as SocketException) != null)
                {
                    if (socketException.SocketErrorCode == SocketError.HostNotFound)
                    {
                        message = socketException.Message;
                    }
                }
                else if (httpResponseMessage != null ||
                         (httpResponseMessage = (HttpResponseMessage)exception.Data[typeof(HttpResponseMessage).FullName]) != null)
                {
                    return(CreateExceptionForStatus(httpResponseMessage.StatusCode, httpResponseMessage.ReasonPhrase, exception, trackingContext, isListener));
                }
            }

            if (trackingContext != null)
            {
                message = trackingContext.EnsureTrackableMessage(message);
            }

            return(new RelayException(message, exception));
        }
コード例 #23
0
            async Task <WebSocket> ConnectAsync(CancellationToken cancellationToken)
            {
                this.listener.ThrowIfDisposed();

                var webSocket = ClientWebSocketFactory.Create(this.listener.UseBuiltInClientWebSocket);

                try
                {
                    var connectDelay = ConnectDelayIntervals[this.connectDelayIndex];
                    if (connectDelay != TimeSpan.Zero)
                    {
                        await Task.Delay(connectDelay, cancellationToken).ConfigureAwait(false);
                    }

                    RelayEventSource.Log.ObjectConnecting(this.listener);
                    webSocket.Options.SetBuffer(this.bufferSize, this.bufferSize);
                    DefaultWebProxy.ConfigureProxy(webSocket.Options, this.listener.Proxy);

                    webSocket.Options.KeepAliveInterval = HybridConnectionConstants.KeepAliveInterval;
                    webSocket.Options.SetRequestHeader(HybridConnectionConstants.Headers.RelayUserAgent, HybridConnectionConstants.ClientAgent);

                    var token = await this.tokenRenewer.GetTokenAsync().ConfigureAwait(false);

                    webSocket.Options.SetRequestHeader(RelayConstants.ServiceBusAuthorizationHeaderName, token.TokenString);

                    // When we reconnect we need to remove the "_GXX" suffix otherwise trackingId gets longer after each reconnect
                    string trackingId = TrackingContext.RemoveSuffix(this.listener.TrackingContext.TrackingId);

                    // Build the websocket uri, e.g. "wss://contoso.servicebus.windows.net:443/$hc/endpoint1?sb-hc-action=listen&sb-hc-id=E2E_TRACKING_ID"
                    var webSocketUri = HybridConnectionUtility.BuildUri(
                        this.address.Host,
                        this.address.Port,
                        this.address.AbsolutePath,
                        this.address.Query,
                        HybridConnectionConstants.Actions.Listen,
                        trackingId);

                    await webSocket.ConnectAsync(webSocketUri, cancellationToken).ConfigureAwait(false);

                    this.OnOnline();
                    RelayEventSource.Log.ObjectConnected(this.listener);
                    return(webSocket.WebSocket);
                }
                catch (Exception exception) when(!WebSocketExceptionHelper.IsRelayContract(exception))
                {
                    throw RelayEventSource.Log.ThrowingException(
                              WebSocketExceptionHelper.ConvertToRelayContract(exception, this.listener.TrackingContext, webSocket.Response), this.listener);
                }
            }
コード例 #24
0
        // This private .ctor handles both of the public overloads which take connectionString
        HybridConnectionListener(string connectionString, string path, bool pathFromConnectionString)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw RelayEventSource.Log.ArgumentNull(nameof(connectionString), this);
            }

            var builder = new RelayConnectionStringBuilder(connectionString);

            builder.Validate();

            if (pathFromConnectionString)
            {
                if (string.IsNullOrWhiteSpace(builder.EntityPath))
                {
                    // connectionString did not have required EntityPath
                    throw RelayEventSource.Log.Argument(nameof(connectionString), SR.GetString(SR.ConnectionStringMustIncludeEntityPath, nameof(HybridConnectionClient)), this);
                }
            }
            else
            {
                if (string.IsNullOrWhiteSpace(path))
                {
                    // path parameter is required
                    throw RelayEventSource.Log.ArgumentNull(nameof(path), this);
                }
                else if (!string.IsNullOrWhiteSpace(builder.EntityPath))
                {
                    // EntityPath must not appear in connectionString
                    throw RelayEventSource.Log.Argument(nameof(connectionString), SR.GetString(SR.ConnectionStringMustNotIncludeEntityPath, nameof(HybridConnectionListener)), this);
                }

                builder.EntityPath = path;
            }

            this.Address              = new Uri(builder.Endpoint, builder.EntityPath);
            this.TokenProvider        = builder.CreateTokenProvider();
            this.ConnectionBufferSize = DefaultConnectionBufferSize;
            this.OperationTimeout     = builder.OperationTimeout;
            this.proxy           = WebRequest.DefaultWebProxy;
            this.TrackingContext = TrackingContext.Create(this.Address);

            this.clientConnections    = new Dictionary <string, DataConnection>();
            this.connectionInputQueue = new InputQueue <HybridConnectionStream>();
            this.controlConnection    = new ControlConnection(this);
        }
コード例 #25
0
        static TrackingContext CreateTrackingContext(Uri address)
        {
#if DEBUG
            // In DEBUG builds allow setting the trackingId via query string: "?id=00000000-0000-0000-0000-000000000000"
            if (!string.IsNullOrEmpty(address.Query))
            {
                string[] kvps = address.Query.TrimStart('?').Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string kvp in kvps)
                {
                    if (kvp.StartsWith("id=", StringComparison.Ordinal))
                    {
                        return(TrackingContext.Create(kvp.Substring(3), address));
                    }
                }
            }
#endif // DEBUG

            return(TrackingContext.Create(address));
        }
コード例 #26
0
        TrackingContext GetTrackingContext()
        {
            var    queryParameters = HybridConnectionUtility.ParseQueryString(this.rendezvousAddress.Query);
            string trackingId      = queryParameters[HybridConnectionConstants.Id];

            string path = this.rendezvousAddress.LocalPath;

            if (path.StartsWith(HybridConnectionConstants.HybridConnectionRequestUri, StringComparison.OrdinalIgnoreCase))
            {
                path = path.Substring(HybridConnectionConstants.HybridConnectionRequestUri.Length);
            }

            Uri logicalAddress = new UriBuilder()
            {
                Scheme = Uri.UriSchemeHttps,
                Host   = this.listener.Address.Host,
                Path   = path,
            }.Uri;

            return(TrackingContext.Create(trackingId, logicalAddress));
        }
コード例 #27
0
        /// <summary>
        /// Create a new HybridConnectionListener instance for accepting HybridConnections.
        /// </summary>
        /// <param name="address">The address on which to listen for HybridConnections.  This address should
        /// be of the format "sb://contoso.servicebus.windows.net/yourhybridconnection".</param>
        /// <param name="tokenProvider">The TokenProvider for connecting this listener to ServiceBus.</param>
        public HybridConnectionListener(Uri address, TokenProvider tokenProvider)
        {
            if (address == null || tokenProvider == null)
            {
                throw RelayEventSource.Log.ThrowingException(new ArgumentNullException(address == null ? nameof(address) : nameof(tokenProvider)), this);
            }
            else if (address.Scheme != RelayConstants.HybridConnectionScheme)
            {
                throw RelayEventSource.Log.ThrowingException(
                          new ArgumentException(SR.InvalidUriScheme.FormatInvariant(address.Scheme, RelayConstants.HybridConnectionScheme), nameof(address)), this);
            }

            this.Address              = address;
            this.TokenProvider        = tokenProvider;
            this.ConnectionBufferSize = DefaultConnectionBufferSize;
            this.OperationTimeout     = RelayConstants.DefaultOperationTimeout;
            this.proxy                = WebRequest.DefaultWebProxy;
            this.TrackingContext      = TrackingContext.Create(this.Address);
            this.connectionInputQueue = new InputQueue <HybridConnectionStream>();
            this.controlConnection    = new ControlConnection(this);
        }
コード例 #28
0
        /// <summary>
        /// Create a new HybridConnectionListener instance for accepting HybridConnections.
        /// </summary>
        /// <param name="address">The address on which to listen for HybridConnections.  This address should
        /// be of the format "sb://contoso.servicebus.windows.net/yourhybridconnection".</param>
        /// <param name="tokenProvider">The TokenProvider for connecting this listener to ServiceBus.</param>
        public HybridConnectionListener(Uri address, TokenProvider tokenProvider)
        {
            if (address == null || tokenProvider == null)
            {
                throw RelayEventSource.Log.ThrowingException(new ArgumentNullException(address == null ? nameof(address) : nameof(tokenProvider)), this);
            }
            else if (address.Scheme != RelayConstants.HybridConnectionScheme)
            {
                throw RelayEventSource.Log.ThrowingException(
                          new ArgumentException(SR.InvalidUriScheme.FormatInvariant(address.Scheme, RelayConstants.HybridConnectionScheme), nameof(address)), this);
            }

            this.Address              = address;
            this.TokenProvider        = tokenProvider;
            this.ConnectionBufferSize = DefaultConnectionBufferSize;
            this.OperationTimeout     = RelayConstants.DefaultOperationTimeout;
            this.proxy                     = DefaultWebProxy.Instance;
            this.TrackingContext           = TrackingContext.Create(this.Address);
            this.connectionInputQueue      = new InputQueue <HybridConnectionStream>();
            this.controlConnection         = new ControlConnection(this);
            this.useBuiltInClientWebSocket = HybridConnectionConstants.DefaultUseBuiltInClientWebSocket;
            this.ClientWebSocketFactory    = Microsoft.Azure.Relay.ClientWebSocketFactory.Default;
            this.KeepAliveInterval         = HybridConnectionConstants.KeepAliveInterval;
        }
コード例 #29
0
        static Exception CreateExceptionForStatus(HttpStatusCode statusCode, string statusDescription, Exception inner, TrackingContext trackingContext, bool isListener)
        {
            if (trackingContext != null)
            {
                statusDescription = trackingContext.EnsureTrackableMessage(statusDescription);
            }

            switch (statusCode)
            {
            case HttpStatusCode.Unauthorized:
                return(new AuthorizationFailedException(statusDescription, inner));

            case HttpStatusCode.NotFound:
                return(new EndpointNotFoundException(statusDescription, inner, isTransient: !isListener));

            case HttpStatusCode.GatewayTimeout:
            case HttpStatusCode.RequestTimeout:
                return(new TimeoutException(statusCode + ": " + statusDescription, inner));

            case HttpStatusCode.BadRequest:
            case HttpStatusCode.InternalServerError:
            case HttpStatusCode.NotImplemented:
            case HttpStatusCode.BadGateway:
            case HttpStatusCode.ServiceUnavailable:
            default:
                return(new RelayException(statusCode + ": " + statusDescription, inner));
            }
        }
コード例 #30
0
 public TraceDetails(string source, TrackingContext trackingContext)
 {
     this.Source          = source;
     this.TrackingContext = trackingContext;
 }