public Boolean ProcessMethodBool <T>(string methodName, bool useCache, MPRequestOptions requestOptions) where T : MPBase { Dictionary <string, string> mapParams = null; T resource = ProcessMethod <T>(this.GetType(), (T)this, methodName, mapParams, useCache, requestOptions); return(resource.Errors == null); }
/// <summary> /// Calls the api and returns an MPApiResponse. /// </summary> /// <returns>A MPAPIResponse object with the results.</returns> public static MPAPIResponse CallAPI( HttpMethod httpMethod, string path, PayloadType payloadType, JObject payload, bool useCache, MPRequestOptions requestOptions) { string cacheKey = httpMethod.ToString() + "_" + path; MPAPIResponse response = null; if (requestOptions == null) { requestOptions = new MPRequestOptions(); } if (response == null) { response = new MPRESTClient().ExecuteRequest( httpMethod, path, payloadType, payload, requestOptions); } return(response); }
/// <summary> /// Calls the api and returns an MPApiResponse. /// </summary> /// <returns>A MPAPIResponse object with the results.</returns> public static MPAPIResponse CallAPI( HttpMethod httpMethod, string path, PayloadType payloadType, JObject payload, WebHeaderCollection colHeaders, bool useCache, int requestTimeout, int retries) { var customHeaders = new Dictionary <String, String>(); foreach (var header in colHeaders) { customHeaders.Add(header.ToString(), colHeaders[header.ToString()]); } var requestOptions = new MPRequestOptions { Timeout = requestTimeout, Retries = retries, CustomHeaders = customHeaders }; return(CallAPI(httpMethod, path, payloadType, payload, useCache, requestOptions)); }
/// <summary> /// Retrieve a MPBase resource based on a specfic method and configuration. /// </summary> /// <param name="methodName">Name of the method we are trying to call.</param> /// <param name="useCache">Cache configuration.</param> /// <param name="requestOptions">Object containing the request options.</param> /// <returns>MPBase resource.</returns> public static MPBase ProcessMethod(string methodName, bool useCache, MPRequestOptions requestOptions) { Type classType = GetTypeFromStack(); AdmitIdempotencyKey(classType); Dictionary<string, string> mapParams = new Dictionary<string, string>(); return ProcessMethod<MPBase>(classType, null, methodName, mapParams, useCache, requestOptions); }
/// <summary> /// Execute a request to an api endpoint. /// </summary> /// <returns>Api response with the result of the call.</returns> public MPAPIResponse ExecuteRequest( HttpMethod httpMethod, string path, PayloadType payloadType, JObject payload, MPRequestOptions requestOptions) { if (requestOptions == null) { requestOptions = new MPRequestOptions(); } MPRequest mpRequest = CreateRequest(httpMethod, path, payloadType, payload, requestOptions); string result = string.Empty; int retriesLeft = requestOptions.Retries; if (new HttpMethod[] { HttpMethod.POST, HttpMethod.PUT }.Contains(httpMethod)) { using (Stream requestStream = mpRequest.Request.GetRequestStream()) { requestStream.Write(mpRequest.RequestPayload, 0, mpRequest.RequestPayload.Length); } } try { return(ExecuteRequest(mpRequest.Request, response => new MPAPIResponse(httpMethod, mpRequest.Request, payload, response), requestOptions.Retries)); } catch (Exception ex) { throw new MPRESTException(ex.Message); } }
/// <summary> /// Calls the api and returns an MPApiResponse. /// </summary> /// <returns>A MPAPIResponse object with the results.</returns> public static MPAPIResponse CallAPI( HttpMethod httpMethod, string path, PayloadType payloadType, JObject payload, bool useCache, MPRequestOptions requestOptions) { string cacheKey = httpMethod.ToString() + "_" + path; MPAPIResponse response = null; if (requestOptions == null) { requestOptions = new MPRequestOptions(); } if (useCache) { response = MPCache.GetFromCache(cacheKey); if (response != null) { response.IsFromCache = true; } } if (response == null) { response = new MPRESTClient().ExecuteRequest( httpMethod, path, payloadType, payload, requestOptions); if (useCache) { MPCache.AddToCache(cacheKey, response); } else { MPCache.RemoveFromCache(cacheKey); } } return(response); }
/// <summary> /// Execute a request to an api endpoint. /// </summary> /// <returns>Api response with the result of the call.</returns> public MPAPIResponse ExecuteRequest( HttpMethod httpMethod, string path, PayloadType payloadType, JObject payload, MPRequestOptions requestOptions) { DateTime start = DateTime.Now; if (requestOptions == null) { requestOptions = new MPRequestOptions(); } MPRequest mpRequest = CreateRequest(httpMethod, path, payloadType, payload, requestOptions); if (new HttpMethod[] { HttpMethod.POST, HttpMethod.PUT }.Contains(httpMethod)) { using (Stream requestStream = mpRequest.Request.GetRequestStream()) { requestStream.Write(mpRequest.RequestPayload, 0, mpRequest.RequestPayload.Length); } } try { Int32 retries; DateTime startRequest = DateTime.Now; var response = ExecuteRequest(mpRequest.Request, requestOptions.Retries, out retries); DateTime endRequest = DateTime.Now; // Send metrics SendMetrics(mpRequest.Request, response, retries, start, startRequest, endRequest); return(new MPAPIResponse(httpMethod, mpRequest.Request, payload, response)); } catch (Exception ex) { throw new MPRESTException(ex.Message); } }
protected static List <T> ProcessMethodBulk <T>(Type clazz, string methodName, Dictionary <string, string> mapParams, bool useCache, MPRequestOptions requestOptions) where T : MPBase { //Validates the method executed if (!ALLOWED_BULK_METHODS.Contains(methodName)) { throw new MPException("Method \"" + methodName + "\" not allowed"); } var annotatedMethod = GetAnnotatedMethod(clazz, methodName); var hashAnnotation = GetRestInformation(annotatedMethod); if (requestOptions == null) { int retries = (int)hashAnnotation["retries"]; int requestTimeout = (int)hashAnnotation["requestTimeout"]; requestOptions = new MPRequestOptions { Retries = retries, Timeout = requestTimeout }; } T resource = null; HttpMethod httpMethod = (HttpMethod)hashAnnotation["method"]; PayloadType payloadType = (PayloadType)hashAnnotation["payloadType"]; string path = ParsePath(hashAnnotation["path"].ToString(), mapParams, resource, requestOptions); JObject payload = (httpMethod == HttpMethod.POST || httpMethod == HttpMethod.PUT) ? new JObject() : null; MPAPIResponse response = CallAPI(httpMethod, path, payloadType, payload, useCache, requestOptions); List <T> resourceArray = new List <T>(); if (response.StatusCode >= 200 && response.StatusCode < 300) { resourceArray = FillArrayWithResponseData <T>(clazz, response); } return(resourceArray); }
public Customer Delete(MPRequestOptions requestOptions) { return((Customer)ProcessMethod <Customer>("Delete", WITHOUT_CACHE, requestOptions)); }
public static Customer FindById(string id, bool useCache, MPRequestOptions requestOptions) { return((Customer)ProcessMethod <Customer>("FindById", id, useCache, requestOptions)); }
public static List <Customer> Search(Dictionary <string, string> filters, bool useCache, MPRequestOptions requestOptions) { return((List <Customer>)ProcessMethodBulk <Customer>(typeof(Customer), "Search", filters, useCache, requestOptions)); }
/// <summary> /// Generates a final Path based on parameters in Dictionary and resource properties. /// </summary> /// <typeparam name="T">MPBase resource.</typeparam> /// <param name="path">Path we are processing.</param> /// <param name="mapParams">Collection of parameters that we will use to process the final path.</param> /// <param name="resource">Resource containing parameters values to include in the final path.</param> /// <param name="requestOptions">Object containing the request options.</param> /// <returns>Processed path to call the API.</returns> public static string ParsePath <T>(string path, Dictionary <string, string> mapParams, T resource, MPRequestOptions requestOptions) where T : MPBase { string param_pattern = @":([a-z0-9_]+)"; MatchCollection matches = Regex.Matches(path, param_pattern); foreach (Match param in matches) { string param_string = param.Value.Replace(":", ""); if (mapParams != null) { foreach (KeyValuePair <String, String> entry in mapParams) { if (param_string == entry.Key) { path = path.Replace(param.Value, entry.Value); } } } JObject json = JObject.FromObject(resource); var resource_value = json.GetValue(ToPascalCase(param_string)); if (resource_value != null) { path = path.Replace(param.Value, resource_value.ToString()); } } StringBuilder result = new StringBuilder(); result.Insert(0, SDK.BaseUrl); result.Append(path); if (requestOptions == null) { requestOptions = new MPRequestOptions(); } string accessToken; if (!String.IsNullOrEmpty(requestOptions.AccessToken)) { accessToken = requestOptions.AccessToken; } else if (resource != null && !String.IsNullOrEmpty(resource.MarketplaceAccessToken)) { accessToken = resource.MarketplaceAccessToken; } else { accessToken = SDK.GetAccessToken(); } if (!String.IsNullOrEmpty(accessToken)) { result.Append(string.Format("{0}{1}", "?access_token=", accessToken)); } bool search = !path.Contains(':') && mapParams != null && mapParams.Any(); if (search) //search url format, no :id type. Params after access_token { foreach (var elem in mapParams) { if (!string.IsNullOrEmpty(elem.Value)) { result.Append(string.Format("{0}{1}={2}", "&", elem.Key, elem.Value)); } } } return(result.ToString()); }
public static List<T> ProcessMethodBulk<T>(Type clazz, string methodName, string param1, bool useCache, MPRequestOptions requestOptions) where T : MPBase { Dictionary<string, string> mapParams = new Dictionary<string, string>(); mapParams.Add("param1", param1); return ProcessMethodBulk<T>(clazz, methodName, mapParams, useCache, requestOptions); }
/// <summary> /// Retrieve a MPBase resource based on a specfic method, parameters and configuration. /// </summary> /// <param name="methodName">Name of the method we are trying to call.</param> /// <param name="param">Parameters to use in the retrieve process.</param> /// <param name="useCache">Cache configuration.</param> /// <param name="requestOptions">Object containing the request options.</param> /// <returns>MPBase resource.</returns> public static MPBase ProcessMethod <T>(string methodName, string param, bool useCache, MPRequestOptions requestOptions) where T : MPBase { Type classType = GetTypeFromStack(); AdmitIdempotencyKey(classType); Dictionary <string, string> mapParams = new Dictionary <string, string>(); mapParams.Add("id", param); return(ProcessMethod <T>(classType, null, methodName, mapParams, useCache, requestOptions)); }
public static MPBase ProcessMethod <T>(Type clazz, string methodName, string param1, string param2, bool useCache, MPRequestOptions requestOptions) where T : MPBase { Dictionary <string, string> mapParams = new Dictionary <string, string>(); mapParams.Add("param0", param1); mapParams.Add("param1", param2); return(ProcessMethod <T>(clazz, null, methodName, mapParams, useCache, requestOptions)); }
public static List <T> ProcessMethodBulk <T>(Type clazz, string methodName, bool useCache, MPRequestOptions requestOptions) where T : MPBase { return(ProcessMethodBulk <T>(clazz, methodName, (Dictionary <string, string>)null, useCache, requestOptions)); }
public Boolean ProcessMethodBool<T>(string methodName, bool useCache, MPRequestOptions requestOptions) where T : MPBase { return ProcessMethodBool<T>(methodName, useCache, null, requestOptions); }
/// <summary> /// Create a request to use in the call to a certain endpoint. /// </summary> /// <returns>Api response with the result of the call.</returns> public MPRequest CreateRequest(HttpMethod httpMethod, string path, PayloadType payloadType, JObject payload, MPRequestOptions requestOptions) { if (string.IsNullOrEmpty(path)) { throw new MPRESTException("Uri can not be an empty string."); } if (httpMethod.Equals(HttpMethod.GET)) { if (payload != null) { throw new MPRESTException("Payload not supported for this method."); } } else if (httpMethod.Equals(HttpMethod.POST)) { //if (payload == null) //{ // throw new MPRESTException("Must include payload for this method."); //} } else if (httpMethod.Equals(HttpMethod.PUT)) { if (payload == null) { throw new MPRESTException("Must include payload for this method."); } } else if (httpMethod.Equals(HttpMethod.DELETE)) { if (payload != null) { throw new MPRESTException("Payload not supported for this method."); } } MPRequest mpRequest = new MPRequest(); mpRequest.Request = (HttpWebRequest)HttpWebRequest.Create(path); mpRequest.Request.Method = httpMethod.ToString(); if (requestOptions == null) { requestOptions = new MPRequestOptions(); } if (requestOptions.Timeout > 0) { mpRequest.Request.Timeout = requestOptions.Timeout; } //mpRequest.Request.Headers.Add("x-product-id", "BC32BHVTRPP001U8NHL0"); if (requestOptions.CustomHeaders != null) { foreach (var header in requestOptions.CustomHeaders) { if (mpRequest.Request.Headers[header.Key] == null) { mpRequest.Request.Headers.Add(header.Key, header.Value); } } } if (payload != null) // POST & PUT { byte[] data = null; if (payloadType != PayloadType.JSON) { var parametersDict = payload.ToObject <Dictionary <string, string> >(); StringBuilder parametersString = new StringBuilder(); parametersString.Append(string.Format("{0}={1}", parametersDict.First().Key, parametersDict.First().Value)); parametersDict.Remove(parametersDict.First().Key); foreach (var value in parametersDict) { parametersString.Append(string.Format("&{0}={1}", value.Key, value.Value.ToString())); } data = Encoding.ASCII.GetBytes(parametersString.ToString()); } else { data = Encoding.ASCII.GetBytes(payload.ToString()); } //mpRequest.Request.UserAgent = "MercadoPago DotNet SDK/" + SDK.Version; mpRequest.Request.ContentLength = data.Length; mpRequest.Request.ContentType = payloadType == PayloadType.JSON ? "application/json" : "application/x-www-form-urlencoded"; mpRequest.RequestPayload = data; } IWebProxy proxy = requestOptions.Proxy != null ? requestOptions.Proxy : (_proxy != null ? _proxy : SDK.Proxy); if (proxy != null) { mpRequest.Request.Proxy = proxy; } return(mpRequest); }
/// <summary> /// Core implementation of processMethod. Retrieves a generic type. /// </summary> /// <typeparam name="T">Generic type that will return.</typeparam> /// <param name="clazz">Type of Class we are using.</param> /// <param name="resource">Resource we will use and return in the implementation.</param> /// <param name="methodName">The name of the method we are trying to call.</param> /// <param name="parameters">Parameters to use in the process.</param> /// <param name="useCache">Cache configuration.</param> /// <param name="requestOptions">Object containing the request options.</param> /// <returns>Generic type object, containing information about retrieval process.</returns> protected static T ProcessMethod <T>(Type clazz, T resource, string methodName, Dictionary <string, string> parameters, bool useCache, MPRequestOptions requestOptions) where T : MPBase { if (resource == null) { try { resource = (T)Activator.CreateInstance(clazz); } catch (Exception ex) { throw new MPException(ex.Message); } } var clazzMethod = GetAnnotatedMethod(clazz, methodName); var restData = GetRestInformation(clazzMethod); HttpMethod httpMethod = (HttpMethod)restData["method"]; PayloadType payloadType = (PayloadType)restData["payloadType"]; JObject payload = GeneratePayload(httpMethod, resource); if (requestOptions == null) { int requestTimeout = (int)restData["requestTimeout"]; int retries = (int)restData["retries"]; requestOptions = new MPRequestOptions { Retries = retries, Timeout = requestTimeout }; } string path = ParsePath(restData["path"].ToString(), parameters, resource, requestOptions); MPAPIResponse response = CallAPI(httpMethod, path, payloadType, payload, useCache, requestOptions); if (response.StatusCode >= 200 && response.StatusCode < 300) { if (httpMethod != HttpMethod.DELETE) { resource = (T)FillResourceWithResponseData(resource, response); resource._lastApiResponse = response; } else { resource = null; } } else if (response.StatusCode >= 400 && response.StatusCode < 500) { BadParamsError badParamsError = MPCoreUtils.GetBadParamsError(response.StringResponse); resource.Errors = badParamsError; } else { MPException webserverError = new MPException() { StatusCode = response.StatusCode, ErrorMessage = response.StringResponse }; webserverError.Cause.Add(response.JsonObjectResponse.ToString()); throw webserverError; } return(resource); }