Esempio n. 1
0
        public AllInOneResponse <T> DoRequest <T>(AllInOneRequest request)
        {
            var response = DoRequest(request);

            if (response.HasError)
            {
                return new AllInOneResponse <T> {
                           code = response.code, message = response.message, ResponseString = response.ResponseString
                }
            }
            ;

            try
            {
                var result = _serializer.DeserializeObject <AllInOneResponse <T> >(response.ResponseString);

                result.ResponseString = response.ResponseString;
                return(result);
            }
            catch (Exception ex)
            {
                Logger.LoggerManager.LogException(ex, response.ResponseString);
                throw;
            }
        }
Esempio n. 2
0
        public async Task <AllInOneResponse <T> > DoRequestAsync <T>(AllInOneRequest request)
        {
            var response = await DoRequestAsync(request);

            var TObject = _serializer.DeserializeObject <AllInOneResponse <T> >(response.ResponseString);

            return(TObject);
        }
Esempio n. 3
0
 protected void AppendLanguageHeader(AllInOneRequest request, string lang)
 {
     request.Headers.Add("lang", lang);
 }
Esempio n. 4
0
        public AllInOneResponse DoRequest(AllInOneRequest request)
        {
            var builder = new StringBuilder();

            try
            {
                if (string.IsNullOrEmpty(request.ServerUrl))
                {
                    throw new AllInOneException("Invalid server");
                }

                var httpWebRequest = (HttpWebRequest)WebRequest.Create(request.ServerUrl);
                if (request.IsAuthorized)
                {
                    httpWebRequest.Headers["Authorization"] = $"{Constants.Headers.Bearer} {request.AccessToken}";
                }
                foreach (var header in request.Headers)
                {
                    httpWebRequest.Headers[header.Key] = header.Value;
                }
                //AddDefaultRequestHeaders(ref httpWebRequest);

                httpWebRequest.Method = request.Method.ToString();
                builder.AppendLine("Request at " + GetDateNowString());
                builder.AppendLine($"{request.ServerUrl} [{request.Method}]");

                builder.Append("Headers: ");
                foreach (var headerKey in httpWebRequest.Headers.AllKeys)
                {
                    builder.AppendLine($"[{headerKey}:{httpWebRequest.Headers[headerKey]}] ");
                }
                builder.AppendLine();

                if (request.Body != null)
                {
                    builder.Append("Body: ");
                    if (request.IsFormUrlEncoded)
                    {
                        httpWebRequest.ContentType = Constants.Headers.FormUrlEncodedContentType;
                        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStreamAsync().Result))
                        {
                            builder.AppendLine(request.Body.ToString());
                            streamWriter.Write(request.Body);
                            streamWriter.Flush();
                        }
                        //httpWebResponse = await httpWebRequest.PostAsync(request.ServerUrl, new FormUrlEncodedContent(request.Body as Dictionary<string, string>));
                    }
                    else // JSON Request.
                    {
                        httpWebRequest.ContentType = Constants.Headers.JsonContentType;
                        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStreamAsync().Result))
                        {
                            var json = _serializer.SerializeObject(request.Body);
                            builder.AppendLine(json);
                            streamWriter.Write(json);
                            streamWriter.Flush();
                        }
                    }
                }
                var responseString = string.Empty; //await httpWebResponse.Content.ReadAsStringAsync();
                if (request.Method == HttpMethod.Post && !request.AllowDuplicate)
                {
                    if (lastPostRequest != null && request.ServerUrl == lastPostRequest.ServerUrl &&
                        request.Body == lastPostRequest.Body &&
                        request.CreatedDate.Subtract(lastPostRequest.CreatedDate).Seconds < 3)
                    {
                        responseString = lastPostResponse;
                        builder.Insert(0, "[DUPLICATED] ");
                    }

                    lastPostRequest = request;
                }

                Logger.LoggerManager.LogRequest(builder);
                builder.Clear();
                if (string.IsNullOrEmpty(responseString))
                {
                    try
                    {
                        httpWebRequest.Timeout = 300000;
                        var httpResponse = httpWebRequest.GetResponseAsync().Result;

                        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                        {
                            responseString = streamReader.ReadToEnd();
                        }
                    }
                    catch (AggregateException ex)
                    {
                        responseString = ex.Message;
                        if (ex.InnerException.GetType() == typeof(WebException))
                        {
                            WebException wex = (WebException)ex.InnerException;
                            if (wex.Response != null)
                            {
                                using (var errorResponse = (HttpWebResponse)wex.Response)
                                {
                                    using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                                    {
                                        responseString = reader.ReadToEnd();
                                        //TODO: use JSON.net to parse this string and look at the error message
                                    }
                                }
                            }
                        }
                    }
                    catch (WebException wex)
                    {
                        if (wex.Response != null)
                        {
                            using (var errorResponse = (HttpWebResponse)wex.Response)
                            {
                                using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                                {
                                    responseString = reader.ReadToEnd();
                                    //TODO: use JSON.net to parse this string and look at the error message
                                }
                            }
                        }
                    }
                }

                builder.AppendLine("Response at " + GetDateNowString());
                builder.AppendLine(responseString);

                AllInOneResponse TObject = new AllInOneResponse();
                try
                {
                    TObject = _serializer.DeserializeObject <AllInOneResponse>(responseString);
                }
                catch (Exception ex)
                {
                    builder.AppendLine("Exception: " + ex.Message);
                }
                finally
                {
                    TObject.ResponseString = responseString;
                    builder.AppendLine("*************************************************************");
                    builder.AppendLine();
                    Logger.LoggerManager.LogRequest(builder);
                }

                if (TObject.HasError) // invalid response.
                {
                    if (TObject.code == INVALID_TOKEN_CODE)
                    {
                        if (request.RefreshTokenDelegate != null)
                        {
                            var result = request.RefreshTokenDelegate();
                            if (string.IsNullOrWhiteSpace(result))
                            {
                                throw new InvalidTokenException();
                            }

                            request.AccessToken = result;
                            TObject             = DoRequest(request);
                        }
                        else
                        {
                            //return TObject;
                            throw new InvalidTokenException();
                        }
                    }

                    // if code = expired/invalid token
                    //throw new ExpiredTokenException();

                    //TODO: throw AllInOne Exception after handling any exception.
                    //throw new AllInOneException(new Error { Code = TObject.code.ToString(), Message = TObject.message }, null);
                }
                else if (request.Method == HttpMethod.Post)
                {
                    lastPostResponse = responseString;
                }

                return(TObject);
            }
            catch (ExpiredTokenException)
            {
                //await authManager.RefreshToken();

                // re generate the old request again.
                //return await DoRequest(request);
                return(null);
            }
            finally
            {
            }
            // TODO: Handle any exception
            //catch (AllInOneException AllInOneException)
            //{
            //    throw;
            //}
        }
Esempio n. 5
0
        public async Task <AllInOneResponse> DoRequestAsync(AllInOneRequest request)
        {
            try
            {
                if (string.IsNullOrEmpty(request.ServerUrl))
                {
                    throw new AllInOneException("Invalid server");
                }

                var httpWebRequest = (HttpWebRequest)WebRequest.Create(request.ServerUrl);
                if (request.IsAuthorized)
                {
                    httpWebRequest.Headers["Authorization"] = $"{Constants.Headers.Bearer} {request.AccessToken}";
                }

                //AddDefaultRequestHeaders(ref httpWebRequest);

                if (request.Body != null)
                {
                    httpWebRequest.Method = request.Method.ToString();
                    if (request.IsFormUrlEncoded)
                    {
                        httpWebRequest.ContentType = Constants.Headers.FormUrlEncodedContentType;
                        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStreamAsync().Result))
                        {
                            streamWriter.Write(request.Body);
                            streamWriter.Flush();
                            streamWriter.Dispose();
                        }
                        //httpWebResponse = await httpWebRequest.PostAsync(request.ServerUrl, new FormUrlEncodedContent(request.Body as Dictionary<string, string>));
                    }
                    else // JSON Request.
                    {
                        httpWebRequest.ContentType = Constants.Headers.JsonContentType;
                        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStreamAsync().Result))
                        {
                            var json = _serializer.SerializeObject(request.Body);
                            streamWriter.Write(json);
                            streamWriter.Flush();
                            streamWriter.Dispose();
                        }
                    }
                }
                else
                {
                    httpWebRequest.Method = request.Method.ToString();
                }

                var responseString = string.Empty; //await httpWebResponse.Content.ReadAsStringAsync();
                try
                {
                    var httpResponse = await httpWebRequest.GetResponseAsync() as HttpWebResponse;

                    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                        responseString = streamReader.ReadToEnd();
                }
                catch (WebException wex)
                {
                    if (wex.Response != null)
                    {
                        using (var errorResponse = (HttpWebResponse)wex.Response)
                        {
                            using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                            {
                                responseString = reader.ReadToEnd();
                                //TODO: use JSON.net to parse this string and look at the error message
                            }
                        }
                    }
                }

                var TObject = _serializer.DeserializeObject <AllInOneResponse>(responseString);
                TObject.ResponseString = responseString;

                if (TObject.HasError) // invalid response.
                {
                    // if code = expired/invalid token
                    //throw new ExpiredTokenException();

                    //TODO: throw AllInOne Exception after handling any exception.
                    //throw new AllInOneException(new Error { Code = TObject.code.ToString(), Message = TObject.message }, null);
                }

                return(TObject);
            }
            catch (ExpiredTokenException)
            {
                //await authManager.RefreshToken();

                // re generate the old request again.
                //return await DoRequest(request);
                return(null);
            }
            // TODO: Handle any exception
            //catch (AllInOneException AllInOneException)
            //{
            //    throw;
            //}
        }
Esempio n. 6
0
        public Stream DoDownloadRequest(AllInOneRequest request)
        {
            var builder = new StringBuilder();

            try
            {
                if (string.IsNullOrEmpty(request.ServerUrl))
                {
                    throw new AllInOneException("Invalid server");
                }

                var httpWebRequest = (HttpWebRequest)WebRequest.Create(request.ServerUrl);
                if (request.IsAuthorized)
                {
                    httpWebRequest.Headers["Authorization"] = $"{Constants.Headers.Bearer} {request.AccessToken}";
                }

                foreach (var header in request.Headers)
                {
                    httpWebRequest.Headers[header.Key] = header.Value;
                }

                //AddDefaultRequestHeaders(ref httpWebRequest);

                httpWebRequest.Method = request.Method.ToString();
                builder.AppendLine("Request at " + GetDateNowString());
                builder.AppendLine($"{request.ServerUrl} [{request.Method}]");

                builder.Append("Headers: ");
                foreach (var headerKey in httpWebRequest.Headers.AllKeys)
                {
                    builder.AppendLine($"[{headerKey}:{httpWebRequest.Headers[headerKey]}] ");
                }
                builder.AppendLine();

                if (request.Body != null)
                {
                    if (request.IsFormUrlEncoded)
                    {
                        httpWebRequest.ContentType = Constants.Headers.FormUrlEncodedContentType;
                        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStreamAsync().Result))
                        {
                            builder.AppendLine(request.Body.ToString());
                            streamWriter.Write(request.Body);
                            streamWriter.Flush();
                        }
                        //httpWebResponse = await httpWebRequest.PostAsync(request.ServerUrl, new FormUrlEncodedContent(request.Body as Dictionary<string, string>));
                    }
                    else // JSON Request.
                    {
                        httpWebRequest.ContentType = Constants.Headers.JsonContentType;
                        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStreamAsync().Result))
                        {
                            var json = _serializer.SerializeObject(request.Body);
                            builder.AppendLine(json);
                            streamWriter.Write(json);
                            streamWriter.Flush();
                        }
                    }
                }

                Logger.LoggerManager.LogRequest(builder);
                builder.Clear();

                Stream responseStream = null; //await httpWebResponse.Content.ReadAsStringAsync();
                try
                {
                    var httpResponse = httpWebRequest.GetResponseAsync().Result as HttpWebResponse;
                    responseStream = httpResponse.GetResponseStream();
                }
                catch (WebException wex)
                {
                    if (wex.Response != null)
                    {
                        using (var errorResponse = (HttpWebResponse)wex.Response)
                        {
                            using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                            {
                                responseStream = null;
                                //TODO: use JSON.net to parse this string and look at the error message
                            }
                        }
                    }
                }

                return(responseStream);
            }
            catch (ExpiredTokenException)
            {
                //await authManager.RefreshToken();

                // re generate the old request again.
                //return await DoRequest(request);
                return(null);
            }
            finally
            {
                builder.AppendLine("*************************************************************");
                builder.AppendLine();
                Logger.LoggerManager.LogRequest(builder);
            }
            // TODO: Handle any exception
            //catch (AllInOneException AllInOneException)
            //{
            //    throw;
            //}
        }