public static RawEventsGetResponse EventsMFCParse(Stream serverResponse, out ErrorResponse errorResponse) { RawEventsGetResponse response = new RawEventsGetResponse(); errorResponse = null; serverResponse.Position = 0; JsonTextReader jsonTextReader = new JsonTextReader(new StreamReader(serverResponse)); try { while (jsonTextReader.Read()) { // MessagesCount if (jsonTextReader.TokenType == JsonToken.PropertyName && string.Equals(jsonTextReader.Value, "nm")) { jsonTextReader.Read(); response.MessagesCount = Convert.ToInt32(jsonTextReader.Value); continue; } // FriendsCount if (jsonTextReader.TokenType == JsonToken.PropertyName && string.Equals(jsonTextReader.Value, "nf")) { jsonTextReader.Read(); response.FriendsCount = Convert.ToInt32(jsonTextReader.Value); continue; } if (jsonTextReader.TokenType == JsonToken.PropertyName && string.Equals(jsonTextReader, "ok")) { errorResponse = new ErrorResponse(); jsonTextReader.Read(); int error_code = Convert.ToInt32(jsonTextReader.Value); switch (error_code) { case -1: //истекшая сессия errorResponse.error_code = "1"; break; case -2: //флуд-контроль errorResponse.error_code = "2"; break; } return null; } } return response; } catch (Exception) { throw; } }
/// <summary> /// Получает список событий и сохраняет в реестр /// </summary> /// <param name="isRefresh">Указывает на необходимость обновления с сайта, если true - данные из кэша не считываются</param> /// <param name="restoreSession"></param> /// <param name="useKeepAwake"></param> public EventsGetResponse EventsGet(bool isRefresh, bool restoreSession, bool useKeepAwake) { DebugHelper.WriteLogEntry("BaseLogic.EventsGet"); try { if (isRefresh) { throw new Exception(); } return _iDataLogic.EventsGet(); } catch (Exception) { try { if (useKeepAwake) timerKeepAwake.Enabled = true; //попытка установить WiFi на всякий случай CoreHelper.TurnWiFi(true); //if (_iDataLogic.GetOnlyWIFI() == "1") //if (!CoreHelper.TurnWiFi(true)) throw new VKException(ExceptionMessage.NoConnection); // восстановливаем сессию if (restoreSession) { AutoLogin(); } RawEventsGetResponse newGetEventsResponse = new RawEventsGetResponse(); ErrorResponse newErrorResponse_LoadShortActivityResponseData = null; ErrorResponse newErrorResponse_LoadShortUpdatesPhotosResponse = null; ErrorResponse newErrorResponse_LoadShortWallResponseData = null; ErrorResponse newErrorResponse_LoadShortPhotosCommentsRespounse = null; ShortActivityResponse newShortActivityResponse = null; ShortUpdatesPhotosResponse newShortUpdatesPhotosResponse = null; ShortWallResponse newShortWallResponse = null; ShortPhotosCommentsRespounse newShortPhotosCommentsRespounse = null; ShortActivityResponse oldShortActivityResponse = null; ShortUpdatesPhotosResponse oldShortUpdatesPhotosResponse = null; ShortWallResponse oldShortWallResponse = null; ShortPhotosCommentsRespounse oldShortPhotosCommentsRespounse = null; try { #region Н О В Ы Е С О О Б Щ Е Н И Я И З А П Р О С Ы Н А Д Р У Ж Б У try { DebugHelper.WriteLogEntry("(Сервер) Загрузка newGetEventsResponse..."); newGetEventsResponse = _iCommunicationLogic.GetEvents(_iDataLogic.GetUid(), _iDataLogic.GetSessionKey()); DebugHelper.WriteLogEntry("(Сервер) newGetEventsResponse успешно загружено."); } catch { newGetEventsResponse.FriendsCount = -1; newGetEventsResponse.MessagesCount = -1; } #endregion #region Н О В Ы Е С Т А Т У С Ы Д Р У З Е Й //загружаем список ID последних 50 статусов //с сервера try { DebugHelper.WriteLogEntry("(Сервер) Загрузка newShortActivityResponse..."); newShortActivityResponse = _iCommunicationLogic.LoadShortActivityResponseData(_iDataLogic.GetUid(), _iDataLogic.GetSessionKey(), "0", "50", out newErrorResponse_LoadShortActivityResponseData); DebugHelper.WriteLogEntry("(Сервер) newShortActivityResponse успешно загружено."); } catch { newGetEventsResponse.FriendsNewsCount = -1; } //из кэша try { DebugHelper.WriteLogEntry("(Кэш) Загрузка oldShortActivityResponse..."); oldShortActivityResponse = Cache.Cache.LoadFromCache<ShortActivityResponse>(string.Empty, "ShortActivityResponse"); DebugHelper.WriteLogEntry("(Кэш) oldShortActivityResponse успешно загружено."); } catch (Exception newExeption) { newGetEventsResponse.FriendsNewsCount = -1; DebugHelper.WriteLogEntry("(Кэш) В процессе загрузки oldShortActivityResponse произошла ошибка: " + newExeption.Message); } //если операции выполнены успешно... if (newShortActivityResponse != null) { if (oldShortActivityResponse != null) { //определяем: не появилось ли новых id? int newIDCount = 0; foreach (int newID in newShortActivityResponse.sadStatusID) { foreach (int oldID in oldShortActivityResponse.sadStatusID) { if (newID == oldID) { newIDCount++; } } } newGetEventsResponse.FriendsNewsCount = newShortActivityResponse.sadStatusID.Count - newIDCount; } else { #region сохраняем в кэш полученные данные try { // чтобы избежать перезаписи string[] cacheData = Cache.Cache.GetEntryNames(string.Empty); foreach (string cacheEntity in cacheData) { if (cacheEntity.Equals("ShortActivityResponse")) { throw new Exception(); } } DebugHelper.WriteLogEntry("(Кэш) Сохранение newShortActivityResponse..."); bool result; result = Cache.Cache.SaveToCache(newShortActivityResponse, string.Empty, "ShortActivityResponse"); if (result) { newGetEventsResponse.FriendsNewsCount = 0; DebugHelper.WriteLogEntry("(Кэш) newShortActivityResponse успешно сохранено."); } else { DebugHelper.WriteLogEntry("(Кэш) newShortActivityResponse не сохранено."); } } catch (Exception newException) { DebugHelper.WriteLogEntry("(Кэш) В процессе сохранения ShortActivityResponse произошла ошибка: " + newException.Message); } #endregion } } #endregion #region Н О В Ы Е Ф О Т О Г Р А Ф И И П О Л Ь З О В А Т Е Л Е Й //загружаем список последних 100 фотографий пользователя //с сервера try { DebugHelper.WriteLogEntry("(Сервер) Загрузка newShortUpdatesPhotosResponse..."); newShortUpdatesPhotosResponse = _iCommunicationLogic.LoadShortUpdatesPhotosResponse(_iDataLogic.GetSessionKey(), "0", "100", out newErrorResponse_LoadShortUpdatesPhotosResponse); DebugHelper.WriteLogEntry("(Сервер) newShortUpdatesPhotosResponse успешно загружено."); } catch { newGetEventsResponse.FriendsPhotosCount = -1; } //из кэша try { DebugHelper.WriteLogEntry("(Кэш) Загрузка oldShortUpdatesPhotosResponse..."); oldShortUpdatesPhotosResponse = Cache.Cache.LoadFromCache<ShortUpdatesPhotosResponse>(string.Empty, "ShortUpdatesPhotosResponse"); DebugHelper.WriteLogEntry("(Кэш) oldShortUpdatesPhotosResponse успешно загружено."); } catch (Exception newExeption) { newGetEventsResponse.FriendsPhotosCount = -1; DebugHelper.WriteLogEntry("(Кэш) В процессе загрузки oldShortUpdatesPhotosResponse произошла ошибка: " + newExeption.Message); } //если операции выполнены успешно... if (newShortUpdatesPhotosResponse != null) { if (oldShortUpdatesPhotosResponse != null) { //определяем: не появилось ли новых id? int newIDCount = 0; foreach (int newID in newShortUpdatesPhotosResponse.suprPhotoID) { foreach (int oldID in oldShortUpdatesPhotosResponse.suprPhotoID) { if (newID == oldID) { newIDCount++; } } } //если > 100 фотографий - не имеем возможности отслежавать (т.к. подмножество фотографии в списке из множества на сервере определяется случайным образом) if (!(oldShortUpdatesPhotosResponse.suprPhotoID.Count < 100)) { newGetEventsResponse.FriendsPhotosCount = 100; } else { newGetEventsResponse.FriendsPhotosCount = newShortUpdatesPhotosResponse.suprPhotoID.Count - newIDCount; } } else { #region сохраняем в кэш полученные данные try { // чтобы избежать перезаписи string[] cacheData = Cache.Cache.GetEntryNames(string.Empty); foreach (string cacheEntity in cacheData) { if (cacheEntity.Equals("ShortUpdatesPhotosResponse")) { throw new Exception(); } } DebugHelper.WriteLogEntry("(Кэш) Сохранение newShortUpdatesPhotosResponse..."); bool result; result = Cache.Cache.SaveToCache(newShortUpdatesPhotosResponse, string.Empty, "ShortUpdatesPhotosResponse"); if (result) { newGetEventsResponse.FriendsPhotosCount = 0; DebugHelper.WriteLogEntry("(Кэш) newShortUpdatesPhotosResponse успешно сохранено."); } else { DebugHelper.WriteLogEntry("(Кэш) newShortUpdatesPhotosResponse не сохранено."); } } catch (Exception newException) { DebugHelper.WriteLogEntry("(Кэш) В процессе сохранения newShortUpdatesPhotosResponse произошла ошибка: " + newException.Message); } #endregion } } #endregion #region Н О В Ы Е С О О Б Щ Е Н И Я Н А С Т Е Н У newGetEventsResponse.WallCount = -1; /* //загружаем список последних 50 сообщений со стены //с сервера try { DebugHelper.WriteLogEntry("(Сервер) Загрузка newShortWallResponse..."); newShortWallResponse = _iCommunicationLogic.LoadShortWallResponseData(_iDataLogic.GetUid(), _iDataLogic.GetSessionKey(), "0", "50", out newErrorResponse_LoadShortWallResponseData); DebugHelper.WriteLogEntry("(Сервер) newShortWallResponse успешно загружено."); } catch { newGetEventsResponse.WallCount = -1; } //из кэша try { DebugHelper.WriteLogEntry("(Кэш) Загрузка oldShortWallResponse..."); oldShortWallResponse = Cache.Cache.LoadFromCache<ShortWallResponse>(string.Empty, "ShortWallResponse"); DebugHelper.WriteLogEntry("(Кэш) oldShortWallResponse успешно загружено."); } catch (Exception newExeption) { newGetEventsResponse.WallCount = -1; DebugHelper.WriteLogEntry("(Кэш) В процессе загрузки oldShortWallResponse произошла ошибка: " + newExeption.Message); } //если операции выполнены успешно... if (newShortWallResponse != null) { if (oldShortWallResponse != null) { //определяем: не появилось ли новых id? int newIDCount = 0; foreach (int newID in newShortWallResponse.swrMessageID) { foreach (int oldID in oldShortWallResponse.swrMessageID) { if (newID == oldID) { newIDCount++; } } } newGetEventsResponse.WallCount = newShortWallResponse.swrMessageID.Count - newIDCount; } else { #region сохраняем в кэш полученные данные try { // чтобы избежать перезаписи string[] cacheData = Cache.Cache.GetEntryNames(string.Empty); foreach (string cacheEntity in cacheData) { if (cacheEntity.Equals("ShortWallResponse")) { throw new Exception(); } } DebugHelper.WriteLogEntry("(Кэш) Сохранение newShortWallResponse..."); bool result; result = Cache.Cache.SaveToCache(newShortWallResponse, string.Empty, "ShortWallResponse"); if (result) { newGetEventsResponse.WallCount = 0; DebugHelper.WriteLogEntry("(Кэш) newShortWallResponse успешно сохранено."); } else { DebugHelper.WriteLogEntry("(Кэш) newShortWallResponse не сохранено."); } } catch (Exception newException) { DebugHelper.WriteLogEntry("(Кэш) В процессе сохранения newShortWallResponse произошла ошибка: " + newException.Message); } #endregion } } */ #endregion #region Н О В Ы Е К О М Е Н Т А Р И И К Ф О Т О Г Р А Ф И Я М //загружаем список последних 50 комменариев к фотографиям пользователя //с сервера try { DebugHelper.WriteLogEntry("(Сервер) Загрузка newShortPhotosCommentsRespounse..."); newShortPhotosCommentsRespounse = _iCommunicationLogic.LoadShortPhotosCommentsRespounse(_iDataLogic.GetUid(), _iDataLogic.GetSessionKey(), "0", "50", "-1", out newErrorResponse_LoadShortPhotosCommentsRespounse); DebugHelper.WriteLogEntry("(Сервер) newShortPhotosCommentsRespounse успешно загружено."); } catch { newGetEventsResponse.CommentsCount = -1; } //из кэша try { DebugHelper.WriteLogEntry("(Кэш) Загрузка oldShortPhotosCommentsRespounse..."); oldShortPhotosCommentsRespounse = Cache.Cache.LoadFromCache<ShortPhotosCommentsRespounse>(string.Empty, "ShortPhotosCommentsRespounse"); DebugHelper.WriteLogEntry("(Кэш) oldShortPhotosCommentsRespounse успешно загружено."); } catch (Exception newExeption) { newGetEventsResponse.CommentsCount = -1; DebugHelper.WriteLogEntry("(Кэш) В процессе загрузки oldShortPhotosCommentsRespounse произошла ошибка: " + newExeption.Message); } // если операции выполнены успешно... if (newShortPhotosCommentsRespounse != null) { if (oldShortPhotosCommentsRespounse != null) { // определяем: не появилось ли новых id? int newIDCount = 0; foreach (int newID in newShortPhotosCommentsRespounse.spcrCommentIDs) { foreach (int oldID in oldShortPhotosCommentsRespounse.spcrCommentIDs) { if (newID == oldID) { newIDCount++; } } } newGetEventsResponse.CommentsCount = newShortPhotosCommentsRespounse.spcrCommentIDs.Count - newIDCount; } else { #region сохраняем в кэш полученные данные try { // чтобы избежать перезаписи string[] cacheData = Cache.Cache.GetEntryNames(string.Empty); foreach (string cacheEntity in cacheData) { if (cacheEntity.Equals("ShortPhotosCommentsRespounse")) { throw new Exception(); } } DebugHelper.WriteLogEntry("(Кэш) Сохранение newShortPhotosCommentsRespounse..."); bool result; result = Cache.Cache.SaveToCache(newShortPhotosCommentsRespounse, string.Empty, "ShortPhotosCommentsRespounse"); if (result) { newGetEventsResponse.CommentsCount = 0; DebugHelper.WriteLogEntry("(Кэш) newShortPhotosCommentsRespounse успешно сохранено."); } else { DebugHelper.WriteLogEntry("(Кэш) newShortPhotosCommentsRespounse не сохранено."); } } catch (Exception newException) { DebugHelper.WriteLogEntry("(Кэш) В процессе сохранения newShortPhotosCommentsRespounse произошла ошибка: " + newException.Message); } #endregion } } #endregion } catch (VKException) { throw; } catch (TimeoutException ex) { DebugHelper.WriteLogEntry("BaseLogic.EventsGet Timeout Exception message: " + ex.Message); DebugHelper.WriteLogEntry("BaseLogic.EventsGet Timeout Exception stack trace: " + ex.StackTrace); throw new VKException(ExceptionMessage.NoConnection); } catch (WebException ex) { DebugHelper.WriteLogEntry("BaseLogic.EventsGet Web Exception message: " + ex.Message); DebugHelper.WriteLogEntry("BaseLogic.EventsGet Web Exception stack trace: " + ex.StackTrace); throw new VKException(ExceptionMessage.NoConnection); } catch (OutOfMemoryException ex) { DebugHelper.WriteLogEntry("BaseLogic.EventsGet OutOfMemory Exception message: " + ex.Message); DebugHelper.WriteLogEntry("BaseLogic.EventsGet OutOfMemory Exception stack trace: " + ex.StackTrace); throw; } catch (Exception ex) { DebugHelper.WriteLogEntry("BaseLogic.EventsGet Unknown Exception message: " + ex.Message); DebugHelper.WriteLogEntry("BaseLogic.EventsGet Unknown Exception stack trace: " + ex.StackTrace); } #region здесь пытаемся ловить ошибку, что сессия истекла или captcha if (newErrorResponse_LoadShortActivityResponseData != null) { if (newErrorResponse_LoadShortActivityResponseData.error_code.Equals("1")) { if (!restoreSession) { return EventsGet(isRefresh, true, true); } else { throw new VKException(ExceptionMessage.ServerUnavalible); } } else if (newErrorResponse_LoadShortActivityResponseData.error_code.Equals("2")) { throw new VKException(ExceptionMessage.AccountBloked); } else { throw new VKException(ExceptionMessage.UnknownError); } } if (newErrorResponse_LoadShortUpdatesPhotosResponse != null) { if (newErrorResponse_LoadShortUpdatesPhotosResponse.error_code.Equals("1")) { if (!restoreSession) { return EventsGet(isRefresh, true, true); } else { throw new VKException(ExceptionMessage.ServerUnavalible); } } else if (newErrorResponse_LoadShortUpdatesPhotosResponse.error_code.Equals("2")) { throw new VKException(ExceptionMessage.AccountBloked); } else { throw new VKException(ExceptionMessage.UnknownError); } } if (newErrorResponse_LoadShortWallResponseData != null) { if (newErrorResponse_LoadShortWallResponseData.error_code.Equals("1")) { if (!restoreSession) { return EventsGet(isRefresh, true, true); } else { throw new VKException(ExceptionMessage.ServerUnavalible); } } else if (newErrorResponse_LoadShortWallResponseData.error_code.Equals("2")) { throw new VKException(ExceptionMessage.AccountBloked); } else { throw new VKException(ExceptionMessage.UnknownError); } } if (newErrorResponse_LoadShortPhotosCommentsRespounse != null) { if (newErrorResponse_LoadShortPhotosCommentsRespounse.error_code.Equals("1")) { if (!restoreSession) { return EventsGet(isRefresh, true, true); } else { throw new VKException(ExceptionMessage.ServerUnavalible); } } else if (newErrorResponse_LoadShortPhotosCommentsRespounse.error_code.Equals("2")) { throw new VKException(ExceptionMessage.AccountBloked); } else { throw new VKException(ExceptionMessage.UnknownError); } } #endregion _iDataLogic.SetEvents(newGetEventsResponse); return _iDataLogic.EventsGet(); } finally { timerKeepAwake.Enabled = false; } } }
/// <summary> /// Десереализует данные по событиям из реестра в объект класса GetEventsResponse /// </summary> /// <returns>GetEventsResponse</returns> /// <exception>исключения, выброшенные RegistryUtility</exception> public RawEventsGetResponse GetEvents() { try { var eventsGetResponse = new RawEventsGetResponse { MessagesCount = Convert.ToInt32(RegistryUtility.GetValue("MessagesCount", SystemConfiguration.EventsRegKey)), FriendsCount = Convert.ToInt32(RegistryUtility.GetValue("FriendsCount", SystemConfiguration.EventsRegKey)), CommentsCount = Convert.ToInt32(RegistryUtility.GetValue("CommentsCount", SystemConfiguration.EventsRegKey)), FriendsNewsCount = Convert.ToInt32(RegistryUtility.GetValue("FriendsNewsCount", SystemConfiguration.EventsRegKey)), FriendsPhotosCount = Convert.ToInt32(RegistryUtility.GetValue("FriendsPhotosCount", SystemConfiguration.EventsRegKey)), WallCount = Convert.ToInt32(RegistryUtility.GetValue("WallCount", SystemConfiguration.EventsRegKey)) }; return eventsGetResponse; } catch (Exception ex) { DebugHelper.WriteLogEntry(ex, null); return null; } }
/// <summary> /// Сохраняет события в реестр. Генерирует исключение в случае неудачи. /// </summary> /// <param name="eventsGetResponse"></param> public void SetEvents(RawEventsGetResponse eventsGetResponse) { try { if (eventsGetResponse.MessagesCount > -1) { RegistryUtility.SetValue("MessagesCount", SystemConfiguration.EventsRegKey, eventsGetResponse.MessagesCount.ToString(), RegistryValueKind.String); } if (eventsGetResponse.FriendsCount > -1) { RegistryUtility.SetValue("FriendsCount", SystemConfiguration.EventsRegKey, eventsGetResponse.FriendsCount.ToString(), RegistryValueKind.String); } if (eventsGetResponse.CommentsCount > -1) { RegistryUtility.SetValue("CommentsCount", SystemConfiguration.EventsRegKey, eventsGetResponse.CommentsCount.ToString(), RegistryValueKind.String); } if (eventsGetResponse.FriendsPhotosCount > -1) { RegistryUtility.SetValue("FriendsPhotosCount", SystemConfiguration.EventsRegKey, eventsGetResponse.FriendsPhotosCount.ToString(), RegistryValueKind.String); } if (eventsGetResponse.FriendsNewsCount > -1) { RegistryUtility.SetValue("FriendsNewsCount", SystemConfiguration.EventsRegKey, eventsGetResponse.FriendsNewsCount.ToString(), RegistryValueKind.String); } if (eventsGetResponse.WallCount > -1) { RegistryUtility.SetValue("WallCount", SystemConfiguration.EventsRegKey, eventsGetResponse.WallCount.ToString(), RegistryValueKind.String); } } catch (Exception ex) { DebugHelper.WriteLogEntry(ex, null); } }
/// <summary> /// Список событий /// </summary> /// <param name="Uid"></param> /// <param name="sessionId"></param> /// <returns></returns> public RawEventsGetResponse GetEvents(string Uid, string sessionId) { RawEventsGetResponse getEventsResponse = new RawEventsGetResponse(); ErrorResponse errorResponse = null; Uri uri = new Uri { Address = SystemConfiguration.ServerConnectionToApiCalls, Method = "/data?act=history&" }; uri.Parameters.Add("sid=" + sessionId); HttpWebRequest newHttpWebRequest = HttpUtility.PrepareHttpWebRequest(uri.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("GetEvents requested: Address: {0} Header: {1}", newHttpWebRequest.Address, newHttpWebRequest.Headers), null)); } else { newStream = HttpUtility.PrepareResponseStream(newHttpWebResponse); } getEventsResponse = ParsingHelper.EventsMFCParse(newStream, out errorResponse); if (logging) { newStream.Position = 0; OnLogResponse(new LogResponseEventArgs("GetEvents responsed: ", newStream)); newStream.Flush(); } return getEventsResponse; } } catch (ObjectDisposedException ex) { DebugHelper.WriteLogEntry(ex, "GetEvents ObjectDisposedException"); return null; } finally { newHttpWebRequest.Abort(); if (newStream != null) { newStream.Close(); } } }