Example #1
0
        /// <summary>
        /// Gets a collection of headers to be used in an HTTP request.
        /// </summary>
        /// <param name="apiContext">APIContext object containing information needed to construct the headers map.</param>
        /// <returns>A collection of headers.</returns>
        public static Dictionary <string, string> GetHeaderMap(APIContext apiContext)
        {
            var headers = new Dictionary <string, string>();
            var config  = apiContext.GetConfigWithDefaults();
            var apiKey  = config.ContainsKey(BaseConstants.ApiKey) ? config[BaseConstants.ApiKey] : null;

            headers[BaseConstants.AuthorizationHeader] = "Basic " + apiKey;

            // Add any custom headers
            if (apiContext.HTTPHeaders != null && apiContext.HTTPHeaders.Count > 0)
            {
                foreach (var header in apiContext.HTTPHeaders)
                {
                    headers[header.Key] = header.Value;
                }
            }
            return(headers);
        }
Example #2
0
        /// <summary>
        /// Configures and executes REST call: Supports JSON
        /// </summary>
        /// <typeparam name="T">Generic Type parameter for response object</typeparam>
        /// <param name="apiContext">APIContext object</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="endpoint">Endpoint to use when generating the full URL for the resource. If none is specified, a default endpoint is generated by the SDK based on other config settings.</param>
        /// <param name="setAuthorizationHeader">Specifies whether or not to set the Authorization header in outgoing requests. Defaults to true.</param>
        /// <returns>Response object or null otherwise for void API calls</returns>
        /// <exception cref="Expressly.HttpException">Thrown if there was an error sending the request.</exception>
        /// <exception cref="Expressly.ExpresslyException">Thrown for any other issues encountered. See inner exception for further details.</exception>
        protected internal static T ConfigureAndExecute <T>(APIContext apiContext, HttpMethod httpMethod, string resource, string payload = "", string endpoint = "", bool setAuthorizationHeader = true)
        {
            // Verify the state of the APIContext object.
            if (apiContext == null)
            {
                throw new ExpresslyException("APIContext object is null");
            }

            try
            {
                var config     = apiContext.GetConfigWithDefaults();
                var headersMap = GetHeaderMap(apiContext);

                if (!setAuthorizationHeader && headersMap.ContainsKey(BaseConstants.AuthorizationHeader))
                {
                    headersMap.Remove(BaseConstants.AuthorizationHeader);
                }

                if (string.IsNullOrEmpty(endpoint))
                {
                    endpoint = GetEndpoint(config);
                }

                // Create the URI where the HTTP request will be sent.
                Uri uniformResourceIdentifier = null;
                var baseUri = new Uri(endpoint);
                if (!Uri.TryCreate(baseUri, resource, out uniformResourceIdentifier))
                {
                    throw new ExpresslyException("Cannot create URL; baseURI=" + baseUri.ToString() + ", resourcePath=" + resource);
                }

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

                // Set custom content type (default to [application/json])
                if (headersMap != null && headersMap.ContainsKey(BaseConstants.ContentTypeHeader))
                {
                    httpRequest.ContentType = headersMap[BaseConstants.ContentTypeHeader].Trim();
                    headersMap.Remove(BaseConstants.ContentTypeHeader);
                }
                else
                {
                    httpRequest.ContentType = BaseConstants.ContentTypeHeaderJson;
                }

                // Set User-Agent HTTP header
                if (headersMap.ContainsKey(BaseConstants.UserAgentHeader))
                {
                    //iso-8859-1
                    var iso8851 = Encoding.GetEncoding("iso-8859-1", new EncoderReplacementFallback(string.Empty), new DecoderExceptionFallback());
                    var bytes   = Encoding.Convert(Encoding.UTF8, iso8851, Encoding.UTF8.GetBytes(headersMap[BaseConstants.UserAgentHeader]));
                    httpRequest.UserAgent = iso8851.GetString(bytes);
                    headersMap.Remove(BaseConstants.UserAgentHeader);
                }

                // Set Custom HTTP headers
                foreach (KeyValuePair <string, string> entry in headersMap)
                {
                    httpRequest.Headers.Add(entry.Key, entry.Value);
                }

                // Log the headers
                foreach (string headerName in httpRequest.Headers)
                {
                    logger.DebugFormat(headerName + ":" + httpRequest.Headers[headerName]);
                }

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

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

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


                if (connectionHttp.ResponseDetails.StatusCode == HttpStatusCode.NoContent)
                {
                    return((T)Convert.ChangeType((int)HttpStatusCode.NoContent, typeof(T)));
                }

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

                return(JsonFormatter.ConvertFromJson <T>(response));
            }
            catch (ExpresslyException)
            {
                // If we get a ExpresslyException, just rethrow to preserve the stack trace.
                throw;
            }
            catch (System.Exception ex)
            {
                throw new ExpresslyException(ex.Message, ex);
            }
        }