private async Task <T> SendRequest <T>(string address) where T : IResponce, new() { var responce = await StartRequest(address); if (string.IsNullOrEmpty(responce)) { return(new T() { Success = false }); } try { var responceDeserialize = await Task.Run(() => Serializer.Deserialize <T>(responce)); return(responceDeserialize); } catch { ContentDialogHelper.ShowMessage("Получены неверные данные", "Загружены ошибочные данные, пожалуйста, попробуйте снова."); return(new T() { Success = false }); } }
private async Task <Tuple <Boolean, String> > createGroupNameInputDialog() { Boolean cancelled = false; String groupName = ""; ContentDialog enterGroupNameDialog = new ContentDialog() { Title = "Rename Group" }; var panel = new StackPanel(); TextBox groupNameBox = setTextBox("Enter a group name", ""); groupNameBox.MaxLength = maxCharacterLength; panel.Children.Add(groupNameBox); enterGroupNameDialog.Content = panel; enterGroupNameDialog.PrimaryButtonText = "OK"; enterGroupNameDialog.PrimaryButtonClick += delegate { groupName = groupNameBox.Text; }; enterGroupNameDialog.SecondaryButtonText = "Cancel"; enterGroupNameDialog.SecondaryButtonClick += delegate { cancelled = true; }; await ContentDialogHelper.CreateContentDialogAsync(enterGroupNameDialog, true); return(Tuple.Create(cancelled, groupName)); }
private async void PlayerIndexBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { if (ViewModel.IsModified && !_dialogOpen) { _dialogOpen = true; var result = await ContentDialogHelper.CreateConfirmationDialog( this.GetVisualRoot() as StyleableWindow, LocaleManager.Instance["DialogControllerSettingsModifiedConfirmMessage"], LocaleManager.Instance["DialogControllerSettingsModifiedConfirmSubMessage"], LocaleManager.Instance["InputDialogYes"], LocaleManager.Instance["InputDialogNo"], LocaleManager.Instance["RyujinxConfirm"]); if (result == UserResult.Yes) { ViewModel.Save(); } _dialogOpen = false; ViewModel.IsModified = false; if (e.AddedItems.Count > 0) { var player = (PlayerModel)e.AddedItems[0]; ViewModel.PlayerId = player.Id; } } }
private void ShowRestartDialog() { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed Dispatcher.UIThread.InvokeAsync(async() => { if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { var result = await ContentDialogHelper.CreateConfirmationDialog( LocaleManager.Instance["DialogThemeRestartMessage"], LocaleManager.Instance["DialogThemeRestartSubMessage"], LocaleManager.Instance["InputDialogYes"], LocaleManager.Instance["InputDialogNo"], LocaleManager.Instance["DialogRestartRequiredMessage"]); if (result == UserResult.Yes) { var path = Process.GetCurrentProcess().MainModule.FileName; var info = new ProcessStartInfo() { FileName = path, UseShellExecute = false }; var proc = Process.Start(info); desktop.Shutdown(); Environment.Exit(0); } } }); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed }
/// <summary> /// Add users to the group /// Wrap method for addUsers(...) /// </summary> private async void addUsers() { string usersToAdd = await ContentDialogHelper.InputDialogAsync("Enter user emails", "Separate multiple emails with a space..."); // Only try to add the user if the OK button was clicked addUsers(usersToAdd); }
/* Constructor * Loads all DelegateCommand objects for button clicks. */ public LoginPageViewModel() { loginCommand = new DelegateCommand(LoginHelper.LoginOrRegisterAsync); LoadingIndicator = false; model = new LoginPageModel(); navService = NavigationService.getNavigationServiceInstance(); LoginHelper.LoginInitiated += (s, args) => { LoadingIndicator = true; }; LoginHelper.UserLoggedIn += async(s, user) => { App.User = user; await App.notificationManager.InitNotificationsAsync(App.User.id); LoadingIndicator = false; navService.Navigate(typeof(MainPage)); }; LoginHelper.AuthError += async(s, errorMsg) => { LoadingIndicator = false; ContentDialog loginFailDialog = new ContentDialog() { Title = "Could not Log in :(", Content = errorMsg, PrimaryButtonText = "Ok" }; await ContentDialogHelper.CreateContentDialogAsync(loginFailDialog, true); }; }
public bool DisplayMessageDialog(string title, string message) { ManualResetEvent dialogCloseEvent = new(false); bool okPressed = false; Dispatcher.UIThread.InvokeAsync(async() => { try { ManualResetEvent deferEvent = new(false); bool opened = false; UserResult response = await ContentDialogHelper.ShowDeferredContentDialog(_parent, title, message, "", LocaleManager.Instance["DialogOpenSettingsWindowLabel"], "", LocaleManager.Instance["SettingsButtonClose"], (int)Symbol.Important, deferEvent, async(window) => { if (opened) { return; } opened = true; _parent.SettingsWindow = new SettingsWindow(_parent.VirtualFileSystem, _parent.ContentManager); await _parent.SettingsWindow.ShowDialog(window); opened = false; }); if (response == UserResult.Ok) { okPressed = true; } dialogCloseEvent.Set(); } catch (Exception ex) { await ContentDialogHelper.CreateErrorDialog(string.Format(LocaleManager.Instance["DialogMessageDialogErrorExceptionMessage"], ex)); dialogCloseEvent.Set(); } }); dialogCloseEvent.WaitOne(); return(okPressed); }
/// <summary> /// Logs in or registers a user whose email has not already been registered. /// If successful, calls the UserLoggedIn event handler and sets the user in ApiHelper /// </summary> /// <param name="info">Information needed by the api to log a user in</param> /// <returns></returns> public static async void LoginOrRegisterAsync() { AuthenticationResult result = null; try { PublicClientApplication pca = App.AuthClient; result = await pca.AcquireTokenAsync(Globals.DefaultScopes); ApiHelper.setToken(result.AccessToken); LoginInitiated?.Invoke(DateTime.Now, null); Models.User user = await ApiHelper.GetAsync <Models.User>("User"); if (user == null || user.Email == null) { user = await ApiHelper.PostAsync <Models.User>("User"); } if (user != null && !String.IsNullOrWhiteSpace(user.Email)) { UserLoggedIn?.Invoke(DateTime.Now, user); } else { AuthError?.Invoke(DateTime.Now, "No connection to server."); } } catch (MsalException ex) { if (ex.ErrorCode != "authentication_canceled") { string message = ex.Message; if (ex.InnerException != null) { message += "\nInner Exception: " + ex.InnerException.Message; } AuthError?.Invoke(DateTime.Now, message); } } catch (System.Net.Http.HttpRequestException ex) { // Launch warning popup ContentDialog notLoggedInDialog = new ContentDialog() { Title = "Could not login", Content = "Please check your wifi signal.", PrimaryButtonText = "Ok" }; await ContentDialogHelper.CreateContentDialogAsync(notLoggedInDialog, true); } }
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed public static bool CanUpdate(bool showWarnings, StyleableWindow parent) { #if !DISABLE_UPDATER if (RuntimeInformation.OSArchitecture != Architecture.X64) { if (showWarnings) { ContentDialogHelper.CreateWarningDialog(parent, LocaleManager.Instance["DialogUpdaterArchNotSupportedMessage"], LocaleManager.Instance["DialogUpdaterArchNotSupportedSubMessage"]); } return(false); } if (!NetworkInterface.GetIsNetworkAvailable()) { if (showWarnings) { ContentDialogHelper.CreateWarningDialog(parent, LocaleManager.Instance["DialogUpdaterNoInternetMessage"], LocaleManager.Instance["DialogUpdaterNoInternetSubMessage"]); } return(false); } if (Program.Version.Contains("dirty") || !ReleaseInformations.IsValid()) { if (showWarnings) { ContentDialogHelper.CreateWarningDialog(parent, LocaleManager.Instance["DialogUpdaterDirtyBuildMessage"], LocaleManager.Instance["DialogUpdaterDirtyBuildSubMessage"]); } return(false); } return(true); #else if (showWarnings) { if (ReleaseInformations.IsFlatHubBuild()) { ContentDialogHelper.CreateWarningDialog(parent, LocaleManager.Instance["UpdaterDisabledWarningTitle"], LocaleManager.Instance["DialogUpdaterFlatpakNotSupportedMessage"]); } else { ContentDialogHelper.CreateWarningDialog(parent, LocaleManager.Instance["UpdaterDisabledWarningTitle"], LocaleManager.Instance["DialogUpdaterDirtyBuildSubMessage"]); } } return(false); #endif }
private Nca TryCreateNca(IStorage ncaStorage, string containerPath) { try { return(new Nca(VirtualFileSystem.KeySet, ncaStorage)); } catch (Exception ex) { Dispatcher.UIThread.InvokeAsync(async() => { await ContentDialogHelper.CreateErrorDialog(string.Format(LocaleManager.Instance["DialogDlcLoadNcaErrorMessage"], ex.Message, containerPath)); }); } return(null); }
/// <summary> /// Creates a popup box to allow the user to change the group name and then sends the /// updated groupname to the server /// </summary> public async Task changeGroupNameAsync(GroupsContent groupContent) { if (App.User != null) { string currentGroupName = groupContent.group.Name; Tuple <Boolean, String> tup = await createGroupNameInputDialog(); // User inputs Boolean cancelled = tup.Item1; string newGroupName = tup.Item2; if (!cancelled && newGroupName != "") { GroupChat updatedGroup = await renameGroupChat(groupContent.group, newGroupName); // Display message to user if the name change failed (no server) if (updatedGroup == null) { ContentDialog noServerDialog = new ContentDialog() { Title = "Cannot change groupname", Content = "Is your wifi down?", PrimaryButtonText = "Ok" }; await ContentDialogHelper.CreateContentDialogAsync(noServerDialog, true); } else { string members = await getGroupMemberNames(updatedGroup); GroupsContent updatedContent = new GroupsContent(updatedGroup, members); updatedContent.updateCanvasFrom(groupContent); // Preserve ordering int originalIndex = getGroupsContentIndex(groupContent.group.id); GroupsList.Remove(groupContent); GroupsList.Insert(originalIndex, updatedContent); // if the user is currently looking at the group, update the group content message history if (RightFrameNavigator.GetLastContext() != null && RightFrameNavigator.GetLastContext().Equals(groupContent.messageHistoryViewModel)) { RightFrameNavigator.Navigate(typeof(MessageHistoryView), updatedContent.messageHistoryViewModel); } } } } }
private async Task AddDownloadableContent(string path) { if (!File.Exists(path) || DownloadableContents.FirstOrDefault(x => x.ContainerPath == path) != null) { return; } using (FileStream containerFile = File.OpenRead(path)) { PartitionFileSystem pfs = new PartitionFileSystem(containerFile.AsStorage()); bool containsDownloadableContent = false; VirtualFileSystem.ImportTickets(pfs); foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca")) { using var ncaFile = new UniqueRef <IFile>(); pfs.OpenFile(ref ncaFile.Ref(), fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); Nca nca = TryCreateNca(ncaFile.Get.AsStorage(), path); if (nca == null) { continue; } if (nca.Header.ContentType == NcaContentType.PublicData) { if ((nca.Header.TitleId & 0xFFFFFFFFFFFFE000) != TitleId) { break; } DownloadableContents.Add(new DownloadableContentModel(nca.Header.TitleId.ToString("X16"), path, fileEntry.FullPath, true)); containsDownloadableContent = true; } } if (!containsDownloadableContent) { await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance["DialogDlcNoDlcErrorMessage"]); } } }
private async void DeleteRunesButton_Click(object sender, RoutedEventArgs e) { if (!(Application.Current.MainWindow.DataContext is MainWindowViewModel viewModel)) { return; } // Set the delete flag, to be deleted by the main view model on close viewModel.ClearRunesCacheOnClose = true; // inform the user that the delete will happen when the window is closed var dialog = ContentDialogHelper.CreateContentDialog(includeSecondaryButton: false); dialog.DefaultButton = ContentDialogButton.Primary; dialog.PrimaryButtonText = TryFindResource("OKButtonText") as string; dialog.Title = TryFindResource("RequestsCacheCloseToDeleteTitle") as string; dialog.SetLabelText(TryFindResource("RequestsCacheCloseToDelete") as string); await dialog.ShowAsync(ContentDialogPlacement.Popup).ConfigureAwait(true); }
private async Task <string> StartRequest(string address) { string httpResponseBody = ""; using (var httpClient = new HttpClient()) { try { var httpResponse = await httpClient.GetAsync(new Uri(address)); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); } catch { ContentDialogHelper.ShowMessage("Ошибка при получении данных", "Произошла ошибка при получении данных, пожалуйста, попробуйте еще раз."); httpResponseBody = ""; } } return(httpResponseBody); }
public bool DisplayErrorAppletDialog(string title, string message, string[] buttons) { ManualResetEvent dialogCloseEvent = new(false); bool showDetails = false; Dispatcher.UIThread.Post(async() => { try { ErrorAppletWindow msgDialog = new(_parent, buttons, message) { Title = title, WindowStartupLocation = WindowStartupLocation.CenterScreen, Width = 400 }; object response = await msgDialog.Run(); if (response != null && buttons.Length > 1 && (int)response != buttons.Length - 1) { showDetails = true; } dialogCloseEvent.Set(); msgDialog.Close(); } catch (Exception ex) { dialogCloseEvent.Set(); await ContentDialogHelper.CreateErrorDialog(string.Format(LocaleManager.Instance["DialogErrorAppletErrorExceptionMessage"], ex)); } }); dialogCloseEvent.WaitOne(); return(showDetails); }
private async Task <Boolean> createLeaveGroupWarningDialog() { Boolean leave = false; ContentDialog leaveGroupWarningDialog = new ContentDialog() { Title = "You are about to leave this group.", Content = "Are you sure you would like to proceed?" }; leaveGroupWarningDialog.PrimaryButtonText = "Yes"; leaveGroupWarningDialog.PrimaryButtonClick += delegate { leave = true; }; leaveGroupWarningDialog.SecondaryButtonText = "No"; leaveGroupWarningDialog.SecondaryButtonClick += delegate { leave = false; }; await ContentDialogHelper.CreateContentDialogAsync(leaveGroupWarningDialog, true); return(leave); }
public bool DisplayInputDialog(SoftwareKeyboardUiArgs args, out string userText) { ManualResetEvent dialogCloseEvent = new(false); bool okPressed = false; bool error = false; string inputText = args.InitialText ?? ""; Dispatcher.UIThread.Post(async() => { try { var response = await SwkbdAppletDialog.ShowInputDialog(_parent, LocaleManager.Instance["SoftwareKeyboard"], args); if (response.Result == UserResult.Ok) { inputText = response.Input; okPressed = true; } } catch (Exception ex) { error = true; await ContentDialogHelper.CreateErrorDialog(string.Format(LocaleManager.Instance["DialogSoftwareKeyboardErrorExceptionMessage"], ex)); } finally { dialogCloseEvent.Set(); } }); dialogCloseEvent.WaitOne(); userText = error ? null : inputText; return(error || okPressed); }
private async void send() { if (App.User == null) { ContentDialog notLoggedInDialog = new ContentDialog() { Title = "Not logged in", Content = "You are not logged in and cannot sync with the server", PrimaryButtonText = "Ok" }; await ContentDialogHelper.CreateContentDialogAsync(notLoggedInDialog, true); return; } try { LoadingIndicator = true; // Create a file for storing the drawing string filename = DateTime.Now.ToString("yyyy-MM-ddTHHmmssffff") + ".png"; StorageFolder storageFolder = ApplicationData.Current.LocalFolder; StorageFile targetFile = await storageFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); System.Diagnostics.Debug.WriteLine("Saving message as " + targetFile.Path); // Used to pass message back to MessagesHistory BitmapImage bitmapImage = new BitmapImage(); Message msgResponse = null; if (targetFile != null) { CanvasDevice device = CanvasDevice.GetSharedDevice(); CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)canvasElements.canvas.ActualWidth, (int)canvasElements.canvas.ActualHeight, BITMAP_DPI_RESOLUTION); using (var drawSession = renderTarget.CreateDrawingSession()) { // Set the background color of the image drawSession.Clear(Colors.White); //Transfer the background image to the bitmap image if there is a background image if (BackgroundImagePath != null && BackgroundImagePath.Length > 0) { CanvasBitmap background = await CanvasBitmap.LoadAsync(device, formatBackgroundFilePath(BackgroundImagePath)); drawSession.DrawImage(background); } if (imageFilePath != null) { System.Diagnostics.Debug.WriteLine(" SENDING IMAGE FILE "); CanvasBitmap image = await CanvasBitmap.LoadAsync(device, imageFilePath); drawSession.DrawImage(image, new Windows.Foundation.Rect(xOffset, yOffset, newWidth, newHeight)); } // Transfer all the strokes to the bitmap image drawSession.DrawInk(canvasElements.canvas.InkPresenter.StrokeContainer.GetStrokes()); } using (IRandomAccessStream stream = await targetFile.OpenAsync(FileAccessMode.ReadWrite)) { await renderTarget.SaveAsync(stream, CanvasBitmapFileFormat.Png, 1f); } MessageApi api = MessageApi.getInstance(); Message sentMsg = new Message { SenderId = App.User.id, GroupChatID = group.group.id }; msgResponse = await api.sendMessageData(sentMsg); if (msgResponse != null) { using (Stream stream = await targetFile.OpenStreamForReadAsync()) { // Send the image file. If successful rename the local file to the id if (await api.sendMessageFile(stream, msgResponse.id)) { // rename the locally saved file to incorporate the server generated id await targetFile.RenameAsync(msgResponse.id + ".png"); } else { System.Diagnostics.Debug.WriteLine("File failed to send"); // Launch warning popup ContentDialog notLoggedInDialog = new ContentDialog() { Title = "File failed to send", Content = "Your message did not send. Please check your wifi signal.", PrimaryButtonText = "Ok" }; await ContentDialogHelper.CreateContentDialogAsync(notLoggedInDialog, true); } } } else { System.Diagnostics.Debug.WriteLine("Message failed to send"); // Launch warning popup ContentDialog notLoggedInDialog = new ContentDialog() { Title = "File failed to send", Content = "Your message did not send. Please check your wifi signal.", PrimaryButtonText = "Ok" }; await ContentDialogHelper.CreateContentDialogAsync(notLoggedInDialog, true); } } MessageContent msg = null; Uri imageUri = new Uri(targetFile.Path, UriKind.Absolute); // If message was not sent to the server, initialize empty message with group id if (msgResponse == null) { msgResponse = new PenscribCommon.Models.Message { id = "---", GroupChatID = group.group.id, }; msg = new MessageContent(msgResponse, App.User, imageUri, MessageContent.errorImage); } else { msg = new MessageContent(msgResponse, App.User, imageUri); } //Uri imageUri = new Uri(targetFile.Path, UriKind.Absolute); //MessageContent msg = new MessageContent(msgResponse, App.User, imageUri); LeftFrameNavigator.NavigateSubFrame(typeof(MessageHistoryView), msg); // Clear the canvas canvasElements.canvas.InkPresenter.StrokeContainer.Clear(); // Clear any background image BackgroundImagePath = null; group.backgroundPath = null; // Clear any loaded image imageFilePath = null; sourceImage = null; ImageBitmap = sourceImage; group.imageContainer = null; } finally { LoadingIndicator = false; } }
private async void addGroup() { GroupsContent group; // Groups can only be retrieved if user is logged in if (App.User != null) { Boolean cancelled = false; String groupName = ""; String groupMembers = ""; //enterGroupNameDialog reference: // https://www.reflectionit.nl/blog/2015/windows-10-xaml-tips-messagedialog-and-contentdialog ContentDialog enterGroupNameDialog = new ContentDialog() { Title = "Create a new group" }; var panel = new StackPanel(); // create the text box for user to set a group name TextBox groupNameBox = setTextBox("Enter a group name (max 20 characters)", ""); // create the text box for user to add initial group members TextBox groupMemberBox = setTextBox("Enter user emails", "Separate multiple emails with a space..."); // add the textboxes to the stackpanel panel.Children.Add(groupNameBox); panel.Children.Add(groupMemberBox); enterGroupNameDialog.Content = panel; enterGroupNameDialog.PrimaryButtonText = "Create"; enterGroupNameDialog.PrimaryButtonClick += delegate { groupName = groupNameBox.Text; groupMembers = groupMemberBox.Text; }; enterGroupNameDialog.SecondaryButtonText = "Cancel"; enterGroupNameDialog.SecondaryButtonClick += delegate { cancelled = true; }; await ContentDialogHelper.CreateContentDialogAsync(enterGroupNameDialog, true); if (!cancelled) { if (groupName != "") { // initial list of users in group includes the logged in user and the groupMembers specified in groupMemberBox List <string> users = await setInitialUserList(groupMembers); GroupChat newGroup = new PenscribCommon.Models.GroupChat { GroupMembers = users, CreationDate = DateTime.Now, Name = groupName }; GroupChatApi api = GroupChatApi.getInstance(); GroupChat createdGroup = await api.postGroupChat(newGroup); // Show error if group was unable to be posted to the server if (createdGroup == null) { ContentDialog errorDialog = new ContentDialog() { Title = "Unable to sync group with server", Content = "You are not connected to the server and so the group could not be pushed", PrimaryButtonText = "Ok" }; await ContentDialogHelper.CreateContentDialogAsync(errorDialog, true); group = new GroupsContent(defaultGroup, ""); } else { string members = await getGroupMemberNames(createdGroup); group = new GroupsContent(createdGroup, members); } // update the content in the view //displayNewGroup(group); LeftFrameNavigator.Navigate(typeof(GroupsView), group); } else { ContentDialog invalidGroupNameDialog = new ContentDialog() { Title = "Invalid group name", Content = "Please enter a group name", PrimaryButtonText = "Ok" }; await ContentDialogHelper.CreateContentDialogAsync(invalidGroupNameDialog, true); addGroup(); } } } else { ContentDialog notLoggedInDialog = new ContentDialog() { Title = "Not logged in", Content = "You are not logged in and cannot sync with the server", PrimaryButtonText = "Ok" }; await ContentDialogHelper.CreateContentDialogAsync(notLoggedInDialog, true); group = new GroupsContent(defaultGroup, ""); // update the content in the view //displayNewGroup(group); LeftFrameNavigator.Navigate(typeof(GroupsView), defaultGroup); } }
public async void sendText() { Message msgResponse = null; if (TextMsg != null && TextMsg != "") { LoadingIndicator = true; if (App.User == null) { ContentDialog notLoggedInDialog = new ContentDialog() { Title = "Not logged in", Content = "You are not logged in and cannot sync with the server", PrimaryButtonText = "Ok" }; await ContentDialogHelper.CreateContentDialogAsync(notLoggedInDialog, true); return; } MessageApi api = MessageApi.getInstance(); Message sentMsg = new Message { SenderId = App.User.id, GroupChatID = group.group.id, Content = TextMsg }; msgResponse = await api.sendMessageData(sentMsg); // If message was not sent to the server, initialize empty message with group id if (msgResponse == null) { msgResponse = new PenscribCommon.Models.Message { id = "---", GroupChatID = group.group.id, Content = TextMsg }; MessageContent badmsg = new MessageContent(msgResponse, App.User, null, MessageContent.errorImage); History.Add(badmsg); // Launch warning popup ContentDialog notLoggedInDialog = new ContentDialog() { Title = "No Wifi", Content = "Your message did not send. Please check your wifi signal.", PrimaryButtonText = "Ok" }; await ContentDialogHelper.CreateContentDialogAsync(notLoggedInDialog, true); } else { MessageContent msg = new MessageContent(msgResponse, App.User, null); History.Add(msg); } TextMsg = ""; LoadingIndicator = false; } }
/** * Method for dispatching a particular dialog depending on the contentDialogType parameter. * The user is the user name which is required for the dialog message content. */ public virtual async void displayContentDialogDispatch(contentDialogType type, String user) { switch (type) { case contentDialogType.DNE: ContentDialog userInGroupDialog = new ContentDialog() { Title = "User Not Added", Content = user + " does not exist.", PrimaryButtonText = "Ok" }; await ContentDialogHelper.CreateContentDialogAsync(userInGroupDialog, true); break; case contentDialogType.InvalidEmail: ContentDialog invalidUserEmailDialog = new ContentDialog() { Title = "User Not Added", Content = user + " is not a valid email address form.", PrimaryButtonText = "Ok" }; await ContentDialogHelper.CreateContentDialogAsync(invalidUserEmailDialog, true); break; case contentDialogType.RepeatMember: ContentDialog repeatMemberDialog = new ContentDialog() { Title = "User Not Added", Content = user + " already in group.", PrimaryButtonText = "Ok" }; await ContentDialogHelper.CreateContentDialogAsync(repeatMemberDialog, true); break; case contentDialogType.NoServer: ContentDialog noServerDialog = new ContentDialog() { Title = "User Not Added", Content = "Could not sync group with server.", PrimaryButtonText = "Ok" }; await ContentDialogHelper.CreateContentDialogAsync(noServerDialog, true); break; case contentDialogType.SuccessfulAdd: ContentDialog successDialog = new ContentDialog() { Title = user + " Successfully Added!", Content = "You will now be able to chat with " + user, PrimaryButtonText = "Ok" }; await ContentDialogHelper.CreateContentDialogAsync(successDialog, true); break; case contentDialogType.NoEmail: ContentDialog noEmailDialog = new ContentDialog() { Title = "No User Added", Content = "Please enter an email address", PrimaryButtonText = "Ok" }; await ContentDialogHelper.CreateContentDialogAsync(noEmailDialog, true); break; } }
public static async Task BeginParse(MainWindow mainWindow, bool showVersionUpToDate) { if (Running) { return; } Running = true; mainWindow.CanUpdate = false; // Detect current platform if (OperatingSystem.IsMacOS()) { _platformExt = "osx_x64.zip"; } else if (OperatingSystem.IsWindows()) { _platformExt = "win_x64.zip"; } else if (OperatingSystem.IsLinux()) { _platformExt = "linux_x64.tar.gz"; } Version newVersion; Version currentVersion; try { currentVersion = Version.Parse(Program.Version); } catch { Logger.Error?.Print(LogClass.Application, "Failed to convert the current Ryujinx version!"); Dispatcher.UIThread.Post(async() => { await ContentDialogHelper.CreateWarningDialog(mainWindow, LocaleManager.Instance["DialogUpdaterConvertFailedMessage"], LocaleManager.Instance["DialogUpdaterCancelUpdateMessage"]); }); return; } // Get latest version number from GitHub API try { using (HttpClient jsonClient = ConstructHttpClient()) { string buildInfoURL = $"{GitHubApiURL}/repos/{ReleaseInformations.ReleaseChannelOwner}/{ReleaseInformations.ReleaseChannelRepo}/releases/latest"; string fetchedJson = await jsonClient.GetStringAsync(buildInfoURL); JObject jsonRoot = JObject.Parse(fetchedJson); JToken assets = jsonRoot["assets"]; _buildVer = (string)jsonRoot["name"]; foreach (JToken asset in assets) { string assetName = (string)asset["name"]; string assetState = (string)asset["state"]; string downloadURL = (string)asset["browser_download_url"]; if (assetName.StartsWith("test-ava-ryujinx") && assetName.EndsWith(_platformExt)) { _buildUrl = downloadURL; if (assetState != "uploaded") { if (showVersionUpToDate) { Dispatcher.UIThread.Post(async() => { await ContentDialogHelper.CreateUpdaterInfoDialog(mainWindow, LocaleManager.Instance["DialogUpdaterAlreadyOnLatestVersionMessage"], ""); }); } return; } break; } } // If build not done, assume no new update are availaible. if (_buildUrl == null) { if (showVersionUpToDate) { Dispatcher.UIThread.Post(async() => { await ContentDialogHelper.CreateUpdaterInfoDialog(mainWindow, LocaleManager.Instance["DialogUpdaterAlreadyOnLatestVersionMessage"], ""); }); } return; } } } catch (Exception exception) { Logger.Error?.Print(LogClass.Application, exception.Message); Dispatcher.UIThread.Post(async() => { await ContentDialogHelper.CreateErrorDialog(mainWindow, LocaleManager.Instance["DialogUpdaterFailedToGetVersionMessage"]); }); return; } try { newVersion = Version.Parse(_buildVer); } catch { Logger.Error?.Print(LogClass.Application, "Failed to convert the received Ryujinx version from Github!"); Dispatcher.UIThread.Post(async() => { await ContentDialogHelper.CreateWarningDialog(mainWindow, LocaleManager.Instance["DialogUpdaterConvertFailedGithubMessage"], LocaleManager.Instance["DialogUpdaterCancelUpdateMessage"]); }); return; } if (newVersion <= currentVersion) { if (showVersionUpToDate) { Dispatcher.UIThread.Post(async() => { await ContentDialogHelper.CreateUpdaterInfoDialog(mainWindow, LocaleManager.Instance["DialogUpdaterAlreadyOnLatestVersionMessage"], ""); }); } Running = false; mainWindow.CanUpdate = true; return; } // Fetch build size information to learn chunk sizes. using (HttpClient buildSizeClient = ConstructHttpClient()) { try { buildSizeClient.DefaultRequestHeaders.Add("Range", "bytes=0-0"); HttpResponseMessage message = await buildSizeClient.GetAsync(new Uri(_buildUrl), HttpCompletionOption.ResponseHeadersRead); _buildSize = message.Content.Headers.ContentRange.Length.Value; } catch (Exception ex) { Logger.Warning?.Print(LogClass.Application, ex.Message); Logger.Warning?.Print(LogClass.Application, "Couldn't determine build size for update, using single-threaded updater"); _buildSize = -1; } } Dispatcher.UIThread.Post(async() => { // Show a message asking the user if they want to update UpdaterWindow updateDialog = new(mainWindow, newVersion, _buildUrl); await updateDialog.ShowDialog(mainWindow); }); }