Esempio n. 1
0
        // этот метод просто перезагружает все фотки
        public void ReloadUserPhotos(bool isRefresh, bool restoreSession)
        {
            try
            {
                if (isRefresh)
                {
                    throw new Exception();
                }
            }
            catch (Exception) // если кэша нет... лезем в сеть
            {
                // WiFi
                if (_iDataLogic.GetOnlyWIFI() == "1")
                {
                    if (!CoreHelper.TurnWiFi(true))
                    {
                        throw new VKException(ExceptionMessage.NoConnection);
                    }
                }

                // восстанавливаем сессию
                if (restoreSession)
                {
                    AutoLogin();
                }

                UpdatesPhotosResponse totalUpdatesPhotosResponse = new UpdatesPhotosResponse();

                int blockSize = 50;
                int countGet = 0;

                bool doLoading = true;

                while (doLoading)
                {
                    ErrorResponse newErrorResponse = null;
                    UpdatesPhotosResponse newUpdatesPhotosResponse = null;

                    try
                    {
                        newUpdatesPhotosResponse = _iCommunicationLogic.LoadUserPhotosData(_iDataLogic.GetUid(), _iDataLogic.GetSessionKey(), countGet.ToString(), (countGet + blockSize).ToString(), out newErrorResponse);
                    }
                    catch (VKException)
                    {
                        throw;
                    }
                    catch (TimeoutException ex)
                    {
                        DebugHelper.WriteLogEntry("BaseLogic.GetPhotoLargeURLByPhotoID TimeoutException Message: " + ex.Message);
                        DebugHelper.WriteLogEntry("BaseLogic.GetPhotoLargeURLByPhotoID TimeoutException StackTrace: " + ex.StackTrace);

                        throw new VKException(ExceptionMessage.NoConnection);
                    }
                    catch (WebException ex)
                    {
                        DebugHelper.WriteLogEntry("BaseLogic.GetPhotoLargeURLByPhotoID WebException Message: " + ex.Message);
                        DebugHelper.WriteLogEntry("BaseLogic.GetPhotoLargeURLByPhotoID WebException StackTrace: " + ex.StackTrace);

                        throw new VKException(ExceptionMessage.NoConnection);
                    }
                    catch (OutOfMemoryException ex)
                    {
                        DebugHelper.WriteLogEntry("BaseLogic.GetPhotoLargeURLByPhotoID OutOfMemoryException Message: " + ex.Message);
                        DebugHelper.WriteLogEntry("BaseLogic.GetPhotoLargeURLByPhotoID OutOfMemoryException StackTrace: " + ex.StackTrace);

                        throw;
                    }
                    catch (Exception ex)
                    {
                        DebugHelper.WriteLogEntry("BaseLogic.GetPhotoLargeURLByPhotoID Exception Message: " + ex.Message);
                        DebugHelper.WriteLogEntry("BaseLogic.GetPhotoLargeURLByPhotoID Exception StackTrace: " + ex.StackTrace);
                    }

                    if (newUpdatesPhotosResponse != null)
                    {
                        foreach (var val in newUpdatesPhotosResponse.uprPhotoDatas)
                        {
                            totalUpdatesPhotosResponse.uprPhotoDatas.Add(val);
                        }

                        if (newUpdatesPhotosResponse.uprPhotoDatas.Count < blockSize) // т.е. в очередном запросе пришло меньше чем просили...
                        {
                            doLoading = false;
                        }

                        countGet += newUpdatesPhotosResponse.uprPhotoDatas.Count;
                    }
                    else
                    {
                        if (newErrorResponse != null)
                        {
                            if (newErrorResponse.error_code == "1")
                            {
                                if (!restoreSession)
                                {
                                    ReloadUserPhotos(isRefresh, true);

                                    return;
                                }
                                else
                                {
                                    throw new VKException(ExceptionMessage.ServerUnavalible);
                                }
                            }
                            else if (newErrorResponse.error_code == "2")
                            {
                                throw new VKException(ExceptionMessage.AccountBloked);
                            }
                            else
                            {
                                throw new VKException(ExceptionMessage.UnknownError);
                            }
                        }
                        else
                        {
                            //throw new VKException(ExceptionMessage.UnknownError);
                        }
                    }
                }

                //// сохраняем в кэш
                //try
                //{
                //    DebugHelper.WriteLogEntry("(Кэш) Сохранение данных UserPhotosResponse...");

                //    bool result;

                //    result = Cache.Cache.SaveToCache(totalUpdatesPhotosResponse, string.Empty, "UserPhotosResponse");

                //    if (result)
                //    {
                //        DebugHelper.WriteLogEntry("(Кэш) Данные UserPhotosResponse успешно сохранены.");
                //    }
                //    else
                //    {
                //        DebugHelper.WriteLogEntry("(Кэш) Данные UserPhotosResponse не сохранены.");
                //    }
                //}
                //catch (Exception)
                //{
                //    DebugHelper.WriteLogEntry("(Кэш) В процессе сохранения данных UserPhotosResponse произошла ошибка.");
                //}

                if (totalUpdatesPhotosResponse != null)
                {
                    DataModel.Data.UserPhotosResponseData = totalUpdatesPhotosResponse;
                }
            }
        }
Esempio n. 2
0
        public bool UploadNextPhotoComments(PhotosCommentsResponseHistory newPhotosCommentsRespounseHistory, PhotosCommentsResponse newPhotosCommentsRespounse, UpdatesPhotosResponse newUpdatesPhotosResponse)
        {
            // загрузка комментариев со списка Новости (Комментарии)
            try
            {
                if (newPhotosCommentsRespounse == null)
                {
                    throw new Exception();
                }

                foreach (var val in newPhotosCommentsRespounse.pcrComments)
                {
                    try
                    {
                        PhotosCommentsResponse oldPhotosCommentsResponse = newPhotosCommentsRespounseHistory.GetItem(val.cpPhotoData.pdPhotoID);

                        if (oldPhotosCommentsResponse == null)
                        {
                            LoadCommentsToPhoto(Convert.ToInt32(_iDataLogic.GetUid()), val.cpPhotoData.pdPhotoID, 50, true, false, newPhotosCommentsRespounseHistory);

                            return true;
                        }
                    }
                    catch (VKException)
                    {
                        throw;
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
            }
            catch (Exception)
            {
                //
            }

            // загрузка комментариев со списка Новости (Друзья)
            try
            {
                if (newUpdatesPhotosResponse == null)
                {
                    throw new Exception();
                }

                foreach (var val in newUpdatesPhotosResponse.uprPhotoDatas)
                {
                    try
                    {
                        PhotosCommentsResponse oldPhotosCommentsResponse = newPhotosCommentsRespounseHistory.GetItem(val.pdPhotoID);

                        if (oldPhotosCommentsResponse == null)
                        {
                            LoadCommentsToPhoto(val.pdUserID, val.pdPhotoID, 50, true, false, newPhotosCommentsRespounseHistory);

                            return true;
                        }
                    }
                    catch (VKException)
                    {
                        throw;
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
            }
            catch (Exception)
            {
                //
            }

            return false;
        }
Esempio n. 3
0
        // список фотографий пользователя
        public UpdatesPhotosResponse LoadUserPhotosData(string uid, string sid, string from, string to, out ErrorResponse newErrorResponse)
        {
            UpdatesPhotosResponse newUpdatesPhotosResponse = new UpdatesPhotosResponse();

            newErrorResponse = null;

            //формируем запрос
            Uri newUri = new Uri
            {
                Address = SystemConfiguration.ServerConnectionToApiCalls,
                Method = "/data?act=photos&"
            };

            newUri.Parameters.Add("id=" + uid);
            newUri.Parameters.Add("sid=" + sid);
            newUri.Parameters.Add("from=" + from);
            newUri.Parameters.Add("to=" + to);

            HttpWebRequest newHttpWebRequest = HttpUtility.PrepareHttpWebRequest(newUri.GetUri());
            //WebResponse newHttpWebResponse = null;
            Stream newStream = null;
            try
            {
                using (WebResponse newHttpWebResponse = newHttpWebRequest.GetResponse())
                {
                    bool logging = (LogRequestEvent != null);

                    if (logging)
                    {
                        newStream = new MemoryStream(2048);

                        HttpUtility.CopyStream(HttpUtility.PrepareResponseStream(newHttpWebResponse), newStream);

                        newStream.Flush();
                        newStream.Position = 0;

                        OnLogRequest(new LogRequestEventArgs(string.Format("LoadUserPhotosData requested: Address: {0} Header: {1}", newHttpWebRequest.Address, newHttpWebRequest.Headers), null));
                    }
                    else
                    {
                        newStream = HttpUtility.PrepareResponseStream(newHttpWebResponse);
                    }

                    using (JsonTextReader newJsonTextReader = new JsonTextReader(new StreamReader(newStream)))
                    {
                        try
                        {
                            #region парсинг

                            while (newJsonTextReader.Read())
                            {
                                // открыли массив 1-ого порядка (список)
                                if (newJsonTextReader.TokenType == JsonToken.StartArray)
                                {
                                    while (newJsonTextReader.Read()) // открываем очередь чтения списка
                                    {
                                        // читаем содержимое списка

                                        // открыли массив 2-ого порядка
                                        if (newJsonTextReader.TokenType == JsonToken.StartArray)
                                        {
                                            PhotoData newPhotoData = new PhotoData();
                                            newUpdatesPhotosResponse.uprPhotoDatas.Add(newPhotoData);

                                            int index = 0;

                                            while (newJsonTextReader.Read()) //открываем очередь чтения
                                            {
                                                //читаем содержимое
                                                if (newJsonTextReader.TokenType == JsonToken.String)
                                                {
                                                    switch (index)
                                                    {
                                                        case 0:
                                                            string[] value = ((string)newJsonTextReader.Value).Split('_');

                                                            newPhotoData.pdUserID = Convert.ToInt32(value[0]);
                                                            newPhotoData.pdPhotoID = Convert.ToInt32(value[1]);
                                                            break;

                                                        case 1:
                                                            newPhotoData.pdPhotoURL130px = (string)newJsonTextReader.Value;
                                                            break;

                                                        case 2:
                                                            newPhotoData.pdPhotoURL604px = (string)newJsonTextReader.Value;
                                                            break;
                                                    }
                                                }
                                                //если до конца массива, то прерываем очередь чтения
                                                else if (newJsonTextReader.TokenType == JsonToken.EndArray)
                                                {
                                                    break;
                                                }

                                                index++;
                                            }
                                        }
                                    }
                                }

                                // ошибки
                                if (newJsonTextReader.TokenType == JsonToken.PropertyName && string.Equals(newJsonTextReader.Value, "ok"))
                                {
                                    newErrorResponse = new ErrorResponse();

                                    newJsonTextReader.Read();

                                    int error_code = Convert.ToInt32(newJsonTextReader.Value);

                                    switch (error_code)
                                    {
                                        case -1:
                                            // истекшая сессия
                                            newErrorResponse.error_code = "1";
                                            break;

                                        case -2:
                                            // флуд-контроль
                                            newErrorResponse.error_code = "2";
                                            break;
                                    }

                                    return null;
                                }
                            }

                            return newUpdatesPhotosResponse;

                            #endregion
                        }
                        finally
                        {
                            if (logging)
                            {
                                newStream.Position = 0;
                                OnLogResponse(new LogResponseEventArgs("LoadUserPhotosData", newStream));
                                newStream.Flush();
                            }

                        }
                    }
                }
            }
            catch (ObjectDisposedException ex)
            {
                DebugHelper.WriteLogEntry(ex, "LoadUserPhotosData ObjectDisposedException");
                newErrorResponse = null;
                return null;
            }
            finally
            {
                newHttpWebRequest.Abort();
                if (newStream != null)
                    newStream.Close();
                //if (newHttpWebResponse != null)
                //    newHttpWebResponse.Close();
            }
        }