public static List <JToken> FindTokens(this JToken containerToken, string name) { List <JToken> matches = new List <JToken>(); MPCoreUtils.FindTokens(containerToken, name, matches); return(matches); }
private static void FindTokens(JToken containerToken, string name, List <JToken> matches) { if (containerToken.Type == JTokenType.Object) { foreach (JProperty child in containerToken.Children <JProperty>()) { if (child.Name == name) { matches.Add(child.Value); } MPCoreUtils.FindTokens(child.Value, name, matches); } } else { if (containerToken.Type != JTokenType.Array) { return; } foreach (JToken child in containerToken.Children()) { MPCoreUtils.FindTokens(child, name, matches); } } }
protected static T ProcessMethod <T>( Type clazz, T resource, string methodName, Dictionary <string, string> parameters, bool useCache, SDK sdk) where T : MPBase { if ((object)resource == null) { try { resource = (T)Activator.CreateInstance(clazz, sdk); } catch (Exception ex) { throw new MPException(ex.Message); } } Dictionary <string, object> restInformation = MPBase.GetRestInformation(MPBase.GetAnnotatedMethod(clazz, methodName)); HttpMethod httpMethod = (HttpMethod)restInformation["method"]; string path = MPBase.ParsePath <T>(restInformation["path"].ToString(), parameters, resource, sdk); PayloadType payloadType = (PayloadType)restInformation["payloadType"]; JObject payload = MPBase.GeneratePayload <T>(httpMethod, resource); int requestTimeout = (int)restInformation["requestTimeout"]; int retries = (int)restInformation["retries"]; WebHeaderCollection colHeaders = new WebHeaderCollection(); MPAPIResponse response = MPBase.CallAPI(httpMethod, path, payloadType, payload, colHeaders, useCache, requestTimeout, retries); if (response.StatusCode >= 200 && response.StatusCode < 300) { if (httpMethod != HttpMethod.DELETE) { resource = (T)MPBase.FillResourceWithResponseData <T>(resource, response); resource._lastApiResponse = response; } else { resource = default(T); } } else if (response.StatusCode >= 400 && response.StatusCode < 500) { BadParamsError badParamsError = MPCoreUtils.GetBadParamsError(response.StringResponse); resource.Errors = new BadParamsError?(badParamsError); } else { MPException mpException = new MPException() { StatusCode = new int?(response.StatusCode), ErrorMessage = response.StringResponse, Cause = { response.JsonObjectResponse.ToString() } }; } return(resource); }
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; }
protected static List <T> FillArrayWithResponseData <T>(Type clazz, MPAPIResponse response) where T : MPBase { List <T> objList = new List <T>(); if (response.JsonObjectResponse != null) { JArray arrayFromJsonElement = MPCoreUtils.GetArrayFromJsonElement <T>(response.JsonObjectResponse); if (arrayFromJsonElement != null) { for (int index = 0; index < arrayFromJsonElement.Count <JToken>(); ++index) { T resourceFromJson = (T)MPCoreUtils.GetResourceFromJson <T>(clazz, (JObject)arrayFromJsonElement[index]); //resourceFromJson.DumpLog(); resourceFromJson._lastKnownJson = MPCoreUtils.GetJsonFromResource <T>(resourceFromJson); objList.Add(resourceFromJson); } } } else { JArray fromStringResponse = MPCoreUtils.GetJArrayFromStringResponse <T>(response.StringResponse); if (fromStringResponse != null) { for (int index = 0; index < fromStringResponse.Count <JToken>(); ++index) { T resourceFromJson = (T)MPCoreUtils.GetResourceFromJson <T>(clazz, (JObject)fromStringResponse[index]); resourceFromJson._lastKnownJson = MPCoreUtils.GetJsonFromResource <T>(resourceFromJson); objList.Add(resourceFromJson); } } } return(objList); }
/// <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> /// <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) 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"]; string path = ParsePath(restData["path"].ToString(), parameters, resource); PayloadType payloadType = (PayloadType)restData["payloadType"]; JObject payload = GeneratePayload(httpMethod, resource); int requestTimeout = (int)restData["requestTimeout"]; int retries = (int)restData["retries"]; WebHeaderCollection colHeaders = new WebHeaderCollection(); MPAPIResponse response = CallAPI(httpMethod, path, payloadType, payload, colHeaders, useCache, requestTimeout, retries); 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()); } return(resource); }
/// <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); }
public static JObject GeneratePayload <T>(HttpMethod httpMethod, T resource) where T : MPBase { if (httpMethod.ToString() == "PUT") { return(MPBase.getDiffFromLastChange((JToken)MPCoreUtils.GetJsonFromResource <T>(resource), (JToken)resource.GetLastKnownJson())); } if (httpMethod.ToString() == "POST") { return(MPCoreUtils.GetJsonFromResource <T>(resource)); } return((JObject)null); }
protected static MPBase FillResourceWithResponseData <T>( T resource, MPAPIResponse response) where T : MPBase { if (response.JsonObjectResponse != null && response.JsonObjectResponse != null) { JObject jsonObjectResponse = response.JsonObjectResponse; resource = (T)MPBase.FillResource <T>((T)MPCoreUtils.GetResourceFromJson <T>(resource.GetType(), jsonObjectResponse), resource); resource._lastKnownJson = MPCoreUtils.GetJsonFromResource <T>(resource); } return((MPBase)resource); }
/// <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() == "POST" || httpMethod.ToString() == "PUT") { JObject actualJSON = MPCoreUtils.GetJsonFromResource(resource); JObject oldJSON = resource.GetLastKnownJson(); return(getDiffFromLastChange(actualJSON, oldJSON)); } else { return(null); } }
/// <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; }
/// <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); }
internal static void ProcessResponse(string path, T resource, MPAPIResponse response, HttpMethod httpMethod) { var errorDetails = response.JsonObjectResponse?.ToString() ?? response.StringResponse ?? "[No additional details could be retrieved from the response]"; var errorMessage = $"HTTP {httpMethod} request to Endpoint '{path}' with payload of type '{typeof(T).Name}' resulted in an unsuccessful HTTP response with status code {response.StatusCode}.\r\nDetails:\r\n{errorDetails}"; if (response.StatusCode >= 200 && response.StatusCode < 300) { if (httpMethod != HttpMethod.DELETE) { FillResourceWithResponseData(resource, response); } } else if (response.StatusCode >= 400 && response.StatusCode < 500) { var badParamsError = MPCoreUtils.GetBadParamsError(response.StringResponse); var exception = new MPException(errorMessage) { Error = badParamsError, ErrorMessage = badParamsError.ToString() }; throw exception; } else { var exception = new MPException(errorMessage) { StatusCode = response.StatusCode, ErrorMessage = response.StringResponse, Cause = { errorDetails } }; throw exception; } }