public void ExecuteTest()
 {
     HttpConnection target = new HttpConnection();
     HttpWebRequest httpRequest = GetHttpWebRequest();
     string actual = target.Execute(payLoad, httpRequest);
     Assert.IsNotNull(actual);
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Makes a request to API service
        /// </summary>
        /// <param name="apiCallHandler"></param>
        /// <returns></returns>
        public string MakeRequestUsing(IAPICallPreHandler apiCallHandler)
        {
            string responseString = string.Empty;
            string uri            = apiCallHandler.GetEndpoint();
            Dictionary <string, string> headers = apiCallHandler.GetHeaderMap();
            string payload = apiCallHandler.GetPayload();

            //Constructing HttpWebRequest object
            ConnectionManager connMngr    = ConnectionManager.Instance;
            HttpWebRequest    httpRequest = connMngr.GetConnection(this.config, uri);

            httpRequest.Method = RequestMethod;
            if (headers != null && headers.ContainsKey(BaseConstants.ContentTypeHeader))
            {
                httpRequest.ContentType = headers[BaseConstants.ContentTypeHeader].Trim();
                headers.Remove(BaseConstants.ContentTypeHeader);
            }
            if (headers != null && headers.ContainsKey(BaseConstants.UserAgentHeader))
            {
                httpRequest.UserAgent = headers[BaseConstants.UserAgentHeader].Trim();
                headers.Remove(BaseConstants.UserAgentHeader);
            }
            foreach (KeyValuePair <string, string> header in headers)
            {
                httpRequest.Headers.Add(header.Key, header.Value);
            }

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

            if (apiCallHandler.GetCredential() is CertificateCredential)
            {
                CertificateCredential certCredential = (CertificateCredential)apiCallHandler.GetCredential();

                //Load the certificate into an X509Certificate2 object.
                if (((CertificateCredential)certCredential).PrivateKeyPassword.Trim() == string.Empty)
                {
                    x509 = new X509Certificate2(((CertificateCredential)certCredential).CertificateFile);
                }
                else
                {
                    x509 = new X509Certificate2(((CertificateCredential)certCredential).CertificateFile, ((CertificateCredential)certCredential).PrivateKeyPassword);
                }
                httpRequest.ClientCertificates.Add(x509);
            }

            HttpConnection connectionHttp = new HttpConnection(config);
            string         response       = connectionHttp.Execute(payload, httpRequest);

            return(response);
        }
Ejemplo n.º 3
0
        private string GenerateOAuthToken(string base64ClientId)
        {
            string response = null;

            Uri uniformResourceIdentifier = null;
            Uri baseUri = null;

            if (config.ContainsKey(BaseConstants.OAuthEndpoint))
            {
                baseUri = new Uri(config[BaseConstants.OAuthEndpoint]);
            }
            else if (config.ContainsKey(BaseConstants.EndpointConfig))
            {
                baseUri = new Uri(config[BaseConstants.EndpointConfig]);
            }
            else if (config.ContainsKey(BaseConstants.ApplicationModeConfig))
            {
                string mode = config[BaseConstants.ApplicationModeConfig];
                if (mode.Equals(BaseConstants.LiveMode))
                {
                    baseUri = new Uri(BaseConstants.RESTLiveEndpoint);
                }
                else if (mode.Equals(BaseConstants.SandboxMode))
                {
                    baseUri = new Uri(BaseConstants.RESTSandboxEndpoint);
                }
                else
                {
                    throw new ConfigException("You must specify one of mode(live/sandbox) OR endpoint in the configuration");
                }
            }
            bool success = Uri.TryCreate(baseUri, OAuthTokenPath, out uniformResourceIdentifier);
            ConnectionManager connManager = ConnectionManager.Instance;
            HttpWebRequest    httpRequest = connManager.GetConnection(this.config, uniformResourceIdentifier.AbsoluteUri);

            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Authorization", "Basic " + base64ClientId);
            string postRequest = "grant_type=client_credentials";

            httpRequest.Method      = "POST";
            httpRequest.Accept      = "*/*";
            httpRequest.ContentType = "application/x-www-form-urlencoded";
            UserAgentHeader             userAgentHeader = new UserAgentHeader(SdkVersion == null ? "" : SdkVersion.GetSDKId(), SdkVersion == null ? "" : SdkVersion.GetSDKVersion());
            Dictionary <string, string> userAgentMap    = userAgentHeader.GetHeader();

            foreach (KeyValuePair <string, string> entry in userAgentMap)
            {
                // aganzha
                //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(entry.Value));
                httpRequest.UserAgent = iso8851.GetString(bytes);
            }
            foreach (KeyValuePair <string, string> header in headers)
            {
                httpRequest.Headers.Add(header.Key, header.Value);
            }

            HttpConnection httpConnection = new HttpConnection(config);

            response = httpConnection.Execute(postRequest, httpRequest);
            JObject deserializedObject = (JObject)JsonConvert.DeserializeObject(response);
            string  generatedToken     = (string)deserializedObject["token_type"] + " " + (string)deserializedObject["access_token"];

            appId              = (string)deserializedObject["app_id"];
            secondsToExpire    = (int)deserializedObject["expires_in"];
            timeInMilliseconds = DateTime.Now.Millisecond;
            return(generatedToken);
        }
        private string GenerateOAuthToken(string base64ClientID)
        {
            string response = null;

                Uri uniformResourceIdentifier = null;
                Uri baseUri = null;
                if (config.ContainsKey(BaseConstants.OAUTH_ENDPOINT))
                {
                    baseUri = new Uri(config[BaseConstants.OAUTH_ENDPOINT]);
                }
                else if (config.ContainsKey(BaseConstants.END_POINT_CONFIG))
                {
                    baseUri = new Uri(config[BaseConstants.END_POINT_CONFIG]);
                }
                bool success = Uri.TryCreate(baseUri, OAUTHTOKENPATH, out uniformResourceIdentifier);
                ConnectionManager connManager = ConnectionManager.Instance;
                HttpWebRequest httpRequest = connManager.GetConnection(ConfigManager.Instance.GetProperties(), uniformResourceIdentifier.AbsoluteUri);

                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("Authorization", "Basic " + base64ClientID);
                string postRequest = "grant_type=client_credentials";
                httpRequest.Method = "POST";
                httpRequest.Accept = "*/*";
                httpRequest.UserAgent = RESTConfiguration.FormUserAgentHeader();
                foreach (KeyValuePair<string, string> header in headers)
                {
                    httpRequest.Headers.Add(header.Key, header.Value);
                }

                HttpConnection httpConnection = new HttpConnection(config);
                response = httpConnection.Execute(postRequest, httpRequest);
                JObject deserializedObject = (JObject)JsonConvert.DeserializeObject(response);
                string generatedToken = (string)deserializedObject["token_type"] + " " + (string)deserializedObject["access_token"];
                appID = (string)deserializedObject["app_id"];
                secondsToExpire = (int)deserializedObject["expires_in"];
                timeInMilliseconds = DateTime.Now.Millisecond;
                return generatedToken;
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Makes a request to API service
        /// </summary>
        /// <param name="apiCallHandler"></param>
        /// <returns></returns>
        public string MakeRequestUsing(IAPICallPreHandler apiCallHandler)
        {
            string responseString = string.Empty;
            string uri            = apiCallHandler.GetEndpoint();
            Dictionary <string, string> headers = apiCallHandler.GetHeaderMap();
            string payload = apiCallHandler.GetPayload();

            //Constructing HttpWebRequest object
            ConnectionManager connMngr    = ConnectionManager.Instance;
            HttpWebRequest    httpRequest = connMngr.GetConnection(this.config, uri);

            httpRequest.Method = RequestMethod;
            if (headers != null && headers.ContainsKey(BaseConstants.ContentTypeHeader))
            {
                httpRequest.ContentType = headers[BaseConstants.ContentTypeHeader].Trim();
                headers.Remove(BaseConstants.ContentTypeHeader);
            }
            if (headers != null && headers.ContainsKey(BaseConstants.UserAgentHeader))
            {
                httpRequest.UserAgent = headers[BaseConstants.UserAgentHeader].Trim();
                headers.Remove(BaseConstants.UserAgentHeader);
            }
            foreach (KeyValuePair <string, string> header in headers)
            {
                httpRequest.Headers.Add(header.Key, header.Value);
            }

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

            if (apiCallHandler.GetCredential() is CertificateCredential)
            {
                CertificateCredential certCredential            = (CertificateCredential)apiCallHandler.GetCredential();
                System.Exception      x509LoadFromFileException = null;
                X509Certificate2      x509 = null;

                try
                {
                    //Load the certificate into an X509Certificate2 object.
                    if (string.IsNullOrEmpty(certCredential.PrivateKeyPassword.Trim()))
                    {
                        x509 = new X509Certificate2(certCredential.CertificateFile);
                    }
                    else
                    {
                        x509 = new X509Certificate2(certCredential.CertificateFile, certCredential.PrivateKeyPassword);
                    }
                }
                catch (System.Exception ex)
                {
                    x509LoadFromFileException = ex;
                }

                // If we failed to load the certificate from the specified file,
                // then try loading it from the certificates store using the provided UserName.
                if (x509 == null)
                {
                    // Start by checking the local machine store.
                    x509 = this.GetX509CertificateForUserName(certCredential.UserName, StoreLocation.LocalMachine);
                }

                // If the certificate couldn't be found in the LM store, check
                // the current user store.
                if (x509 == null)
                {
                    x509 = this.GetX509CertificateForUserName(certCredential.UserName, StoreLocation.CurrentUser);
                }

                // If the certificate still hasn't been loaded by this point,
                // then it means it failed to be loaded from a file and was not
                // found in any of the certificate stores.
                if (x509 == null)
                {
                    throw new PayPalException("Failed to load the certificate file", x509LoadFromFileException);
                }

                httpRequest.ClientCertificates.Add(x509);
            }

            HttpConnection connectionHttp = new HttpConnection(config);
            string         response       = connectionHttp.Execute(payload, httpRequest);

            return(response);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Configures and executes REST call: Supports JSON
        /// </summary>
        /// <typeparam name="T">Generic Type parameter for response object</typeparam>
        /// <param name="config">Configuration Dictionary</param>
        /// <param name="apiCallPreHandler">IAPICallPreHandler instance</param>
        /// <param name="httpMethod">HttpMethod type</param>
        /// <param name="resourcePath">URI path of the resource</param>
        /// <returns>Response object or null otherwise for void API calls</returns>
        /// <exception cref="PayPal.HttpException">Thrown if there was an error sending the request.</exception>
        /// <exception cref="PayPal.PaymentsException">Thrown if an HttpException was raised and contains a Payments API error object.</exception>
        /// <exception cref="PayPal.PayPalException">Thrown for any other issues encountered. See inner exception for further details.</exception>
        private static T ConfigureAndExecute <T>(Dictionary <string, string> config, IAPICallPreHandler apiCallPreHandler, HttpMethod httpMethod, string resourcePath)
        {
            try
            {
                string response = null;
                Uri    uniformResourceIdentifier = null;
                Uri    baseUri = null;
                Dictionary <string, string> headersMap = apiCallPreHandler.GetHeaderMap();

                baseUri = new Uri(apiCallPreHandler.GetEndpoint());
                if (Uri.TryCreate(baseUri, resourcePath, out uniformResourceIdentifier))
                {
                    ConnectionManager connMngr = ConnectionManager.Instance;
                    connMngr.GetConnection(config, uniformResourceIdentifier.ToString());
                    HttpWebRequest 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))
                    {
                        // aganzha
                        //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);
                    }

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

                    // Execute call
                    HttpConnection connectionHttp = new HttpConnection(config);
                    response = connectionHttp.Execute(apiCallPreHandler.GetPayload(), httpRequest);

                    if (typeof(T).Name.Equals("Object"))
                    {
                        return(default(T));
                    }
                    else if (typeof(T).Name.Equals("String"))
                    {
                        return((T)Convert.ChangeType(response, typeof(T)));
                    }
                    else
                    {
                        return(JsonFormatter.ConvertFromJson <T>(response));
                    }
                }
                else
                {
                    throw new PayPalException("Cannot create URL; baseURI=" + baseUri.ToString() + ", resourcePath=" + resourcePath);
                }
            }
            catch (HttpException ex)
            {
                //  Check to see if we have a Payments API error.
                if (ex.StatusCode == HttpStatusCode.BadRequest)
                {
                    PaymentsException paymentsEx;
                    if (ex.TryConvertTo <PaymentsException>(out paymentsEx))
                    {
                        throw paymentsEx;
                    }
                }
                throw;
            }
            catch (PayPalException)
            {
                throw;
            }
            catch (System.Exception ex)
            {
                throw new PayPalException(ex.Message, ex);
            }
        }
        private string GenerateOAuthToken(string base64ClientID)
        {
            string response = null;

                Uri uniformResourceIdentifier = null;
                Uri baseUri = null;
                if (config.ContainsKey(BaseConstants.OAUTH_ENDPOINT))
                {
                    baseUri = new Uri(config[BaseConstants.OAUTH_ENDPOINT]);
                }
                else if (config.ContainsKey(BaseConstants.END_POINT_CONFIG))
                {
                    baseUri = new Uri(config[BaseConstants.END_POINT_CONFIG]);
                }
                else if (config.ContainsKey(BaseConstants.APPLICATION_MODE_CONFIG))
                {
                    string mode = config[BaseConstants.APPLICATION_MODE_CONFIG];
                    if (mode.Equals(BaseConstants.LIVE_MODE))
                    {
                        baseUri = new Uri(BaseConstants.REST_LIVE_ENDPOINT);
                    }
                    else if (mode.Equals(BaseConstants.SANDBOX_MODE))
                    {
                        baseUri = new Uri(BaseConstants.REST_SANDBOX_ENDPOINT);
                    }
                    else
                    {
                        throw new ConfigException("You must specify one of mode(live/sandbox) OR endpoint in the configuration");
                    }
                }
                bool success = Uri.TryCreate(baseUri, OAUTHTOKENPATH, out uniformResourceIdentifier);
                ConnectionManager connManager = ConnectionManager.Instance;
                HttpWebRequest httpRequest = connManager.GetConnection(this.config, uniformResourceIdentifier.AbsoluteUri);

                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("Authorization", "Basic " + base64ClientID);
                string postRequest = "grant_type=client_credentials";
                httpRequest.Method = "POST";
                httpRequest.Accept = "*/*";
                httpRequest.ContentType = "application/x-www-form-urlencoded";
                httpRequest.UserAgent = RESTConfiguration.FormUserAgentHeader();
                foreach (KeyValuePair<string, string> header in headers)
                {
                    httpRequest.Headers.Add(header.Key, header.Value);
                }

                HttpConnection httpConnection = new HttpConnection(config);
                response = httpConnection.Execute(postRequest, httpRequest);
                JObject deserializedObject = (JObject)JsonConvert.DeserializeObject(response);
                string generatedToken = (string)deserializedObject["token_type"] + " " + (string)deserializedObject["access_token"];
                appID = (string)deserializedObject["app_id"];
                secondsToExpire = (int)deserializedObject["expires_in"];
                timeInMilliseconds = DateTime.Now.Millisecond;
                return generatedToken;
        }
Ejemplo n.º 8
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>
        /// <returns>Response object or null otherwise for void API calls</returns>
        /// <exception cref="PayPal.HttpException">Thrown if there was an error sending the request.</exception>
        /// <exception cref="PayPal.PaymentsException">Thrown if an HttpException was raised and contains a Payments API error object.</exception>
        /// <exception cref="PayPal.PayPalException">Thrown for any other issues encountered. See inner exception for further details.</exception>
        public static T ConfigureAndExecute <T>(APIContext apiContext, HttpMethod httpMethod, string resource, string payload = "")
        {
            // Verify the state of the APIContext object.
            if (apiContext == null)
            {
                throw new PayPalException("APIContext object is null");
            }

            try
            {
                var config     = apiContext.GetConfigWithDefaults();
                var headersMap = GetHeaderMap(apiContext);
                var 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 PayPalException("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;
                connMngr.GetConnection(config, uniformResourceIdentifier.ToString());
                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))
                {
                    // aganzha
                    //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);
                var response       = connectionHttp.Execute(payload, httpRequest);

                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 (HttpException ex)
            {
                //  Check to see if we have a Payments API error.
                if (ex.StatusCode == HttpStatusCode.BadRequest)
                {
                    PaymentsException paymentsEx;
                    if (ex.TryConvertTo <PaymentsException>(out paymentsEx))
                    {
                        throw paymentsEx;
                    }
                }
                throw;
            }
            catch (PayPalException)
            {
                // If we get a PayPalException, just rethrow to preserve the stack trace.
                throw;
            }
            catch (System.Exception ex)
            {
                throw new PayPalException(ex.Message, ex);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Makes a request to API service
        /// </summary>
        /// <param name="apiCallHandler"></param>
        /// <returns></returns>
        public string MakeRequestUsing(IAPICallPreHandler apiCallHandler)
        {
            string responseString = string.Empty;
            string uri = apiCallHandler.GetEndpoint();
            Dictionary<string, string> headers = apiCallHandler.GetHeaderMap();
            string payload = apiCallHandler.GetPayload();

            //Constructing HttpWebRequest object
            ConnectionManager connMngr = ConnectionManager.Instance;
            HttpWebRequest httpRequest = connMngr.GetConnection(this.config, uri);
            httpRequest.Method = RequestMethod;
            if (headers != null && headers.ContainsKey(BaseConstants.ContentTypeHeader))
            {
                httpRequest.ContentType = headers[BaseConstants.ContentTypeHeader].Trim();
                headers.Remove(BaseConstants.ContentTypeHeader);
            }
            if (headers != null && headers.ContainsKey(BaseConstants.UserAgentHeader))
            {
                httpRequest.UserAgent = headers[BaseConstants.UserAgentHeader].Trim();
                headers.Remove(BaseConstants.UserAgentHeader);
            }
            foreach (KeyValuePair<string, string> header in headers)
            {
                httpRequest.Headers.Add(header.Key, header.Value);
            }

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

            if (apiCallHandler.GetCredential() is CertificateCredential)
            {
                CertificateCredential certCredential = (CertificateCredential)apiCallHandler.GetCredential();
                System.Exception x509LoadFromFileException = null;
                X509Certificate2 x509 = null;

                try
                {
                    //Load the certificate into an X509Certificate2 object.
                    if (string.IsNullOrEmpty(certCredential.PrivateKeyPassword.Trim()))
                    {
                        x509 = new X509Certificate2(certCredential.CertificateFile);
                    }
                    else
                    {
                        x509 = new X509Certificate2(certCredential.CertificateFile, certCredential.PrivateKeyPassword);
                    }
                }
                catch (System.Exception ex)
                {
                    x509LoadFromFileException = ex;
                }

                // If we failed to load the certificate from the specified file,
                // then try loading it from the certificates store using the provided UserName.
                if (x509 == null)
                {
                    // Start by checking the local machine store.
                    x509 = this.GetX509CertificateForUserName(certCredential.UserName, StoreLocation.LocalMachine);
                }

                // If the certificate couldn't be found in the LM store, check
                // the current user store.
                if (x509 == null)
                {
                    x509 = this.GetX509CertificateForUserName(certCredential.UserName, StoreLocation.CurrentUser);
                }

                // If the certificate still hasn't been loaded by this point,
                // then it means it failed to be loaded from a file and was not
                // found in any of the certificate stores.
                if (x509 == null)
                {
                    throw new PayPalException("Failed to load the certificate file", x509LoadFromFileException);
                }

                httpRequest.ClientCertificates.Add(x509);
            }

            HttpConnection connectionHttp = new HttpConnection(config);
            string response = connectionHttp.Execute(payload, httpRequest);

            return response;
        }
Ejemplo n.º 10
0
        private string GenerateOAuthToken(string base64ClientId)
        {
            string response = null;

            Uri uniformResourceIdentifier = null;
            Uri baseUri = null;
            if (config.ContainsKey(BaseConstants.OAuthEndpoint))
            {
                baseUri = new Uri(config[BaseConstants.OAuthEndpoint]);
            }
            else if (config.ContainsKey(BaseConstants.EndpointConfig))
            {
                baseUri = new Uri(config[BaseConstants.EndpointConfig]);
            }
            else if (config.ContainsKey(BaseConstants.ApplicationModeConfig))
            {
                string mode = config[BaseConstants.ApplicationModeConfig];
                if (mode.Equals(BaseConstants.LiveMode))
                {
                    baseUri = new Uri(BaseConstants.RESTLiveEndpoint);
                }
                else if (mode.Equals(BaseConstants.SandboxMode))
                {
                    baseUri = new Uri(BaseConstants.RESTSandboxEndpoint);
                }
                else
                {
                    throw new ConfigException("You must specify one of mode(live/sandbox) OR endpoint in the configuration");
                }
            }
            bool success = Uri.TryCreate(baseUri, OAuthTokenPath, out uniformResourceIdentifier);
            ConnectionManager connManager = ConnectionManager.Instance;
                HttpWebRequest httpRequest = connManager.GetConnection(this.config, uniformResourceIdentifier.AbsoluteUri);

            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("Authorization", "Basic " + base64ClientId);
            string postRequest = "grant_type=client_credentials";
            httpRequest.Method = "POST";
            httpRequest.Accept = "*/*";
            httpRequest.ContentType = "application/x-www-form-urlencoded";
            UserAgentHeader userAgentHeader = new UserAgentHeader(SdkVersion == null ? "" : SdkVersion.GetSDKId(), SdkVersion == null ? "" : SdkVersion.GetSDKVersion());
            Dictionary<string, string> userAgentMap = userAgentHeader.GetHeader();
            foreach (KeyValuePair<string, string> entry in userAgentMap)
            {
                // aganzha
                //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(entry.Value));
                httpRequest.UserAgent = iso8851.GetString(bytes);
            }
            foreach (KeyValuePair<string, string> header in headers)
            {
                httpRequest.Headers.Add(header.Key, header.Value);
            }

            HttpConnection httpConnection = new HttpConnection(config);
            response = httpConnection.Execute(postRequest, httpRequest);
            JObject deserializedObject = (JObject)JsonConvert.DeserializeObject(response);
            string generatedToken = (string)deserializedObject["token_type"] + " " + (string)deserializedObject["access_token"];
            appId = (string)deserializedObject["app_id"];
            secondsToExpire = (int)deserializedObject["expires_in"];
            timeInMilliseconds = DateTime.Now.Millisecond;
            return generatedToken;
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Makes a request to API service
        /// </summary>
        /// <param name="apiCallHandler"></param>
        /// <returns></returns>
        public string MakeRequestUsing(IAPICallPreHandler apiCallHandler)
        {
            string responseString = string.Empty;
            string uri = apiCallHandler.GetEndpoint();
            Dictionary<string, string> headers = apiCallHandler.GetHeaderMap();
            string payload = apiCallHandler.GetPayload();

            //Constructing HttpWebRequest object
            ConnectionManager connMngr = ConnectionManager.Instance;
            HttpWebRequest httpRequest = connMngr.GetConnection(this.config, uri);
            httpRequest.Method = RequestMethod;
            if (headers != null && headers.ContainsKey(BaseConstants.ContentTypeHeader))
            {
                httpRequest.ContentType = headers[BaseConstants.ContentTypeHeader].Trim();
                headers.Remove(BaseConstants.ContentTypeHeader);
            }
            if (headers != null && headers.ContainsKey(BaseConstants.UserAgentHeader))
            {
                httpRequest.UserAgent = headers[BaseConstants.UserAgentHeader].Trim();
                headers.Remove(BaseConstants.UserAgentHeader);
            }
            foreach (KeyValuePair<string, string> header in headers)
            {
                httpRequest.Headers.Add(header.Key, header.Value);
            }

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

            if (apiCallHandler.GetCredential() is CertificateCredential)
            {
                CertificateCredential certCredential = (CertificateCredential)apiCallHandler.GetCredential();

                //Load the certificate into an X509Certificate2 object.
                if (((CertificateCredential)certCredential).PrivateKeyPassword.Trim() == string.Empty)
                {
                    x509 = new X509Certificate2(((CertificateCredential)certCredential).CertificateFile);
                }
                else
                {
                    x509 = new X509Certificate2(((CertificateCredential)certCredential).CertificateFile, ((CertificateCredential)certCredential).PrivateKeyPassword);
                }
                httpRequest.ClientCertificates.Add(x509);
            }

            HttpConnection connectionHttp = new HttpConnection(config);
            string response = connectionHttp.Execute(payload, httpRequest);

            return response;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Configures and executes REST call: Supports JSON
        /// </summary>
        /// <typeparam name="T">Generic Type parameter for response object</typeparam>
        /// <param name="config">Configuration Dictionary</param>
        /// <param name="apiCallPreHandler">IAPICallPreHandler instance</param>
        /// <param name="httpMethod">HttpMethod type</param>
        /// <param name="resourcePath">URI path of the resource</param>
        /// <returns>Response object or null otherwise for void API calls</returns>
        private static T ConfigureAndExecute <T>(Dictionary <string, string> config, IAPICallPreHandler apiCallPreHandler, HttpMethod httpMethod, string resourcePath)
        {
            try
            {
                string response = null;
                Uri    uniformResourceIdentifier = null;
                Uri    baseUri = null;
                Dictionary <string, string> headersMap = apiCallPreHandler.GetHeaderMap();

                baseUri = new Uri(apiCallPreHandler.GetEndpoint());
                if (Uri.TryCreate(baseUri, resourcePath, out uniformResourceIdentifier))
                {
                    ConnectionManager connMngr = ConnectionManager.Instance;
                    connMngr.GetConnection(config, uniformResourceIdentifier.ToString());
                    HttpWebRequest 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))
                    {
                        httpRequest.UserAgent = headersMap[BaseConstants.UserAgentHeader];
                        headersMap.Remove(BaseConstants.UserAgentHeader);
                    }

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

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

                    // Execute call
                    HttpConnection connectionHttp = new HttpConnection(config);
                    response = connectionHttp.Execute(apiCallPreHandler.GetPayload(), httpRequest);
                    if (typeof(T).Name.Equals("Object"))
                    {
                        return(default(T));
                    }
                    else if (typeof(T).Name.Equals("String"))
                    {
                        return((T)Convert.ChangeType(response, typeof(T)));
                    }
                    else
                    {
                        return(JsonConvert.DeserializeObject <T>(response));
                    }
                }
                else
                {
                    throw new PayPalException("Cannot create URL; baseURI=" + baseUri.ToString() + ", resourcePath=" + resourcePath);
                }
            }
            catch (PayPalException ex)
            {
                throw ex;
            }
            catch (System.Exception ex)
            {
                throw new PayPalException(ex.Message, ex);
            }
        }
Ejemplo n.º 13
0
        public static T ConfigureAndExecute <T>(APIContext apiContext, HttpMethod httpMethod, string resource, Dictionary <string, string> headersMap, string payLoad)
        {
            try
            {
                string response = null;
                Dictionary <string, String> headers;
                Uri uniformResourceIdentifier = null;
                Uri baseUri = null;
                Dictionary <string, string> config = null;
                if (apiContext.Config == null)
                {
                    config = ConfigManager.getConfigWithDefaults(ConfigManager.Instance.GetProperties());
                }
                else
                {
                    config = ConfigManager.getConfigWithDefaults(apiContext.Config);
                }
                baseUri = GetBaseURI(config);
                bool success = Uri.TryCreate(baseUri, resource, out uniformResourceIdentifier);

                RESTConfiguration restConfiguration = new RESTConfiguration(config, headersMap);
                restConfiguration.authorizationToken = apiContext.AccessToken;
                restConfiguration.requestId          = apiContext.RequestID;
                headers = restConfiguration.GetHeaders();

                ConnectionManager connMngr = ConnectionManager.Instance;
                connMngr.GetConnection(config, uniformResourceIdentifier.ToString());
                HttpWebRequest httpRequest = connMngr.GetConnection(config, uniformResourceIdentifier.ToString());
                httpRequest.Method = httpMethod.ToString();
                if (headers != null && headers.ContainsKey("Content-Type"))
                {
                    httpRequest.ContentType = headers["Content-Type"];
                    headers.Remove("Content-Type");
                }
                else
                {
                    httpRequest.ContentType = "application/json";
                }
                httpRequest.ContentLength = payLoad.Length;
                foreach (KeyValuePair <string, string> header in headers)
                {
                    if (header.Key.Trim().Equals("User-Agent"))
                    {
                        httpRequest.UserAgent = header.Value;
                    }
                    else
                    {
                        httpRequest.Headers.Add(header.Key, header.Value);
                    }
                }
                if (logger.IsDebugEnabled)
                {
                    foreach (string headerName in httpRequest.Headers)
                    {
                        logger.Debug(headerName + ":" + httpRequest.Headers[headerName]);
                    }
                }
                HttpConnection connectionHttp = new HttpConnection(config);
                response = connectionHttp.Execute(payLoad, httpRequest);
                if (typeof(T).Name.Equals("Object"))
                {
                    return(default(T));
                }
                else
                {
                    return(JsonConvert.DeserializeObject <T>(response));
                }
            }
            catch (PayPalException ex)
            {
                throw ex;
            }
            catch (System.Exception ex)
            {
                throw new PayPalException(ex.Message, ex);
            }
        }
Ejemplo n.º 14
0
        private string GenerateOAuthToken(string base64ClientID)
        {
            string response = null;

            Uri uniformResourceIdentifier = null;
            Uri baseUri = null;

            if (config.ContainsKey(BaseConstants.OAUTH_ENDPOINT))
            {
                baseUri = new Uri(config[BaseConstants.OAUTH_ENDPOINT]);
            }
            else if (config.ContainsKey(BaseConstants.END_POINT_CONFIG))
            {
                baseUri = new Uri(config[BaseConstants.END_POINT_CONFIG]);
            }
            else if (config.ContainsKey(BaseConstants.APPLICATION_MODE_CONFIG))
            {
                string mode = config[BaseConstants.APPLICATION_MODE_CONFIG];
                if (mode.Equals(BaseConstants.LIVE_MODE))
                {
                    baseUri = new Uri(BaseConstants.REST_LIVE_ENDPOINT);
                }
                else if (mode.Equals(BaseConstants.SANDBOX_MODE))
                {
                    baseUri = new Uri(BaseConstants.REST_SANDBOX_ENDPOINT);
                }
                else
                {
                    throw new ConfigException("You must specify one of mode(live/sandbox) OR endpoint in the configuration");
                }
            }
            bool success = Uri.TryCreate(baseUri, OAUTHTOKENPATH, out uniformResourceIdentifier);
            ConnectionManager connManager = ConnectionManager.Instance;
            HttpWebRequest    httpRequest = connManager.GetConnection(this.config, uniformResourceIdentifier.AbsoluteUri);


            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Authorization", "Basic " + base64ClientID);
            string postRequest = "grant_type=client_credentials";

            httpRequest.Method      = "POST";
            httpRequest.Accept      = "*/*";
            httpRequest.ContentType = "application/x-www-form-urlencoded";
            httpRequest.UserAgent   = RESTConfiguration.FormUserAgentHeader();
            foreach (KeyValuePair <string, string> header in headers)
            {
                httpRequest.Headers.Add(header.Key, header.Value);
            }

            HttpConnection httpConnection = new HttpConnection(config);

            response = httpConnection.Execute(postRequest, httpRequest);
            JObject deserializedObject = (JObject)JsonConvert.DeserializeObject(response);
            string  generatedToken     = (string)deserializedObject["token_type"] + " " + (string)deserializedObject["access_token"];

            appID              = (string)deserializedObject["app_id"];
            secondsToExpire    = (int)deserializedObject["expires_in"];
            timeInMilliseconds = DateTime.Now.Millisecond;
            return(generatedToken);
        }