Ejemplo n.º 1
0
 public void Add(CancelableRequest request)
 {
     lock (RequestList) {
         RequestList.Add(request);
     }
 }
Ejemplo n.º 2
0
 public void Remove(CancelableRequest request)
 {
     lock (RequestList) {
         RequestList.TryTake(out request);
     }
 }
Ejemplo n.º 3
0
        public static async Task <ContentAndHeads> GetJsonAndHeadsAsync(string url, string method = "GET", string data = null, bool isLog     = false, bool
                                                                        isCancelable = false, bool isCatalog           = false, bool isBanner = false)
        {
            //			if (!OnePage.mainPage.ValidInternetConnection ())
            //				return null;

#if DEBUG
            // Посчитать разницу по времени
            DateTime oldDate = DateTime.Now;
            Console.WriteLine("********************** method :" + method);
            Console.WriteLine("********************** url :" + url);
            if (method != "GET")
            {
                Console.WriteLine("********************** data :" + data);
            }
#endif
            CancelableRequest cancelableRequest = null;
            ContentAndHeads   сontentAndHeads   = new ContentAndHeads();

            HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.ContentType = "application/json";
            request.Method      = method;


            //OnePage.mainPage.appRequest.AbortAll();
            if (isCancelable)
            {
                OnePage.mainPage.appRequest.Add(cancelableRequest = new CancelableRequest {
                    ParamRequest = request, IsProduct = isCatalog
                });
            }
            try {
                if (method != "GET")
                {
                    request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
                    if (data != null)
                    {
                        using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream())) {
                            streamWriter.Write(data);
                            streamWriter.Flush();
                            streamWriter.Close();
                        }

                        //byte[] byteArray = Encoding.UTF8.GetBytes(data);
                        //request.ContentLength = byteArray.Length;
                        //Stream dataStream = request.GetRequestStream();
                        //dataStream.Write(byteArray, 0, byteArray.Length);
                        //dataStream.Close();
                    }
                }

                //			if (!string.IsNullOrEmpty (header))
                //			{
                //				byte[] data = Encoding.UTF8.GetBytes(header);
                //				request.ContentLength = data.Length;
                //				using (var stream = request.GetRequestStream())
                //				{
                //					stream.Write(data, 0, data.Length);
                //				}
                //			}
                string _key;
                if (isBanner)
                {
                    _key = Convert.ToBase64String(Encoding.UTF8.GetBytes("alex.gal:qazwsx"));
                    request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + _key);
                }
                else if (isLog)
                {
                    _key = Convert.ToBase64String(Encoding.UTF8.GetBytes("codetekteam:Samsung86GaL"));
                    request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + _key);
                }
                else
                {
                    if (User.Singleton != null && User.Singleton.IsAuth)
                    {
                        _key = Convert.ToBase64String(Encoding.UTF8.GetBytes(User.Singleton.Email + ":" + User.Singleton.HashKey));
                        request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + _key);
                    }
                }
                request.Headers.Add(Constants.HeaderAppKey, Constants.HeaderAppValue);

                int pageCount   = 0;
                int pageCurrent = 0;

                request.Timeout = Constants.RequestTimeOut;


                using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse) {
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        new Exception("Не удалось получить данные!");
                    }

                    int.TryParse(response.Headers[XPagination.PageCount], out pageCount);
                    int.TryParse(response.Headers[XPagination.CurrentPage], out pageCurrent);

                    using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
                        string str = await reader.ReadToEndAsync();


#if DEBUG
                        DateTime newDate = DateTime.Now;
                        TimeSpan ts      = newDate - oldDate;
                        Console.WriteLine("###################### Total minutes :" + ts.TotalMilliseconds + " url = " + url);
#endif

                        сontentAndHeads.Content = new List <string> {
                            str
                        };
                        сontentAndHeads.countPage     = pageCount;
                        сontentAndHeads.currentPage   = pageCurrent;
                        сontentAndHeads.requestStatus = response.StatusCode;
                        return(сontentAndHeads);
                    }
                }
            } catch (WebException ex) {
                if (ex.Status != WebExceptionStatus.RequestCanceled)
                {
                    if (ex.Status == WebExceptionStatus.ProtocolError)
                    {
                        HttpWebResponse response = ex.Response as HttpWebResponse;
                        if (response != null && response.StatusCode == HttpStatusCode.Unauthorized)
                        {
                            return(сontentAndHeads);
                        }
                        //if (response != null && response.StatusCode == HttpStatusCode.NotFound)
                        //	return сontentAndHeads;
                    }
                    if (ex.Response == null)
                    {
                        сontentAndHeads.requestStatus = HttpStatusCode.InternalServerError;
                        throw new Exception();
                    }
                    string result = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
                    сontentAndHeads.Content = new List <string> {
                        result
                    };

                    SendLog(ex, result, method, url, data);
                    Console.WriteLine("*******  ERROR  *****");
                    string messageFromServer = ex.Message;
                    //ev.error = messageFromServer;
                    string title   = "Ошибка";
                    string message = "Не удалось подключиться к серверу!";


                    Console.WriteLine("Web Error: " + result);
                    message = "Не удалось подключиться к серверу!";
                    message = "";
                    JObject      jobjectMess  = null;
                    APIException aPIException = null;
                    try {
                        aPIException = JsonConvert.DeserializeObject <APIException>(result);
                        сontentAndHeads.serverException = aPIException;
                        if (aPIException != null)
                        {
                            string mes = aPIException.Message.Replace("\\\"", "");
                            jobjectMess = JObject.Parse(mes);
                        }
                    } catch (JsonReaderException) {
                        jobjectMess = null;
                    }
                    if (jobjectMess != null)
                    {
                        try {
                            title = (string)jobjectMess["errorPlace"];
                            JObject errorData = (JObject)jobjectMess["errorData"];
                            foreach (var o in errorData)
                            {
                                message += o.Value[0].Value <string>() + " ";
                            }
                            message = message.Trim();
                        } catch {
                            message = "Запрос не выполнился, попробуйте снова";
                        }
                    }
                    else
                    {
                        if (aPIException != null && !string.IsNullOrEmpty(aPIException.Message))
                        {
                            message = aPIException.Message;
                        }
                    }
                    //var json = System.Json.JsonValue.Parse(message);
                    // Выводит сообщение от АПИ
#if DEBUG
                    Console.WriteLine("Error sql: " + title);
#else
                    //OnePage.mainPage.DisplayMessage ("Произошла ошибка на сервере", title);
#endif
                    //				}
                }
                else
                {
                    сontentAndHeads.exceptionStatus = WebExceptionStatus.RequestCanceled;
                    Console.WriteLine("WebExceptionStatus.RequestCanceled");
                    сontentAndHeads.requestStatus = HttpStatusCode.OK;
                    return(сontentAndHeads);
                }
            } catch (FormatException e) {
            } catch (ObjectDisposedException e) {
                Console.WriteLine("*******  ERROR ObjectDisposedException  *****", e);
                сontentAndHeads.requestStatus = HttpStatusCode.OK;
                return(сontentAndHeads);
            } catch (Exception e) {
                Console.WriteLine("*******  ERROR  *****", e);
                //				OnePage.mainPage.DisplayMessage ("Не удалось подключиться к серверу!");
                OnePage.mainPage.ShowMessageError();
            } finally {
                if (isCancelable)
                {
                    OnePage.mainPage.appRequest.Remove(cancelableRequest);
                }
            }

            сontentAndHeads.requestStatus = HttpStatusCode.InternalServerError;
            return(сontentAndHeads);
        }