private void AsyncGetViewData(LoadingControlInterface lc)
        {
            lc.Current = 0;

            MessShortCorrespondence newMessShortCorrespondence = null;

            try
            {
                lc.Current = 5;

                newMessShortCorrespondence = Globals.BaseLogic.GetShortCorrespondence(true, false);
                lc.Current = 95;
            }
            catch (VKException ex)
            {
                //timerKeepAwake.Enabled = false;
                string error = ExceptionTranslation.TranslateException(ex);

                if (!string.IsNullOrEmpty(error))
                {
                    ViewData["LoadListResponseMessage"] = error;
                    view.UpdateView("LoadListResponseNegative");

                    if (ex.LocalizedMessage.Equals(ExceptionMessage.IncorrectLoginOrPassword))
                    {
                        Globals.BaseLogic.IDataLogic.SetToken(string.Empty);

                        view.UpdateView("GoToLogin");
                    }
                }
            }
            catch (OutOfMemoryException)
            {
                ViewData["LoadListResponseMessage"] = Resources.OutOfMemory;
                view.UpdateView("LoadListResponseNegative");
            }

            if (newMessShortCorrespondence != null)
            {
                FillListModel(newMessShortCorrespondence);
            }
            else
            {
                //view.Model.Clear();
            }

            ViewData["ListID"] = Globals.BaseLogic.IDataLogic.GetUid(); // сохраняем ID пользователя для которого был построен список

            view.UpdateView("LoadListResponse");

            // запускаем поток || прогрузки фотографий
            var t = new Thread(delegate { Globals.BaseLogic.ICommunicationLogic.LoadImagesInDictionary(); })
            {
                IsBackground = true
            };

            t.Start();

            lc.Current = 100;
        }
Exemple #2
0
        protected override void OnViewStateChanged(string key)
        {
            if (key == "DoLogin")
            {
                string login    = (string)view.ViewData["Login"];
                string password = (string)view.ViewData["Password"];

                try
                {
                    // авторизация по логину/паролю
                    using (new WaitWrapper())
                    {
                        Globals.BaseLogic.AuthLogin(login, password, true);
                    }

                    try
                    {
                        Globals.BaseLogic.IDataLogic.SetSavedLogin(login);
                    }
                    catch (Exception ex)
                    {
                        SystemConfiguration.Log.Write(LogEntryType.Error, "DataLogic.SetSavedLogin failed: " + ex.Message);
                    }

                    MasterForm.Navigate <StatusUpdatesListController>("LoginSuccess", "1");
                }
                catch (VKException ex)
                {
                    string message = ExceptionTranslation.TranslateException(ex);

                    if (!string.IsNullOrEmpty(message))
                    {
                        ViewData["LoginError"] = message;

                        view.UpdateView("LoginFail");
                    }
                }
                catch (OutOfMemoryException)
                {
                    ViewData["LoginError"] = Resources.OutOfMemory;

                    view.UpdateView("LoginFail");
                }
            }

            if (key == "CancelLogin")
            {
                Application.Exit();
            }
        }
Exemple #3
0
        /// <summary>
        /// This method indicates that something has been changed in the view.
        /// </summary>
        /// <param name="key">The string key to identify what has been changed.</param>
        protected override void OnViewStateChanged(string key)
        {
            #region SetStatus

            if (key == "SetStatus")
            {
                StringBuilder newStringBuilder = new StringBuilder();

                var status = (string)view.ViewData["CurrentStatus"];

                status = status.Replace("\r", string.Empty);
                status = status.Replace("\n", " ");
                status = status.Trim();

                //// пилим по переносам строки...
                //string[] lines = status.Split('\n');

                //foreach (string line in lines)
                //{
                //    newStringBuilder.Append(line);
                //    newStringBuilder.Append(" ");
                //}

                //status = newStringBuilder.ToString();

                //if (status.EndsWith(" "))
                //{
                //    status = status.Remove(status.Length - 1, 1);
                //}

                // ?
                ViewData["CurrentStatus"] = status;

                // обновление статуса
                try
                {
                    // обновление информации о пользователе
                    using (new WaitWrapper())
                    {
                        if (!string.IsNullOrEmpty(status))
                        {
                            Globals.BaseLogic.SetStatus(status, StatusActionType.Refresh, false);
                        }
                        else
                        {
                            Globals.BaseLogic.SetStatus(status, StatusActionType.Clear, false);
                        }
                    }

                    view.UpdateView("SetStatusSuccess");
                    view.UpdateView("HideCursor");

                    MasterForm.Navigate <ShareController>("UpdateStatus", view.ViewData["CurrentStatus"]);

                    //NavigationService.GoBack();

                    // ?
                    //MasterForm.Navigate<MainController>("Status", (string)ViewData["CurrentStatus"]);
                }
                catch (VKException ex)
                {
                    string error = ExceptionTranslation.TranslateException(ex);

                    if (!string.IsNullOrEmpty(error))
                    {
                        // показывать сообщение об ошибке вроде как не нужно
                        if (ex.LocalizedMessage == ExceptionMessage.IncorrectLoginOrPassword)
                        {
                            Globals.BaseLogic.IDataLogic.SetToken(string.Empty);
                            //MasterForm.Navigate<LoginController>();

                            view.UpdateView("GoToLogin");
                        }

                        ViewData["SetStatusError"] = error;
                        view.UpdateView("SetStatusFail");
                    }
                }
                catch (OutOfMemoryException)
                {
                    ViewData["SetStatusError"] = Resources.OutOfMemory;
                    view.UpdateView("SetStatusFail");
                }
            }

            #endregion

            #region Cancel

            if (key == "Cancel")
            {
                view.UpdateView("HideCursor");
                NavigationService.GoBack();
            }

            #endregion

            //OnViewStateChanged("GoGoToLogin");

            if (key == "GoGoToLogin")
            {
                MasterForm.Navigate <LoginController>();
            }
        }
        protected override void OnViewStateChanged(string key)
        {
            //ViewData["ResponseMessage"] = string.Empty; // а раньше работало как-то без этого

            #region key == "ClearRegistry"

            if (key == "ClearRegistry")
            {
                Globals.BaseLogic.IDataLogic.SetUplPhtViewHasMdfPht(false);
                Globals.BaseLogic.IDataLogic.SetUplPhtViewPhtCmnt(string.Empty);
                Globals.BaseLogic.IDataLogic.SetUplPhtViewPhtRtnAnglZero();
            }

            #endregion

            #region key == "ActivateForm"

            if (key == "ActivateForm")
            {
                try
                {
                    ViewData["ResponseMessage"] = string.Empty; // а раньше работало как-то без этого

                    ViewData["ImageFile"]      = SystemConfiguration.AppInstallPath + @"\Cache\Files\image.jpg";
                    ViewData["ThumbImageFile"] = SystemConfiguration.AppInstallPath + @"\Cache\Files\t_image.jpg";
                    ViewData["EmptyImageFile"] = SystemConfiguration.AppInstallPath + @"\Cache\Files\empty.jpg";

                    // "пустышка" для подмены
                    if (ViewData["EmptyImage"] == null)
                    {
                        IImage newIImage;

                        ImageHelper.SaveImageFromMemory(MasterForm.SkinManager.GetImage("EmptyImage"), (string)ViewData["EmptyImageFile"]);

                        ImageHelper.LoadImageFromFile((string)ViewData["EmptyImageFile"], out newIImage);

                        ViewData["EmptyImage"] = newIImage;
                    }

                    int displayAreaWidth  = (int)view.ViewData["DisplayAreaWidth"];
                    int displayAreaHeight = (int)view.ViewData["DisplayAreaHeight"];

                    // изображение
                    if (File.Exists((string)ViewData["ImageFile"]))
                    {
                        if (ViewData["Image"] == null)
                        {
                            IImage newIImage;
                            System.Drawing.Size imageSize;

                            ImageHelper.SaveScaledImage((string)ViewData["ImageFile"], (string)ViewData["ThumbImageFile"], (int)Math.Min(displayAreaWidth, displayAreaHeight), Globals.BaseLogic.IDataLogic.GetUplPhtViewPhtRtnAngl());

                            ImageHelper.LoadImageFromFile((string)ViewData["ThumbImageFile"], out newIImage, out imageSize);

                            ViewData["Image"]       = newIImage;
                            ViewData["ImageWidth"]  = imageSize.Width;
                            ViewData["ImageHeight"] = imageSize.Height;
                        }
                        else
                        {
                            if (Math.Max((int)ViewData["ImageWidth"], (int)ViewData["ImageHeight"]) != Math.Min(displayAreaWidth, displayAreaHeight))
                            {
                                IImage newIImage;
                                System.Drawing.Size imageSize;

                                newIImage         = (IImage)ViewData["Image"];
                                ViewData["Image"] = ViewData["EmptyImage"];
                                Marshal.FinalReleaseComObject(newIImage);

                                ImageHelper.SaveScaledImage((string)ViewData["ImageFile"], (string)ViewData["ThumbImageFile"], (int)Math.Min(displayAreaWidth, displayAreaHeight), Globals.BaseLogic.IDataLogic.GetUplPhtViewPhtRtnAngl());

                                ImageHelper.LoadImageFromFile((string)ViewData["ThumbImageFile"], out newIImage, out imageSize);

                                ViewData["Image"]       = newIImage;
                                ViewData["ImageWidth"]  = imageSize.Width;
                                ViewData["ImageHeight"] = imageSize.Height;
                            }
                        }
                    }
                    else
                    {
                        NavigationService.GoBack();
                    }
                }
                catch (OutOfMemoryException ex)
                {
                    ViewData["ResponseMessage"] = Resources.OutOfMemory;

                    DebugHelper.WriteLogEntry("UploadPhotoController.SnapPhotoWithinCamera OutOfMemoryException Message: " + ex.Message);
                    DebugHelper.WriteLogEntry("UploadPhotoController.SnapPhotoWithinCamera OutOfMemoryException StackTrace: " + ex.StackTrace);
                }
                catch (Exception ex)
                {
                    ViewData["ResponseMessage"] = Resources.ErrorMessages_OperationIsDoneUnsuccsessfully;

                    DebugHelper.WriteLogEntry("UploadPhotoController.ActivateForm Exception Message: " + ex.Message);
                    DebugHelper.WriteLogEntry("UploadPhotoController.ActivateForm Exception StackTrace: " + ex.StackTrace);
                }
                finally
                {
                    view.UpdateView("MainResponse");
                }
            }

            #endregion

            #region key == "DeactivateForm"

            if (key == "DeactivateForm")
            {
                if (ViewData["EmptyImage"] != null)
                {
                    Marshal.FinalReleaseComObject((IImage)ViewData["EmptyImage"]);
                    ViewData["EmptyImage"] = null;
                }

                if (ViewData["Image"] != null)
                {
                    Marshal.FinalReleaseComObject((IImage)ViewData["Image"]);
                    ViewData["Image"] = null;
                }

                ViewData["ImageFile"]      = SystemConfiguration.AppInstallPath + @"\Cache\Files\image.jpg";
                ViewData["ThumbImageFile"] = SystemConfiguration.AppInstallPath + @"\Cache\Files\t_image.jpg";
                ViewData["EmptyImageFile"] = SystemConfiguration.AppInstallPath + @"\Cache\Files\empty.jpg";

                if (File.Exists((string)ViewData["ImageFile"]))
                {
                    File.Delete((string)ViewData["ImageFile"]);
                }

                if (File.Exists((string)ViewData["ThumbImageFile"]))
                {
                    File.Delete((string)ViewData["ThumbImageFile"]);
                }

                if (File.Exists((string)ViewData["EmptyImageFile"]))
                {
                    File.Delete((string)ViewData["EmptyImageFile"]);
                }
            }

            #endregion

            #region key == "RotareImageClockwise" || key == "RotareImageCounterclockwise"

            if (key == "RotareImageClockwise" || key == "RotareImageCounterclockwise")
            {
                try
                {
                    IImage newIImage;
                    System.Drawing.Size imageSize;

                    int displayAreaWidth  = (int)view.ViewData["DisplayAreaWidth"];
                    int displayAreaHeight = (int)view.ViewData["DisplayAreaHeight"];

                    if (key == "RotareImageClockwise")
                    {
                        Globals.BaseLogic.IDataLogic.SetUplPhtViewPhtRtnAnglCW();
                    }

                    if (key == "RotareImageCounterclockwise")
                    {
                        Globals.BaseLogic.IDataLogic.SetUplPhtViewPhtRtnAnglCCW();
                    }

                    newIImage         = (IImage)ViewData["Image"];
                    ViewData["Image"] = ViewData["EmptyImage"];
                    Marshal.FinalReleaseComObject(newIImage);

                    ImageHelper.SaveScaledImage((string)ViewData["ImageFile"], (string)ViewData["ThumbImageFile"], (int)Math.Min(displayAreaWidth, displayAreaHeight), Globals.BaseLogic.IDataLogic.GetUplPhtViewPhtRtnAngl());

                    ImageHelper.LoadImageFromFile((string)ViewData["ThumbImageFile"], out newIImage, out imageSize);

                    ViewData["Image"]       = newIImage;
                    ViewData["ImageWidth"]  = imageSize.Width;
                    ViewData["ImageHeight"] = imageSize.Height;
                }
                catch (OutOfMemoryException ex)
                {
                    ViewData["ResponseMessage"] = Resources.OutOfMemory;

                    DebugHelper.WriteLogEntry("UploadPhotoController.RotareImage OutOfMemoryException Message: " + ex.Message);
                    DebugHelper.WriteLogEntry("UploadPhotoController.RotareImage OutOfMemoryException StackTrace: " + ex.StackTrace);
                }
                catch (Exception ex)
                {
                    ViewData["ResponseMessage"] = Resources.ErrorMessages_OperationIsDoneUnsuccsessfully;

                    DebugHelper.WriteLogEntry("UploadPhotoController.RotareImage Exception Message: " + ex.Message);
                    DebugHelper.WriteLogEntry("UploadPhotoController.RotareImage Exception StackTrace: " + ex.StackTrace);
                }
                finally
                {
                    view.UpdateView("MainResponse");
                }
            }

            #endregion

            #region key == "UploadPhoto"

            if (key == "UploadPhoto")
            {
                /*
                 * LoadingControlInterface lc = LoadingControl.CreateLoading(Resources.ImageUpload);
                 *
                 * Thread asyncDataThread = new Thread(delegate { AsyncGetViewData(lc); });
                 * asyncDataThread.IsBackground = true;
                 * asyncDataThread.Start();
                 *
                 * lc.ShowLoading(true);
                 *
                 * if (lc.Abort)
                 * {
                 *  asyncDataThread.Abort();
                 * }
                 */

                try
                {
                    ImageHelper.PostProcessImageFile((string)ViewData["ImageFile"], Globals.BaseLogic.IDataLogic.GetUplPhtViewPhtRtnAngl());
                    Globals.BaseLogic.IDataLogic.SetUplPhtViewPhtRtnAnglZero(); // после PostProcess угол необходимо сбросить

                    byte[] file;

                    using (BinaryReader newBinaryReader = new BinaryReader(File.Open((string)ViewData["ImageFile"], FileMode.Open)))
                    {
                        file = new byte[newBinaryReader.BaseStream.Length];
                        newBinaryReader.Read(file, 0, file.Length);
                    }

                    using (new WaitWrapper())
                    {
                        Globals.BaseLogic.UploadPhoto(file, false, false);
                    }

                    ViewData["ResponseMessage"] = Resources.UploadPhoto_Controller_ResponseMessage_ImageSuccessfullyDownloaded;
                }
                catch (VKException ex)
                {
                    string error = ExceptionTranslation.TranslateException(ex);

                    if (ex.LocalizedMessage.Equals(ExceptionMessage.IncorrectLoginOrPassword))
                    {
                        Globals.BaseLogic.IDataLogic.SetToken(string.Empty);

                        view.UpdateView("GoToLogin");
                    }

                    ViewData["ResponseMessage"] = error;
                }
                catch (OutOfMemoryException ex)
                {
                    ViewData["ResponseMessage"] = Resources.OutOfMemory;

                    DebugHelper.WriteLogEntry("UploadPhotoController.UploadPhoto OutOfMemoryException Message: " + ex.Message);
                    DebugHelper.WriteLogEntry("UploadPhotoController.UploadPhoto OutOfMemoryException StackTrace: " + ex.StackTrace);
                }
                catch (Exception ex)
                {
                    ViewData["ResponseMessage"] = Resources.ErrorMessages_OperationIsDoneUnsuccsessfully;

                    DebugHelper.WriteLogEntry("UploadPhotoController.UploadPhoto Exception Message: " + ex.Message);
                    DebugHelper.WriteLogEntry("UploadPhotoController.UploadPhoto Exception StackTrace: " + ex.StackTrace);
                }
                finally
                {
                    view.UpdateView("MainResponse");
                }
            }

            #endregion

            //

            #region key == "GoBack"

            if (key == "GoBack")
            {
                //NavigationService.GoBack();

                MasterForm.Navigate <ShareController>("AllowReloadData", "false");
            }

            #endregion

            if (key == "GoGoToLogin")
            {
                MasterForm.Navigate <LoginController>();
            }
        }
Exemple #5
0
        protected override void OnViewStateChanged(string key)
        {
            #region Check AutoLogin

            if (key == "CheckAutoLogin")
            {
                try
                {
                    using (new WaitWrapper())
                    {
                        Globals.BaseLogic.AutoLogin();
                    }

                    Initialize("LoginSuccess");
                }
                catch (VKException ex)
                {
                    string message = ExceptionTranslation.TranslateException(ex);

                    if (!string.IsNullOrEmpty(message))
                    {
                        if (ex.LocalizedMessage == ExceptionMessage.IncorrectLoginOrPassword)
                        {
                            Globals.BaseLogic.IDataLogic.SetToken(string.Empty);

                            MasterForm.Navigate <LoginController>("IncorrectLoginOrPassword");
                        }
                        else if (ex.LocalizedMessage == ExceptionMessage.NoSavedToken)
                        {
                            MasterForm.Navigate <LoginController>();
                        }
                        else if (ex.LocalizedMessage == ExceptionMessage.UnknownError)
                        {
                            MasterForm.Navigate <LoginController>("UnknownError");
                        }
                        else
                        {
                            Initialize("LoginSuccess");
                        }
                    }
                }
                catch (OutOfMemoryException)
                {
                    DialogControl.ShowQuery(Resources.OutOfMemory, DialogButtons.OK);
                }
            }

            #endregion

            #region InitializeSettings

            else if (key == "InitializeSettings")
            {
                using (new WaitWrapper())
                {
                    // если приложение запущено при остановленном нотификаторе, то очищаем кэш
                    // это единственное место, где осуществляется это действие

                    //if (!Interprocess.IsServiceRunning)
                    {
                        Cache.DeleteEntryFromCache(string.Empty, "ShortActivityResponse");
                        Cache.DeleteEntryFromCache(string.Empty, "ShortUpdatesPhotosResponse");
                        Cache.DeleteEntryFromCache(string.Empty, "ShortWallResponse");
                        Cache.DeleteEntryFromCache(string.Empty, "ShortPhotosCommentsRespounse");
                    }

                    #region SetShowEventButtons

                    if (Globals.BaseLogic.IDataLogic.GetShowButtonMessages())
                    {
                        Globals.BaseLogic.IDataLogic.SetShowButtonMessages();
                    }

                    if (Globals.BaseLogic.IDataLogic.GetShowButtonComments())
                    {
                        Globals.BaseLogic.IDataLogic.SetShowButtonComments();
                    }

                    if (Globals.BaseLogic.IDataLogic.GetShowButtonFriends())
                    {
                        Globals.BaseLogic.IDataLogic.SetShowButtonFriends();
                    }

                    if (Globals.BaseLogic.IDataLogic.GetShowButtonFriendsNews())
                    {
                        Globals.BaseLogic.IDataLogic.SetShowButtonFriendsNews();
                    }

                    if (Globals.BaseLogic.IDataLogic.GetShowButtonFriendsPhotos())
                    {
                        Globals.BaseLogic.IDataLogic.SetShowButtonFriendsPhotos();
                    }

                    if (Globals.BaseLogic.IDataLogic.GetShowButtonWallMessages())
                    {
                        Globals.BaseLogic.IDataLogic.SetShowButtonWallMessages();
                    }

                    #endregion

                    Configuration.LoadConfigSettings();
                    Configuration.SaveConfigSettings();

                    #region старт/стоп нотификатора

                    if (Configuration.BackgroundNotification != BackgroundNotificationTypes.Off)
                    {
                        Globals.BaseLogic.IDataLogic.SetNtfAutorun();

                        OnViewStateChanged("StartNotificator");
                    }
                    else
                    {
                        OnViewStateChanged("StopNotificator");

                        Globals.BaseLogic.IDataLogic.DelNtfAutorun();
                    }

                    OnViewStateChanged("StopNotificator");

                    #endregion
                }
            }

            #endregion

            #region StartNotificator

            if (key == "StartNotificator")
            {
                if (!string.IsNullOrEmpty(Globals.BaseLogic.IDataLogic.GetToken()))
                {
                    //// запуск службы нотификатора
                    //try
                    //{
                    //    if (!Interprocess.IsServiceRunning)
                    //    {
                    //        Interprocess.StartService();
                    //    }
                    //}
                    //catch (Exception ex)
                    //{
                    //    ViewData["NotificatorStartError"] = ex.Message;
                    //    view.UpdateView("NotificatorStartFail");
                    //}
                }
                else
                {
                    DialogControl.ShowQuery(Resources.MainView_Button_NotificatorCantStart, DialogButtons.OK);
                }
            }

            #endregion

            #region StopNotificator

            if (key == "StopNotificator")
            {
                // остановка службы нотификатора
                //Interprocess.StopService();
            }

            #endregion

            #region GetMainViewData

            if (key == "GetMainViewData")
            {
                LoadingControlInterface lc = LoadingControl.CreateLoading(Resources.DataLoading);

                Thread asyncDataThread = new Thread(delegate { AsyncGetMainViewData(lc); });

                asyncDataThread.IsBackground = true;
                asyncDataThread.Start();

                lc.ShowLoading(false);

                if (lc.Abort)
                {
                    asyncDataThread.Abort();
                }
            }

            #endregion

            #region GoToUploadPhoto

            if (key == "GoToUploadPhoto")
            {
                MasterForm.Navigate <UploadPhotoController>();
            }

            #endregion

            #region AutoUpdate

            if (key == "AutoUpdate")
            {
                var updateHelper = new UpdateHelper((UIViewBase)ViewData["MainViewThis"]);

                updateHelper.CheckNewVersion();
            }

            #endregion

            #region ChangeStatus

            if (key == "ChangeStatus")
            {
                MasterForm.Navigate <ChangeStatusController>((string)ViewData["UserStatus"]);
            }

            #endregion

            #region CheckNewEvents

            if (key == "CheckNewEvents")
            {
                // проверка флага необходимости обновления списка событий
                if (Globals.BaseLogic.IDataLogic.GetRefreshEventsFlag() == "1")
                {
                    try
                    {
                        // загрузка событий
                        EventsGetResponse newEventsGetResponse = Globals.BaseLogic.EventsGet(false, false, false);

                        ViewData["MessagesCount"]      = string.Empty;
                        ViewData["CommentsCount"]      = string.Empty;
                        ViewData["FriendsCount"]       = string.Empty;
                        ViewData["FriendsNewsCount"]   = string.Empty;
                        ViewData["FriendsPhotosCount"] = string.Empty;
                        ViewData["WallCount"]          = string.Empty;

                        foreach (Event newEvent in newEventsGetResponse.events)
                        {
                            switch (newEvent.type)
                            {
                            case EventType.Messages:
                                ViewData["MessagesCount"] = newEvent.number.ToString();
                                break;

                            case EventType.Comments:
                                ViewData["CommentsCount"] = newEvent.number.ToString();
                                break;

                            case EventType.Friends:
                                ViewData["FriendsCount"] = newEvent.number.ToString();
                                break;

                            case EventType.FriendsNews:
                                ViewData["FriendsNewsCount"] = newEvent.number.ToString();
                                break;

                            case EventType.FriendsPhotos:
                                ViewData["FriendsPhotosCount"] = newEvent.number.ToString();
                                break;

                            case EventType.WallMessages:
                                ViewData["WallCount"] = newEvent.number.ToString();
                                break;
                            }
                        }

                        view.UpdateView("RefreshEventsInfo");
                    }
                    catch (Exception ex)
                    {
                        //
                    }
                }
            }

            #endregion



            #region GoToNews

            if (key == "GoToNews")
            {
                MasterForm.Navigate <StatusUpdatesListController>();
            }

            #endregion

            #region GoToFriends

            if (key == "GoToFriends")
            {
                MasterForm.Navigate <FriendsListController>();
            }

            #endregion

            #region GoToMessages

            if (key == "GoToMessages")
            {
                MasterForm.Navigate <MessagesChainsListController>();
            }

            #endregion

            #region GoToExtras

            if (key == "GoToExtras")
            {
                MasterForm.Navigate <ExtraController>();
            }

            #endregion
        }
Exemple #6
0
        private void AsyncGetMainViewData(LoadingControlInterface lc)
        {
            bool isRefresh = (Configuration.AutoUpdateAtStart || (string)ViewData["IsRefreshMainViewData"] == "1");

            // загрузка данных главной страницы
            try
            {
                lc.Current = 5;

                // загрузка событий
                EventsGetResponse newEventsGetResponse = Globals.BaseLogic.EventsGet(isRefresh, false, true);
                lc.Current = 10;

                FillEventsListModel(newEventsGetResponse);
                view.UpdateView("RefreshEventsInfo");

                if (lc.Abort)
                {
                    isRefresh = false;
                }

                // загрузка профиля
                User user = Globals.BaseLogic.GetAuthorizedUserInfo(isRefresh, false);
                lc.Current = 20;

                ViewData["UserName"]   = user.FirstName + " " + user.LastName;
                ViewData["UserStatus"] = user.Status;
                view.UpdateView("RefreshUserInfo");

                if (lc.Abort)
                {
                    isRefresh = false;
                }

                //загрузка аватара
                bool res = Globals.BaseLogic.ICommunicationLogic.LoadImage(user.Photo200px, HttpUtility.GetMd5Hash(user.Photo200px), isRefresh, _afterLoadImageEventHandler, UISettings.CalcPix(50), 0, "int");
                lc.Current = 30;

                if (res)
                {
                    ViewData["AvatarPath"] = SystemConfiguration.AppInstallPath + "//Cache//Files//" + HttpUtility.GetMd5Hash(user.Photo200px);
                }
                else
                {
                    ViewData["AvatarPath"] = string.Empty;
                }

                view.UpdateView("RefreshAvatarFromCache");

                // прогружаем очередь...
                var t = new Thread(delegate { Globals.BaseLogic.ICommunicationLogic.LoadImagesInDictionary(); })
                {
                    IsBackground = true
                };

                t.Start();
            }
            catch (VKException ex)
            {
                string error = ExceptionTranslation.TranslateException(ex);

                if (!String.IsNullOrEmpty(error))
                {
                    ViewData["GetError"] = error;

                    view.UpdateView("GetFail");

                    if (ex.LocalizedMessage.Equals(ExceptionMessage.IncorrectLoginOrPassword))
                    {
                        Globals.BaseLogic.IDataLogic.SetToken(string.Empty);

                        MasterForm.Navigate <LoginController>();
                    }
                }

                // если не обновились, грузим из кэша
                try
                {
                    // загрузка событий
                    EventsGetResponse newEventsGetResponse = Globals.BaseLogic.EventsGet(false, false, true);
                    lc.Current = 40;

                    FillEventsListModel(newEventsGetResponse);
                    view.UpdateView("RefreshEventsInfo");

                    // профиль
                    User user = Globals.BaseLogic.GetAuthorizedUserInfo(false, false);
                    lc.Current = 50;

                    ViewData["UserName"]   = user.FirstName + " " + user.LastName;
                    ViewData["UserStatus"] = user.Status;

                    view.UpdateView("RefreshUserInfo");

                    // аватар
                    bool res = Globals.BaseLogic.ICommunicationLogic.LoadImage(user.Photo200px, HttpUtility.GetMd5Hash(user.Photo200px), false, _afterLoadImageEventHandler, UISettings.CalcPix(50), 0, "int");
                    lc.Current = 60;

                    if (res)
                    {
                        ViewData["AvatarPath"] = SystemConfiguration.AppInstallPath + "//Cache//Files//" + HttpUtility.GetMd5Hash(user.Photo200px);
                    }
                    else
                    {
                        ViewData["AvatarPath"] = string.Empty;
                    }

                    view.UpdateView("RefreshAvatarFromCache");
                }
                catch (Exception e)
                {
                    DebugHelper.WriteLogEntry(e, "Error reading from cache");
                }
            }
            catch (OutOfMemoryException)
            {
                ViewData["GetError"] = Resources.OutOfMemory;
                view.UpdateView("GetFail");
            }
            catch (Exception ex)
            {
                DebugHelper.WriteLogEntry(ex.Message);
            }

            // прогрузить остальные данные при старте
            if (((string)ViewData["IsFirstStart"]).Equals("1") && Configuration.AutoUpdateAtStart)
            {
                try
                {
                    // список друзей
                    if (lc.Abort)
                    {
                        isRefresh = false;
                    }

                    Globals.BaseLogic.LoadFriendsList(isRefresh, false);
                    lc.Current = 70;

                    // список обновлений статусов
                    if (lc.Abort)
                    {
                        isRefresh = false;
                    }

                    Globals.BaseLogic.LoadActivityDataList(25, isRefresh, false);
                    lc.Current = 80;

                    // список комментариев к фотографиям пользователя
                    if (lc.Abort)
                    {
                        isRefresh = false;
                    }

                    Globals.BaseLogic.LoadPhotosComments(25, isRefresh, false);
                    lc.Current = 90;

                    // список заголовков цепочек сообщений пользователя
                    if (lc.Abort)
                    {
                        isRefresh = false;
                    }

                    Globals.BaseLogic.GetShortCorrespondence(isRefresh, false);
                    lc.Current = 95;
                }
                catch (VKException ex)
                {
                    DebugHelper.WriteLogEntry("Can't download data at start: " + ex.LocalizedMessage + ex.StackTrace);
                }
                catch (OutOfMemoryException ex)
                {
                    DebugHelper.WriteLogEntry("Can't download data at start: " + ex.Message + ex.StackTrace);
                }
                catch (Exception ex)
                {
                    DebugHelper.WriteLogEntry("Can't download data at start: " + ex.Message);
                }
            }

            lc.Current = 100;
        }
Exemple #7
0
        private void AsyncGetViewData(LoadingControlInterface lc)
        {
            lc.Current = 0;

            ActivityResponse newActivityResponse = null;
            User             currentUser         = null;

            try
            {
                lc.Current = 5;

                // загружаем прошлые статусы пользователя
                newActivityResponse = Globals.BaseLogic.LoadUserActivityDataList(25, true, false);
                lc.Current          = 50;

                currentUser = Globals.BaseLogic.GetAuthorizedUserInfo(true, false);
                lc.Current  = 95;
            }
            catch (VKException ex)
            {
                //timerKeepAwake.Enabled = false;
                string error = ExceptionTranslation.TranslateException(ex);

                if (!string.IsNullOrEmpty(error))
                {
                    ViewData["LoadListResponseMessage"] = error;
                    view.UpdateView("LoadListResponseNegative");

                    if (ex.LocalizedMessage.Equals(ExceptionMessage.IncorrectLoginOrPassword))
                    {
                        //Globals.BaseLogic.IDataLogic.SetToken(string.Empty);
                        //MasterForm.Navigate<LoginController>();

                        view.UpdateView("GoToLogin");
                    }

                    //newActivityResponse = LoadDataFromCache();
                }
            }
            catch (OutOfMemoryException)
            {
                ViewData["GetViewDataResponseMessage"] = Resources.OutOfMemory;
                view.UpdateView("GetViewDataResponseNegative");
            }

            if (newActivityResponse != null)
            {
                FillListModel(newActivityResponse, true);

                if (currentUser != null)
                {
                    UpdateListModel(currentUser.Status);
                }
            }
            else
            {
                //view.Model.Statuses.Clear();
            }

            ViewData["ListID"] = Globals.BaseLogic.IDataLogic.GetUid(); // сохраняем ID пользователя для которого был построен список

            view.UpdateView("LoadListResponse");

            lc.Current = 100;
        }
        private void AsyncGetViewData(LoadingControlInterface lc)
        {
            lc.Current = 0;

            // приходит через initialize
            int uid = Convert.ToInt32((string)ViewData["UserID"]);
            //ViewData["UserName"] = Globals.BaseLogic.GetFriendName(uid.ToString());

            MessUserCorrespondence newMessUserCorrespondence = null;

            try
            {
                lc.Current = 5;

                newMessUserCorrespondence = Globals.BaseLogic.RefreshUserCorrespondence(uid, true, false, null);
                lc.Current = 95;
            }
            catch (VKException ex)
            {
                //timerKeepAwake.Enabled = false;
                string error = ExceptionTranslation.TranslateException(ex);

                if (!string.IsNullOrEmpty(error))
                {
                    //newMessUserCorrespondence = LoadDataFromCache(uid);

                    ViewData["LoadListResponseMessage"] = error;
                    view.UpdateView("LoadListResponseNegative");

                    if (ex.LocalizedMessage.Equals(ExceptionMessage.IncorrectLoginOrPassword))
                    {
                        Globals.BaseLogic.IDataLogic.SetToken(string.Empty);

                        view.UpdateView("GoToLogin");;
                    }
                }
            }
            catch (OutOfMemoryException)
            {
                ViewData["LoadListResponseMessage"] = Resources.OutOfMemory;
                view.UpdateView("LoadListResponseNegative");
            }

            if (newMessUserCorrespondence != null)
            {
                FillListModel(newMessUserCorrespondence);
            }
            else
            {
                //view.Model.Clear();
            }

            //ViewData["MessageDraftInput"] = DraftMessagesDataIO.GetDraftMessage(uid);

            view.UpdateView("LoadListResponse");

            // запускаем поток || прогрузки фотографий
            var t = new Thread(delegate { Globals.BaseLogic.ICommunicationLogic.LoadImagesInDictionary(); })
            {
                IsBackground = true
            };

            t.Start();

            lc.Current = 100;
        }
        /// <summary>
        /// This method indicates that something has been changed in the view.
        /// </summary>
        /// <param name="key">The string key to identify what has been changed.</param>
        protected override void OnViewStateChanged(string key)
        {
            #region Activate

            if (key == "Activate")
            {
                int uid = Convert.ToInt32((string)ViewData["UserID"]);

                //string friendName = Globals.BaseLogic.GetFriendName(uid.ToString());
                string oldText = DraftMessagesDataIO.GetDraftMessage(uid);

                //view.ViewData["UserName"] = friendName;
                view.ViewData["MessageDraftInput"] = oldText;

                // проверяем: запретить ли смену пользователя?
                if (((string)ViewData["BackLink"]).Equals("ImageDetailedView"))
                {
                    ViewData["AFRHideButton"] = true;
                }
                else
                {
                    ViewData["AFRHideButton"] = false;
                }

                view.UpdateView("ActivateResponse");
            }

            #endregion

            #region SentMessage

            if (key == "SentMessage")
            {
                bool result = false;

                int    uid  = Convert.ToInt32((string)ViewData["UserID"]);
                string text = (string)ViewData["MessageDraftOutput"];

                try
                {
                    using (new WaitWrapper())
                    {
                        // проверка на Empty во вьюхе
                        result = Globals.BaseLogic.SendMessage(uid, text, false);
                    }
                }
                catch (VKException ex)
                {
                    string error = ExceptionTranslation.TranslateException(ex);

                    ViewData["SentMessageResponseMessage"] = error;
                    ViewData["MessageIsSent"] = "false";

                    view.UpdateView("SentMessageResponse");

                    if (ex.LocalizedMessage.Equals(ExceptionMessage.IncorrectLoginOrPassword))
                    {
                        Globals.BaseLogic.IDataLogic.SetToken(string.Empty);

                        view.UpdateView("GoToLogin");
                    }

                    return;
                }
                catch (OutOfMemoryException)
                {
                    ViewData["SentMessageResponseMessage"] = Resources.OutOfMemory;
                    ViewData["MessageIsSent"] = "false";

                    view.UpdateView("SentMessageResponse");
                    return;
                }

                using (new WaitWrapper(false))
                {
                    if (result)
                    {
                        DraftMessagesDataIO.DeleteDraftMessage(uid);
                        ViewData["MsgForChangedReceiver"] = string.Empty;

                        Globals.BaseLogic.SaveSendMessageToCache(uid, text);

                        ViewData["SentMessageResponseMessage"] =
                            Resources.MessagesList_Controller_Messages_MessageSentSuccessfully;
                        ViewData["MessageIsSent"] = "true";
                    }
                    else
                    {
                        ViewData["SentMessageResponseMessage"] =
                            Resources.MessagesList_Controller_Messages_MessageSentUnsuccessfully;
                        ViewData["MessageIsSent"] = "false";
                    }
                }

                view.UpdateView("SentMessageResponse");
            }

            #endregion

            #region Back
            if (key == "Back")
            {
                int    uid  = Convert.ToInt32((string)ViewData["UserID"]);
                string text = ((string)ViewData["MessageDraftOutput"]).Trim();;

                DraftMessagesDataIO.SetDraftMessage(text, uid);
                NavigateBack();
            }
            #endregion

            #region SendComplete
            if (key == "SendComplete")
            {
                NavigateBack();
            }
            #endregion

            #region ChangeReceiver

            if (key == "ChangeReceiver")
            {
                using (new WaitWrapper(false))
                {
                    MasterForm.Navigate <FriendsSearchListController>((string)ViewData["BackLink"]);
                }
            }

            #endregion

            if (key == "GoGoToLogin")
            {
                MasterForm.Navigate <LoginController>();
            }
        }
Exemple #10
0
        private void AsyncGetViewData(LoadingControlInterface lc)
        {
            lc.Current = 0;

            FriendsListResponse newFriendsListResponse = null;

            //bool isRefresh = Convert.ToBoolean((string)ViewData["IsRefresh"]);

            try
            {
                lc.Current = 5;

                //if (lc.Abort)
                //{
                //    isRefresh = false;
                //}

                newFriendsListResponse = Globals.BaseLogic.LoadFriendsList(true, false);
                lc.Current             = 95;
            }
            catch (VKException ex)
            {
                string error = ExceptionTranslation.TranslateException(ex);

                if (!string.IsNullOrEmpty(error))
                {
                    ViewData["LoadListResponseMessage"] = error;
                    view.UpdateView("LoadListResponseNegative");

                    if (ex.LocalizedMessage.Equals(ExceptionMessage.IncorrectLoginOrPassword))
                    {
                        Globals.BaseLogic.IDataLogic.SetToken(string.Empty);

                        view.UpdateView("GoToLogin");
                    }
                }
            }
            catch (OutOfMemoryException)
            {
                ViewData["LoadListResponseMessage"] = Resources.OutOfMemory;
                view.UpdateView("LoadListResponseNegative");
            }

            if (newFriendsListResponse != null)
            {
                ViewData["OriginalFrendListResponse"] = newFriendsListResponse;

                FillListModel(newFriendsListResponse, string.Empty);
            }

            view.UpdateView("LoadListResponse");

            //// запускаем поток || прогрузки фотографий
            //var t = new Thread(() => Globals.BaseLogic.ICommunicationLogic.LoadImagesInDictionary())
            //{
            //    IsBackground = true
            //};

            //t.Start();

            lc.Current = 100;
        }
        protected override void OnViewStateChanged(string key)
        {
            #region InitializeSettings

            if (key == "InitializeSettings")
            {
                using (new WaitWrapper())
                {
                    // если приложение запущено при остановленном нотификаторе, то очищаем кэш
                    // это единственное место, где осуществляется это действие
                    //if (!Interprocess.IsServiceRunning)
                    {
                        Cache.DeleteEntryFromCache(string.Empty, "ShortActivityResponse");
                        Cache.DeleteEntryFromCache(string.Empty, "ShortUpdatesPhotosResponse");
                        Cache.DeleteEntryFromCache(string.Empty, "ShortWallResponse");
                        Cache.DeleteEntryFromCache(string.Empty, "ShortPhotosCommentsRespounse");
                    }

                    Configuration.LoadConfigSettings();
                    Configuration.SaveConfigSettings();

                    #region старт/стоп нотификатора

                    if (Configuration.BackgroundNotification != BackgroundNotificationTypes.Off)
                    {
                        Globals.BaseLogic.IDataLogic.SetNtfAutorun();

                        OnViewStateChanged("StartNotificator");
                    }
                    else
                    {
                        OnViewStateChanged("StopNotificator");

                        Globals.BaseLogic.IDataLogic.DelNtfAutorun();
                    }

                    OnViewStateChanged("StopNotificator");

                    #endregion
                }
            }

            #endregion

            #region StartNotificator

            if (key == "StartNotificator")
            {
                if (!string.IsNullOrEmpty(Globals.BaseLogic.IDataLogic.GetToken()))
                {
                    // запуск службы нотификатора
                    try
                    {
                        //if (!Interprocess.IsServiceRunning)
                        //{
                        //    Interprocess.StartService();
                        //}
                    }
                    catch (Exception ex)
                    {
                        ViewData["NotificatorStartError"] = ex.Message;
                        view.UpdateView("NotificatorStartFail");
                    }
                }
                else
                {
                    DialogControl.ShowQuery(Resources.MainView_Button_NotificatorCantStart, DialogButtons.OK);
                }
            }

            #endregion

            #region StopNotificator

            if (key == "StopNotificator")
            {
                // остановка службы нотификатора
                //Interprocess.StopService();
            }

            #endregion

            #region GetViewData

            if (key == "GetViewData")
            {
                bool isRefrsh = Convert.ToBoolean(ViewData["IsRefresh"]);

                if (isRefrsh)
                {
                    LoadingControlInterface lc = LoadingControl.CreateLoading((string)ViewData["NeedChangeText"] != "1" ? Resources.DataLoading : Resources.FirstDataLoading);
                    ViewData["NeedChangeText"] = "0";

                    timerKeepAwake.Enabled = true;

                    Thread asyncDataThread = new Thread(delegate
                    {
                        try
                        {
                            timerKeepAwake.Enabled = true;

                            AsyncGetViewData(lc);
                        }
                        finally
                        {
                            timerKeepAwake.Enabled = false;
                        }
                    });
                    asyncDataThread.IsBackground = true;
                    asyncDataThread.Start();

                    lc.ShowLoading(true);

                    if (lc.Abort)
                    {
                        asyncDataThread.Abort();
                    }
                }
                else
                {
                    try
                    {
                        ActivityResponse      newActivityResponse      = Globals.BaseLogic.LoadActivityDataList(25, false, false);
                        UpdatesPhotosResponse newUpdatesPhotosResponse = Globals.BaseLogic.LoadUpdatesPhotos(25, false, false);

                        if (newActivityResponse != null)
                        {
                            FillListModel(newActivityResponse, false);
                        }
                        else
                        {
                            view.Model.Statuses.Clear();
                        }

                        if (newUpdatesPhotosResponse != null)
                        {
                            FillListModel(newUpdatesPhotosResponse, false);
                        }
                        else
                        {
                            view.Model.Photos.Clear();
                        }

                        view.UpdateView("LoadListResponse");
                    }
                    catch
                    {
                        // гасим
                    }
                }
            }

            #endregion

            #region Check AutoLogin

            if (key == "CheckAutoLogin")
            {
                try
                {
                    using (new WaitWrapper())
                    {
                        //Globals.BaseLogic.AutoLogin();
                    }

                    Initialize("AutoLoginSuccess");
                }
                catch (VKException ex)
                {
                    string message = ExceptionTranslation.TranslateException(ex);

                    //if (!string.IsNullOrEmpty(message))
                    //{
                    //    if (ex.LocalizedMessage == ExceptionMessage.IncorrectLoginOrPassword)
                    //    {
                    //        Globals.BaseLogic.IDataLogic.SetToken(string.Empty);

                    //        MasterForm.Navigate<LoginController>("IncorrectLoginOrPassword");
                    //    }
                    //    else if (ex.LocalizedMessage == ExceptionMessage.NoSavedToken)
                    //    {
                    //        MasterForm.Navigate<LoginController>("NoSavedToken");
                    //    }
                    //    else if (ex.LocalizedMessage == ExceptionMessage.UnknownError)
                    //    {
                    //        MasterForm.Navigate<LoginController>("UnknownError");
                    //    }
                    //    else
                    //    {
                    //        Initialize("LoginSuccess");
                    //    }
                    //}
                }
                catch (OutOfMemoryException)
                {
                    DialogControl.ShowQuery(Resources.OutOfMemory, DialogButtons.OK);
                }
            }

            #endregion

            #region AutoUpdate

            if (key == "AutoUpdate")
            {
                UpdateHelper updateHelper = new UpdateHelper((UIViewBase)ViewData["StatusUpdatesListView"]);
                updateHelper.CheckNewVersion();
            }

            #endregion

            #region GoToSendMessage

            if (key == "GoToSendMessage")
            {
                MasterForm.Navigate <SendMessageController>("FriendsStatus", ViewData["Uid"]);
            }

            #endregion



            // верхнее меню

            #region ReloadList

            if (key == "ReloadList")
            {
                view.UpdateView("ReloadListResponse");
            }

            #endregion

            #region RefreshList

            if (key == "RefreshList")
            {
                view.UpdateView("RefreshListResponse");
            }

            #endregion

            #region GoToPhotoComments

            if (key == "GoToPhotoComments")
            {
                MasterForm.Navigate <PhotoCommentsUpdatesListController>();
            }

            #endregion



            #region GoToMessages

            if (key == "GoToMessages")
            {
                MasterForm.Navigate <MessagesChainsListController>();
            }

            #endregion

            #region GoToFriends

            if (key == "GoToFriends")
            {
                MasterForm.Navigate <FriendsListController>();
            }

            #endregion

            #region GoToPhoto

            if (key == "GoToPhotos")
            {
                //MasterForm.Navigate<UploadPhotoController>();
                MasterForm.Navigate <ShareController>();
            }

            #endregion

            #region GoDetailedView

            if (key == "GoDetailedView")
            {
                int    uid           = Convert.ToInt32((string)ViewData["Uid"]);
                int    photoID       = Convert.ToInt32((string)ViewData["PhotoID"]);
                string largePhotoURL = (string)ViewData["LargePhotoURL"];

                if (uid > 0 && photoID > 0)
                {
                    MasterForm.Navigate <ImageCommentController>("Load", uid.ToString(), photoID.ToString(), largePhotoURL);
                }
            }

            #endregion

            #region GoToExtras

            if (key == "GoToExtras")
            {
                MasterForm.Navigate <ExtraController>();
            }

            #endregion



            #region ListActualization

            if (key == "ListActualization")
            {
                // на этой форме необходимости проверять нет, так как переход Login -> this вызывает Reload списка

                //string currentID = Globals.BaseLogic.IDataLogic.GetUid();
                //string listID = (string)ViewData["ListID"];

                //if (currentID != listID)
                //{
                //    OnViewStateChanged("GetViewData");
                //}
            }

            #endregion

            if (key == "GoGoToLogin")
            {
                MasterForm.Navigate <LoginController>();
            }
        }
        private void AsyncGetViewData(LoadingControlInterface lc)
        {
            string isFirstStart = (string)ViewData["IsFirstStart"];

            ViewData["IsFirstStart"] = "0";

            lc.Current = 2;

            ActivityResponse      newActivityResponse      = null;
            UpdatesPhotosResponse newUpdatesPhotosResponse = null;

            // первичные данные формы
            try
            {
                // загружаем новые новости
                newActivityResponse = Globals.BaseLogic.LoadActivityDataList(25, true, false);
                lc.Current          = 4;

                // загружаем новые фото
                newUpdatesPhotosResponse = Globals.BaseLogic.LoadUpdatesPhotos(25, true, false);
                lc.Current = 10;

                ViewData["FirstActivate"] = string.Empty;
            }
            catch (VKException ex)
            {
                timerKeepAwake.Enabled = false;
                string error = ExceptionTranslation.TranslateException(ex);

                if (!string.IsNullOrEmpty(error))
                {
                    ViewData["GetViewDataResponseMessage"] = error;
                    view.UpdateView("GetViewDataResponseNegative");

                    if (ex.LocalizedMessage.Equals(ExceptionMessage.IncorrectLoginOrPassword))
                    {
                        Globals.BaseLogic.IDataLogic.SetToken(string.Empty);

                        //view.UpdateView("GoToLogin");
                        OnViewStateChanged("GoToLogin");
                    }
                }
            }
            catch (OutOfMemoryException)
            {
                ViewData["GetViewDataResponseMessage"] = Resources.OutOfMemory;
                view.UpdateView("GetViewDataResponseNegative");
            }

            if (newActivityResponse != null)
            {
                FillListModel(newActivityResponse, true);
            }

            if (newUpdatesPhotosResponse != null)
            {
                FillListModel(newUpdatesPhotosResponse, true);
            }

            ViewData["ListID"] = Globals.BaseLogic.IDataLogic.GetUid(); // сохраняем ID пользователя для которого был построен список

            view.UpdateView("LoadListResponse");

            // прочие данные при старте приложения
            if (isFirstStart.Equals("1") && Configuration.DataRenewType != DataRenewVariants.DontUpdate)
            {
                try
                {
                    int  totalCount;
                    int  alreadyGet;
                    bool isData;

                    // список друзей
                    Globals.BaseLogic.LoadFriendsList(true, false);
                    lc.Current = 12;

                    // список комментариев к фотографиям пользователя
                    Globals.BaseLogic.LoadPhotosComments(25, true, false);
                    lc.Current = 14;

                    // список заголовков цепочек сообщений пользователя
                    Globals.BaseLogic.GetShortCorrespondence(true, false);
                    lc.Current = 16;

                    // список статусов пользователя (для формы поделиться)
                    Globals.BaseLogic.LoadUserActivityDataList(25, true, false);
                    lc.Current = 18;

                    // список фотографий пользователя
                    Globals.BaseLogic.ReloadUserPhotos(true, false);
                    lc.Current = 20;

                    // З А Г Р У З К А   Ц Е П О Ч Е К   П Е Р Е П И С О К
                    Globals.BaseLogic.ClearMessageCorrespondence();
                    totalCount = Globals.BaseLogic.PredictCorrespondCount();
                    alreadyGet = 0;
                    isData     = false;

                    MessShortCorrespondence newMessShortCorrespondence = DataModel.Data.MessageShortCorrespondence;

                    if (newMessShortCorrespondence == null)
                    {
                        newMessShortCorrespondence = new MessShortCorrespondence();
                    }

                    MessCorrespondence newMessCorrespondence = DataModel.Data.MessageCorrespondence;

                    if (newMessCorrespondence == null)
                    {
                        newMessCorrespondence = new MessCorrespondence();
                    }

                    do
                    {
                        isData = Globals.BaseLogic.UploadNextUserCorrespond(newMessShortCorrespondence, newMessCorrespondence);

                        if (isData)
                        {
                            alreadyGet++;

                            if (totalCount > 0)
                            {
                                lc.Current = 40 - (int)(20 * (((double)(totalCount - alreadyGet)) / ((double)totalCount)));
                            }
                        }
                    }while (isData);

                    DataModel.Data.MessageCorrespondence = newMessCorrespondence;

                    // З А Г Р У З К А   К О М М Е Н Т А Р И Е В
                    Globals.BaseLogic.ClearAllPhotoComments();
                    totalCount = Globals.BaseLogic.PredictPhotoCommentsCount();
                    alreadyGet = 0;
                    isData     = false;

                    PhotosCommentsResponseHistory newPhotosCommentsRespounseHistory = DataModel.Data.PhotosCommentsResponseHistoryData;

                    if (newPhotosCommentsRespounseHistory == null)
                    {
                        newPhotosCommentsRespounseHistory = new PhotosCommentsResponseHistory();
                    }

                    PhotosCommentsResponse newPhotosCommentsRespounse = DataModel.Data.PhotosCommentsResponseData;

                    if (newPhotosCommentsRespounse == null)
                    {
                        newPhotosCommentsRespounse = new PhotosCommentsResponse();
                    }

                    UpdatesPhotosResponse nwUpdatesPhotosResponse = DataModel.Data.UpdatesPhotosResponseData;

                    if (nwUpdatesPhotosResponse == null)
                    {
                        nwUpdatesPhotosResponse = new UpdatesPhotosResponse();
                    }

                    do
                    {
                        isData = Globals.BaseLogic.UploadNextPhotoComments(newPhotosCommentsRespounseHistory, newPhotosCommentsRespounse, nwUpdatesPhotosResponse);

                        if (isData)
                        {
                            alreadyGet++;

                            if (totalCount > 0)
                            {
                                lc.Current = 60 - (int)(20 * (((double)(totalCount - alreadyGet)) / ((double)totalCount)));
                            }
                        }
                    }while (isData);

                    DataModel.Data.PhotosCommentsResponseHistoryData = newPhotosCommentsRespounseHistory;

                    // З А Г Р У З К А   П Р О Ф И Л Е Й   П О Л Ь З О В А Т Е Л Е Й
                    totalCount = Globals.BaseLogic.PredictFriendsCount();
                    alreadyGet = 0;
                    isData     = false;

                    FriendsListResponse additionalFriendsListResponse = additionalFriendsListResponse = DataModel.Data.FriendsListAdditionalResponseData;

                    if (additionalFriendsListResponse == null)
                    {
                        additionalFriendsListResponse = new FriendsListResponse();
                    }

                    FriendsListResponse oldFriendsListResponse = DataModel.Data.FriendsListResponseData;

                    if (oldFriendsListResponse == null)
                    {
                        oldFriendsListResponse = new FriendsListResponse();
                    }

                    do
                    {
                        isData = Globals.BaseLogic.GetNextFriendsInfo(true, false, additionalFriendsListResponse, oldFriendsListResponse);

                        if (isData)
                        {
                            alreadyGet++;

                            if (totalCount > 0)
                            {
                                lc.Current = 98 - (int)(38 * (((double)(totalCount - alreadyGet)) / ((double)totalCount)));
                            }
                        }
                    } while (isData);

                    DataModel.Data.FriendsListAdditionalResponseData = additionalFriendsListResponse;

                    // все фото
                    Globals.BaseLogic.DownloadAllPhotoData();

                    lc.Current = 99;
                }
                catch (VKException)
                {
                    DebugHelper.WriteLogEntry("Ошибка при загрузке данных при старте приложения");
                }
                catch (OutOfMemoryException)
                {
                    DebugHelper.WriteLogEntry("Ошибка при загрузке данных при старте приложения");
                }
                catch (Exception)
                {
                    DebugHelper.WriteLogEntry("Ошибка при загрузке данных при старте приложения");
                }
            }

            // запускаем поток || прогрузки фотографий
            var t = new Thread(delegate { Globals.BaseLogic.ICommunicationLogic.LoadImagesInDictionary(); })
            {
                IsBackground = true
            };

            t.Start();

            lc.Current = 100;
        }
        private void AsyncGetViewData(LoadingControlInterface lc)
        {
            lc.Current = 0;

            PhotosCommentsResponse newPhotosCommentsResponse = null;

            //

            int    uid           = Convert.ToInt32((string)ViewData["UserID"]);
            int    photoID       = Convert.ToInt32((string)ViewData["PhotoID"]);
            string largePhotoURL = (string)ViewData["LargePhotoURL"];

            try
            {
                lc.Current = 5;

                newPhotosCommentsResponse = Globals.BaseLogic.LoadCommentsToPhoto(uid, photoID, 50, true, false, null);
                lc.Current = 95;
            }
            catch (VKException ex)
            {
                //timerKeepAwake.Enabled = false;
                string error = ExceptionTranslation.TranslateException(ex);

                if (!string.IsNullOrEmpty(error))
                {
                    ViewData["LoadListResponseMessage"] = error;
                    view.UpdateView("LoadListResponseNegative");

                    if (ex.LocalizedMessage.Equals(ExceptionMessage.IncorrectLoginOrPassword))
                    {
                        Globals.BaseLogic.IDataLogic.SetToken(string.Empty);

                        view.UpdateView("GoToLogin");
                    }

                    //newPhotosCommentsResponse = LoadDataFromCache(photoID);
                }
            }
            catch (OutOfMemoryException)
            {
                ViewData["LoadListResponseMessage"] = Resources.OutOfMemory;
                view.UpdateView("LoadListResponseNegative");
            }

            if (newPhotosCommentsResponse != null)
            {
                FillListModel(largePhotoURL, newPhotosCommentsResponse);
            }
            else
            {
                //view.Model.Clear();
            }

            view.UpdateView("LoadListResponse");

            // запускаем поток || прогрузки фотографий
            var t = new Thread(delegate { Globals.BaseLogic.ICommunicationLogic.LoadImagesInDictionary(); })
            {
                IsBackground = true
            };

            t.Start();

            lc.Current = 100;
        }
        protected override void OnViewStateChanged(string key)
        {
            #region SendMessage

            if (key == "SendMessage")
            {
                try
                {
                    using (new WaitWrapper(false))
                    {
                        Globals.BaseLogic.AddComments((string)ViewData["Message"],
                                                      (string)ViewData["UserID"] + "_" +
                                                      (string)ViewData["PhotoID"],
                                                      false);
                    }
                    view.UpdateView("SendCommentSuccess");

                    using (new WaitWrapper(false))
                    {
                        PhotosCommentsResponseHistory pchResponse = null;
                        PhotosCommentsResponse        pcResponse  = null;

                        try
                        {
                            //pchResponse = Cache.LoadFromCache<PhotosCommentsResponseHistory>(string.Empty, "PhotosCommentsResponseHistory");

                            pchResponse = DataModel.Data.PhotosCommentsResponseHistoryData;

                            if (pchResponse == null)
                            {
                                throw new Exception();
                            }
                        }
                        catch (Exception)
                        {
                            pchResponse = new PhotosCommentsResponseHistory();
                        }

                        pcResponse = pchResponse.GetItem(Convert.ToInt32((string)ViewData["PhotoID"]));

                        if (pcResponse == null)
                        {
                            pcResponse = new PhotosCommentsResponse();
                            pchResponse.AddItem(pcResponse);
                        }

                        var newPhotoData = new PhotoData
                        {
                            pdPhotoID       = Convert.ToInt32((string)ViewData["PhotoID"]),
                            pdUserID        = Convert.ToInt32((string)ViewData["UserID"]),
                            pdPhotoURL604px = (string)ViewData["LargePhotoUrl"]
                        };

                        var newPostReceiver = new PostReceiver
                        {
                            prUserID = Convert.ToInt32((string)ViewData["UserID"])
                        };

                        var newPostSender = new PostSender
                        {
                            psUserID =
                                Convert.ToInt32(Globals.BaseLogic.IDataLogic.GetUid()),
                            psUserName = Resources.MessageI
                        };

                        var newWallData = new WallData
                        {
                            wdWallDataType = WallDataType.PlainText,
                            wdText         = (string)ViewData["Message"]
                        };

                        pcResponse.pcrPhotoID = Convert.ToInt32((string)ViewData["PhotoID"]);
                        pcResponse.pcrComments.Insert(0, new CommentPost
                        {
                            cpID           = 0,
                            cpTime         = DateTime.Now,
                            cpPhotoData    = newPhotoData,
                            cpPostReceiver = newPostReceiver,
                            cpPostSender   = newPostSender,
                            cpWallData     = newWallData
                        }
                                                      );

                        //try
                        //{
                        //    bool result = Cache.SaveToCache(pchResponse, string.Empty,
                        //                                    "PhotosCommentsResponseHistory");
                        //    DebugHelper.WriteLogEntry(result
                        //                                  ? "Новый комментарий сохранен в кэш."
                        //                                  : "Новый комментарий не сохранены в кэш.");
                        //}
                        //catch (IOException newException)
                        //{
                        //    DebugHelper.WriteLogEntry("Ошибка сохранения комментария к фото в кэш: " +
                        //                              newException.Message);
                        //}

                        DataModel.Data.PhotosCommentsResponseHistoryData = pchResponse;

                        if ((string)ViewData["UserID"] == Globals.BaseLogic.IDataLogic.GetUid())
                        {
                            try
                            {
                                //pcResponse = Cache.LoadFromCache<PhotosCommentsResponse>(string.Empty,
                                //                                                         "PhotosCommentsResponse");

                                pcResponse = DataModel.Data.PhotosCommentsResponseData;

                                if (pcResponse == null)
                                {
                                    throw new Exception();
                                }
                            }
                            catch (Exception)
                            {
                                pcResponse = new PhotosCommentsResponse();
                            }

                            pcResponse.pcrPhotoID = Convert.ToInt32((string)ViewData["PhotoID"]);
                            pcResponse.pcrComments.Insert(0, new CommentPost
                            {
                                cpID           = 0,
                                cpTime         = DateTime.Now,
                                cpPhotoData    = newPhotoData,
                                cpPostReceiver = newPostReceiver,
                                cpPostSender   = newPostSender,
                                cpWallData     = newWallData
                            }
                                                          );

                            //try
                            //{
                            //    bool result = Cache.SaveToCache(pcResponse, string.Empty, "PhotosCommentsResponse");
                            //    DebugHelper.WriteLogEntry(result
                            //                                  ? "Новый комментарий сохранен в кэш комментариев к своим фото."
                            //                                  : "Новый комментарий не сохранен в кэш комментариев к своим фото.");
                            //}
                            //catch (IOException newException)
                            //{
                            //    DebugHelper.WriteLogEntry("Ошибка сохранения комментария к своему фото в кэш: " +
                            //                              newException.Message);
                            //}

                            DataModel.Data.PhotosCommentsResponseData = pcResponse;
                        }
                        NavigationService.GoBack();
                    }
                }
                catch (VKException ex)
                {
                    //timerKeepAwake.Enabled = false;
                    string err = ExceptionTranslation.TranslateException(ex);
                    if (!string.IsNullOrEmpty(err))
                    {
                        ViewData["SendCommentError"] = err;
                        view.UpdateView("SendCommentFail");

                        if (ex.LocalizedMessage == ExceptionMessage.IncorrectLoginOrPassword)
                        {
                            Globals.BaseLogic.IDataLogic.SetToken(string.Empty);

                            view.UpdateView("GoToLogin");
                        }
                    }
                }
                catch (OutOfMemoryException)
                {
                    ViewData["SendCommentError"] = Resources.OutOfMemory;
                    view.UpdateView("SendCommentFail");
                }
            }

            #endregion

            #region GoBack

            if (key == "GoBack")
            {
                using (new WaitWrapper(false))
                {
                    NavigationService.GoBack();
                }
            }

            #endregion

            if (key == "GoGoToLogin")
            {
                MasterForm.Navigate <LoginController>();
            }
        }