Ejemplo n.º 1
0
        /// <summary>
        /// Gets access token for current ClientId and ClientSecret
        /// </summary>
        /// <returns>Access token.</returns>
        public static string GetAccessToken()
        {
            if (string.IsNullOrEmpty(SDK.ClientId) || string.IsNullOrEmpty(SDK.ClientSecret))
            {
                throw new MPException("\"client_id\" and \"client_secret\" can not be \"null\" when getting the \"access_token\"");
            }

            JObject jsonPayload = new JObject();

            jsonPayload.Add("grant_type", "client_credentials");
            jsonPayload.Add("client_id", SDK.ClientId);
            jsonPayload.Add("client_secret", SDK.ClientSecret);

            string        access_token, refresh_token = null;
            MPAPIResponse response = new MPRESTClient().ExecuteRequest(
                HttpMethod.POST,
                SDK.BaseUrl + "/oauth/token",
                PayloadType.X_WWW_FORM_URLENCODED,
                jsonPayload,
                null,
                0,
                0);

            JObject jsonResponse = JObject.Parse(response.StringResponse.ToString());

            if (response.StatusCode == 200)
            {
                List <JToken> accessTokenElem  = MPCoreUtils.FindTokens(jsonResponse, "access_token");
                List <JToken> refreshTokenElem = MPCoreUtils.FindTokens(jsonResponse, "refresh_token");

                if (accessTokenElem != null && accessTokenElem.Count == 1)
                {
                    access_token = accessTokenElem.First().ToString();
                }
                else
                {
                    throw new MPException("Can not retrieve the \"access_token\"");
                }

                // Making refresh token an optional param
                if (refreshTokenElem != null && refreshTokenElem.Count == 1)
                {
                    refresh_token    = refreshTokenElem.First().ToString();
                    SDK.RefreshToken = refresh_token;
                }
            }
            else
            {
                throw new MPException("Can not retrieve the \"access_token\"");
            }

            return(access_token);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Fills all the attributes members of the Resource obj.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="resource"></param>
        /// <param name="response"></param>
        /// <returns></returns>
        protected static MPBase FillResourceWithResponseData <T>(T resource, MPAPIResponse response) where T : MPBase
        {
            if (response.JsonObjectResponse != null &&
                response.JsonObjectResponse is JObject)
            {
                JObject jsonObject = null;

                jsonObject = (JObject)response.JsonObjectResponse;
                T resourceObject = (T)MPCoreUtils.GetResourceFromJson <T>(resource.GetType(), jsonObject);
                resource = (T)FillResource(resourceObject, resource);
                resource._lastKnownJson = MPCoreUtils.GetJsonFromResource(resource);
            }

            return(resource);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Transforms all attributes members of the instance in a JSON String. Only for POST and PUT methods.
 /// POST gets the full object in a JSON object.
 /// PUT gets only the differences with the last known state of the object.
 /// </summary>
 /// <returns>a JSON Object with the attributes members of the instance. Null for GET and DELETE methods</returns>
 public static JObject GeneratePayload <T>(HttpMethod httpMethod, T resource) where T : MPBase
 {
     if (httpMethod.ToString() == "PUT")
     {
         JObject actualJSON = MPCoreUtils.GetJsonFromResource(resource);
         JObject oldJSON    = resource.GetLastKnownJson();
         return(getDiffFromLastChange(actualJSON, oldJSON));
     }
     else if (httpMethod.ToString() == "POST")
     {
         return(MPCoreUtils.GetJsonFromResource(resource));
     }
     else
     {
         return(null);
     }
 }
Ejemplo n.º 4
0
        /// <summary>
        ///  Refreshes access token for current refresh token
        /// </summary>
        /// <returns>Refreshed access token</returns>
        public static string RefreshAccessToken()
        {
            if (string.IsNullOrEmpty(SDK.RefreshToken))
            {
                throw new MPException("\"RefreshToken\" can not be \"null\". Refresh access token could not be completed.");
            }

            JObject jsonPayload = new JObject();

            jsonPayload.Add("client_secret", SDK.ClientSecret);
            jsonPayload.Add("grant_type", "refresh_token");
            jsonPayload.Add("refresh_token", SDK.RefreshToken);

            string        new_access_token = null;
            MPAPIResponse response         = new MPRESTClient().ExecuteRequest(
                HttpMethod.POST,
                SDK.BaseUrl + "/oauth/token",
                PayloadType.X_WWW_FORM_URLENCODED,
                jsonPayload,
                null,
                0,
                0);

            JObject jsonResponse = JObject.Parse(response.StringResponse.ToString());

            if (response.StatusCode == 200)
            {
                List <JToken> accessTokenElem = MPCoreUtils.FindTokens(jsonResponse, "access_token");

                if (accessTokenElem != null && accessTokenElem.Count == 1)
                {
                    new_access_token = accessTokenElem.First().ToString();
                }
                else
                {
                    throw new MPException("Can not retrieve the new \"access_token\"");
                }
            }
            else
            {
                throw new MPException("Can not retrieve the new \"access_token\"");
            }

            return(new_access_token);
        }
Ejemplo n.º 5
0
        protected static List <T> FillArrayWithResponseData <T>(Type clazz, MPAPIResponse response) where T : MPBase
        {
            List <T> resourceArray = new List <T>();

            if (response.JsonObjectResponse != null)
            {
                JArray jsonArray = MPCoreUtils.GetArrayFromJsonElement <T>(response.JsonObjectResponse);

                if (jsonArray != null)
                {
                    for (int i = 0; i < jsonArray.Count(); i++)
                    {
                        T resource = (T)MPCoreUtils.GetResourceFromJson <T>(clazz, (JObject)jsonArray[i]);

                        resource.DumpLog();

                        resource._lastKnownJson = MPCoreUtils.GetJsonFromResource(resource);
                        resourceArray.Add(resource);
                    }
                }
            }
            else
            {
                JArray jsonArray = MPCoreUtils.GetJArrayFromStringResponse <T>(response.StringResponse);
                if (jsonArray != null)
                {
                    for (int i = 0; i < jsonArray.Count(); i++)
                    {
                        T resource = (T)MPCoreUtils.GetResourceFromJson <T>(clazz, (JObject)jsonArray[i]);
                        resource._lastKnownJson = MPCoreUtils.GetJsonFromResource(resource);
                        resourceArray.Add(resource);
                    }
                }
            }
            return(resourceArray);
        }
Ejemplo n.º 6
0
        /// <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);
        }