示例#1
0
        private async Task HandleConnection()
        {
            // Todo: Add connection limit here

            _trace.ConnectionStart(ConnectionFeature.ConnectionId);

            try
            {
                var context = new HttpConnectionContext
                {
                    ServiceContext = ServiceContext,
                    ReceivePipe    = ReceivePipe,
                    SendPipe       = SendPipe
                };
                context.Features.Connection = ConnectionFeature;

                _httpConnection = new HttpConnection(context);
                Task adapterTask = Task.FromResult(false);

                if (ServiceContext.ServerOptions.SslEnabled && ServiceContext.ServerOptions.IsHttps)
                {
                    // Wrap SSL and open new pipes
                    _sslAdapter = new SslAdapter(context);
                    await _sslAdapter.PrepareSsl(_httpConnection);

                    adapterTask = _sslAdapter.ReceiveNSend();
                }

                _initializing = false;
                var processTask = _httpConnection.Execute();

                CreateAssociatedClosing();

                await processTask;
                await adapterTask;
                await _socketClosedTcs.Task;
            }
            catch (Exception ex)
            {
                _trace.LogError($"{nameof(SocketConnection)}.{nameof(HandleConnection)}() {ConnectionFeature.ConnectionId}", ex);
            }
            finally
            {
                if (_sslAdapter != null)
                {
                    _sslAdapter.Dispose();
                }

                _trace.ConnectionStop(ConnectionFeature.ConnectionId);
            }
        }
        /// <summary>
        /// Configures and executes REST call: Supports JSON
        /// </summary>
        /// <typeparam name="T">Generic Type parameter for response object</typeparam>
        /// <param name="requestType"></param>
        /// <param name="httpMethod">HttpMethod type</param>
        /// <param name="resource">URI path of the resource</param>
        /// <param name="payload">JSON request payload</param>
        /// <param name="queryParameters"></param>
        /// <returns>Response object or null otherwise for void API calls</returns>
        /// <exception cref="HttpException">Thrown if there was an error sending the request.</exception>
        protected static ApiResponse <T> ConfigureAndExecute <T>(RequestType requestType, HttpMethod httpMethod,
                                                                 string resource = "",
                                                                 QueryParameters queryParameters = null, string payload = "")
        {
            try
            {
                // Create the URI where the HTTP request will be sent.
                Uri uniformResourceIdentifier;
                var endPoint = GetEndpoint(requestType, resource, queryParameters);
                var baseUri  = new Uri(endPoint);
                if (resource != null)
                {
                    var resourceUri = baseUri;
                    if (!Uri.TryCreate(resourceUri, resource, out uniformResourceIdentifier))
                    {
                        throw new LoginRadiusException("Cannot create URL; baseURI=" + baseUri + ", resourcePath=" +
                                                       resource);
                    }
                    uniformResourceIdentifier = resourceUri;
                }
                else
                {
                    uniformResourceIdentifier = baseUri;
                }

                var config = GetConfiguration();

                // Create the HttpRequest object that will be used to send the HTTP request.
                var connMngr    = ConnectionManager.Instance;
                var httpRequest = ConnectionManager.GetConnection(config, uniformResourceIdentifier.ToString());
                httpRequest.Method = httpMethod.ToString();

                httpRequest.ContentType = BaseConstants.ContentTypeHeaderJson;

                // Execute call
                var connectionHttp = new HttpConnection(config);

                // Setup the last request & response details.
                LastRequestDetails.Value  = connectionHttp.RequestDetails;
                LastResponseDetails.Value = connectionHttp.ResponseDetails;

                payload = payload == null ? "" : payload;

                var response = connectionHttp.Execute(payload, httpRequest, payload.Length);

                if (typeof(T).Name.Equals("Object"))
                {
                    return(default(ApiResponse <T>));
                }
                if (typeof(T).Name.Equals("String"))
                {
                    return((ApiResponse <T>)Convert.ChangeType(response, typeof(T)));
                }

                return(new ApiResponse <T> {
                    Response = JsonFormatter.ConvertFromJson <T>(response)
                });
            }
            catch (ConnectionException ex)
            {
                try
                {
                    return(new ApiResponse <T>
                    {
                        _ApiExceptionResponse =
                            JsonConvert.DeserializeObject <ApiExceptionResponse>(((ConnectionException)ex).Response)
                    });
                }
                catch
                {
                    throw ex;
                }
            }
            catch (LoginRadiusException e)
            {
                // If get a LoginRadius, just rethrow to preserve the stack trace.
                return(new ApiResponse <T> {
                    _ApiExceptionResponse = e.ErrorResponse
                });
            }
            catch (System.Exception ex)
            {
                throw new LoginRadiusException(ex.Message, ex);
            }
        }
        /// <summary>
        /// Configures and executes REST call: Supports JSON
        /// </summary>
        /// <typeparam name="T">Generic Type parameter for response object</typeparam>
        /// <param name="requestType"></param>
        /// <param name="httpMethod">HttpMethod type</param>
        /// <param name="resource">URI path of the resource</param>
        /// <param name="payload">JSON request payload</param>
        /// <param name="queryParameters"></param>
        /// <param name="headers"></param>
        /// <returns>Response object or null otherwise for void API calls</returns>
        /// <exception cref="HttpException">Thrown if there was an error sending the request.</exception>
        protected static ApiResponse <T> ConfigureAndExecute <T>(HttpMethod httpMethod, string resource = "",
                                                                 QueryParameters queryParameters        = null, string payload = "", Dictionary <string, string> headers = null)
        {
            try
            {
                // Create the URI where the HTTP request will be sent.
                Uri uniformResourceIdentifier;
                var apiPath  = resource;
                var endPoint = GetEndpoint(apiPath, out Dictionary <string, string> authHeaders, queryParameters);
                if (ConfigDictionary[LRConfigConstants.ApiRequestSigning] != null && ConfigDictionary[LRConfigConstants.ApiRequestSigning] == "true" && authHeaders.Count > 0)
                {
                    var time = DateTime.UtcNow.AddMinutes(15).ToString("yyyy-M-d h:m:s tt");
                    var hash = CreateHash(ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret], endPoint, httpMethod.ToString(), time, payload);
                    authHeaders.Remove("apiSecret");
                    if (headers == null)
                    {
                        headers = new Dictionary <string, string>();
                    }

                    headers.Add("digest", "SHA-256=" + hash);
                    headers.Add("X-Request-Expires", time);
                }
                var baseUri = new Uri(endPoint);
                if (apiPath != null)
                {
                    var resourceUri = baseUri;
                    if (!Uri.TryCreate(resourceUri, apiPath, out uniformResourceIdentifier))
                    {
                        throw new LoginRadiusException("Cannot create URL; baseURI=" + baseUri + ", resourcePath=" +
                                                       apiPath);
                    }
                    uniformResourceIdentifier = resourceUri;
                }
                else
                {
                    uniformResourceIdentifier = baseUri;
                }

                var connMngr    = ConnectionManager.Instance;
                var httpRequest = connMngr.GetConnection(ConfigDictionary, uniformResourceIdentifier.ToString(), headers, authHeaders);
                httpRequest.Method = httpMethod.ToString();

                httpRequest.ContentType = BaseConstants.ContentTypeHeaderJson;

                // Execute call
                var connectionHttp = new HttpConnection(ConfigDictionary);

                // Setup the last request & response details.
                LastRequestDetails.Value  = connectionHttp.RequestDetails;
                LastResponseDetails.Value = connectionHttp.ResponseDetails;

                payload = payload ?? "";

                var response = connectionHttp.Execute(payload, httpRequest, payload.Length);
                if (response.Contains("errorCode"))
                {
                    var exception = new ApiResponse <T>
                    {
                        RestException = JsonConvert.DeserializeObject <ApiExceptionResponse>(response)
                    };
                    return(exception);
                }
                if (typeof(T).Name.Equals("Object"))
                {
                    return(default(ApiResponse <T>));
                }
                if (typeof(T).Name.Equals("String"))
                {
                    return((ApiResponse <T>)Convert.ChangeType(response, typeof(T)));
                }


                return(new ApiResponse <T> {
                    Response = JsonFormatter.ConvertFromJson <T>(response)
                });
            }
            catch (ConnectionException ex)
            {
                try
                {
                    if (ex.Response == string.Empty)
                    {
                        throw;
                    }
                    var exception = new ApiResponse <T>
                    {
                        RestException = JsonConvert.DeserializeObject <ApiExceptionResponse>(ex.Response)
                    };
                    return(exception);
                }
                catch
                {
                    throw ex;
                }
            }
            catch (LoginRadiusException e)
            {
                // If get a LoginRadius, just rethrow to preserve the stack trace.
                return(new ApiResponse <T> {
                    RestException = e.ErrorResponse
                });
            }
            catch (System.Exception ex)
            {
                throw new LoginRadiusException(ex.Message, ex);
            }
        }