Ejemplo n.º 1
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
        }
Ejemplo n.º 2
0
        private void FillEventsListModel(EventsGetResponse eventsGetResponse)
        {
            view.Model.Clear();

            EventButton viewItemMessages      = null;
            EventButton viewItemComments      = null;
            EventButton viewItemFriends       = null;
            EventButton viewItemFriendsNews   = null;
            EventButton viewItemFriendsPhotos = null;
            EventButton viewItemWallMessages  = null;

            foreach (Event ev in eventsGetResponse.events)
            {
                switch (ev.type)
                {
                case EventType.Messages:
                    viewItemMessages       = new EventButton(Resources.MainView_Label_Messages, Convert.ToInt16(ev.number), ev.type, MasterForm.SkinManager.GetImage("Message"));
                    viewItemMessages.Count = ev.number;
                    break;

                case EventType.Comments:
                    viewItemComments       = new EventButton(Resources.MainView_Label_Comments, Convert.ToInt16(ev.number), ev.type, MasterForm.GetSkinManagerImageInvoked("Guest"));
                    viewItemComments.Count = ev.number;
                    break;

                case EventType.Friends:
                    viewItemFriends       = new EventButton(Resources.MainView_Label_Friends, Convert.ToInt16(ev.number), ev.type, MasterForm.GetSkinManagerImageInvoked("Mark"));
                    viewItemFriends.Count = ev.number;
                    break;

                case EventType.FriendsNews:
                    viewItemFriendsNews       = new EventButton(Resources.MainView_Label_FriendsNews, Convert.ToInt16(ev.number), ev.type, MasterForm.GetSkinManagerImageInvoked("Notification"));
                    viewItemFriendsNews.Count = ev.number;
                    break;

                case EventType.FriendsPhotos:
                    viewItemFriendsPhotos       = new EventButton(Resources.MainView_Label_FriendsPhotos, Convert.ToInt16(ev.number), ev.type, MasterForm.GetSkinManagerImageInvoked("Activities"));
                    viewItemFriendsPhotos.Count = ev.number;
                    break;

                case EventType.WallMessages:
                    viewItemWallMessages       = new EventButton(Resources.MainView_Label_WallMessages, Convert.ToInt16(ev.number), ev.type, MasterForm.GetSkinManagerImageInvoked("Discussion"));
                    viewItemWallMessages.Count = ev.number;
                    break;
                }
            }

            // формирование списка по порядку

            // сообщения
            if (Globals.BaseLogic.IDataLogic.GetShowButtonMessages())
            {
                if (viewItemMessages == null)
                {
                    viewItemMessages       = new EventButton(Resources.MainView_Label_Messages, 0, EventType.Messages, MasterForm.GetSkinManagerImageInvoked("Message"));
                    viewItemMessages.Count = 0;
                    view.Model.Add(viewItemMessages);
                }
                else
                {
                    view.Model.Add(viewItemMessages);
                }
            }

            // уведомления
            if (Globals.BaseLogic.IDataLogic.GetShowButtonComments())
            {
                if (viewItemComments == null)
                {
                    viewItemComments       = new EventButton(Resources.MainView_Label_FriendsNews, 0, EventType.Comments, MasterForm.GetSkinManagerImageInvoked("Notification"));
                    viewItemComments.Count = 0;
                    view.Model.Add(viewItemComments);
                }
                else
                {
                    view.Model.Add(viewItemComments);
                }
            }

            // обсуждения
            if (Globals.BaseLogic.IDataLogic.GetShowButtonFriends())
            {
                if (viewItemFriends == null)
                {
                    viewItemFriends       = new EventButton(Resources.MainView_Label_WallMessages, 0, EventType.Friends, MasterForm.GetSkinManagerImageInvoked("Discussion"));
                    viewItemFriends.Count = 0;
                    view.Model.Add(viewItemFriends);
                }
                else
                {
                    view.Model.Add(viewItemFriends);
                }
            }

            // лента
            if (Globals.BaseLogic.IDataLogic.GetShowButtonFriendsNews())
            {
                if (viewItemFriendsNews == null)
                {
                    viewItemFriendsNews       = new EventButton(Resources.MainView_Label_FriendsPhotos, 0, EventType.FriendsNews, MasterForm.GetSkinManagerImageInvoked("Activities"));
                    viewItemFriendsNews.Count = 0;
                    view.Model.Add(viewItemFriendsNews);
                }
                else
                {
                    view.Model.Add(viewItemFriendsNews);
                }
            }

            // гости
            if (Globals.BaseLogic.IDataLogic.GetShowButtonFriendsPhotos())
            {
                if (viewItemFriendsPhotos == null)
                {
                    viewItemFriendsPhotos       = new EventButton(Resources.MainView_Label_Comments, 0, EventType.FriendsPhotos, MasterForm.GetSkinManagerImageInvoked("Guest"));
                    viewItemFriendsPhotos.Count = 0;
                    view.Model.Add(viewItemFriendsPhotos);
                }
                else
                {
                    view.Model.Add(viewItemFriendsPhotos);
                }
            }

            // оценки
            if (Globals.BaseLogic.IDataLogic.GetShowButtonWallMessages())
            {
                if (viewItemWallMessages == null)
                {
                    viewItemWallMessages       = new EventButton(Resources.MainView_Label_Friends, 0, EventType.WallMessages, MasterForm.GetSkinManagerImageInvoked("Mark"));
                    viewItemWallMessages.Count = 0;
                    view.Model.Add(viewItemWallMessages);
                }
                else
                {
                    view.Model.Add(viewItemWallMessages);
                }
            }
        }
Ejemplo n.º 3
0
        protected override void OnInitialize(params object[] parameters)
        {
            if ((parameters != null) && (parameters.Length > 0))
            {
                string param0 = parameters[0] as string;

                if (param0.Equals("LoadingPreview"))
                {
                    try
                    {
                        // загрузка событий
                        EventsGetResponse newEventsGetResponse = Globals.BaseLogic.EventsGet(false, false, true);

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

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

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

                        view.UpdateView("RefreshUserInfo");

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

                        if (res)
                        {
                            ViewData["AvatarPath"] = SystemConfiguration.AppInstallPath + "//Cache//Files//" + HttpUtility.GetMd5Hash(user.Photo200px);
                            view.UpdateView("RefreshAvatarFromCache");
                        }
                    }
                    catch (Exception)
                    {
                        //
                    }
                }
                else if (param0.Equals("LoginSuccess"))
                {
                    SetOnlineMode(this, new EventArgs());

                    //???
                    OnViewStateChanged("InitializeSettings");
                    ViewData["IsFirstStart"] = "1";
                    OnViewStateChanged("GetMainViewData");
                }
                else if (param0.Equals("LoginFail"))
                {
                    if (SetOfflineMode != null)
                    {
                        SetOfflineMode(this, new EventArgs());
                    }
                }
                else if (param0.Equals("LoginConnectionErrorFail"))
                {
                    ViewData["ConnectionError"] = true;
                }
                else if (param0.Equals("Status"))
                {
                    string param1 = parameters[1] as string;

                    if (param1 != null)
                    {
                        ViewData["CurrentStatus"] = parameters[1] as string;
                        ViewData["UserStatus"]    = ViewData["CurrentStatus"];

                        view.UpdateView("RefreshStatusBox");
                    }
                }
            }

            base.OnInitialize(parameters);
        }
Ejemplo n.º 4
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;
        }
Ejemplo n.º 5
0
        /* Ненужный код
         *  DebugHelper.WriteLogEntry("Notificator OnTimerTick.");
         *  System.Drawing.Icon curIcon = Properties.Resources.Events;
         *
         *  bool newEvent = false;
         *  bool newMessage = false;
         *  bool newComment = false;
         *  bool newFriend = false;
         *  bool newFriendsPhotos = false;
         *  bool newFriendsNews = false;
         *  bool newWallMessages = false;
         *  bool oldEvent = false;
         *  string nfnText = "";
         *
         *  GetEventsResponse eventsGetResponse = _baseLogic.EventsGet(true, false);
         *
         *  try
         *  {
         #region Проверка событий (пришли новые или нет)
         *      if (eventsGetResponse.MessagesCount > _eventsGetResponsePrev.MessagesCount) newMessage = true;
         *      if (eventsGetResponse.CommentsCount > _eventsGetResponsePrev.CommentsCount) newComment = true;
         *      if (eventsGetResponse.FriendsCount > _eventsGetResponsePrev.FriendsCount)   newFriend = true;
         *      if (eventsGetResponse.FriendsPhotosCount > _eventsGetResponsePrev.FriendsPhotosCount) newFriendsPhotos = true;
         *      if (eventsGetResponse.FriendsNewsCount > _eventsGetResponsePrev.FriendsNewsCount) newFriendsNews = true;
         *      if (eventsGetResponse.WallCount > _eventsGetResponsePrev.WallCount) newWallMessages = true;
         #endregion
         *
         #region Проверяем пришли ли новые типы событий
         *      if (newMessage)
         *          oldEvent = _eventsGetResponsePrev.MessagesCount > 0;
         *      if (newComment)
         *          oldEvent = _eventsGetResponsePrev.CommentsCount > 0;
         *      if (newFriend)
         *          oldEvent = _eventsGetResponsePrev.FriendsCount > 0;
         *      if (newFriendsPhotos)
         *          oldEvent = _eventsGetResponsePrev.FriendsPhotosCount > 0;
         *      if (newFriendsNews)
         *          oldEvent = _eventsGetResponsePrev.FriendsNewsCount > 0;
         *      if (newWallMessages)
         *          oldEvent = _eventsGetResponsePrev.WallCount > 0;
         #endregion
         *
         #region Обработка по каждому типу
         *      if (newMessage && !(newComment || newFriend || newFriendsPhotos || newFriendsNews || newWallMessages))
         *      {
         *          DebugHelper.WriteLogEntry("Notificator new message.");
         *          curIcon = Properties.Resources.Messages;
         *          nfnText = String.Format("{0} ({1})", "Новых сообщений", eventsGetResponse.MessagesCount);
         *          if (nfnText != "") newEvent = true;
         *      }
         *      if (!newMessage && (newComment || newFriend || newFriendsPhotos || newFriendsNews || newWallMessages))
         *      {
         *          DebugHelper.WriteLogEntry("Notificator new event.");
         *          curIcon = Properties.Resources.Events;
         *          nfnText = "";
         *          if (newComment) nfnText += String.Format("{0} ({1})<br>", "Новых комментариев к фото",  eventsGetResponse.CommentsCount);
         *          if (newFriend)  nfnText += String.Format("{0} ({1})<br>", "Hовых приглашений дружить", eventsGetResponse.FriendsCount);
         *          if (newFriendsPhotos) nfnText += String.Format("{0} ({1})<br>", "Новых фотографий друзей", eventsGetResponse.FriendsPhotosCount);
         *          if (newFriendsNews) nfnText += String.Format("{0} ({1})<br>", "Новостей друзей", eventsGetResponse.FriendsNewsCount);
         *          if (newWallMessages) nfnText += String.Format("{0} ({1})<br>", "Новых сообщений на стене", eventsGetResponse.WallCount);
         *
         *          if (nfnText != "") newEvent = true;
         *      }
         *      if (newMessage && (newComment || newFriend || newFriendsPhotos || newFriendsNews || newWallMessages))
         *      {
         *          DebugHelper.WriteLogEntry("Notificator new message and event.");
         *          curIcon = Properties.Resources.BothEvMes;
         *          nfnText = "";
         *
         *          if (newMessage) nfnText += String.Format("{0} ({1})<br>", "Новых сообщений",            eventsGetResponse.MessagesCount);
         *          if (newComment) nfnText += String.Format("{0} ({1})<br>", "Новых комментариев к фото",   eventsGetResponse.CommentsCount);
         *          if (newFriend)  nfnText += String.Format("{0} ({1})<br>", "Hовых приглашений дружить",  eventsGetResponse.FriendsCount);
         *          if (newFriendsPhotos) nfnText += String.Format("{0} ({1})<br>", "Новых фотографий друзей", eventsGetResponse.FriendsPhotosCount);
         *          if (newFriendsNews) nfnText += String.Format("{0} ({1})<br>", "Новостей друзей", eventsGetResponse.FriendsNewsCount);
         *          if (newWallMessages) nfnText += String.Format("{0} ({1})<br>", "Новых сообщений на стене", eventsGetResponse.WallCount);
         *
         *          if (nfnText != "") newEvent = true;
         *
         *      }
         #endregion
         *
         *      _eventsGetResponsePrev = eventsGetResponse;
         *
         #region Вывод нотификации если есть новые события
         *      //Вывод нотификации если есть новые события
         *      try
         *      {
         *          if (newEvent)
         *          {
         *              //SetEvent для приложения, сигнализирующий о том, что есть новые события
         *              _baseLogic.IDataLogic.SetRefreshEventsFlag("1");
         *
         *              OnNotificationShow(nfnText, curIcon, oldEvent);
         *          }
         *      }
         *      catch (Exception ex)
         *      {
         *          DebugHelper.WriteLogEntry(String.Format("{0}: {1}", Properties.Resources.Program_OnTimerTick_NfnError, ex.Message));
         *          //#if DEBUG
         *          //MessageBox.Show(String.Format("{0}: {1}", Properties.Resources.Program_OnTimerTick_NfnError, ex.Message));
         *          //#endif
         *      }
         #endregion
         *  }
         *  catch (Exception ex)
         *  {
         *      DebugHelper.WriteLogEntry(String.Format("{0}: {1}", Properties.Resources.Program_OnTimerTick_Error, ex.Message));
         *      //#if DEBUG
         *      //MessageBox.Show(String.Format("{0}: {1}", Properties.Resources.Program_OnTimerTick_Error, ex.Message));
         *      //#endif
         *  }
         * }
         */
        #endregion

        static void GetData()
        {
            DebugHelper.WriteLogEntry("Notificator GetData");
            bool showMessage, showComments, showFriends, showFriendsNews, showFriendsPhotos, showWallMessages, newEvent, oldEvent = true;
            bool newMessage, newComments, newFriends, newFriendsNews, newFriendsPhotos, newWallMessages;
            Icon curIcon = Resources.Messages;

            showMessage = showComments = showFriends = showFriendsNews = showFriendsPhotos = showWallMessages = newEvent = newMessage = newComments = newFriends = newFriendsNews = newFriendsPhotos = newWallMessages = false;
            string nfnText = "";

            try
            {
                //Инициализация _eventsGetResponsePrev значениями из реестра
                if (_eventsGetResponsePrev.events.Count == 0)
                {
                    _eventsGetResponsePrev = _baseLogic.IDataLogic.EventsGet();
                }

                //Оновление событий с сервера
                //получение обновленных значений из реестра
                EventsGetResponse eventsGetResponse = null;
                try
                {
                    eventsGetResponse = _baseLogic.EventsGet(true, false, true);
                }
                catch (VKException ex)
                {
                    DebugHelper.WriteLogEntry("***7");
                    CatchErrors(ex);
                    DebugHelper.WriteLogEntry("***8");
                }
                catch (Exception ex)
                {
                    DebugHelper.WriteLogEntry(ex, "Unexpected error");
                }
                DebugHelper.WriteLogEntry("***9");

                //Если значений в реестре не было, то делаю количество всех ивентов 0
                if (_eventsGetResponsePrev.events.Count == 0)
                {
                    _eventsGetResponsePrev = eventsGetResponse;
                    foreach (Event ev in _eventsGetResponsePrev.events)
                    {
                        ev.number = 0;
                    }
                }
                DebugHelper.WriteLogEntry("***10");

                if (eventsGetResponse != null)
                {
                    #region Проверка какие события показывать
                    foreach (Event ev in eventsGetResponse.events)
                    {
                        switch (ev.type)
                        {
                        case EventType.Messages:
                            if (ev.number > 0)
                            {
                                showMessage = true;
                            }
                            break;

                        case EventType.Comments:
                            if (ev.number > 0)
                            {
                                showComments = true;
                            }
                            break;

                        case EventType.Friends:
                            if (ev.number > 0)
                            {
                                showFriends = true;
                            }
                            break;

                        case EventType.FriendsNews:
                            if (ev.number > 0)
                            {
                                showFriendsNews = true;
                            }
                            break;

                            /*
                             * case EventType.FriendsPhotos:
                             * if (ev.number > 0) showFriendsPhotos = true;
                             * break;
                             * case EventType.WallMessages:
                             * if (ev.number > 0) showWallMessages = true;
                             * break;
                             */
                        }
                    }
                    #endregion
                    DebugHelper.WriteLogEntry("***11");

                    #region Проверяем изменился ли счетчик событий с последнего обновления
                    foreach (Event ev in eventsGetResponse.events)
                    {
                        switch (ev.type)
                        {
                        case EventType.Messages:
                            foreach (Event evPrev in _eventsGetResponsePrev.events)
                            {
                                if (evPrev.type == ev.type)
                                {
                                    if (ev.number > evPrev.number)
                                    {
                                        newMessage = true;
                                    }
                                }
                            }
                            break;

                        case EventType.Comments:
                            foreach (Event evPrev in _eventsGetResponsePrev.events)
                            {
                                if (evPrev.type == ev.type)
                                {
                                    if (ev.number > evPrev.number)
                                    {
                                        newComments = true;
                                    }
                                }
                            }
                            break;

                        case EventType.Friends:
                            foreach (Event evPrev in _eventsGetResponsePrev.events)
                            {
                                if (evPrev.type == ev.type)
                                {
                                    if (ev.number > evPrev.number)
                                    {
                                        newFriends = true;
                                    }
                                }
                            }
                            break;

                        case EventType.FriendsNews:
                            foreach (Event evPrev in _eventsGetResponsePrev.events)
                            {
                                if (evPrev.type == ev.type)
                                {
                                    if (ev.number > evPrev.number)
                                    {
                                        newFriendsNews = true;
                                    }
                                }
                            }
                            break;

                            /*
                             * case EventType.FriendsPhotos:
                             * foreach (Event evPrev in _eventsGetResponsePrev.events)
                             * if (evPrev.type == ev.type)
                             * if (ev.number > evPrev.number) newFriendsPhotos = true;
                             * break;
                             * case EventType.WallMessages:
                             * foreach (Event evPrev in _eventsGetResponsePrev.events)
                             * if (evPrev.type == ev.type)
                             * if (ev.number > evPrev.number) newWallMessages = true;
                             * break;
                             */
                        }
                    }

                    #endregion
                    DebugHelper.WriteLogEntry("***12");

                    #region Проверка происходило ли событие раньше
                    oldEvent = true;
                    foreach (Event evPrev in _eventsGetResponsePrev.events)
                    {
                        switch (evPrev.type)
                        {
                        case EventType.Messages:
                            if (newMessage)
                            {
                                if (evPrev.number == 0)
                                {
                                    oldEvent = false;
                                }
                            }
                            break;

                        case EventType.Comments:
                            if (newComments)
                            {
                                if (evPrev.number == 0)
                                {
                                    oldEvent = false;
                                }
                            }
                            break;

                        case EventType.Friends:
                            if (newFriends)
                            {
                                if (evPrev.number == 0)
                                {
                                    oldEvent = false;
                                }
                            }
                            break;

                        case EventType.FriendsNews:
                            if (newFriendsNews)
                            {
                                if (evPrev.number == 0)
                                {
                                    oldEvent = false;
                                }
                            }
                            break;

                            /*
                             * case EventType.FriendsPhotos:
                             * if (newFriendsPhotos)
                             * if (evPrev.number == 0) oldEvent = false;
                             * break;
                             * case EventType.WallMessages:
                             * if (newWallMessages)
                             * if (evPrev.number == 0) oldEvent = false;
                             * break;
                             */
                        }
                    }
                    #endregion
                    DebugHelper.WriteLogEntry("***13");

                    #region Определение иконки
                    curIcon = showMessage ? Resources.Messages : Resources.Events;

                    #endregion
                    DebugHelper.WriteLogEntry("***14");

                    //MessageBox.Show(showMessage + ":" + showFriends + ":" + showFriendsNews);
                    //MessageBox.Show(newMessage + ":" + newFriends + ":" + newFriendsNews);

                    #region Формирование текста сообщения

                    if (newMessage || newComments || newFriends || newFriendsNews /*|| newFriendsPhotos || newWallMessages*/)
                    {
                        DebugHelper.WriteLogEntry("Got new event");
                        nfnText = "";

                        #region текст
                        foreach (Event ev in eventsGetResponse.events)
                        {
                            switch (ev.type)
                            {
                            case EventType.Messages:
                                if (showMessage)
                                {
                                    nfnText += String.Format("{0} (+{1})<br>", Resources.Program_OnTimerTick_NfnMess, ev.number);
                                }
                                break;
                            }
                        }
                        foreach (Event ev in eventsGetResponse.events)
                        {
                            switch (ev.type)
                            {
                            case EventType.Comments:
                                if (showComments)
                                {
                                    nfnText += String.Format("{0} (+{1})<br>", Resources.Program_OnTimerTick_NfnCmnts, ev.number);
                                }
                                break;
                            }
                        }
                        foreach (Event ev in eventsGetResponse.events)
                        {
                            switch (ev.type)
                            {
                            case EventType.Friends:
                                if (showFriends)
                                {
                                    nfnText += String.Format("{0} (+{1})<br>", Resources.Program_OnTimerTick_NfnFrnds, ev.number);
                                }
                                break;
                            }
                        }

                        foreach (Event ev in eventsGetResponse.events)
                        {
                            switch (ev.type)
                            {
                            case EventType.FriendsNews:
                                if (showFriendsNews)
                                {
                                    nfnText += String.Format("{0} (+{1})<br>", Resources.Program_OnTimerTick_NfnFrndsNs, ev.number);
                                }
                                break;
                            }
                        }

                        /*
                         * foreach (Event ev in eventsGetResponse.events)
                         * {
                         *  switch (ev.type)
                         *  {
                         *      case EventType.FriendsPhotos:
                         *          if (showFriendsPhotos) nfnText += String.Format("{0} (+{1})<br>", Resources.Program_OnTimerTick_NfnFrndsPh, ev.number);
                         *          break;
                         *  }
                         * }
                         *
                         * foreach (Event ev in eventsGetResponse.events)
                         * {
                         *  switch (ev.type)
                         *  {
                         *      case EventType.WallMessages:
                         *          if (showWallMessages) nfnText += String.Format("{0} (+{1})<br>", Resources.Program_OnTimerTick_NfnFrnds, ev.number);
                         *          break;
                         *  }
                         * }
                         */

                        #endregion
                        DebugHelper.WriteLogEntry("***15");

                        DebugHelper.WriteLogEntry("Notification text(new event): " + nfnText);
                        if (nfnText != "")
                        {
                            newEvent = true;
                        }

                        //Чтобы попапилась и будила
                        _notification.StraightToTray = false;
                        _notification.DisplayOn      = true;
                    }
                    else
                    {
                        #region Если не пришло новое событие - модификация текста
                        // меняем текст в нотификаторе
                        DebugHelper.WriteLogEntry("No new events, just change text (dec counters)");
                        if (_notification != null)
                        {
                            nfnText = "";

                            #region текст
                            foreach (Event ev in eventsGetResponse.events)
                            {
                                switch (ev.type)
                                {
                                case EventType.Messages:
                                    if (showMessage)
                                    {
                                        nfnText += String.Format("{0} (+{1})<br>", Resources.Program_OnTimerTick_NfnMess, ev.number);
                                    }
                                    break;
                                }
                            }
                            foreach (Event ev in eventsGetResponse.events)
                            {
                                switch (ev.type)
                                {
                                case EventType.Comments:
                                    if (showComments)
                                    {
                                        nfnText += String.Format("{0} (+{1})<br>", Resources.Program_OnTimerTick_NfnCmnts, ev.number);
                                    }
                                    break;
                                }
                            }
                            foreach (Event ev in eventsGetResponse.events)
                            {
                                switch (ev.type)
                                {
                                case EventType.Friends:
                                    if (showFriends)
                                    {
                                        nfnText += String.Format("{0} (+{1})<br>", Resources.Program_OnTimerTick_NfnFrnds, ev.number);
                                    }
                                    break;
                                }
                            }

                            foreach (Event ev in eventsGetResponse.events)
                            {
                                switch (ev.type)
                                {
                                case EventType.FriendsNews:
                                    if (showFriendsNews)
                                    {
                                        nfnText += String.Format("{0} (+{1})<br>", Resources.Program_OnTimerTick_NfnFrndsNs, ev.number);
                                    }
                                    break;
                                }
                            }

                            /*
                             * foreach (Event ev in eventsGetResponse.events)
                             * {
                             *  switch (ev.type)
                             *  {
                             *      case EventType.FriendsPhotos:
                             *          if (showFriendsPhotos) nfnText += String.Format("{0} (+{1})<br>", Resources.Program_OnTimerTick_NfnFrnds, ev.number);
                             *          break;
                             *  }
                             * }
                             *
                             * foreach (Event ev in eventsGetResponse.events)
                             * {
                             *  switch (ev.type)
                             *  {
                             *      case EventType.WallMessages:
                             *          if (showWallMessages) nfnText += String.Format("{0} (+{1})<br>", Resources.Program_OnTimerTick_NfnFrnds, ev.number);
                             *          break;
                             *  }
                             * }
                             */
                            #endregion
                            DebugHelper.WriteLogEntry("***16");

                            DebugHelper.WriteLogEntry("Notification text(mod): " + nfnText);

                            //Чтобы не попапилась и не будила
                            _notification.StraightToTray = true;
                            _notification.DisplayOn      = false;
                            //Если текст нотификации изменился на "ничто" - скрыть ее
                            if (nfnText == "")
                            {
                                _notification.Visible = false;
                            }
                            else
                            {
                                _notification.Text = nfnText;
                            }
                        }
                        #endregion
                    }
                    #endregion

                    //if (nfnText != "")
                    //nfnText += string.Format("<br>{0}", GetBirthdayString());

                    DebugHelper.WriteLogEntry("***17");
                }


                DebugHelper.WriteLogEntry("***21");

                #region Вывод нотификации если есть новые события
                //Вывод нотификации если есть новые события
                try
                {
                    if (newEvent)
                    {
                        DebugHelper.WriteLogEntry("***22");

                        //SetEvent для приложения, сигнализирующий о том, что есть новые события
                        _baseLogic.IDataLogic.SetRefreshEventsFlag("1");

                        OnNotificationShow(nfnText, curIcon, oldEvent);
                    }
                }
                catch (Exception ex)
                {
                    DebugHelper.WriteLogEntry(ex, Resources.Program_OnTimerTick_NfnError);
                }
                #endregion
                DebugHelper.WriteLogEntry("***23");

                if (eventsGetResponse != null)
                {
                    _eventsGetResponsePrev = eventsGetResponse;
                }
            }
            catch (Exception ex)
            {
                DebugHelper.WriteLogEntry(ex, Resources.Program_OnTimerTick_Error);
            }
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            InitNotification();

            //Определение нотификаций и событий
            _notification                    = new NotificationWithSoftKeys();
            _notification.LeftSoftKey        = new NotificationSoftKey(SoftKeyType.Hide, Properties.Resources.Program_LeftSoftKey);
            _notification.RightSoftKey       = new NotificationSoftKey(SoftKeyType.Dismiss, Properties.Resources.Program_RightSoftKey);
            _notification.RightSoftKeyClick += OnNotificationRightSoftKeyClick;

            //Запуск сервиса и регистрация сообщения для него
            ServiceApplication.Name = Interprocess.ServiceName;
            ServiceApplication.RegisterMessage(Interprocess.WM_QUIT_SERVICE);
            ServiceApplication.RegisterMessage(Interprocess.WM_TIMER_TICK);
            ServiceApplication.OnRegisteredMessage += ServiceApplication_OnRegisteredMessage;

            Cache.InitPath(SystemConfiguration.AppInstallPath + "\\Cache");
            _baseLogic = new BaseLogic(new DataLogic(), new CommunicationLogic());
            //_baseLogic.IDataLogic.ClearNotificationTempDataInCache();
            _eventsGetResponsePrev = new EventsGetResponse();

            //автовход
            if (_baseLogic.IDataLogic.GetToken() != "")
            {
                try
                {
                    _baseLogic.AutoLogin();
                    _eventsGetResponsePrev = _baseLogic.EventsGet(true, false, true);

                    DebugHelper.WriteLogEntry("Notificator AutoLogin success.");

                    /*_eventsGetResponsePrev.CommentsCount = 0;
                    *  _eventsGetResponsePrev.FriendsCount = 0;
                    *  _eventsGetResponsePrev.MessagesCount = 0;*/
                }
                catch (VKException ex)
                {
                    CatchErrors(ex);
                }
                catch (Exception ex)
                {
                    DebugHelper.WriteLogEntry(ex, "Unexpected error.");
                }
            }
            else
            {
                DebugHelper.WriteLogEntry("Notificator service can't be started, there are no token in registry.");
                Application.Exit();
            }

            //Устанавливаем время последней проверки
            _lastCheckedTime = DateTime.Now;

            //Считываем из реестра значение периода проверки
            _checkInterval = GetCheckInterval();

            //Задаем время, когда необходимо будет разбудить устройство
            try
            {
                WakeupScheduler.ScheduleWakeUp(_lastCheckedTime.AddMilliseconds(_checkInterval));
            }
            catch (ExternalException exception)
            {
                DebugHelper.WriteLogEntry(exception, exception.Message);
                throw;
            }
            catch (Exception exception)
            {
                DebugHelper.WriteLogEntry(exception, "Error in scheduling wakeup program launch");
                throw;
            }

            ServiceApplication.Run();
        }