示例#1
0
        private async void Chat_NewChatMessage(ChatDataTemplate chat, Data_Manager2.Classes.Events.NewChatMessageEventArgs args)
        {
            if (!MODEL.IsDummy)
            {
                await MODEL.OnNewChatMessageAsync(args.MESSAGE, chat.Chat, chat.MucInfo);

                if (args.MESSAGE.state == MessageState.UNREAD)
                {
                    // Mark message as read and update the badge notification count:
                    await Task.Run(() =>
                    {
                        ChatDBManager.INSTANCE.markMessageAsRead(args.MESSAGE);
                        ToastHelper.UpdateBadgeNumber();
                    });
                }
            }
        }
示例#2
0
        public static async Task <Result <ToastNotificationVisibility> > CheckSystemUptime(Some <NotificationProfile> userProfile, double maxUpTimeHours, bool isDisabled)
        {
            var category             = typeof(CheckSystemUptimeCommand).GetPolicyCategory();
            var policyMaxUptimeHours = Profile.GetIntegerPolicyValue(Context.Machine, category, "MaxUptimeHours", (int)maxUpTimeHours);
            var groupName            = ToastGroups.CheckSystemUptime;
            var tag = ToastGroups.CheckSystemUptime;
            var systemUptimeCheckIsDisabled = Profile.IsCheckDisabled(isDisabled, typeof(CheckSystemUptimeCommand));

            bool IsNonCompliant(SystemUptimeInfo info) => info.Uptime.TotalHours > (double)policyMaxUptimeHours;

            return(await CheckSystemUptimePure(() => ComplianceInfo.LoadInfo <SystemUptimeInfo>(SystemUptime.LoadSystemUptimeInfo, IsNonCompliant, ScheduledTasks.ComplianceSystemMeasurements, true),
                                               IsNonCompliant,
                                               (uptime) => SystemUptime.ShowSystemUptimeToastNotification(userProfile, tag, groupName, uptime),
                                               () => ToastHelper.RemoveToastNotification(groupName),
                                               systemUptimeCheckIsDisabled
                                               ).ConfigureAwait(false));
        }
        /// <summary>
        /// Caller must have already established lock and is on background thread
        /// </summary>
        /// <param name="task"></param>
        private static AdditionalDataTasks UpdateTaskHelper(DataItemTask task)
        {
            _conn.InsertOrReplace(task);

            if (OnTaskUpdated != null)
            {
                OnTaskUpdated(null, task);
            }

            ToastHelper.HandleOnTaskUpdated(task);

            var additional = new AdditionalDataTasks();

            additional.ResetPrimaryTileTask = ResetPrimaryTileWorker.Instance.Start();

            return(additional);
        }
示例#4
0
        private async Task <bool> TrySendInput(string message)
        {
#if DEBUG
            await Task.Delay(3000);
#endif

            if (await this.GetAgent().DesktopClient.SendKeysAsync(message))
            {
                ToastHelper.DisplaySuccess(true, ToastLength.Short);
                return(true);
            }
            else
            {
                ToastHelper.DisplaySuccess(false, ToastLength.Long);
                return(false);
            }
        }
示例#5
0
        public override async void Execute(object parameter)
        {
            LogHelper.Log("PlayVideoCommand called");

            VideoItem videoVm = null;

            if (parameter is ItemClickEventArgs)
            {
                ItemClickEventArgs args = parameter as ItemClickEventArgs;
                videoVm = args.ClickedItem as VideoItem;
            }
            else if (parameter is VideoItem)
            {
                videoVm = parameter as VideoItem;
            }

            // If the VM is null, we can't do anything. So just return.
            if (videoVm == null)
            {
#if DEBUG
                ToastHelper.Basic("Failed to load the selected video, the video view model is null.");
#endif
                LogHelper.Log("PLAYVIDEO: VideoVm is null, returning");
                return;
            }

            LogHelper.Log("PLAYVIDEO: VideoVm is not null, continuing");
            try
            {
                // If the video file is null (For example, the user deleted the video, and it's on
                // their favorites list.) We need to make sure the whole app does not crash.

                // TODO: If user selectes a video from their favoites, and it has been moved or deleted, we should ask them if we want to remove it from their list

                await Locator.PlaybackService.SetPlaylist(new List <IMediaItem> {
                    videoVm
                });
            }
            catch (System.Exception)
            {
                // TODO: Enhance error handling
                // TODO: Remove hardcoded English
                ToastHelper.Basic(Strings.FailOpenVideo);
                return;
            }
        }
示例#6
0
        protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
        {
            var deferral = args.TaskInstance.GetDeferral();

            switch (args.TaskInstance.Task.Name)
            {
            case BackgroundTaskHelper.TOAST_BACKGROUND_TASK_NAME:
                ToastNotificationActionTriggerDetail details = args.TaskInstance.TriggerDetails as ToastNotificationActionTriggerDetail;
                if (details != null)
                {
                    initLogLevel();

                    string arguments = details.Argument;
                    var    userInput = details.UserInput;

                    Logger.Debug("App activated in background through toast with: " + arguments);
                    AbstractToastActivation abstractToastActivation = ToastActivationArgumentParser.parseArguments(arguments);

                    if (abstractToastActivation is MarkChatAsReadToastActivation markChatAsRead)
                    {
                        ToastHelper.removeToastGroup(markChatAsRead.CHAT_ID);
                        ChatDBManager.INSTANCE.markAllMessagesAsRead(markChatAsRead.CHAT_ID);
                    }
                    else if (abstractToastActivation is MarkMessageAsReadToastActivation markMessageAsRead)
                    {
                        ChatDBManager.INSTANCE.markMessageAsRead(markMessageAsRead.CHAT_MESSAGE_ID);
                    }
                    else if (abstractToastActivation is SendReplyToastActivation sendReply)
                    {
                        ChatTable chat = ChatDBManager.INSTANCE.getChat(sendReply.CHAT_ID);
                        if (chat != null && userInput[ToastHelper.TEXT_BOX_ID] != null)
                        {
                            if (isRunning)
                            {
                            }
                            else
                            {
                            }
                        }
                    }
                }
                break;
            }

            deferral.Complete();
        }
示例#7
0
        public void AddDownItem(Book book)
        {
            var temp = DownloadItems.FirstOrDefault(p => p.Book.BookId == book.BookId);

            if (temp != null)
            {
                ToastHelper.ShowMessage(book.BookName + "已在缓存队列中");
                return;
            }

            var downloadItem = new DownloadItemViewModel(book);

            DownloadItems.Insert(0, downloadItem);
            downloadItem.StartDownload();

            ToastHelper.ShowMessage(book.BookName + "开始缓存,您可在设置-下载中心查看进度");
        }
示例#8
0
        public async void GetData()
        {
            if (!CookieHelper.CheckLogin() || IsLoading)
            {
                return;
            }
            try
            {
                IsLoading = true;

                var html = await GetHtmlData2(SoduPageValue.BookShelfPage, false, true);

                var list = ListPageDataHelper.GetBookShelftListFromHtml(html);
                if (list == null || list.Count == 0)
                {
                    if (html != null && html.Contains(SoduPageValue.BookShelfPage))
                    {
                        Books = null;
                        ToastHelper.ShowMessage("您的在线书架为空");
                    }
                    else
                    {
                        ToastHelper.ShowMessage("获取在线书架数据失败");
                    }
                }
                else
                {
                    var result = await CompareWithLocalCache(list.ToList());

                    Books?.Clear();
                    foreach (var book in list)
                    {
                        Books?.Add(book);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message + "\n" + ex.StackTrace);
            }
            finally
            {
                IsLoading = false;
            }
        }
        private void OnLaunchedOrActivated(IActivatedEventArgs e)
        {
            try
            {
                Frame rootFrame = Window.Current.Content as Frame;

                // Do not repeat app initialization when the Window already has content,
                // just ensure that the window is active
                if (rootFrame == null)
                {
                    // Create a Frame to act as the navigation context and navigate to the first page
                    rootFrame = new Frame();

                    rootFrame.NavigationFailed += OnNavigationFailed;

                    if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                    {
                        //TODO: Load state from previously suspended application
                    }

                    // Place the frame in the current Window
                    Window.Current.Content = rootFrame;
                }

                // Register the background task for toast notifications
                ToastHelper.RegisterToastActionBackgroundTask();

                if ((e is LaunchActivatedEventArgs launchArgs) && launchArgs.PrelaunchActivated == false)
                {
                    if (rootFrame.Content == null)
                    {
                        // When the navigation stack isn't restored navigate to the first page,
                        // configuring the new page by passing required information as a navigation
                        // parameter
                        rootFrame.Navigate(typeof(MainPage), launchArgs.Arguments);
                    }
                    // Ensure the current window is active
                    Window.Current.Activate();
                }
            }
            catch
            {
                // Report to your telemetry
            }
        }
示例#10
0
        public Task Initialize()
        {
            return(DispatchHelper.InvokeInUIThread(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                var param = new List <string>
                {
                    "-I",
                    "dummy",
                    "--no-osd",
                    "--verbose=3",
                    "--no-stats",
                    "--avcodec-fast",
                    "--subsdec-encoding",
                    Locator.SettingsVM.SubtitleEncodingValue == "System" ? "" : Locator.SettingsVM.SubtitleEncodingValue,
                    DeviceHelper.GetDeviceType() == DeviceTypeEnum.Phone ? "--deinterlace-mode=bob" : string.Empty,
                    "--aout=winstore",
                    string.Format("--keystore-file={0}\\keystore", ApplicationData.Current.LocalFolder.Path),
                };

                // So far, this NEEDS to be called from the main thread
                try
                {
                    App.RootPage.SwapChainPanel.CompositionScaleChanged += SwapChainPanel_CompositionScaleChanged;
                    App.RootPage.SwapChainPanel.SizeChanged += SwapChainPanel_SizeChanged;
                    Instance = new Instance(param, App.RootPage.SwapChainPanel);
                    Instance?.setDialogHandlers(
                        async(title, text) => await _dialogService.ShowErrorDialog(title, text),
                        async(dialog, title, text, defaultUserName, askToStore) => await _dialogService.ShowLoginDialog(dialog, title, text, defaultUserName, askToStore),
                        async(dialog, title, text, qType, cancel, action1, action2) => await _dialogService.ShowQuestionDialog(dialog, title, text, qType, cancel, action1, action2),
                        (dialog, title, text, intermidiate, position, cancel) => { },
                        async(dialog) => await _dialogService.CancelCurrentDialog(),
                        (dialog, position, text) => { }
                        );

                    // Audio device management also needs to be called from the main thread
                    MediaDevice.DefaultAudioRenderDeviceChanged += onDefaultAudioRenderDeviceChanged;
                    PlayerInstanceReady.TrySetResult(Instance != null);
                }
                catch (Exception e)
                {
                    LogHelper.Log("VLC Service : Couldn't create VLC Instance\n" + StringsHelper.ExceptionToString(e));
                    ToastHelper.Basic(Strings.FailStartVLCEngine);
                }
            }));
        }
示例#11
0
        async void CreateNotification(string title, string description)
        {
            NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;

            Intent uiIntent = new Intent(this, typeof(MainActivity));

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

            Android.Graphics.BitmapFactory.Options options = new Android.Graphics.BitmapFactory.Options
            {
                InJustDecodeBounds = true
            };

            Android.Graphics.Bitmap largeIcon = await Android.Graphics.BitmapFactory.DecodeResourceAsync(Resources, XamarinMastering.Droid.Resource.Drawable.icon, options);

            //responding to the notification: show to device
            ToastHelper.ProcessNotification(this, notificationManager, uiIntent, builder, title, description, largeIcon);
        }
示例#12
0
        private void RegistrationCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            ApplicationDataContainer container = ApplicationData.Current.LocalSettings;

            try
            {
                var content = container.Values["RawMessage"].ToString();
                if (content != null)
                {
                    ToastMessage message = JsonConvert.DeserializeObject <ToastMessage>(content);
                    ToastHelper.DisplayTextToast(ToastTemplateType.ToastImageAndText01, message.FromId, message.Content, message.FromPicture);
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }
示例#13
0
 private void DeleteLogsClicked()
 {
     try
     {
         var root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
         var path = Path.Combine(root, "logs", "nlog.csv");
         if (File.Exists(path))
         {
             File.Delete(path);
         }
         ToastHelper.Display("Logs deleted", ToastLength.Short);
     }
     catch (Exception e)
     {
         ToastHelper.Display("Failed to clear logs", ToastLength.Short);
         Log.Error(e);
     }
 }
示例#14
0
 public static void GoBack()
 {
     if (ContentFrame.CanGoBack)
     {
         ContentFrame.GoBack();
     }
     else
     {
         if (CheckIfShutDown())
         {
             Application.Current.Exit();
         }
         else
         {
             ToastHelper.ShowMessage("再按一次返回键退出");
         }
     }
 }
示例#15
0
        private void showChatMessages(ChatTable newChat, ChatTable oldChat)
        {
            if (newChat != null)
            {
                // Only show chat messages if the chat changed:
                if (oldChat != null && Equals(newChat.id, oldChat.id))
                {
                    return;
                }

                // Show loading:
                loading_ldng.IsLoading           = true;
                invertedListView_lstv.Visibility = Visibility.Collapsed;

                // Create a copy to prevent multi threading issues:
                ChatTable chatCpy = newChat;

                Task.Run(async() =>
                {
                    // Mark all unread messages as read for this chat:
                    ChatDBManager.INSTANCE.markAllMessagesAsRead(chatCpy.id);
                    // Remove notification group:
                    ToastHelper.removeToastGroup(chatCpy.id);

                    // Show all chat messages:
                    List <ChatMessageDataTemplate> msgs = new List <ChatMessageDataTemplate>();
                    foreach (ChatMessageTable msg in ChatDBManager.INSTANCE.getAllChatMessagesForChat(chatCpy.id))
                    {
                        msgs.Add(new ChatMessageDataTemplate()
                        {
                            message = msg,
                            chat    = chatCpy
                        });
                    }
                    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        chatMessages.Clear();
                        chatMessages.AddRange(msgs);
                        invertedListView_lstv.Visibility = Visibility.Visible;
                        loading_ldng.IsLoading           = false;
                    });
                });
            }
        }
示例#16
0
        public void ToastTileCoordinatesTest()
        {
            try
            {
                var expectedTiles = new List <TestTile>(16);
                expectedTiles.Add(new TestTile(0, 0, 0, 0, 0));
                expectedTiles.Add(new TestTile(1, 1, 1, 0, 1));
                expectedTiles.Add(new TestTile(2, 2, 2, 1, 2));
                expectedTiles.Add(new TestTile(3, 4, 5, 3, 4));
                expectedTiles.Add(new TestTile(4, 9, 10, 6, 8));
                expectedTiles.Add(new TestTile(5, 19, 21, 12, 16));
                expectedTiles.Add(new TestTile(6, 39, 43, 24, 32));
                expectedTiles.Add(new TestTile(7, 78, 86, 49, 64));
                expectedTiles.Add(new TestTile(8, 156, 173, 99, 128));
                expectedTiles.Add(new TestTile(9, 313, 346, 198, 256));
                expectedTiles.Add(new TestTile(10, 627, 692, 398, 512));
                expectedTiles.Add(new TestTile(11, 1255, 1384, 796, 1024));
                expectedTiles.Add(new TestTile(12, 2511, 2768, 1593, 2048));
                expectedTiles.Add(new TestTile(13, 5023, 5536, 3187, 4096));
                expectedTiles.Add(new TestTile(14, 10047, 11072, 6375, 8192));
                expectedTiles.Add(new TestTile(15, 20094, 22145, 12750, 16384));

                int maxLevel = 15;
                var boundary = new Boundary(-136.40173 + 180, 58.35286, -135.91382 + 180, 58.75443);
                var tiles    = ToastHelper.ComputeTileCoordinates(boundary, maxLevel);
                Assert.AreEqual(tiles.Count, maxLevel + 1);
                for (int index = 0; index <= maxLevel; index++)
                {
                    Assert.IsTrue(tiles.ContainsKey(index));
                    Assert.IsNotNull(tiles[index]);
                    Assert.IsTrue(tiles[index].Count > 0);

                    var tilesAtBase = tiles[index];
                    Assert.AreEqual(tilesAtBase.Min(item => item.X), expectedTiles[index].XMin);
                    Assert.AreEqual(tilesAtBase.Max(item => item.X), expectedTiles[index].XMax);
                    Assert.AreEqual(tilesAtBase.Min(item => item.Y), expectedTiles[index].YMin);
                    Assert.AreEqual(tilesAtBase.Max(item => item.Y), expectedTiles[index].YMax);
                }
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
示例#17
0
        private async Task SetHostClipboard()
        {
            if (!TryGetClipboardContent(out var content))
            {
                ToastHelper.Display($"Clipboard cannot be sent", ToastLength.Long);
                return;
            }

            try
            {
                var result = await this.GetAgent().DesktopClient.SetClipboardAsync(TimeSpan.FromMinutes(1), GetRemoteName(), content);

                ToastHelper.Display(result ? "Host clipboard updated" : "error", ToastLength.Short);
            }
            catch (RpcException e) when(e.StatusCode == StatusCode.PermissionDenied)
            {
                ToastHelper.Display(e.Message, ToastLength.Long);
            }
        }
        public static Task <AdditionalDataTasks> AddTaskAsync(DataItemTask task)
        {
            return(Execute(delegate
            {
                _conn.Insert(task);

                if (OnTaskAdded != null)
                {
                    OnTaskAdded(null, task);
                }

                var additional = new AdditionalDataTasks();

                ToastHelper.HandleOnTaskAdded(task);
                additional.ResetPrimaryTileTask = ResetPrimaryTileWorker.Instance.Start();

                return additional;
            }));
        }
        public static Task <AdditionalDataTasks> RemoveTaskAsync(int taskId)
        {
            return(Execute(delegate
            {
                _conn.Delete <DataItemTask>(taskId);

                if (OnTaskRemoved != null)
                {
                    OnTaskRemoved(null, taskId);
                }

                ToastHelper.HandleOnTaskRemoved(taskId);

                return new AdditionalDataTasks()
                {
                    ResetPrimaryTileTask = ResetPrimaryTileWorker.Instance.Start()
                };
            }));
        }
示例#20
0
        public async Task AddToPlaylist(AlbumItem albumItem)
        {
            if (Locator.MusicLibraryVM.CurrentTrackCollection == null)
            {
                return;
            }
            var playlistId = Locator.MusicLibraryVM.CurrentTrackCollection.Id;

            Locator.MusicLibraryVM.CurrentTrackCollection.Playlist.AddRange(albumItem.Tracks);
            foreach (TrackItem trackItem in albumItem.Tracks)
            {
                await tracklistItemRepository.Add(new TracklistItem()
                {
                    TrackId           = trackItem.Id,
                    TrackCollectionId = playlistId,
                }).ConfigureAwait(false);
            }
            ToastHelper.Basic(string.Format(Strings.TrackAddedToYourPlaylist, albumItem.Name), false, string.Empty, "playlistview");
        }
示例#21
0
        public void Execute(Dictionary <string, object> arguments)
        {
            string headerText = (string)arguments["HeaderText"];
            string alertText  = (string)arguments["AlertText"];
            bool   persistent = (bool)arguments["Persistent"];

            string      toastId  = (++TOAST_COUNTER).ToString();
            XmlDocument document = ToastHelper.BuildToastXml(toastId, headerText, alertText, persistent);

            if (arguments.ContainsKey("Delay"))
            {
                long delay = long.Parse(arguments["Delay"].ToString());
                ToastHelper.ScheduleToast(toastId, document, delay);
            }
            else
            {
                ToastHelper.CreateToast(document);
            }
        }
示例#22
0
        /// <summary>
        /// Invoked when the Activated event is raised, this can be raised from a toast notification being tapped
        /// </summary>
        /// <param name="e">The toast activated argments</param>
        protected override void OnActivated(IActivatedEventArgs e)
        {
            // if e is from a toast notification then cast it and strip the argument out.
            var argument = e as ToastNotificationActivatedEventArgs;

            if (argument == null)
            {
                return;
            }
            // strip the IncidentId out of the argument
            int incidentId = ToastHelper.GetIncidentNumber(argument.Argument);

            Window.Current.CoreWindow.KeyDown += ApplicationKeyDown();

            // Navigate to the incident
            Frame rootFrame = (Frame)Window.Current.Content;

            rootFrame.Navigate(typeof(MainPage), new IncidentSelectedEventArgs(incidentId));
        }
示例#23
0
        private void handleTextMessage(/*@NonNull MasterSecretUnion masterSecret,*/
            SignalServiceEnvelope envelope,
            SignalServiceDataMessage message,
            May <long> smsMessageId)
        {
            var    textMessageDatabase = DatabaseFactory.getTextMessageDatabase();
            String body = message.getBody().HasValue ? message.getBody().ForceGetValue() : "";


            IncomingTextMessage textMessage = new IncomingTextMessage(envelope.getSource(),
                                                                      envelope.getSourceDevice(),
                                                                      message.getTimestamp(), body,
                                                                      message.getGroupInfo());

            textMessage = new IncomingEncryptedMessage(textMessage, body);
            var messageAndThreadId = textMessageDatabase.InsertMessageInbox(textMessage);

            ToastHelper.NotifyNewMessage(messageAndThreadId.second(), DatabaseFactory.getDirectoryDatabase().GetForNumber(envelope.getSource()).Name, body);
        }
示例#24
0
        public static async Task <Result <ToastNotificationVisibility> > CheckMissingMsUpdates(
            Some <NotificationProfile> userProfile, int hoursToWaitBeforeNotifyUser, bool isDisabled)
        {
            var category = typeof(CheckMissingMsUpdatesCommand).GetPolicyCategory();
            var policyHoursToWaitBeforeNotifyUser = Profile.GetIntegerPolicyValue(Context.Machine, category, "HoursToWaitBeforeNotifyingUser", (int)hoursToWaitBeforeNotifyUser);

            var groupName = ToastGroups.CheckMissingMsUpdates;
            var tag       = ToastGroups.CheckMissingMsUpdates;
            var systemUptimeCheckIsDisabled = Profile.IsCheckDisabled(isDisabled, typeof(CheckMissingMsUpdatesCommand));

            bool IsNonCompliant(MissingMsUpdatesInfo info) => info.Updates.Count > 0 && info.Updates.Any(update => (DateTime.Now - update.FirstMeasuredMissing).TotalHours >= policyHoursToWaitBeforeNotifyUser);

            return(await CheckMissingMsUpdatesPure(() => ComplianceInfo.LoadInfo(MissingMsUpdates.LoadMissingMsUpdatesInfo, IsNonCompliant, ScheduledTasks.ComplianceSystemMeasurements, true),
                                                   IsNonCompliant,
                                                   (info) => MissingMsUpdates.ShowMissingUpdatesToastNotification(userProfile, tag, groupName, info),
                                                   () => ToastHelper.RemoveToastNotification(groupName),
                                                   systemUptimeCheckIsDisabled
                                                   ).ConfigureAwait(false));
        }
示例#25
0
        public static void AddAlbumToPlaylist(object args)
        {
            if (Locator.MusicLibraryVM.CurrentTrackCollection == null)
            {
#if WINDOWS_PHONE_APP
                if (args is ContentDialogButtonClickEventArgs)
                {
                    ((ContentDialogButtonClickEventArgs)args).Cancel = true;
                }
#endif
                ToastHelper.Basic(Strings.HaveToSelectPlaylist, false, "selectplaylist");
                return;
            }
#if WINDOWS_APP
            var flyout = ((AddAlbumToPlaylistBase)args).GetFirstDescendantOfType <SettingsFlyout>();
            flyout?.Hide();
#endif
            Locator.MusicLibraryVM.AddToPlaylistCommand.Execute(Locator.MusicLibraryVM.CurrentAlbum);
        }
示例#26
0
        public CustomerListPage()
        {
            InitializeComponent();

            BindingContext = VM = new CustomerListViewModel();

            // handle auth login/logout

            var tbLoginOut = ToolbarHelper.GenerateToolbarButton("Auth", new Command(async() =>
            {
                if (Settings.AzureADUserInfo != null)
                {
                    // logout
                    new AuthenticationContext(Settings.AzureADAuthority).TokenCache.Clear();

                    DependencyService.Get <IAuthenticator>().ClearCookies();

                    VM.CustomerList.Clear();
                    Settings.AzureADUserInfo = null;

                    await ToastHelper.Success("Logged Out!");
                }
                else
                {
                    // login
                    try
                    {
                        await D365AuthHelper.GetAuthorizationHeader();
                    }
                    catch (Exception ex)
                    {
                        await DisplayAlert("Authentication Error", ex.Message, "Ok");
                        return;
                    }

                    await VM.ExecuteLoadCustomersCommand();

                    await ToastHelper.Success("Customers Loaded!");
                }
            }));

            ToolbarItems.Add(tbLoginOut);
        }
示例#27
0
        public void InsertOrUpdateBookCatalogs(Book book)
        {
            var result = DbLocalBook.InsertOrUpdateBookCatalogs(AppDataPath.GetLocalBookDbPath(), book.CatalogList);

            if (!result)
            {
                ToastHelper.ShowMessage(book.BookName + "下载失败", false);
                ViewModelInstance.Instance.DownloadCenter.RemoveDownItem(this);
                return;
            }
            var value = DbLocalBook.InsertOrUpdatBook(AppDataPath.GetLocalBookDbPath(), book);

            if (value)
            {
                ToastHelper.ShowMessage(book.BookName + "下载成功,您可在本地书架中阅读");
                ViewModelInstance.Instance.DownloadCenter.RemoveDownItem(this);
                ViewModelInstance.Instance.LocalBookPage.InserOrUpdateBook(book);
            }
        }
示例#28
0
        public static async Task AddToPlaylist(AlbumItem albumItem)
        {
            if (Locator.MusicLibraryVM.CurrentTrackCollection == null)
            {
                return;
            }
            var playlistId = Locator.MusicLibraryVM.CurrentTrackCollection.Id;

            foreach (TrackItem trackItem in albumItem.Tracks)
            {
                Locator.MusicLibraryVM.CurrentTrackCollection.Playlist.Add(trackItem);
                await Locator.MusicLibraryVM.TracklistItemRepository.Add(new TracklistItem()
                {
                    TrackId           = trackItem.Id,
                    TrackCollectionId = playlistId,
                });
            }
            ToastHelper.Basic(string.Format(Strings.TrackAddedToYourPlaylist, albumItem.Name));
        }
示例#29
0
        private void SeekBarOnProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e)
        {
            const int step     = 5;
            var       progress = e.Progress;

            progress       = progress / step;
            progress       = progress * step;
            _textView.Text = $"Master volume: {progress}";
            _seekBar.SetProgress(progress, true);

            Log.Info("Setting master volume to {Value} FromUser: {FromUser}", progress, e.FromUser);
            if (e.FromUser)
            {
                Debouncer.Debounce(nameof(AudioFragment) + nameof(SeekBarOnProgressChanged), async() =>
                {
                    await _agent.DesktopClient.SetMasterVolumeAsync(TimeSpan.FromSeconds(5), progress);
                    ToastHelper.Display("Volume updated", ToastLength.Short);
                }, TimeSpan.FromSeconds(2));
            }
        }
        public async void GetData()
        {
            var url  = SoduPageValue.HomePage;
            var html = await GetHtmlData(url, true, true);

            var list = ListPageDataHelper.GetHotAndRecommendList(html);

            if (list == null || list.Count == 0)
            {
                ToastHelper.ShowMessage("热门推荐数据获取失败");
            }
            else
            {
                Books?.Clear();
                foreach (var book in list)
                {
                    Books?.Add(book);
                }
            }
        }