コード例 #1
0
        protected static List <T> ProcessMethodBulk <T>(
            Type clazz,
            string methodName,
            Dictionary <string, string> mapParams,
            bool useCache, SDK sdk)
            where T : MPBase
        {
            if (!MPBase.ALLOWED_BULK_METHODS.Contains(methodName))
            {
                throw new MPException("Method \"" + methodName + "\" not allowed");
            }
            List <T> objList1 = new List <T>();
            Dictionary <string, object> restInformation = MPBase.GetRestInformation(MPBase.GetAnnotatedMethod(clazz, methodName));
            HttpMethod httpMethod     = (HttpMethod)restInformation["method"];
            T          resource       = default(T);
            string     path           = MPBase.ParsePath <T>(restInformation["path"].ToString(), mapParams, resource, sdk);
            int        retries        = (int)restInformation["retries"];
            int        requestTimeout = (int)restInformation["requestTimeout"];

            Console.WriteLine("Path: {0}", (object)path);
            PayloadType         payloadType     = (PayloadType)restInformation["payloadType"];
            WebHeaderCollection standardHeaders = MPBase.GetStandardHeaders();
            MPAPIResponse       response        = MPBase.CallAPI(httpMethod, path, payloadType, (JObject)null, standardHeaders, useCache, requestTimeout, retries);
            List <T>            objList2        = new List <T>();

            if (response.StatusCode >= 200 && response.StatusCode < 300)
            {
                objList2 = MPBase.FillArrayWithResponseData <T>(clazz, response);
            }
            return(objList2);
        }
コード例 #2
0
        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);
        }
コード例 #3
0
ファイル: MPBase.cs プロジェクト: ulili5/dx-dotnet
        /// <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);
        }
コード例 #4
0
ファイル: MPBase.cs プロジェクト: fritzen/dx-dotnet
        /// <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);
        }
コード例 #5
0
ファイル: MPBase.cs プロジェクト: mrdemarchi/dx-dotnet
        protected static List <T> ProcessMethodBulk <T>(Type clazz, string methodName, Dictionary <string, string> mapParams, bool useCache) where T : MPBase
        {
            //Validates the method executed
            if (!ALLOWED_BULK_METHODS.Contains(methodName))
            {
                throw new MPException("Method \"" + methodName + "\" not allowed");
            }

            List <T> resourcesList = new List <T>();

            var        annotatedMethod   = GetAnnotatedMethod(clazz, methodName);
            var        hashAnnotation    = GetRestInformation(annotatedMethod);
            HttpMethod httpMethod        = (HttpMethod)hashAnnotation["method"];
            T          resource          = null;
            string     path              = ParsePath(hashAnnotation["path"].ToString(), mapParams, resource);
            int        retries           = (int)hashAnnotation["retries"];
            int        connectionTimeout = (int)hashAnnotation["requestTimeout"];

            Console.WriteLine("Path: {0}", path);
            PayloadType         payloadType = (PayloadType)hashAnnotation["payloadType"];
            WebHeaderCollection colHeaders  = GetStandardHeaders();

            MPAPIResponse response = CallAPI(httpMethod, path, payloadType, null, colHeaders, useCache, connectionTimeout, retries);

            List <T> resourceArray = new List <T>();

            if (response.StatusCode >= 200 &&
                response.StatusCode < 300)
            {
                resourceArray = FillArrayWithResponseData <T>(clazz, response);
            }

            return(resourceArray);
        }
コード例 #6
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;
        }
コード例 #7
0
        public static MPAPIResponse CallAPI(
            HttpMethod httpMethod,
            string path,
            PayloadType payloadType,
            JObject payload,
            WebHeaderCollection colHeaders,
            bool useCache,
            int requestTimeout,
            int retries)
        {
            string        key      = httpMethod.ToString() + "_" + path;
            MPAPIResponse response = (MPAPIResponse)null;

            if (useCache)
            {
                response = MPCache.GetFromCache(key);
                if (response != null)
                {
                    response.IsFromCache = true;
                }
            }
            if (response == null)
            {
                response = new MPRESTClient().ExecuteRequest(httpMethod, path, payloadType, payload, colHeaders, requestTimeout, retries);
                if (useCache)
                {
                    MPCache.AddToCache(key, response);
                }
                else
                {
                    MPCache.RemoveFromCache(key);
                }
            }
            return(response);
        }
コード例 #8
0
        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);
        }
コード例 #9
0
 internal static void FillResourceWithResponseData(T resource, MPAPIResponse response)
 {
     if (response.JsonObjectResponse is JObject jsonObject)
     {
         var result = jsonObject.Deserialize <T>();
         CopyProperties(result, resource);
         resource.LastKnownJson   = jsonObject;
         resource.LastApiResponse = response;
     }
 }
コード例 #10
0
 /// <summary>
 /// Adds a response to the cache structure.
 /// </summary>
 /// <param name="key">Key representing the URL.</param>
 /// <param name="response">Response representing the response of the given URL parameter.</param>
 public static void AddToCache(string key, MPAPIResponse response)
 {
     try
     {
     }
     catch (Exception ex)
     {
         throw new MPException("An error has occured in the cache structure (ADD): " + ex.Message);
     }
 }
コード例 #11
0
 private static void TryAddToCache(bool useCache, string cacheKey, MPAPIResponse response)
 {
     if (useCache)
     {
         MPCache.AddToCache(cacheKey, response);
     }
     else
     {
         MPCache.RemoveFromCache(cacheKey);
     }
 }
コード例 #12
0
ファイル: MPCache.cs プロジェクト: fritzen/dx-dotnet
 /// <summary>
 /// Adds a response to the cache structure.
 /// </summary>
 /// <param name="key">Key representing the URL.</param>
 /// <param name="response">Response representing the response of the given URL parameter.</param>
 public static void AddToCache(string key, MPAPIResponse response)
 {
     try
     {
         HttpRuntime.Cache.Add(key, response, null, DateTime.MaxValue, new TimeSpan(0, 1, 0), System.Web.Caching.CacheItemPriority.Default, null);
     }
     catch (Exception ex)
     {
         throw new MPException("An error has occured in the cache structure (ADD): " + ex.Message);
     }
 }
コード例 #13
0
 public static void AddToCache(string key, MPAPIResponse response)
 {
     try
     {
         // HttpRuntime.Cache.Add(key, (object) response, (CacheDependency) null, DateTime.MaxValue, new TimeSpan(0, 1, 0), CacheItemPriority.Normal, (CacheItemRemovedCallback) null);
         CacheItemDictionary <string, object> cache = new CacheItemDictionary <string, object>();
         cache.Add(key, (object)response);
     }
     catch (Exception ex)
     {
         throw new MPException("An error has occured in the cache structure (ADD): " + ex.Message);
     }
 }
コード例 #14
0
 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);
 }
コード例 #15
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;
        }
コード例 #16
0
        private static MPAPIResponse TryGetFromCache(bool useCache, string cacheKey)
        {
            MPAPIResponse response = null;

            if (useCache)
            {
                response = MPCache.GetFromCache(cacheKey);

                if (response != null)
                {
                    response.IsFromCache = true;
                }
            }

            return(response);
        }
コード例 #17
0
ファイル: MPBase.cs プロジェクト: miguelgimenez/dx-dotnet
        /// <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);
        }
コード例 #18
0
        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;
            }
        }
コード例 #19
0
        public static List <T> ToList <T>(this MPAPIResponse response) where T : ResourceBase
        {
            var result = new List <T>();

            var jsonArray =
                response.JsonObjectResponse != null
                    ? GetArrayFromJsonElement(response.JsonObjectResponse)
                    : JArray.Parse(response.StringResponse);

            if (jsonArray != null)
            {
                foreach (var jObject in jsonArray.OfType <JObject>())
                {
                    //TODO: Por que esto deserializa y serializa de nuevo?
                    T resource = jObject.Deserialize <T>();
                    resource.LastKnownJson = resource.Serialize();
                    result.Add(resource);
                }
            }

            return(result);
        }
コード例 #20
0
        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);
        }