/// <summary>
        /// Загружает информацию о настройках.
        /// </summary>
        private async Task LoadSettings()
        {
            LoadingText = "Загрузка информации о настройках";
            IsLoading   = true;

            var parameters = new Dictionary <string, string>
            {
                { "group_id", Group.ID.ToString() }
            };
            var request  = new Request <VKGroupSettings>("groups.getSettings", parameters);
            var response = await vkService.ExecuteRequestAsync(request);

            if (response.IsSuccess)
            {
                Settings            = response.Response;
                CurrentSubjectIndex = Settings.AvailableSubjects.FindIndex(s => s.ID == Settings.Subject);
            }
            else if (response.Error == VKErrors.AccessDenied)
            {
                var notification = new AppNotification
                {
                    Type     = AppNotificationType.Error,
                    Title    = "Нет доступа к параметрам сообщества",
                    Content  = "Не удалось получить текущие значения параметров",
                    ImageUrl = Group.Photo100
                };
                appNotificationsService.SendNotification(notification);

                if (navigationService.CanGoBack())
                {
                    navigationService.GoBack();
                }
            }
            else
            {
                var notification = new AppNotification
                {
                    Type     = AppNotificationType.Error,
                    Title    = "Не удалось получить текущие значения параметров",
                    Content  = "Повторите попытку позднее",
                    ImageUrl = Group.Photo100
                };
                appNotificationsService.SendNotification(notification);

                if (navigationService.CanGoBack())
                {
                    navigationService.GoBack();
                }
            }

            IsLoading = false;
        }
Beispiel #2
0
        public AppNotification AppUpdateMaster(AppNotification objAppNotification)
        {
            UserManagementLogic obj = new UserManagementLogic();

            objAppNotification.LstRecepient = obj.GetAppUpdateDropdown();

            objAppNotification.LstSubRecepient.Add(new MasterListItem {
                Text = "Data Wipeup", Value = "data wipeup"
            });
            objAppNotification.LstSubRecepient.Add(new MasterListItem {
                Text = "App Update", Value = "App Update"
            });
            return(objAppNotification);
        }
Beispiel #3
0
        private void TryShowLikeInfo(AppNotification notification)
        {
            LikeInfoNotification.Message = notification;
            LikeInfoNotification.Visibility = Visibility.Visible;

            LikeInfoNotification.Loaded += async (s, e) =>
            {
                LikeInfoNotification.Show();
                await Task.Delay(2000);

                LikeControl.PlayLikeAnimation();
                await Task.Delay(200);
                LikeControl.PlayLikeAnimation();
            };
        }
        /// <summary>
        /// Вызывается при получении новых обновлений.
        /// </summary>
        /// <param name="response">Данные ответа LongPoll сервера.</param>
        private void OnUpdatesReceived(VKLongPollResponse response)
        {
            if (UpdatesReceived != null)
            {
                UpdatesReceived(this, response.Updates);
            }

            var notification = new AppNotification
            {
                Type    = AppNotificationType.Info,
                Title   = "Полученые новые обновления",
                Content = "Сервис мгновенных собщений",
            };

            appNotificationsService.SendNotification(notification);
        }
Beispiel #5
0
        public override void OnNavigatedTo(NavigatedToEventArgs e, Dictionary <string, object> viewModelState)
        {
            if (sessionStateService.SessionState.ContainsKey("NewsfeedNextFrom"))
            {
                nextFrom = (string)sessionStateService.SessionState["NewsfeedNextFrom"];
            }

            if (sessionStateService.SessionState.ContainsKey("Newsfeed"))
            {
                var newsfeed = (PaginatedCollection <VKNewsfeedItem>)sessionStateService.SessionState["Newsfeed"];
                newsfeed.LoadMoreItems = LoadMoreItems;
                Newsfeed = newsfeed;

                if (sessionStateService.SessionState.ContainsKey("NewsfeedSuspended"))
                {
                    sessionStateService.SessionState.Remove("NewsfeedSuspended");
                    var notification = new AppNotification
                    {
                        Type       = AppNotificationType.Warning,
                        Title      = "Новости могли устареть",
                        Content    = "Коснитесь, чтобы обновить",
                        Duration   = TimeSpan.FromSeconds(10),
                        ActionToDo = () =>
                        {
                            FirstVisibleIndex = 0;
                            nextFrom          = null;
                            Newsfeed.Refresh();
                        }
                    };
                    appNotificationsService.SendNotification(notification);
                }

                if (sessionStateService.SessionState.ContainsKey("FirstVisibleNewsfeedIndex"))
                {
                    FirstVisibleIndex = (int)sessionStateService.SessionState["FirstVisibleNewsfeedIndex"];
                }
            }
            else
            {
                Newsfeed = new PaginatedCollection <VKNewsfeedItem>(LoadMoreItems);
            }

            base.OnNavigatedTo(e, viewModelState);
        }
Beispiel #6
0
        private void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var    data = e.Exception.ToString();
            string name = e.Exception.GetType().ToString();

            var notification = new AppNotification
            {
                Type                = AppNotificationType.Error,
                Title               = $"Произошла ошибка\n{name}",
                Content             = "Коснитесь для подробностей",
                DestinationView     = "ErrorView",
                NavigationParameter = JsonConvert.SerializeObject(new Tuple <string, string>(name, data)),
                Duration            = TimeSpan.FromSeconds(9)
            };

            container.Resolve <IAppNotificationsService>().SendNotification(notification);

            e.Handled = true;
        }
        /// <summary>
        /// Вызывается при остановке сервиса.
        /// </summary>
        /// <param name="reason">Причина остановки.</param>
        private void OnServiceStopped(VKLongPollServiceStopReason reason)
        {
            IsWorking = false;
            if (ServiceStopped != null)
            {
                ServiceStopped(this, reason);
            }

            var notification = new AppNotification
            {
                Type       = AppNotificationType.Error,
                Title      = "Сервис мгновенных сообщений остановлен",
                Content    = "Коснитесь для перезапуска",
                ActionToDo = Start,
                Duration   = TimeSpan.FromSeconds(15)
            };

            appNotificationsService.SendNotification(notification);
        }
Beispiel #8
0
        public static AppNotification Get()
        {
            var    client = new WebClient();
            string values = client.DownloadString("http://cfxconnect.com/applications/SalesLogixMobileDeveloperTools/notification.txt?id=" + Machine.ID);

            if (!string.IsNullOrEmpty(values))
            {
                string[] notificationValues = values.Split('|');
                var      notification       = new AppNotification();
                notification.LinkAddress       = notificationValues[0];
                notification.ImageMainAddress  = notificationValues[1];
                notification.ImageHoverAddress = notificationValues[2];
                return(notification);
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Возвращает данные для подключения к LongPoll серверу.
        /// </summary>
        private async Task <VKLongPollServerData> GetServerData()
        {
            appNotificationsService.SendNotification(new AppNotification
            {
                Type    = AppNotificationType.Default,
                Content = "Получение данных для подключения к серверу..."
            });

            byte currentRetry = 0;

            while (currentRetry < MAX_RETRIES_NUMBER)
            {
                var request  = new Request <VKLongPollServerData>("messages.getLongPollServer", token: cts.Token);
                var response = await vkService.ExecuteRequestAsync(request);

                if (response.IsSuccess)
                {
                    return(response.Response);
                }
                else if (response.Error == VKErrors.ConnectionError)
                {
                    if (++currentRetry < MAX_RETRIES_NUMBER)
                    {
                        int timeout = currentRetry * 5;
                        SendConnectionErrorPush(timeout);
                        await Task.Delay(timeout * 1000, cts.Token);

                        continue;
                    }
                }
            }

            var notification = new AppNotification
            {
                Type    = AppNotificationType.Error,
                Title   = "Не удалось получить данные для подключения",
                Content = "Сервис мгновенных сообщений будет остановлен"
            };

            appNotificationsService.SendNotification(notification);

            throw new Exception("Exit from GetServerData loop");
        }
Beispiel #10
0
        private void OnShowCustomPush()
        {
            var notification = new AppNotification
            {
                Title       = CustomPushTitle,
                Content     = CustomPushContent,
                NoSound     = CustomPushNoSound,
                NoVibration = CustomPushNoVibration,
                Type        = (AppNotificationType)CustomPushType
            };

            int duration = 6;

            if (int.TryParse(CustomPushDuration, out duration))
            {
                notification.Duration = TimeSpan.FromSeconds(duration);
            }

            switch (CustomPushView)
            {
            case 1:
                notification.DestinationView     = "ErrorView";
                notification.NavigationParameter = JsonConvert.SerializeObject(new Tuple <string, string>(
                                                                                   "Уведомление",
                                                                                   "Вы попали сюда через настраиваемое тестовое уведомление. Нажмите кнопку Назад, чтобы вернуться."));
                break;

            case 2:
                notification.DestinationView = "SettingsView";
                break;

            case 3:
                notification.DestinationView = "NewsView";
                break;

            case 4:
                notification.DestinationView = "AboutView";
                break;
            }

            appNotificationsService.SendNotification(notification);
        }
Beispiel #11
0
        /// <summary>
        /// Отображает всплывающее сообщение в приложении.
        /// </summary>
        public void ShowPopup(PopupMessage message)
        {
            var notification = new AppNotification
            {
                Type       = (AppNotificationType)message.Type,
                Title      = message.Title,
                Content    = message.Content,
                ImageUrl   = message.ImageUrl,
                ActionToDo = message.ActionToDo,
                Duration   = message.Duration
            };

            if (message.Parameter != null)
            {
                notification.DestinationView     = message.Parameter.Page.ToString();
                notification.NavigationParameter = message.Parameter.Parameter;
            }

            ((App)App.Current).Container.Resolve <IAppNotificationsService>().SendNotification(notification);
        }
        /// <summary>
        /// Запустить LongPoll сервис.
        /// </summary>
        public async void Start()
        {
            if (IsWorking)
            {
                return;
            }

            try
            {
                IsWorking = true;
                cts       = new CancellationTokenSource();
                if (ServiceStarted != null)
                {
                    ServiceStarted(this, EventArgs.Empty);
                }

                await ProcessLongPoll();

                var notification = new AppNotification
                {
                    Type     = AppNotificationType.Info,
                    Title    = "Сервис мгновенных сообщений успешно запущен",
                    Content  = "Теперь вы будете в курсе всех новых сообщений",
                    Duration = TimeSpan.FromSeconds(6)
                };
                appNotificationsService.SendNotification(notification);
            }
            catch (OperationCanceledException)
            {
                OnServiceStopped(VKLongPollServiceStopReason.ByUser);
            }
            catch (WebConnectionException)
            {
                OnServiceStopped(VKLongPollServiceStopReason.ConnectionError);
            }
            catch (Exception)
            {
                OnServiceStopped(VKLongPollServiceStopReason.InternalError);
                throw;
            }
        }
Beispiel #13
0
 private void NotificationRunner()
 {
     while (true)
     {
         if (AppNotificationManager.Count > 0)
         {
             AppNotification notification = AppNotificationManager.PullMessage();
             Dispatcher.Invoke
                 (() =>
             {
                 ShowNotification(notification.Message);
             });
             Thread.Sleep(5000);
             Dispatcher.Invoke(() => { notificationPanel.Visibility = Visibility.Collapsed; });
         }
         else
         {
             Thread.Sleep(200);
         }
     }
 }
        public Feedback save(string tenant, AppNotification data)
        {
            Feedback feedback = new Feedback();

            try
            {
                if (_notificationRepo.GetInstance(tenant).save(ref data))
                {
                    feedback = new Feedback
                    {
                        Code    = 1,
                        Message = "Data saved sucessfully",
                        data    = data
                    };
                }
            }
            catch (Exception ex)
            {
                GitHub.createIssue(ex, new { tenant = tenant, data = data }, _accessor.HttpContext.Request.Headers);
            }
            return(feedback);
        }
Beispiel #15
0
        public string SendNotificationFromFirebaseCloud(AppNotification objAppNotification, bool ISAppUpdate = false)

        {
            // string deviceToken = "cIb5sbjgNo0:APA91bEB18OdXVxW4obSmkgXTKsl84OWg-dSgMVXO3gExgF2iZTVDYiS4axHJaUZgsKKMTN4GyYRfiLQO7-Yd4-oZmWDHeI_IWHmA6HSya6-ajFezXLqRwv22ovmcrgfYDeXsAsbWZpL";
            string serverKey = ConfigurationManager.AppSettings["FCMServerKey"].ToString();
            string senderId  = ConfigurationManager.AppSettings["FCMsenderId"].ToString();
            string FCMURL    = ConfigurationManager.AppSettings["FCMAPIURL"].ToString();


            string     result    = string.Empty;
            string     Status    = string.Empty;
            string     SubStatus = string.Empty;
            WebRequest tRequest  = WebRequest.Create(FCMURL);

            tRequest.Method      = "post";
            tRequest.ContentType = "application/json";


            //if (ISAppUpdate)
            if (objAppNotification.SelectSubRecepient == "App Update")
            {
                Status    = objAppNotification.SelectSubRecepient;
                SubStatus = "Update available";
            }
            else if (objAppNotification.SelectSubRecepient == "Data Wipeup")
            {
                Status    = objAppNotification.SelectSubRecepient;
                SubStatus = "Clear Data";
            }
            else
            {
                Status    = "AppNotification";
                SubStatus = "General Notification";
            }

            var objNotification = new
            {
                to                = objAppNotification.AllDeviceTokenID,
                priority          = "high",
                content_available = true,

                notification = new
                {
                    status   = Status,
                    title    = Status,
                    subtitle = SubStatus,
                    body     = objAppNotification.Message,
                }
            };
            string jsonNotificationFormat = Newtonsoft.Json.JsonConvert.SerializeObject(objNotification);

            Byte[] byteArray = Encoding.UTF8.GetBytes(jsonNotificationFormat);
            tRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
            tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));

            tRequest.ContentLength = byteArray.Length;
            tRequest.ContentType   = "application/json";



            using (Stream dataStream = tRequest.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);

                using (WebResponse tResponse = tRequest.GetResponse())
                {
                    using (Stream dataStreamResponse = tResponse.GetResponseStream())
                    {
                        using (StreamReader tReader = new StreamReader(dataStreamResponse))
                        {
                            String responseFromFirebaseServer = tReader.ReadToEnd();
                            responseFromFirebaseServer = responseFromFirebaseServer.Replace(@"\", "");

                            FCMResponse response = Newtonsoft.Json.JsonConvert.DeserializeObject <FCMResponse>(responseFromFirebaseServer);
                            if (response.success == 1)
                            {
                                objAppNotification.Result = "Notification sent Successfully.";
                            }
                            else if (response.failure == 1)
                            {
                                objAppNotification.Result = "Notification sending Failed";
                            }
                            else
                            {
                                objAppNotification.Result = "Notification sending Failed";
                            }
                        }
                    }
                }
            }
            return(objAppNotification.Result);
        }
Beispiel #16
0
        public Feedback save(string tenant, Products data)
        {
            Feedback feedback = new Feedback();

            try
            {
                AppNotification notification = new AppNotification()
                {
                    type     = "Product",
                    message  = "Saving data",
                    progress = 0
                };
                if (data.notificationid == 0)
                {
                    notification = new AppNotification()
                    {
                        type     = "Product",
                        message  = "Saving data",
                        progress = 0
                    };
                    _notificationRepo.GetInstance(tenant).save(ref notification);
                    _hubContext.Clients.All.SendAsync("SendNotification", notification);
                }
                else
                {
                    notification = _notificationRepo.GetInstance(tenant).getById(data.notificationid);
                }
                try
                {
                    if (_productRepo.GetInstance(tenant).save(data))
                    {
                        notification.progress = 1;
                        notification.message  = "Data saved sucessfully for Product: " + data.name;
                        _notificationRepo.GetInstance(tenant).save(ref notification);
                        feedback = new Feedback
                        {
                            Code    = 1,
                            Message = notification.message,
                            data    = null
                        };
                        _hubContext.Clients.All.SendAsync("SendNotification", notification);
                    }
                }
                catch (Exception ex)
                {
                    notification.progress = -1;
                    notification.message  = "Got the error while saving data";
                    _notificationRepo.GetInstance(tenant).save(ref notification);
                    feedback = new Feedback
                    {
                        Code    = 0,
                        Message = notification.message,
                        data    = ex
                    };
                    GitHub.createIssue(ex, new { tenant = tenant, data = data }, _accessor.HttpContext.Request.Headers);
                    _hubContext.Clients.All.SendAsync("SendNotification", notification);
                }
            }
            catch (Exception ex)
            {
                GitHub.createIssue(ex, new { tenant = tenant, data = data }, _accessor.HttpContext.Request.Headers);
            }
            return(feedback);
        }
Beispiel #17
0
        public async Task <Feedback> reset(string tenant, ResetModel reset)
        {
            Feedback feedback = new Feedback();

            try
            {
                AppNotification notification;
                notification = new AppNotification()
                {
                    type     = _userRepo.GetInstance(tenant).tableName,
                    message  = "Forgot Password Email Sending",
                    progress = 0
                };
                _notificationRepo.GetInstance(tenant).save(ref notification);
                _hubContext.Clients.All.SendAsync("SendNotification", notification);
                try
                {
                    var _userData = _userRepo.GetInstance(tenant).getByUserName(reset.email);
                    if (reset.otp.ToString() == _userData.otp)
                    {
                        if (_userData != null)
                        {
                            using (var transaction = DBServer.BeginTransaction())
                            {
                                _userData.otp      = "";
                                _userData.password = reset.password;
                                _userRepo.GetInstance(tenant).save(ref _userData, transaction);
                                //Email.Send(reset.email, "Reset Password",
                                //    "Password Reset Successfully.");
                                transaction.Commit();
                                notification.progress = 1;
                                notification.message  = "Forgot password email sent sucessfully";
                                _notificationRepo.GetInstance(tenant).save(ref notification);
                                _hubContext.Clients.All.SendAsync("SendNotification", notification);
                                feedback = new Feedback
                                {
                                    Code    = 1,
                                    Message = "Forgot password email sent sucessfully",
                                    data    = reset.email
                                };
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    notification.progress = -1;
                    notification.message  = "Got the error while sending reset password email";
                    _notificationRepo.GetInstance(tenant).save(ref notification);
                    _hubContext.Clients.All.SendAsync("SendNotification", notification);
                    feedback = new Feedback
                    {
                        Code    = 0,
                        Message = "Got the error while sending reset password email",
                        data    = ex
                    };
                    GitHub.createIssue(ex, new { tenant = tenant, data = reset.email }, _accessor.HttpContext.Request.Headers);
                }
            }
            catch (Exception ex)
            {
                GitHub.createIssue(ex, new { tenant = tenant, data = reset.email }, _accessor.HttpContext.Request.Headers);
            }
            return(feedback);
        }
Beispiel #18
0
        public async Task <Feedback> save(string tenant, List <AppPermission> data)
        {
            Feedback feedback = new Feedback();

            try
            {
                AppNotification notification;
                if (data[0].notificationid == 0)
                {
                    notification = new AppNotification()
                    {
                        type     = _userRepo.GetInstance(tenant).tableName,
                        message  = "Saving data",
                        progress = 0
                    };
                    _notificationRepo.GetInstance(tenant).save(ref notification);
                    _hubContext.Clients.All.SendAsync("SendNotification", notification);
                }
                else
                {
                    notification = _notificationRepo.GetInstance(tenant).getById(data[0].notificationid);
                }
                try
                {
                    using (var transaction = DBServer.BeginTransaction())
                    {
                        if (data != null && data.Count > 0 && _permissionRepo.GetInstance(tenant).save(data, transaction))
                        {
                            transaction.Commit();
                            notification.progress = 1;
                            notification.message  = "Data saved sucessfully";
                            notification.recordId = data[0].appuserid;
                            _notificationRepo.GetInstance(tenant).save(ref notification);
                            _hubContext.Clients.All.SendAsync("SendNotification", notification);
                            feedback = new Feedback
                            {
                                Code    = 1,
                                Message = "Data saved sucessfully",
                                data    = null
                            };
                        }
                    }
                }
                catch (Exception ex)
                {
                    notification.progress = -1;
                    notification.message  = "Got the error while saving data";
                    _notificationRepo.GetInstance(tenant).save(ref notification);
                    _hubContext.Clients.All.SendAsync("SendNotification", notification);
                    feedback = new Feedback
                    {
                        Code    = 0,
                        Message = "Got the error while saving data",
                        data    = ex
                    };
                    GitHub.createIssue(ex, new { tenant = tenant, data = data }, _accessor.HttpContext.Request.Headers);
                }
            }
            catch (Exception ex)
            {
                GitHub.createIssue(ex, new { tenant = tenant, data = data }, _accessor.HttpContext.Request.Headers);
            }
            return(feedback);
        }
Beispiel #19
0
        public Feedback saveUser(string tenant, AppUserInfo data)
        {
            Feedback feedback = new Feedback();

            try
            {
                AppNotification notification;
                if (data.notificationid == 0)
                {
                    notification = new AppNotification()
                    {
                        type     = _userRepo.GetInstance(tenant).tableName,
                        message  = "Saving data",
                        progress = 0
                    };
                    _notificationRepo.GetInstance(tenant).save(ref notification);
                    _hubContext.Clients.All.SendAsync("SendNotification", notification);
                }
                else
                {
                    notification = _notificationRepo.GetInstance(tenant).getById(data.notificationid);
                }
                try
                {
                    using (var transaction = DBServer.BeginTransaction())
                    {
                        if (_userRepo.GetInstance(tenant).saveUser(ref data, transaction))
                        {
                            transaction.Commit();
                            notification.progress = 1;
                            notification.message  = "Data saved sucessfully for User: "******"SendNotification", notification);
                            feedback = new Feedback
                            {
                                Code    = 1,
                                Message = "Data saved sucessfully",
                                data    = data
                            };
                        }
                        else
                        {
                            transaction.Commit();
                            notification.progress = 1;
                            notification.message  = "Data saved sucessfully";
                            notification.recordId = data.USID;
                            _notificationRepo.GetInstance(tenant).save(ref notification);
                            _hubContext.Clients.All.SendAsync("SendNotification", notification);
                            feedback = new Feedback
                            {
                                Code    = 1,
                                Message = "Data saved sucessfully",
                                data    = data
                            };
                        }
                    }
                }
                catch (Exception ex)
                {
                    notification.progress = -1;
                    notification.message  = "Got the error while removing data";
                    _notificationRepo.GetInstance(tenant).save(ref notification);
                    _hubContext.Clients.All.SendAsync("SendNotification", notification);
                    feedback = new Feedback
                    {
                        Code    = 0,
                        Message = "Got the error while removing data",
                        data    = ex
                    };
                    GitHub.createIssue(ex, new { tenant = tenant, data = data }, _accessor.HttpContext.Request.Headers);
                }
            }
            catch (Exception ex)
            {
                GitHub.createIssue(ex, new { tenant = tenant, data = data }, _accessor.HttpContext.Request.Headers);
            }
            return(feedback);
        }
Beispiel #20
0
 public void ShowNotification(AppNotification notification)
 {
     Debug.WriteLine($"App notification: {notification.Title} - {notification.Content}\nDuration {notification.Duration}");
 }
Beispiel #21
0
 public AppNotification AppNotificationMaster(AppNotification objAppNotification)
 {
     return(objUserManagementBusiness.AppNotificationMaster(objAppNotification));
 }
Beispiel #22
0
        public async void ShowNotification(AppNotification notification)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                if (notification.IsHided)
                {
                    return;
                }

                if (NotificationsPanel == null)
                {
                    lock (_lockObject)
                    {
                        _waitingNotifications.Add(notification);
                        if (_waitingNotifications.Count >= 5)
                        {
                            _waitingNotifications.RemoveAt(0);
                        }

                        return;
                    }
                }

                var anc = new AppNotificationControl {
                    Message = notification
                };
                anc.Loaded += (s, e) => anc.Show();
                anc.Tapped += (s, e) =>
                {
                    lock (_lockObject)
                        _notificationsCount--;

                    anc.Hide();
                    if (!String.IsNullOrWhiteSpace(anc.Message.DestinationView))
                    {
                        _navigationService.Navigate(anc.Message.DestinationView, anc.Message.NavigationParameter);
                    }

                    anc.Message.ActionToDo?.Invoke();
                };
                notification.HideRequested += (s, e) =>
                {
                    lock (_lockObject)
                        _notificationsCount--;
                    anc.Hide();
                };

                lock (_lockObject)
                {
                    NotificationsPanel.Children.Insert(0, anc);
                    _notificationsCount++;

                    if (_notificationsCount >= 5)
                    {
                        //var notificationControl = NotificationsPanel.Children.LastOrDefault() as AppNotificationControl;
                        NotificationsPanel.Children.RemoveAt(NotificationsPanel.Children.Count - 1);
                        _notificationsCount--;
                    }
                }

                Debug.WriteLine($"Count: {_notificationsCount}");
            });
        }
Beispiel #23
0
 public Feedback Save(AppNotification data, string tenant = "")
 {
     return(_notifyProvider.GetInstance(tenant).save(tenant, data));
 }
Beispiel #24
0
        private void TransferProgressChanged(TransferType type, TransferItem e)
        {
            AppNotification notification = null;

            _notifications.TryGetValue(e.OperationGuid, out notification);

            if (notification == null)
            {
                if (e.Status == BackgroundTransferStatus.Running && e.ProcessedSize.Bytes > 0)
                {
                    notification = new AppNotification
                    {
                        Type        = AppNotificationType.Default,
                        NoVibration = true,
                        NoSound     = true
                    };

                    notification.ProgressPercent = e.TotalSize.Bytes == 0 ? 0 : e.ProcessedSize.Bytes / (e.TotalSize.Bytes / 100);
                    notification.Content         = String.Format(_locService["TransferView_SizeMask_Text"],
                                                                 e.ProcessedSize.ToFormattedString(_locService), e.TotalSize.ToFormattedString(_locService));
                    notification.Duration = TimeSpan.MaxValue;

                    if (type == TransferType.Download)
                    {
                        notification.Title    = String.Format(_locService["TransferView_Downloading_Notification_Text"], e.Name);
                        notification.ImageUrl = "ms-appx:///Assets/Popups/Download.png";
                    }
                    else
                    {
                        notification.Title    = String.Format(_locService["TransferView_Uploading_Notification_Text"], e.Name);
                        notification.ImageUrl = "ms-appx:///Assets/Popups/Upload.png";
                    }

                    _notifications[e.OperationGuid] = notification;
                    _appNotificationsService.SendNotification(notification);
                }
            }
            else
            {
                if (e.Status == BackgroundTransferStatus.Running)
                {
                    notification.ProgressPercent = e.TotalSize.Bytes == 0 ? 0 : e.ProcessedSize.Bytes / (e.TotalSize.Bytes / 100);
                    notification.Content         = String.Format(_locService["TransferView_SizeMask_Text"],
                                                                 e.ProcessedSize.ToFormattedString(_locService), e.TotalSize.ToFormattedString(_locService));
                }
                else
                {
                    _notifications.Remove(e.OperationGuid);
                    notification.Hide();
                }
            }

            if (e.Status == BackgroundTransferStatus.Error)
            {
                _appNotificationsService.SendNotification(new AppNotification
                {
                    Type  = AppNotificationType.Error,
                    Title = type == TransferType.Download ?
                            _locService["Toast_Downloads_Fail_Text"] :
                            _locService["Toast_Uploads_Fail_Text"],
                    Content = e.Name
                });
                _notifications.Remove(e.OperationGuid);
            }
            else if (e.Status == BackgroundTransferStatus.Completed)
            {
                if (type == TransferType.Download)
                {
                    _appNotificationsService.SendNotification(new AppNotification
                    {
                        Type    = AppNotificationType.Info,
                        Title   = _locService["Toast_Downloads_Success_Text"],
                        Content = e.Name
                    });
                }

                _notifications.Remove(e.OperationGuid);
            }
        }
Beispiel #25
0
        /// <summary>
        /// Отправить уведомление.
        /// </summary>
        /// <param name="notification">Данные уведомления.</param>
        public void SendNotification(AppNotification notification)
        {
            if (notification == null)
            {
                throw new ArgumentNullException(nameof(notification));
            }

            if (!_settingsService.GetNoCache(ENABLE_IN_APP_POPUPS, true) && !notification.IsImportant)
            {
                return;
            }

            Task.Run(async() =>
            {
                try
                {
                    if (!notification.NoSound && _settingsService.GetNoCache(ENABLE_IN_APP_SOUND, true))
                    {
                        await PlaySound(notification.Type);
                    }
                }
                catch (Exception)
                {
                    _settingsService.Set(ENABLE_IN_APP_SOUND, false);
                    var error = new AppNotification
                    {
                        Type        = AppNotificationType.Error,
                        NoSound     = true,
                        Title       = _locService["AppNotifications_SoundNotWorking_Title"],
                        Content     = _locService["AppNotifications_SoundNotWorking_Content"],
                        IsImportant = true
                    };
                    SendNotification(error);
                }
            });

            _presenter.ShowNotification(notification);

            Task.Run(async() =>
            {
                try
                {
                    if (!notification.NoVibration && _settingsService.GetNoCache(ENABLE_IN_APP_VIBRATION, true))
                    {
                        await StartVibration(notification.Type);
                    }
                }
                catch (Exception)
                {
                    _settingsService.Set(ENABLE_IN_APP_VIBRATION, false);
                    var error = new AppNotification
                    {
                        Type        = AppNotificationType.Error,
                        NoVibration = true,
                        Title       = _locService["AppNotifications_VibrationNotWorking_Title"],
                        Content     = _locService["AppNotifications_VibrationNotWorking_Content"],
                        IsImportant = true
                    };
                    SendNotification(error);
                }
            });

            NewNotification?.Invoke(this, notification);
        }