/// <summary>
 /// Call method exposed to user
 /// </summary>
 /// <param name="apiCallHandler"></param>
 /// <returns></returns>
 public string Call(IAPICallPreHandler apiCallHandler)
 {
     APIService apiServ = new APIService(this.config);
     this.lastRequest = apiCallHandler.GetPayLoad();
     this.lastResponse = apiServ.MakeRequestUsing(apiCallHandler);
     return this.lastResponse;
 }
Exemple #2
0
        /// <summary>
        /// Call method exposed to user
        /// </summary>
        /// <param name="apiCallHandler"></param>
        /// <returns></returns>
        public string Call(IAPICallPreHandler apiCallHandler)
        {
            APIService apiServ = new APIService(this.config);

            this.lastReq  = apiCallHandler.GetPayload();
            this.lastResp = apiServ.MakeRequestUsing(apiCallHandler);
            return(this.lastResp);
        }
 /// <summary>
 ///  SOAPAPICallPreHandler decorating basic IAPICallPreHandler using ICredential
 /// </summary>
 /// <param name="apiCallHandler"></param>
 /// <param name="credential"></param>
 public MerchantAPICallPreHandler(Dictionary <string, string> config, IAPICallPreHandler apiCallHandler, ICredential credential) : this(apiCallHandler, config)
 {
     if (credential == null)
     {
         throw new ArgumentException("Credential is null in SOAPAPICallPreHandler");
     }
     this.credential = credential;
 }
 public void MakeRequestUsingSOAPSignatureCredential()
 {
     defaultSOAPHandler = new DefaultSOAPAPICallHandler(UnitTestConstants.PayloadSOAP, null, null);
     handler = new MerchantAPICallPreHandler(defaultSOAPHandler, UnitTestConstants.APIUserName, null, null);
     service = new APIService();
     string response = service.MakeRequestUsing(handler);
     Assert.IsNotNull(response);
     Assert.IsTrue(response.Contains("<Ack xmlns=\"urn:ebay:apis:eBLBaseComponents\">Success</Ack>"));
 }
 public void MakeRequestUsingNVPSignatureCredential()
 {
     handler = new PlatformAPICallPreHandler(UnitTestConstants.PayloadNVP, "AdaptivePayments", "ConvertCurrency", UnitTestConstants.APIUserName, null, null);
     Thread.Sleep(5000);
     service = new APIService();
     string response = service.MakeRequestUsing(handler);
     Assert.IsNotNull(response);
     Assert.IsTrue(response.Contains("responseEnvelope.ack=Success"));
 }
 public void MakeRequestUsingNVPCertificateCredential()
 {
     handler = new PlatformAPICallPreHandler(ConfigManager.Instance.GetProperties(), Constants.PayloadNVP, "AdaptivePayments", "ConvertCurrency", Constants.CertificateAPIUserName, null, null);
     Thread.Sleep(5000);
     APIService service = new APIService(ConfigManager.Instance.GetProperties());
     string response = service.MakeRequestUsing(handler);
     Assert.IsNotNull(response);
     Assert.IsTrue(response.Contains("responseEnvelope.ack=Success"));
 }
Exemple #7
0
        public void MakeRequestUsingNVPSignatureCredential()
        {
            handler = new PlatformAPICallPreHandler(ConfigManager.Instance.GetProperties(), UnitTestConstants.PayloadNVP, "AdaptivePayments", "ConvertCurrency", UnitTestConstants.APIUserName, null, null);
            Thread.Sleep(5000);
            service = new APIService(ConfigManager.Instance.GetProperties());
            string response = service.MakeRequestUsing(handler);

            Assert.IsNotNull(response);
            Assert.IsTrue(response.Contains("responseEnvelope.ack=Success"));
        }
Exemple #8
0
        public void MakeRequestUsingSOAPSignatureCredential()
        {
            defaultSOAPHandler = new DefaultSOAPAPICallHandler(ConfigManager.Instance.GetProperties(), UnitTestConstants.PayloadSOAP, null, null);
            handler            = new MerchantAPICallPreHandler(ConfigManager.Instance.GetProperties(), defaultSOAPHandler, UnitTestConstants.APIUserName, null, null);
            service            = new APIService(ConfigManager.Instance.GetProperties());
            string response = service.MakeRequestUsing(handler);

            Assert.IsNotNull(response);
            Assert.IsTrue(response.Contains("<Ack xmlns=\"urn:ebay:apis:eBLBaseComponents\">Success</Ack>"));
        }
        /// <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);
        }
Exemple #10
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;
        }
 /// <summary>
 /// SOAPAPICallPreHandler decorating basic IAPICallPreHandler using API Username
 /// </summary>
 /// <param name="apiCallHandler"></param>
 /// <param name="apiUserName"></param>
 /// <param name="accessToken"></param>
 /// <param name="tokenSecret"></param>
 public MerchantAPICallPreHandler(Dictionary <string, string> config, IAPICallPreHandler apiCallHandler, string apiUserName, string accessToken, string tokenSecret) : this(apiCallHandler, config)
 {
     try
     {
         this.apiUserName = apiUserName;
         this.accessToken = accessToken;
         this.tokenSecret = tokenSecret;
         InitCredential();
     }
     catch (System.Exception ex)
     {
         throw ex;
     }
 }
 /// <summary>
 /// SOAPAPICallPreHandler decorating basic IAPICallPreHandler using API Username
 /// </summary>
 /// <param name="apiCallHandler"></param>
 /// <param name="apiUserName"></param>
 /// <param name="accessToken"></param>
 /// <param name="tokenSecret"></param>
 public MerchantAPICallPreHandler(Dictionary<string, string> config, IAPICallPreHandler apiCallHandler, string apiUserName, string accessToken, string tokenSecret)
     : this(apiCallHandler, config)
 {
     try
     {
         this.apiUserName = apiUserName;
         this.accessToken = accessToken;
         this.tokenSecret = tokenSecret;
         InitCredential();
     }
     catch(System.Exception ex)
     {
         throw ex;
     }
 }
        public static T ConfigureAndExecute <T>(APIContext apiContext, HttpMethodEnum httpMethod, string resource, string payload)
        {
            if (apiContext == null)
            {
                throw new Exception("APIContext object is null");
            }

            Dictionary <string, string> config = apiContext.Config;
            string resourcePath = resource;
            Dictionary <string, string> httpHeaders = apiContext.HTTPHeaders;
            string             requestId            = apiContext.RequestId;
            IAPICallPreHandler iApiCallPreHandler   = Helper.CreateIAPICallPreHandler(config, httpHeaders, requestId, payload);

            return(Helper.ConfigureAndExecute <T>(config, iApiCallPreHandler, httpMethod, resourcePath));
        }
        /// <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 = "")
        {
            Dictionary <string, string> config = null;
            String authorizationToken          = null;
            String resourcePath = null;
            Dictionary <string, string> headersMap = null;
            String requestId = null;

            if (apiContext == null)
            {
                throw new PayPalException("APIContext object is null");
            }

            // Fix config object befor proceeding further
            if (apiContext.Config == null)
            {
                config = ConfigManager.GetConfigWithDefaults(ConfigManager.Instance.GetProperties());
            }
            else
            {
                config = ConfigManager.GetConfigWithDefaults(apiContext.Config);
            }

            // Access Token
            authorizationToken = apiContext.AccessToken;

            // Resource URI path
            resourcePath = resource;

            // Custom HTTP Headers
            headersMap = apiContext.HTTPHeaders;

            // PayPal Request Id
            requestId = apiContext.MaskRequestId ? null : apiContext.RequestId;

            // Create an instance of IAPICallPreHandler
            IAPICallPreHandler apiCallPreHandler = CreateIAPICallPreHandler(config, headersMap, authorizationToken, requestId, payload, apiContext.SdkVersion);

            return(ConfigureAndExecute <T>(config, apiCallPreHandler, httpMethod, resourcePath));
        }
        private static T ConfigureAndExecute <T>(Dictionary <string, string> config, IAPICallPreHandler apiCallPreHandler, HttpMethodEnum httpMethod, string resourcePath)
        {
            try
            {
                Uri result = (Uri)null;
                Dictionary <string, string> headerMap = apiCallPreHandler.GetHeaderMap();
                Uri baseUri = new Uri(apiCallPreHandler.GetEndpoint());
                if (!Uri.TryCreate(baseUri, resourcePath, out result))
                {
                    throw null;
                }
                ConnectionManager instance = ConnectionManager.Instance;
                instance.GetConnection(config, result.ToString());

                ServicePointManager.Expect100Continue = false;

                HttpWebRequest connection = CreateHttpWebRequestConnection(config, httpMethod, result, instance);

                SetHttpHeaders(headerMap, connection);

                string str = new HttpConnection(config).Execute(apiCallPreHandler.GetPayload(), connection);
                if (typeof(T).Name.Equals("Object"))
                {
                    return(default(T));
                }
                if (typeof(T).Name.Equals("String"))
                {
                    return((T)Convert.ChangeType((object)str, typeof(T)));
                }
                else
                {
                    return(JsonConvert.DeserializeObject <T>(str));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 /// <summary>
 ///  SOAPAPICallPreHandler decorating basic IAPICallPreHandler using ICredential
 /// </summary>
 /// <param name="apiCallHandler"></param>
 /// <param name="credential"></param>
 public MerchantAPICallPreHandler(Dictionary<string, string> config, IAPICallPreHandler apiCallHandler, ICredential credential)
     : this(apiCallHandler, config)
 {
     if (credential == null)
     {
         throw new ArgumentException("Credential is null in SOAPAPICallPreHandler");
     }
     this.credential = credential;
 }
Exemple #17
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);
        }
 /// <summary>
 /// Private constructor
 /// </summary>
 /// <param name="apiCallHandler"></param>
 private MerchantAPICallPreHandler(IAPICallPreHandler apiCallHandler, Dictionary <string, string> config)
     : base()
 {
     this.apiCallHandler = apiCallHandler;
     this.config         = (config == null) ? ConfigManager.Instance.GetProperties() : config;
 }
        /// <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);
            }
        }
 /// <summary>
 /// Private constructor
 /// </summary>
 /// <param name="apiCallHandler"></param>
 private MerchantAPICallPreHandler(IAPICallPreHandler apiCallHandler)
     : base()
 {
     this.apiCallHandler = apiCallHandler;
 }
 /// <summary>
 ///  SOAPAPICallPreHandler decorating basic IAPICallPreHandler using ICredential
 /// </summary>
 /// <param name="apiCallHandler"></param>
 /// <param name="credential"></param>
 public MerchantAPICallPreHandler(IAPICallPreHandler apiCallHandler, ICredential credential)
     : this(apiCallHandler)
 {
     if (credential == null)
     {
         throw new ArgumentException("Credential is null in SOAPAPICallPreHandler");
     }
     this.credential = credential;
 }
Exemple #22
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;
            foreach (KeyValuePair<string, string> header in headers)
            {
                httpRequest.Headers.Add(header.Key, header.Value);
            }
            if (logger.IsDebugEnabled)
            {
                foreach (string headerName in httpRequest.Headers)
                {
                    logger.Debug(headerName + ":" + httpRequest.Headers[headerName]);
                }
            }
            // Adding payLoad to HttpWebRequest object
            using (StreamWriter myWriter = new StreamWriter(httpRequest.GetRequestStream()))
            {
                myWriter.Write(payLoad);
                logger.Debug(payLoad);
            }

            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);
            }

            // Fire request. Retry if configured to do so
            int numRetries = (this.config.ContainsKey(BaseConstants.HTTP_CONNECTION_RETRY_CONFIG)) ?
                    Convert.ToInt32(config[BaseConstants.HTTP_CONNECTION_RETRY_CONFIG]) : 0;
            int retries = 0;

            do
            {
                try
                {
                    // Calling the plaftform API web service and getting the response
                    using (WebResponse response = httpRequest.GetResponse())
                    {
                        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                        {
                            responseString = sr.ReadToEnd();
                            logger.Debug("Service response");
                            logger.Debug(responseString);
                            return responseString;
                        }
                    }
                }
                // Server responses in the range of 4xx and 5xx throw a WebException
                catch (WebException we)
                {
                    HttpStatusCode statusCode = ((HttpWebResponse)we.Response).StatusCode;

                    logger.Info("Got " + statusCode.ToString() + " response from server");
                    if (!RequiresRetry(we))
                    {
                        throw new ConnectionException("Invalid HTTP response " + we.Message);
                    }
                }
                catch(System.Exception ex)
                {
                    throw ex;
                }
            } while (retries++ < numRetries);
            throw new ConnectionException("Invalid HTTP response");
        }
Exemple #23
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);
            }
        }
 /// <summary>
 /// Private constructor
 /// </summary>
 /// <param name="apiCallHandler"></param>
 private MerchantAPICallPreHandler(IAPICallPreHandler apiCallHandler, Dictionary<string, string> config)
     : base()
 {
     this.apiCallHandler = apiCallHandler;
     this.config = (config == null) ? ConfigManager.Instance.GetProperties() : config;
 }
Exemple #25
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;
        }
Exemple #26
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;
            foreach (KeyValuePair <string, string> header in headers)
            {
                httpRequest.Headers.Add(header.Key, header.Value);
            }
            if (logger.IsDebugEnabled)
            {
                foreach (string headerName in httpRequest.Headers)
                {
                    logger.Debug(headerName + ":" + httpRequest.Headers[headerName]);
                }
            }
            // Adding payLoad to HttpWebRequest object
            using (StreamWriter myWriter = new StreamWriter(httpRequest.GetRequestStream()))
            {
                myWriter.Write(payLoad);
                logger.Debug(payLoad);
            }

            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);
            }

            // Fire request. Retry if configured to do so
            int numRetries = (this.config.ContainsKey(BaseConstants.HTTP_CONNECTION_RETRY_CONFIG)) ?
                             Convert.ToInt32(config[BaseConstants.HTTP_CONNECTION_RETRY_CONFIG]) : 0;
            int retries = 0;

            do
            {
                try
                {
                    // Calling the plaftform API web service and getting the response
                    using (WebResponse response = httpRequest.GetResponse())
                    {
                        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                        {
                            responseString = sr.ReadToEnd();
                            logger.Debug("Service response");
                            logger.Debug(responseString);
                            return(responseString);
                        }
                    }
                }
                // Server responses in the range of 4xx and 5xx throw a WebException
                catch (WebException we)
                {
                    HttpStatusCode statusCode = ((HttpWebResponse)we.Response).StatusCode;

                    logger.Info("Got " + statusCode.ToString() + " response from server");
                    if (!RequiresRetry(we))
                    {
                        throw new ConnectionException("Invalid HTTP response " + we.Message);
                    }
                }
                catch (System.Exception ex)
                {
                    throw ex;
                }
            } while (retries++ < numRetries);
            throw new ConnectionException("Invalid HTTP response");
        }