Beispiel #1
0
        /// <summary>
        /// Меняет статус пользователя на сервере и сохраняет его в кэш
        /// </summary>
        /// <param name="status">Требуемый статус</param>
        /// <param name="action">Требуемое действие</param>
        /// <param name="restoreSession">Необходимость обновления сессии</param>
        public void SetStatus(string status, StatusActionType actionType, bool restoreSession)
        {
            DebugHelper.WriteLogEntry("BaseLogic.SetStatus");

            //WiFi
            if (_iDataLogic.GetOnlyWIFI() == "1")
                if (!CoreHelper.TurnWiFi(true)) throw new VKException(ExceptionMessage.NoConnection);

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

            ErrorResponse errorResponse = null;

            bool res = false;

            try
            {
                res = _iCommunicationLogic.SetStatus(_iDataLogic.GetUid(), _iDataLogic.GetSessionKey(), status, actionType, out errorResponse);
            }
            catch (VKException)
            {
                throw;
            }
            catch (TimeoutException ex)
            {
                DebugHelper.WriteLogEntry("BaseLogic.SetStatus Timeout Exception message: " + ex.Message);
                DebugHelper.WriteLogEntry("BaseLogic.SetStatus Timeout Exception stack trace: " + ex.StackTrace);

                throw new VKException(ExceptionMessage.NoConnection);
            }
            catch (WebException ex)
            {
                DebugHelper.WriteLogEntry("BaseLogic.SetStatus Web Exception message: " + ex.Message);
                DebugHelper.WriteLogEntry("BaseLogic.SetStatus Web Exception stack trace: " + ex.StackTrace);

                throw new VKException(ExceptionMessage.NoConnection);
            }
            catch (OutOfMemoryException ex)
            {
                DebugHelper.WriteLogEntry("BaseLogic.SetStatus OutOfMemory Exception message: " + ex.Message);
                DebugHelper.WriteLogEntry("BaseLogic.SetStatus OutOfMemory Exception stack trace: " + ex.StackTrace);

                throw;
            }
            catch (Exception ex)
            {
                DebugHelper.WriteLogEntry("BaseLogic.SetStatus Unknown Exception message: " + ex.Message);
                DebugHelper.WriteLogEntry("BaseLogic.SetStatus Unknown Exception stack trace: " + ex.StackTrace);
            }

            if (res)
            {
                //// cохранение в кэш // что-то ни одного try ... catch ... нет =(
                //var loggedInUser = Cache.Cache.LoadFromCache<User>(string.Empty, "LoggedInUserData");

                //loggedInUser.Status = status;

                //Cache.Cache.SaveToCache(loggedInUser, string.Empty, "LoggedInUserData");
            }
            else
            {
                if (errorResponse != null)
                {
                    if (errorResponse.error_code == "1")
                    {
                        if (!restoreSession)
                        {
                            SetStatus(status, actionType, true);
                        }
                        else
                        {
                            throw new VKException(ExceptionMessage.ServerUnavalible);
                        }
                    }
                    else if (errorResponse.error_code == "2")
                    {
                        throw new VKException(ExceptionMessage.AccountBloked);
                    }
                    else if (errorResponse.error_code == "3")
                    {
                        throw new VKException(ExceptionMessage.UnsuccessfullOperation);
                    }
                    else
                    {
                        throw new VKException(ExceptionMessage.UnknownError);
                    }
                }
                else
                {
                    //throw new VKException(ExceptionMessage.UnknownError);
                }
            }
        }
Beispiel #2
0
        /// <summary>
        /// Редактирование текущего статуса
        /// </summary>
        /// <param name="uid">Идентификатор пользователя</param>
        /// <param name="sid">Идентификатор сессии</param>
        /// <param name="newStatus">Тест нового статуса</param>
        /// <param name="action">Действие со статусом (ST_REFRESH - обновить, ST_CLEAR - очистить, ST_DELETE - удалить)</param>
        /// <returns>Статус операции (прошла: 1 - успешно, 0 - неуспешно)</returns>
        public bool SetStatus(string uid, string sid, string newStatus, StatusActionType actionType, out ErrorResponse errorResponse)
        {
            errorResponse = null;

            // подготовка строки запроса для редактирования
            Uri uri = new Uri();
            uri.Address = SystemConfiguration.ServerConnectionToApiCalls;

            switch (actionType)
            {
                case StatusActionType.Refresh:
                    uri.Method = "/data?act=set_activity&";
                    uri.Parameters.Add("text=" + newStatus);
                    break;

                case StatusActionType.Clear:
                    uri.Method = "/data?act=clear_activity&";
                    break;

                case StatusActionType.Delete:
                    uri.Method = "/data?act=del_activity&";
                    break;

                default:
                    return false;
            }

            uri.Parameters.Add("id=" + uid);
            uri.Parameters.Add("sid=" + sid);

            var request = HttpUtility.PrepareHttpWebRequest(uri.GetUri());
            Stream webResponseStream = null;

            try
            {
                bool logging = (LogRequestEvent != null);

                if (logging)
                {
                    OnLogRequest(new LogRequestEventArgs(String.Format("SetStatus requested: Address: {0} Header: {1}", request.Address, request.Headers), null));
                }

                // получение и разбор ответа
                using (WebResponse webResponse = request.GetResponse())
                {
                    webResponseStream = HttpUtility.PrepareResponseStream(webResponse);

                    var response = new StreamReader(webResponseStream).ReadToEnd();

                    if (response.IndexOf("\"ok\":0") != -1)
                    {
                        errorResponse = new ErrorResponse();

                        errorResponse.error_code = "3";

                        return false;
                    }
                    if (response.IndexOf("\"ok\":-1") != -1)
                    {
                        errorResponse = new ErrorResponse();

                        errorResponse.error_code = "1";

                        return false;
                    }
                    if (response.IndexOf("\"ok\":-2") != -1)
                    {
                        errorResponse = new ErrorResponse();

                        errorResponse.error_code = "2";

                        return false;
                    }

                    if (logging)
                    {
                        OnLogResponse(new LogResponseEventArgs(String.Format("SetStatus responsed: {0}", response), null));
                    }

                    return true;
                }
            }
            catch (ObjectDisposedException ex)
            {
                DebugHelper.WriteLogEntry(ex, "SetStatus ObjectDisposedException");

                return false;
            }
            finally
            {
                request.Abort();

                if (webResponseStream != null)
                {
                    webResponseStream.Close();
                }
            }
        }