示例#1
0
        public JToken ExecuteGenericRequest(
            HttpMethod httpMethod,
            string path,
            PayloadType payloadType,
            JObject payload, SDK sdk)
        {
            if (sdk.GetAccessToken() != null)
            {
                path = sdk.BaseUrl + path + "?access_token=" + sdk.GetAccessToken();
            }
            MPRequest request = this.CreateRequest(httpMethod, path, payloadType, payload, (WebHeaderCollection)null, 0, 0);

            if (((IEnumerable <HttpMethod>) new HttpMethod[2]
            {
                HttpMethod.POST,
                HttpMethod.PUT
            }).Contains <HttpMethod>(httpMethod))
            {
                Stream requestStream = request.Request.GetRequestStream();
                requestStream.Write(request.RequestPayload, 0, request.RequestPayload.Length);
                requestStream.Close();
            }
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.Request.GetResponse())
                    return(JToken.Parse(new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd()));
            }
            catch (WebException ex)
            {
                return(JToken.Parse(new StreamReader((ex.Response as HttpWebResponse).GetResponseStream(), Encoding.UTF8).ReadToEnd()));
            }
        }
示例#2
0
        /// <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>
        /// <returns>Processed path to call the API.</returns>
        public static string ParsePath <T>(string path, Dictionary <string, string> mapParams, T resource) where T : MPBase
        {
            StringBuilder result = new StringBuilder();

            bool search = !path.Contains(':') && mapParams != null && mapParams.Any();

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


            // URL
            result.Insert(0, SDK.BaseUrl);

            result.Append(path);

            // Access Token
            string accessToken = SDK.GetAccessToken();

            if (!string.IsNullOrEmpty(accessToken))
            {
                result.Append(string.Format("{0}{1}", "?access_token=", accessToken));
            }

            if (search) //search url format, no :id type. Params after access_token
            {
                foreach (var elem in mapParams)
                {
                    result.Append(string.Format("{0}{1}={2}", "&", elem.Key, elem.Value));
                }
            }

            return(result.ToString());
        }
        internal static string CreatePath(string path, string accessToken, Dictionary <string, string> queryParameters)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new MPException("Must specify a valid path.");
            }

            var queryString =
                queryParameters != null
                    ? "&" + string.Join("&", queryParameters.Select(x => $"{x.Key}={x.Value}"))
                    : "";

            return($"{SDK.BaseUrl}{path}?access_token={accessToken ?? SDK.GetAccessToken()}{queryString}");
        }
示例#4
0
        public JToken ExecuteGenericRequest(
            HttpMethod httpMethod,
            string path,
            PayloadType payloadType,
            JObject payload)
        {
            WebHeaderCollection header = new WebHeaderCollection();

            if (SDK.GetAccessToken() != null)
            {
                if (!path.Contains("/oauth/token"))
                {
                    header.Add("Authorization", String.Format("Bearer {0}", SDK.GetAccessToken()));
                }

                path = SDK.BaseUrl + path;
            }

            MPRequest mpRequest = CreateRequest(httpMethod, path, payloadType, payload, header, 0, 0);

            if (new HttpMethod[] { HttpMethod.POST, HttpMethod.PUT }.Contains(httpMethod))
            {
                Stream requestStream = mpRequest.Request.GetRequestStream();
                requestStream.Write(mpRequest.RequestPayload, 0, mpRequest.RequestPayload.Length);
                requestStream.Close();
            }

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)mpRequest.Request.GetResponse())
                {
                    Stream       dataStream     = response.GetResponseStream();
                    StreamReader reader         = new StreamReader(dataStream, Encoding.UTF8);
                    String       StringResponse = reader.ReadToEnd();
                    return(JToken.Parse(StringResponse));
                }
            }
            catch (WebException ex)
            {
                HttpWebResponse errorResponse  = ex.Response as HttpWebResponse;
                Stream          dataStream     = errorResponse.GetResponseStream();
                StreamReader    reader         = new StreamReader(dataStream, Encoding.UTF8);
                String          StringResponse = reader.ReadToEnd();
                return(JToken.Parse(StringResponse));
            }
        }
示例#5
0
        public JToken ExecuteGenericRequest(
            HttpMethod httpMethod,
            string path,
            PayloadType payloadType,
            JObject payload)
        {
            if (SDK.GetAccessToken() != null)
            {
                path = SDK.BaseUrl + path + "?access_token=" + SDK.GetAccessToken();
            }

            MPRequest mpRequest = CreateRequest(httpMethod, path, payloadType, payload, null, 0, 0);

            if (new HttpMethod[] { HttpMethod.POST, HttpMethod.PUT }.Contains(httpMethod))
            {
                Stream requestStream = mpRequest.Request.GetRequestStream();
                requestStream.Write(mpRequest.RequestPayload, 0, mpRequest.RequestPayload.Length);
                requestStream.Close();
            }

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)mpRequest.Request.GetResponse())
                {
                    Stream dataStream = response.GetResponseStream();
                    StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
                    String StringResponse = reader.ReadToEnd();
                    return JToken.Parse(StringResponse);
                }

            }
            catch (WebException ex)
            {
                HttpWebResponse errorResponse = ex.Response as HttpWebResponse;
                Stream dataStream = errorResponse.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
                String StringResponse = reader.ReadToEnd();
                return JToken.Parse(StringResponse);
            }

        }
示例#6
0
        /// <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);
                        }
                    }
                }

                if (resource != null)
                {
                    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) && !path.Equals("/oauth/token", StringComparison.InvariantCultureIgnoreCase))
            {
                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();
        }
示例#7
0
        public static string ParsePath <T>(
            string path,
            Dictionary <string, string> mapParams,
            T resource, SDK sdk)
            where T : MPBase
        {
            StringBuilder stringBuilder = new StringBuilder();
            bool          flag          = !path.Contains <char>(':') && mapParams != null && mapParams.Any <KeyValuePair <string, string> >();
            string        pattern       = ":([a-z0-9_]+)";

            foreach (Match match in Regex.Matches(path, pattern))
            {
                string text = match.Value.Replace(":", "");
                if (mapParams != null)
                {
                    foreach (KeyValuePair <string, string> mapParam in mapParams)
                    {
                        if (text == mapParam.Key)
                        {
                            path = path.Replace(match.Value, mapParam.Value);
                        }
                    }
                }
                JToken jtoken = JObject.FromObject((object)resource).GetValue(MPBase.ToPascalCase(text));
                if (jtoken != null)
                {
                    path = path.Replace(match.Value, jtoken.ToString());
                }
            }
            stringBuilder.Insert(0, sdk.BaseUrl);
            stringBuilder.Append(path);
            string str = (object)resource != null ? (!string.IsNullOrEmpty(resource.MarketplaceAccessToken) ? resource.MarketplaceAccessToken : sdk.GetAccessToken()) : sdk.GetAccessToken();

            Console.Out.WriteLine("STOP");
            if (!string.IsNullOrEmpty(str))
            {
                stringBuilder.Append(string.Format("{0}{1}", (object)"?access_token=", (object)str));
            }
            if (flag)
            {
                foreach (KeyValuePair <string, string> mapParam in mapParams)
                {
                    stringBuilder.Append(string.Format("{0}{1}={2}", (object)"&", (object)mapParam.Key, (object)mapParam.Value));
                }
            }
            return(stringBuilder.ToString());
        }
示例#8
0
        /// <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;
            }

            if (!path.Contains("/oauth/token"))
            {
                mpRequest.Request.Headers.Add("Authorization", String.Format("Bearer {0}", !string.IsNullOrEmpty(requestOptions.AccessToken) ? requestOptions.AccessToken : SDK.GetAccessToken()));
            }

            mpRequest.Request.Headers.Add("x-product-id", SDK.ProductId);
            mpRequest.Request.Headers.Add("x-tracking-id", SDK.TrackingId);

            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 (requestOptions.TrackHeaders != null)
            {
                foreach (var trackHeader in requestOptions.TrackHeaders)
                {
                    if (mpRequest.Request.Headers[trackHeader.Key] == null && trackHeader.Value != null)
                    {
                        mpRequest.Request.Headers[trackHeader.Key] = trackHeader.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);

            mpRequest.Request.Proxy = proxy;

            return(mpRequest);
        }
示例#9
0
        /// <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>
        /// <returns>Processed path to call the API.</returns>
        public static string ParsePath <T>(string path, Dictionary <string, string> mapParams, T resource) where T : MPBase
        {
            StringBuilder result = new StringBuilder();
            bool          search = !path.Contains(':') && mapParams != null && mapParams.Any();

            if (path.Contains(':'))
            {
                int paramIterator = 0;
                while (path.Contains(':'))
                {
                    result.Append(path.Substring(0, path.IndexOf(':')));
                    path = path.Substring(path.IndexOf(':') + 1);
                    string param = path;
                    if (path.Contains('/'))
                    {
                        param = path.Substring(0, path.IndexOf('/'));
                    }

                    string value = string.Empty;
                    if (paramIterator <= 2 &&
                        mapParams != null &&
                        !string.IsNullOrEmpty(mapParams[string.Format("param{0}", paramIterator.ToString())]))
                    {
                        value = mapParams[string.Format("param{0}", paramIterator.ToString())];
                    }
                    else if (mapParams != null &&
                             !string.IsNullOrEmpty(mapParams[param]))
                    {
                        value = mapParams[param];
                    }
                    else
                    {
                        if (resource != null)
                        {
                            var newResource = resource;
                            newResource._lastApiResponse = null;

                            JObject json = JObject.FromObject(newResource);

                            var jValuePC = json.GetValue(ToPascalCase(param));

                            if (jValuePC != null)
                            {
                                value = jValuePC.ToString();
                            }
                        }
                    }

                    if (string.IsNullOrEmpty(value))
                    {
                        throw new MPException("No argument supplied/found for path argument");
                    }
                    if (path.Contains('/'))
                    {
                        path = path.Substring(path.IndexOf('/'));
                    }
                    else
                    {
                        path = string.Empty;
                    }

                    result.Append(value);
                }

                if (!string.IsNullOrEmpty(path))
                {
                    result.Append(path);
                }
            }
            else
            {
                result.Append(path);
            }

            // URL
            result.Insert(0, SDK.BaseUrl);

            // Access Token
            string accessToken = SDK.GetAccessToken();

            if (!string.IsNullOrEmpty(accessToken))
            {
                result.Append(string.Format("{0}{1}", "?access_token=", accessToken));
            }

            if (search) //search url format, no :id type. Params after access_token
            {
                foreach (var elem in mapParams)
                {
                    result.Append(string.Format("{0}{1}={2}", "&", elem.Key, elem.Value));
                }
            }

            return(result.ToString());
        }