Beispiel #1
0
        private static async Task <string> CallServiceAsync(Format restType, RestMethod restConstant, string authorizationHeader, Uri requestUri, string serializedParameters, string TransactionKey = "",
                                                            Guid?identityWorkID = null, Guid?instanceID = null)
        {
            HttpClient client = new HttpClient();

            client.Timeout = TimeSpan.FromMinutes(40);
            string result = string.Empty;

            ConfigureEndPoints(requestUri);
            HttpRequestMessage reqmsg = new HttpRequestMessage();

            reqmsg.RequestUri = requestUri;
            reqmsg.Method     = new HttpMethod(restConstant.ToString("g"));
            reqmsg.Headers.TryAddWithoutValidation(ServiceHelperConstants.authorizationHeaderTitle, authorizationHeader);
            reqmsg.Headers.TryAddWithoutValidation(ServiceHelperConstants.transactionHeaderTitle, TransactionKey);

            if (identityWorkID != null)
            {
                reqmsg.Headers.TryAddWithoutValidation("companyid", identityWorkID.ToString());
            }
            if (instanceID != null)
            {
                reqmsg.Headers.TryAddWithoutValidation("instanceid", instanceID.ToString());
            }

            if (reqmsg.Method == HttpMethod.Post || reqmsg.Method == HttpMethod.Put)
            {
                reqmsg.Content = new StringContent(serializedParameters, Encoding.UTF8, resolveContentType(restType));
            }
            var response = await client.SendAsync(reqmsg, HttpCompletionOption.ResponseContentRead);

            result = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                if (!String.IsNullOrEmpty(result))
                {
                    try
                    {
                        var contentHelper = Newtonsoft.Json.JsonConvert.DeserializeObject <ContentHelper>(result);
                        manageWebException(contentHelper);
                    }
                    catch (Newtonsoft.Json.JsonReaderException ex)
                    {
                        throw new CallRestException().getDefault(ex.TargetSite, result, (int)response.StatusCode);
                    }
                }
                else
                {
                    throw new CallRestException().getDefault(MethodBase.GetCurrentMethod(), "No se pudo conectar al servicio.", (int)response.StatusCode);
                }
            }
            else
            {
                result = await response.Content.ReadAsStringAsync();
            }
            return(result);
        }
Beispiel #2
0
        public async Task <RestResponse> SendAsync(RestMethod method, string url = null, string value = null)
        {
            url = url.TrimStart('/');

            HttpMethod m = new HttpMethod(method.ToString().ToUpper());

            using (HttpRequestMessage msg = new HttpRequestMessage(m, url))
            {
                if (!string.IsNullOrWhiteSpace(value))
                {
                    msg.Content = new StringContent(value, Encoding.UTF8, "application/json");
                }

                return(await SendAsync(msg));
            }
        }
        private async Task <CFDIWrapperResult> CallServiceAsync(Format restType,
                                                                RestMethod restConstant, string token, Uri requestUri,
                                                                string serializedParameters)
        {
            CFDIWrapperResult cFDIWrapperResult = new CFDIWrapperResult()
            {
                status = "400", detail = "Error no controlado"
            };
            HttpClient client = new HttpClient();

            client.Timeout = TimeSpan.FromMinutes(40);
            string result = string.Empty;

            ConfigureEndPoints(requestUri);
            HttpRequestMessage reqmsg = new HttpRequestMessage();

            reqmsg.RequestUri = requestUri;
            reqmsg.Method     = new HttpMethod(restConstant.ToString("g"));
            reqmsg.Headers.TryAddWithoutValidation("token", token);

            if (reqmsg.Method == HttpMethod.Post || reqmsg.Method == HttpMethod.Put)
            {
                reqmsg.Content = new StringContent(serializedParameters, Encoding.UTF8, resolveContentType(restType));
            }
            var response = await client.SendAsync(reqmsg, HttpCompletionOption.ResponseContentRead);

            result = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                if (!String.IsNullOrEmpty(result))
                {
                    cFDIWrapperResult = JsonConvert.DeserializeObject <CFDIWrapperResult>(result);
                }
                else
                {
                    throw new CotorraException(1000, "1000", "No se pudo conectar al servicio.", null);
                }
            }
            else
            {
                cFDIWrapperResult.detail = await response.Content.ReadAsStringAsync();
            }

            return(cFDIWrapperResult);
        }
Beispiel #4
0
        private HttpCall ExecuteSync()
        {
            if (Executed)
            {
                throw new System.InvalidOperationException("A HttpCall can only be executed once");
            }

            _allDone = new ManualResetEvent(false);
            _request = (HttpWebRequest)HttpWebRequest.Create(_url);

            // Setting method
            _request.Method = _method.ToString();

            // Setting header
            if (_headers != null)
            {
                foreach (KeyValuePair <string, string> item in _headers)
                {
                    _request.Headers[item.Key] = item.Value;
                }
            }

            if (_method == RestMethod.GET || _method == RestMethod.HEAD || _method == RestMethod.DELETE)
            {
                // Start the asynchronous operation to get the response
                _request.BeginGetResponse(new AsyncCallback(GetResponseCallback), null);
            }
            else if (_method == RestMethod.POST || _method == RestMethod.PUT || _method == RestMethod.PATCH)
            {
                // Setting content type
                _request.ContentType = _contentType.MimeType();

                // Start the asynchronous operation to send the request body
                _request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), null);
            }

            // Keep the thread from continuing while the asynchronous
            _allDone.WaitOne();

            return(this);
        }
Beispiel #5
0
        private T FetchRESTResponse <T>(ServiceType serviceType, RestMethod methodType,
                                        string clientUrl, string resourceUrl, Dictionary <string, string> headerList, bool addDirectToBody,
                                        Dictionary <string, string> parametersList, Object parametersObj)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            string jStr = string.Empty;

            try
            {
                string postData = string.Empty;

                if (parametersList != null)
                {
                    StringBuilder updatedParameterList = new StringBuilder();
                    foreach (var key in parametersList.Keys)
                    {
                        if (!string.IsNullOrEmpty(updatedParameterList.ToString()))
                        {
                            updatedParameterList.Append("&");
                        }

                        updatedParameterList.Append(string.Format("{0}={1}", key, parametersList[key]));
                    }

                    if (!string.IsNullOrEmpty(updatedParameterList.ToString()))
                    {
                        postData = updatedParameterList.ToString();
                    }

                    postData = (!string.IsNullOrEmpty(postData) ? string.Format("{0}{1}", "?", postData) : string.Empty);
                }
                else if (parametersObj != null)
                {
                    if (serviceType != ServiceType.XML)
                    {
                        postData = Newtonsoft.Json.JsonConvert.SerializeObject(parametersObj);
                    }
                    else
                    {
                        postData = SafeTypeHelper.SafeString(parametersObj);
                    }
                }

                if (serviceType != ServiceType.DEFAULT_OAUTH)
                {
                    if (serviceType == ServiceType.SOA || methodType == RestMethod.GET || (methodType == RestMethod.POST && parametersList != null) ||
                        (methodType == RestMethod.GET && parametersObj != null))
                    {
                        if (methodType == RestMethod.GET && parametersObj != null)
                        {
                            HttpWebRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(string.Format("{0}{1}/{2}/", clientUrl, resourceUrl, SafeTypeHelper.SafeString(parametersObj))));
                        }
                        else
                        {
                            HttpWebRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(string.Format("{0}{1}{2}", clientUrl, resourceUrl, postData)));
                        }
                    }
                    else
                    {
                        HttpWebRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(string.Format("{0}{1}", clientUrl, resourceUrl)));
                    }
                }
                else
                {
                    HttpWebRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(string.Format("{0}{1}", clientUrl, resourceUrl)));
                }

                HttpWebRequest.ContentType = "application/json";
                if (serviceType == ServiceType.DEFAULT_OAUTH)
                {
                    HttpWebRequest.ContentType = "application/x-www-form-urlencoded";
                }
                if (serviceType == ServiceType.XML)
                {
                    HttpWebRequest.ContentType = "application/xml";
                    HttpWebRequest.Accept      = "application/xml";
                }

                if (RequestTimeout > 0)
                {
                    HttpWebRequest.Timeout = RequestTimeout;
                }
                if (headerList != null)
                {
                    foreach (var key in headerList.Keys)
                    {
                        HttpWebRequest.Headers.Add(key, headerList[key]);
                    }
                }

                if (serviceType == ServiceType.SOA)
                {
                    HttpWebRequest.Method = RestMethod.POST.ToString();
                }
                else
                {
                    HttpWebRequest.Method = methodType.ToString();
                    if (methodType != RestMethod.GET)
                    {
                        if (parametersList == null && !string.IsNullOrEmpty(postData) && serviceType != ServiceType.XML)
                        {
                            byte[] postArray = System.Text.Encoding.UTF8.GetBytes(postData);
                            HttpWebRequest.ContentLength = postArray.Length;
                            using (Stream reqStream = HttpWebRequest.GetRequestStream())
                            {
                                reqStream.Write(postArray, 0, postArray.Length);
                                reqStream.Close();
                            }
                        }
                        else
                        {
                            if ((serviceType == ServiceType.DEFAULT_OAUTH ||
                                 serviceType == ServiceType.XML) && !string.IsNullOrEmpty(postData))
                            {
                                postData = postData.TrimStart('?');

                                byte[] postArray = System.Text.Encoding.UTF8.GetBytes(postData);
                                if (serviceType == ServiceType.XML)
                                {
                                    postArray = System.Text.Encoding.ASCII.GetBytes(postData);
                                }

                                HttpWebRequest.ContentLength = postArray.Length;
                                using (Stream reqStream = HttpWebRequest.GetRequestStream())
                                {
                                    reqStream.Write(postArray, 0, postArray.Length);
                                    reqStream.Close();
                                }
                            }
                            else
                            {
                                HttpWebRequest.ContentLength = 0;
                            }
                        }
                    }
                }

                //get response
                HttpWebResponse = (HttpWebResponse)HttpWebRequest.GetResponse();
                using (StreamReader sr = new StreamReader(GetStreamForResponse(HttpWebResponse)))
                    jStr = sr.ReadToEnd();

                Type typeParameterType = typeof(T);
                if (!typeParameterType.Equals(typeof(string)))
                {
                    return(Newtonsoft.Json.JsonConvert.DeserializeObject <T>(jStr));
                }
                else
                {
                    return((T)(object)jStr);
                }
            }
            catch (WebException ex)
            {
                string errorMessage = string.Empty;
                if (ex.Response != null)
                {
                    HttpWebResponse = (HttpWebResponse)ex.Response;
                    using (var stream = GetStreamForResponse(ex.Response))
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            errorMessage = reader.ReadToEnd();
                        }
                    }
                }

                ClientError restException = new ClientError()
                {
                    StatusCode   = HttpWebResponse != null ? HttpWebResponse.StatusCode : HttpStatusCode.BadRequest,
                    InnerMessage = ex.Message,
                    Content      = errorMessage
                };
                throw new Exception(Newtonsoft.Json.JsonConvert.SerializeObject(restException));
            }
            catch (Exception ex)
            {
                ClientError restException = new ClientError()
                {
                    StatusCode   = HttpWebResponse != null ? HttpWebResponse.StatusCode : HttpStatusCode.BadRequest,
                    InnerMessage = ex.Message,
                    Content      = jStr
                };
                throw new Exception(Newtonsoft.Json.JsonConvert.SerializeObject(restException));
            }
        }
Beispiel #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="endpoint"></param>
        /// <param name="type"></param>
        /// <param name="restMethod"></param>
        /// <param name="middlewares"></param>
        private static void RegisterRestFunction(
            string endpoint,
            Type type,
            RestMethod restMethod,
            List <Action <FlimsyRouteContext> > middlewares)
        {
            var route = new FlimsyRoute {
                IsRestRoute         = true,
                RestType            = type,
                MiddlewareFunctions = middlewares
            };

            var method = type.GetMethod(restMethod.ToString());

            if (method == null)
            {
                return;
            }

            route.RestMethod         = method;
            route.RestMethodIsStatic = method.IsStatic;

            // Endpoint and HTTP method.
            switch (restMethod)
            {
            case RestMethod.GetAll:
                route.Endpoint   = endpoint;
                route.HttpMethod = HttpMethod.GET;

                break;

            case RestMethod.Get:
                route.Endpoint       = endpoint + "/{id}";
                route.HttpMethod     = HttpMethod.GET;
                route.RestHasIdParam = true;

                break;

            case RestMethod.Create:
                route.Endpoint            = endpoint;
                route.HttpMethod          = HttpMethod.POST;
                route.RestHasPayloadParam = true;

                break;

            case RestMethod.Update:
                route.Endpoint            = endpoint + "/{id}";
                route.HttpMethod          = HttpMethod.POST;
                route.RestHasIdParam      = true;
                route.RestHasPayloadParam = true;

                break;

            case RestMethod.Delete:
                route.Endpoint       = endpoint + "/{id}";
                route.HttpMethod     = HttpMethod.DELETE;
                route.RestHasIdParam = true;

                break;
            }

            route.EndpointSections = route.Endpoint.Split('/');

            // ReturnType
            if (method.ReturnType != typeof(void))
            {
                route.RestReturnType = method.ReturnType;
            }

            // Params
            var mparams = method.GetParameters();

            // Id param
            if (route.RestHasIdParam)
            {
                var found = false;

                foreach (var mparam in mparams)
                {
                    if (mparam.Name.ToLower() != "id")
                    {
                        continue;
                    }

                    found = true;
                    route.RestIdParamType = mparam.ParameterType;
                    break;
                }

                if (!found)
                {
                    throw new Exception(
                              string.Format(
                                  "Missing param 'id' in function {0}.{1}",
                                  route.RestType.ToString(),
                                  route.RestMethod.Name));
                }
            }

            // Payload param
            if (route.RestHasPayloadParam)
            {
                var found = false;

                foreach (var mparam in mparams)
                {
                    if (mparam.Name.ToLower() == "id")
                    {
                        continue;
                    }

                    if (mparam.ParameterType == typeof(FlimsyRouteContext))
                    {
                        route.RestHasContextParam = true;
                    }
                    else
                    {
                        found = true;
                        route.RestPayloadParamType = mparam.ParameterType;
                        break;
                    }
                }

                if (!found)
                {
                    throw new Exception(
                              string.Format(
                                  "Missing payload param in function {0}.{1}",
                                  route.RestType.ToString(),
                                  route.RestMethod.Name));
                }
            }

            // Route Context?
            foreach (var mparam in mparams)
            {
                if (mparam.ParameterType == typeof(FlimsyRouteContext))
                {
                    route.RestHasContextParam = true;
                }
            }

            // Done
            FlimsyRouteHandler.Routes.Add(route);
        }