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

            PhotosCommentsResponse newPhotosCommentsResponse = null;

            try
            {
                lc.Current = 5;

                newPhotosCommentsResponse = Globals.BaseLogic.LoadPhotosComments(25, true, false); // комментарии
                lc.Current = 50;

                Globals.BaseLogic.ReloadUserPhotos(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");
                    }

                    if (ex.LocalizedMessage == ExceptionMessage.UnknownError)
                    {
                        MessageBox.Show("!!!!!11!!!");
                    }
                }
            }
            catch (OutOfMemoryException)
            {
                ViewData["LoadListResponseMessage"] = Resources.OutOfMemory;
                view.UpdateView("LoadListResponseNegative");
            }

            if (newPhotosCommentsResponse != null)
            {
                FillListModel(newPhotosCommentsResponse);
            }
            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;
        }
Esempio n. 2
0
        protected override void OnViewStateChanged(string key)
        {
            #region LoadList

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

                if (isRefrsh)
                {
                    LoadingControlInterface lc = LoadingControl.CreateLoading(Resources.DataLoading);

                    Thread asyncDataThread = new Thread(delegate { AsyncGetViewData(lc); });
                    asyncDataThread.IsBackground = true;
                    asyncDataThread.Start();

                    lc.ShowLoading(true);

                    if (lc.Abort)
                    {
                        asyncDataThread.Abort();
                    }
                }
                else
                {
                    try
                    {
                        PhotosCommentsResponse newPhotosCommentsResponse = Globals.BaseLogic.LoadPhotosComments(25, false, false); // комментарии

                        if (newPhotosCommentsResponse != null)
                        {
                            FillListModel(newPhotosCommentsResponse);

                            Globals.BaseLogic.ICommunicationLogic.ClearImagesInDictionary();
                        }
                        else
                        {
                            view.Model.Clear();
                        }

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

                        view.UpdateView("LoadListResponse");
                    }
                    catch
                    {
                        //
                    }
                }
            }

            #endregion

            #region ReloadList

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

            #endregion

            #region RefreshList

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

            #endregion

            #region GoToStatuses

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

            #endregion

            #region GoToSendMessage

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

            #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 && !string.IsNullOrEmpty(largePhotoURL))
                {
                    MasterForm.Navigate <ImageCommentController>("Load", uid.ToString(), photoID.ToString(), largePhotoURL);
                }
            }

            #endregion

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

                if (uid > 0 && photoID > 0)
                {
                    MasterForm.Navigate <SendCommentController>(uid.ToString(), photoID.ToString(), url);
                }
            }


            #region GoToMessages

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

            #endregion

            #region GoToFriends

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

            #endregion

            #region GoToPhotos

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

            #endregion

            #region GoToExtras

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

            #endregion



            #region ListActualization

            if (key == "ListActualization")
            {
                string currentID = Globals.BaseLogic.IDataLogic.GetUid();
                string listID    = (string)ViewData["ListID"];

                if (currentID != listID)
                {
                    ViewData["IsRefresh"] = false;

                    OnViewStateChanged("LoadList");
                }
            }

            #endregion

            if (key == "GoGoToLogin")
            {
                MasterForm.Navigate <LoginController>();
            }
        }
Esempio n. 3
0
        protected override void OnViewStateChanged(string key)
        {
            if (key == "LoadList")
            {
                try
                {
                    //ActivityResponse newActivityResponse = Globals.BaseLogic.LoadActivityDataList(25, true, false);
                    PhotosCommentsResponse newPhotosCommentsRespounse = Globals.BaseLogic.LoadPhotosComments(20, true, false);

                    view.Model.Clear();

                    foreach (CommentPost newCommentPost in newPhotosCommentsRespounse.pcrComments)
                    {
                        WallPostListViewItem newWallPostListViewItem = new WallPostListViewItem();

                        newWallPostListViewItem.UserName         = newCommentPost.cpPostSender.psUserName; //newActivityData.adDataSender.psUserName;
                        newWallPostListViewItem.Status           = newCommentPost.cpWallData.wdText;       //newActivityData.adText;
                        newWallPostListViewItem.StatusChangeDate = newCommentPost.cpTime.ToString();       //newActivityData.adTime.ToString();

                        newWallPostListViewItem.Avatar = SystemConfiguration.AppInstallPath + @"\Cache\Files\Thumb\" + HttpUtility.GetMd5Hash(newCommentPost.cpPhotoData.pdPhotoURL130px);

                        bool res;

                        //загрузка превьюшки
                        res = Globals.BaseLogic.ICommunicationLogic.LoadImage(newCommentPost.cpPhotoData.pdPhotoURL130px, @"Thumb\" + HttpUtility.GetMd5Hash(newCommentPost.cpPhotoData.pdPhotoURL130px), false, _afterLoadImageEventHandler, UISettings.CalcPix(50), 0, "int");

                        if (res)
                        {
                            newWallPostListViewItem.IsAvatarLoaded = true;
                        }
                        else
                        {
                            newWallPostListViewItem.IsAvatarLoaded = false;
                        }

                        view.Model.Add(newWallPostListViewItem);
                    }

                    //foreach (ActivityData newActivityData in newActivityResponse.arActivityDatas)
                    //{
                    //    WallPostListViewItem newWallPostListViewItem = new WallPostListViewItem();

                    //    newWallPostListViewItem.UserName = newActivityData.adDataSender.psUserName;
                    //    newWallPostListViewItem.Status = newActivityData.adText;
                    //    newWallPostListViewItem.StatusChangeDate = newActivityData.adTime.ToString();

                    //    newWallPostListViewItem.Avatar = SystemConfiguration.AppInstallPath + @"\Cache\Files\Thumb\" + HttpUtility.GetMd5Hash(newActivityData.adDataSender.psUserPhotoURL);

                    //    bool res;

                    //    if (newActivityData.adDataSender.psUserPhotoURL == "0")
                    //    {
                    //        res = false;
                    //    }
                    //    else
                    //    {
                    //        //загрузка аватара
                    //        res = Globals.BaseLogic.ICommunicationLogic.LoadImage(newActivityData.adDataSender.psUserPhotoURL, @"Thumb\" + HttpUtility.GetMd5Hash(newActivityData.adDataSender.psUserPhotoURL), false, _afterLoadImageEventHandler);
                    //    }

                    //    if (res)
                    //    {
                    //        newWallPostListViewItem.IsAvatarLoaded = true;
                    //    }
                    //    else
                    //    {
                    //        newWallPostListViewItem.IsAvatarLoaded = false;
                    //    }

                    //    view.Model.Add(newWallPostListViewItem);
                    //}

                    //view.Model.Sort();

                    view.UpdateView("LoadListResponse");
                }
                catch (Exception newException)
                {
                    ViewData["LoadListResponseMessage"] = newException.Message;

                    view.UpdateView("LoadListResponseNegative");
                }

                #region оригинальный код
                //try
                //{
                //    WallResponse newWallResponse = Globals.BaseLogic.LoadWallPostList(15, true, false);

                //    //WallResponse newWallResponse = new WallResponse();

                //    #region Тестовые данные
                //    //WallPost WallPost1 = new WallPost();
                //    //newWallResponse.wrWallPosts.Add(WallPost1);

                //    //WallData WallData1 = new WallData();
                //    //WallPost1.wpWallData = WallData1;
                //    //WallData1.wdText = "Сообщение со стены!!!";

                //    //PostSender PostSender1 = new PostSender();
                //    //WallPost1.wpPostSender = PostSender1;
                //    //PostSender1.psUserName = "******";

                //    //WallPost WallPost2 = new WallPost();
                //    //newWallResponse.wrWallPosts.Add(WallPost2);

                //    //WallData WallData2 = new WallData();
                //    //WallPost2.wpWallData = WallData2;
                //    //WallData2.wdText = "Привет мир! Hello World!";

                //    //PostSender PostSender2 = new PostSender();
                //    //WallPost2.wpPostSender = PostSender2;
                //    //PostSender2.psUserName = "******";

                //    //newWallResponse.wrWallPosts.Add(WallPost1);
                //    //newWallResponse.wrWallPosts.Add(WallPost2);
                //    #endregion

                //    view.Model.Clear();

                //    foreach (WallPost newWallPost in newWallResponse.wrWallPosts)
                //    {
                //        WallPostListViewItem newWallPostListViewItem = new WallPostListViewItem();

                //        newWallPostListViewItem.Name = newWallPost.wpPostSender.psUserName;
                //        newWallPostListViewItem.Text = newWallPost.wpWallData.wdText;

                //        view.Model.Add(newWallPostListViewItem);
                //    }

                //    view.Model.Sort();

                //    view.UpdateView("LoadListResponse");
                //}
                //catch (Exception newException)
                //{
                //    ViewData["LoadListResponseMessage"] = newException.Message;

                //    view.UpdateView("LoadListResponseNegative");
                //}
                #endregion
                //
            }

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

            if (key == "GoToMain")
            {
                MasterForm.Navigate <MainController>();
            }

            if (key == "CloseApplication")
            {
                //TODO Закрыть приложение
                Application.Exit();
            }
        }
Esempio n. 4
0
        private void FillListModel(PhotosCommentsResponse newPhotosCommentsResponse)
        {
            view.Model.Clear();

            foreach (CommentPost newCommentPost in newPhotosCommentsResponse.pcrComments)
            {
                PhotoCommentsUpdatesViewItem newPhotoCommentsUpdatesViewItem = new PhotoCommentsUpdatesViewItem();

                #region установка группы

                newPhotoCommentsUpdatesViewItem.Group = string.Empty;

                if (newCommentPost.cpTime.Date == DateTime.Now.Date)
                {
                    newPhotoCommentsUpdatesViewItem.Group = Resources.PhotoCommentsUpdatesList_Controller_Group_Today;
                }
                else if (newCommentPost.cpTime.Date == DateTime.Now.AddDays(-1).Date)
                {
                    newPhotoCommentsUpdatesViewItem.Group = Resources.PhotoCommentsUpdatesList_Controller_Group_Yesterday;
                }
                else
                {
                    newPhotoCommentsUpdatesViewItem.Group = newCommentPost.cpTime.Date.ToString("d MMMM");
                }

                #endregion

                newPhotoCommentsUpdatesViewItem.Uid            = newCommentPost.cpID.ToString();
                newPhotoCommentsUpdatesViewItem.UserID         = newCommentPost.cpPostSender.psUserID.ToString();
                newPhotoCommentsUpdatesViewItem.SenderName     = newCommentPost.cpPostSender.psUserName;
                newPhotoCommentsUpdatesViewItem.Comment        = newCommentPost.cpWallData.wdText;
                newPhotoCommentsUpdatesViewItem.CommentSetDate = newCommentPost.cpTime;
                newPhotoCommentsUpdatesViewItem.PhotoID        = newCommentPost.cpPhotoData.pdPhotoID.ToString();
                newPhotoCommentsUpdatesViewItem.LargePhotoURL  = Globals.BaseLogic.GetPhotoLargeURLByPhotoID(newCommentPost.cpPhotoData.pdPhotoID);

                if (newCommentPost.cpID > 0)
                {
                    newPhotoCommentsUpdatesViewItem.Photo = SystemConfiguration.AppInstallPath + @"\Cache\Files\Thumb\" + HttpUtility.GetMd5Hash(newCommentPost.cpPhotoData.pdPhotoURL130px);

                    bool result =
                        Globals.BaseLogic.ICommunicationLogic.LoadImage(newCommentPost.cpPhotoData.pdPhotoURL130px,
                                                                        @"Thumb\" +
                                                                        HttpUtility.GetMd5Hash(
                                                                            newCommentPost.cpPhotoData.pdPhotoURL130px),
                                                                        false, _afterLoadImageEventHandler,
                                                                        UISettings.CalcPix(50), newCommentPost.cpTime,
                                                                        "DateTime");

                    newPhotoCommentsUpdatesViewItem.IsPhotoLoaded = result;
                }
                else
                {
                    newPhotoCommentsUpdatesViewItem.Photo         = string.Empty;
                    newPhotoCommentsUpdatesViewItem.IsPhotoLoaded = false;
                }

                view.Model.Add(newPhotoCommentsUpdatesViewItem);
            }

            view.Model.Sort();
        }
        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;
        }
Esempio n. 6
0
        protected override void OnViewStateChanged(string key)
        {
            #region LoadList

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

                if (isRefrsh)
                {
                    LoadingControlInterface lc = LoadingControl.CreateLoading(Resources.DataLoading);

                    Thread asyncDataThread = new Thread(delegate { AsyncGetViewData(lc); });
                    asyncDataThread.IsBackground = true;
                    asyncDataThread.Start();

                    lc.ShowLoading(true);

                    if (lc.Abort)
                    {
                        asyncDataThread.Abort();
                    }
                }
                else
                {
                    try
                    {
                        int    uid           = Convert.ToInt32((string)ViewData["UserID"]);
                        int    photoID       = Convert.ToInt32((string)ViewData["PhotoID"]);
                        string largePhotoURL = (string)ViewData["LargePhotoURL"];

                        PhotosCommentsResponse newPhotosCommentsResponse = Globals.BaseLogic.LoadCommentsToPhoto(uid, photoID, 50, false, false, null);

                        if (newPhotosCommentsResponse != null)
                        {
                            FillListModel(largePhotoURL, newPhotosCommentsResponse);

                            Globals.BaseLogic.ICommunicationLogic.ClearImagesInDictionary();
                        }
                        else
                        {
                            //view.Model.Clear();

                            //NavigationService.GoBack();
                        }

                        view.UpdateView("LoadListResponse");
                    }
                    catch
                    {
                        //
                    }
                }
            }

            #endregion

            #region ReloadList

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

            #endregion

            #region RefreshList

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

            #endregion

            #region NewComment

            if (key == "NewComment")
            {
                using (new WaitWrapper(false))
                {
                    MasterForm.Navigate <SendCommentController>(ViewData["UserID"], ViewData["PhotoID"], ViewData["LargePhotoURL"]);
                }
            }

            #endregion

            #region PutInAlbum

            if (key == "PutInAlbum")
            {
                try
                {
                    byte[] file;

                    using (
                        var newBinaryReader =
                            new BinaryReader(File.Open(SystemConfiguration.AppInstallPath + @"\Cache\Files\" +
                                                       HttpUtility.GetMd5Hash((string)ViewData["LargePhotoURL"]),
                                                       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 errMessage;

                    switch (ex.LocalizedMessage)
                    {
                    case ExceptionMessage.UnknownError:
                        errMessage = Resources.VK_ERRORS_UnknownError;
                        break;

                    case ExceptionMessage.ServerUnavalible:
                        errMessage = Resources.VK_ERRORS_ServerUnavalible;
                        break;

                    case ExceptionMessage.NoConnection:
                        errMessage = Resources.VK_ERRORS_NoConnection;
                        break;

                    default:
                        errMessage = string.Empty;
                        break;
                    }

                    ViewData["ResponseMessage"] = errMessage;
                }
                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 SaveOnDisk

            if (key == "SaveOnDisk")
            {
                var sfDialog = new SaveFileDialog();

                var bmp = new Bitmap(SystemConfiguration.AppInstallPath + @"\Cache\Files\" +
                                     HttpUtility.GetMd5Hash((string)ViewData["LargePhotoURL"]));

                sfDialog.Filter = "файлы jpeg (*.jpeg)|*.jpeg";

                sfDialog.FileName = Resources.DefaultFileNameToSave;
                if (sfDialog.ShowDialog() == DialogResult.OK)
                {
                    bmp.Save(sfDialog.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                }

                bmp.Dispose();
            }

            #endregion

            #region GoToSendMessage

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

            #endregion

            #region GoBack

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

            #endregion

            if (key == "GoGoToLogin")
            {
                MasterForm.Navigate <LoginController>();
            }
        }
Esempio n. 7
0
        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;
        }
Esempio n. 8
0
        private void FillListModel(string imageURL, PhotosCommentsResponse newPhotosCommentsResponse)
        {
            ImageDetailedListViewItem newImageDetailedListViewItem;

            view.Model.Clear();

            #region формирование первого элемента списка // фото

            newImageDetailedListViewItem = new ImageDetailedListViewItem();

            string fileSmallName = SystemConfiguration.AppInstallPath + @"\Cache\Files\Thumb\" + HttpUtility.GetMd5Hash(imageURL);
            string fileBigName   = SystemConfiguration.AppInstallPath + @"\Cache\Files\" + HttpUtility.GetMd5Hash(imageURL);

            newImageDetailedListViewItem.Type   = ImageDetailedListViewItemType.Photo;
            newImageDetailedListViewItem.Uid    = string.Empty;
            newImageDetailedListViewItem.UserID = string.Empty;
            newImageDetailedListViewItem.Photo  = fileSmallName;

            int listMinSize = (int)ViewData["ListMinSize"];
            //listMinSize -= UISettings.CalcPix(5); // добавим хоть какой-то отступ...

            // загрузка фото (большого)
            bool result = Globals.BaseLogic.ICommunicationLogic.LoadImage(imageURL, HttpUtility.GetMd5Hash(imageURL), false, _afterLoadImageEventHandler, listMinSize, 0, "int");

            if (result)                          // если в кэше есть большая картинка надо удостовериться, что есть и маленькая в thumb
            {
                if (!File.Exists(fileSmallName)) // а если нет, то преобразовать и добавить
                {
                    //ImageHelper.SaveScaledImage(fileBigName, fileSmallName, listMinSize, OpenNETCF.Drawing.RotationAngle.Zero);
                    ImageHelper.CustomSaveScaledImage(fileBigName, fileSmallName, listMinSize, OpenNETCF.Drawing.RotationAngle.Zero);
                }

                Size newSize;

                ImageHelper.GetImageSize(fileSmallName, out newSize);

                newImageDetailedListViewItem.PhotoHeight = newSize.Height;
            }

            newImageDetailedListViewItem.IsPhotoLoaded          = result;
            newImageDetailedListViewItem.UserComment            = string.Empty;
            newImageDetailedListViewItem.CommentSetDate         = new DateTime(0);
            newImageDetailedListViewItem.CommentWroteDateString = string.Empty;
            //newImageDetailedListViewItem.Group = string.Empty;
            newImageDetailedListViewItem.Group = null;

            view.Model.Add(newImageDetailedListViewItem);

            #endregion

            #region формирование второго элемента списка // автор

            newImageDetailedListViewItem = new ImageDetailedListViewItem();

            newImageDetailedListViewItem.Type          = ImageDetailedListViewItemType.Author;
            newImageDetailedListViewItem.Uid           = string.Empty;
            newImageDetailedListViewItem.UserID        = string.Empty;
            newImageDetailedListViewItem.Photo         = string.Empty;
            newImageDetailedListViewItem.IsPhotoLoaded = false;
            if (newPhotosCommentsResponse.pcrAuthor != null)
            {
                newImageDetailedListViewItem.UserName = newPhotosCommentsResponse.pcrAuthor.FullName;
            }
            else
            {
                newImageDetailedListViewItem.UserName = Resources.MessageI;
            }
            newImageDetailedListViewItem.UserComment            = string.Empty;
            newImageDetailedListViewItem.CommentSetDate         = new DateTime(1);
            newImageDetailedListViewItem.CommentWroteDateString = string.Empty;
            newImageDetailedListViewItem.Group = Resources.ImageDetailedList_Group_Author;

            view.Model.Add(newImageDetailedListViewItem);

            #endregion

            // формирование последующих элементов списка
            foreach (var val in newPhotosCommentsResponse.pcrComments)
            {
                newImageDetailedListViewItem = new ImageDetailedListViewItem();

                newImageDetailedListViewItem.Type           = ImageDetailedListViewItemType.Comment;
                newImageDetailedListViewItem.Uid            = val.cpID.ToString();
                newImageDetailedListViewItem.UserID         = val.cpPostSender.psUserID.ToString();
                newImageDetailedListViewItem.Photo          = string.Empty;
                newImageDetailedListViewItem.IsPhotoLoaded  = false;
                newImageDetailedListViewItem.UserName       = val.cpPostSender.psUserName;
                newImageDetailedListViewItem.UserComment    = val.cpWallData.wdText;
                newImageDetailedListViewItem.CommentSetDate = val.cpTime;
                newImageDetailedListViewItem.Group          = Resources.ImageDetailedList_Group_Comments;

                #region текстовое представление даты

                string datatimeText;

                if (val.cpTime.Date == DateTime.Now.Date)
                {
                    datatimeText = val.cpTime.ToString("HH:mm");
                }
                else if (val.cpTime.Date == DateTime.Now.AddDays(-1).Date)
                {
                    datatimeText = Resources.Yesterday;
                }
                else
                {
                    datatimeText = val.cpTime.ToString("d.MM.yyyy");
                }

                newImageDetailedListViewItem.CommentWroteDateString = datatimeText;

                #endregion

                view.Model.Add(newImageDetailedListViewItem);
            }

            //view.Model.Sort();
        }
Esempio n. 9
0
        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>();
            }
        }