private async void TeamOneName() { TextBox txtName = new TextBox(); Grid contentGrid = new Grid(); contentGrid.Children.Add(txtName); ContentDialog nameDialog = new ContentDialog() { Title = "Enter Team One Name", Content = contentGrid, PrimaryButtonText = "Submit" }; await nameDialog.ShowAsync(); if (txtName.Text!="") { team1Name= txtName.Text; } else { team1Name = "Team One"; } teamOneName.Text = team1Name; }
private async void buttonConnect_Click(object sender, RoutedEventArgs e) { if (!App.serialPort.IsConnected()) { int selection = listbox1.SelectedIndex; if (selection < 0) return; await App.serialPort.Connect(selection); if (!App.serialPort.IsConnected()) { ContentDialog dialog = new ContentDialog(); dialog.Title = "Connection failed"; dialog.Content = "Try to select another device"; dialog.PrimaryButtonText = "OK"; await dialog.ShowAsync(); return; } App.ledStripController.Connect(); Frame.Navigate(typeof(ControlPage)); } else { App.ledStripController.Disconnect(); App.serialPort.Disconnect(); } // RefrashInterface(); }
private async void OnTakeScreenshotButtonClicked(object sender, RoutedEventArgs e) { // Export the image from mapview and assign it to the imageview var exportedImage = await Esri.ArcGISRuntime.UI.RuntimeImageExtensions.ToImageSourceAsync(await MyMapView.ExportImageAsync()); // Create dialog that is used to show the picture var dialog = new ContentDialog() { Title = "Screenshot", MaxWidth = ActualWidth, MaxHeight = ActualHeight }; // Create Image var imageView = new Image() { Source = exportedImage, Margin = new Thickness(10), Stretch = Stretch.Uniform }; // Set image as a content dialog.Content = imageView; // Show dialog as a full screen overlay. await dialog.ShowAsync(); }
public static async void ShowContentDialog(string dialogTitle, string dialogMessage) { var dialog = new ContentDialog() { Title = string.IsNullOrEmpty(dialogTitle) ? "Storage Demo Client" : dialogTitle }; // Setup Content var panel = new StackPanel(); panel.Children.Add(new TextBlock { Text = dialogMessage, TextWrapping = TextWrapping.Wrap, }); dialog.Content = panel; // Add Buttons dialog.PrimaryButtonText = "Close"; dialog.IsPrimaryButtonEnabled = false; // Show Dialog var result = await dialog.ShowAsync(); }
private async static void Tela_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) { var tela = sender.Content as MyUserControl1; var readDataa = await ReadWrite.readStringFromLocalFile("data"); Profile profile = JsonSerilizer.ToProfile(readDataa); if (tela.passwordBoxSenha.Password == profile.Password) { } else { var acessar = new MyUserControl1(); ContentDialog dialogo = new ContentDialog(); dialogo.PrimaryButtonText = "Войти"; dialogo.PrimaryButtonClick += Tela_PrimaryButtonClick; dialogo.Content = acessar; await dialogo.ShowAsync(); } }
async Task CallWebApiAsync() { HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetAsync("http://forecastlabo2.azurewebsites.net/api/Forecast"); if (response.StatusCode == System.Net.HttpStatusCode.OK) { string json = await response.Content.ReadAsStringAsync(); var forecasts = Newtonsoft.Json.JsonConvert.DeserializeObject<Forecasts[]>(json); ForeCastListView.ItemsSource = forecasts; }else { var dialog = new ContentDialog() { Title = "Ooooops", MaxWidth = this.ActualWidth }; var panel = new StackPanel(); panel.Children.Add(new TextBlock { Text = "Une erreur s'est produite lors de la récupération des prévisions météo", TextWrapping = TextWrapping.Wrap, }); dialog.Content = panel; await dialog.ShowAsync(); //try catch et appeler une méthode qui gère l'erreur //recherche google mot clé UWP / WPF Universal App/ faire les recherches en anglais } }
} // end void private async void StartRecognizing_Click(object sender, RoutedEventArgs e) { // Create an instance of SpeechRecognizer. var speechRecognizer = new Windows.Media.SpeechRecognition.SpeechRecognizer(); // Compile the dictation grammar by default. await speechRecognizer.CompileConstraintsAsync(); // Start recognition. Windows.Media.SpeechRecognition.SpeechRecognitionResult speechRecognitionResult = await speechRecognizer.RecognizeWithUIAsync(); ContentDialog notifyDelete = new ContentDialog() { Title = "Confirm delete?", Content = speechRecognitionResult.Text, PrimaryButtonText = "Save Note", SecondaryButtonText = "Cancel" }; ContentDialogResult result = await notifyDelete.ShowAsync(); if (result == ContentDialogResult.Primary) { tbNote.Text = speechRecognitionResult.Text; } else { // User pressed Cancel or the back arrow. // Terms of use were not accepted. } // Do something with the recognition result. //var messageDialog = new Windows.UI.Popups.MessageDialog(speechRecognitionResult.Text, "Text spoken"); //await messageDialog.ShowAsync(); } // end StartRecognizing_Click
protected void CancelPreviousAndShowDialog(ContentDialog dialog) { if (previous == null) previous = dialog; CancelPreviousDialog(); LastDialogControl = dialog.ShowAsync(); }
private async void buttonAddPerson_Click(object sender, RoutedEventArgs e) { var dialog = new ContentDialog(); dialog.Title = "Add a person to your list"; dialog.Content = new TextBox(); dialog.PrimaryButtonText = "Add"; dialog.IsPrimaryButtonEnabled = true; var result = await dialog.ShowAsync(); if (ContentDialogResult.Primary == result) { try { var textBox = (TextBox)dialog.Content; string text = textBox.Text; if (text != "") { Person person = new Person(text); ListViewItem item = new ListViewItem { Content = person.Name, Tag = person }; listViewPerson.Items.Add(item); person.Save(); } } catch (NullReferenceException) { } } }
private async void showDialog() { dialog = new ContentDialog() { Title = "Authenticeren met de Hue Bridge", MaxWidth = this.ActualWidth, Background = new SolidColorBrush(Color.FromArgb(0xff, 0xff, 0xff, 0xff)) }; var panel = new StackPanel(); panel.Children.Add(new TextBlock { Text = "Druk op de link knop op uw Hue bridge om verbinding te maken.", TextWrapping = TextWrapping.Wrap }); BitmapImage bitmapImage = new BitmapImage(new Uri("ms-appx:///Assets/smartbridge.jpg")); panel.Children.Add(new Image { Source = bitmapImage }); dialog.Content = panel; var result = await dialog.ShowAsync(); }
private async void Error(string title) { ContentDialog dialogo = new ContentDialog(); dialogo.PrimaryButtonText = "Ок"; dialogo.Title = title; await dialogo.ShowAsync(); }
private async void button_Click(object sender, RoutedEventArgs e) { var dialog = new ContentDialog(); dialog.Title = "Add a gift to your list"; dialog.Content = new TextBox(); dialog.PrimaryButtonText = "Add"; dialog.IsPrimaryButtonEnabled = true; var result = await dialog.ShowAsync(); if (ContentDialogResult.Primary == result) { try { var textBox = (TextBox)dialog.Content; string text = textBox.Text; if (text != "") { listViewGifts.Items.Add(text); _currentPerson.Gifts.Add(text); _currentPerson.TransformListToString(); _currentPerson.Save(); } } catch (NullReferenceException) { } } }
private async void button_Click(object sender, RoutedEventArgs e) { if (MapControl1.IsStreetsideSupported) { BasicGeoposition cityPosition = new BasicGeoposition() { Latitude = 48.858, Longitude = 2.295 }; Geopoint cityCenter = new Geopoint(cityPosition); StreetsidePanorama panoramaNearCity = await StreetsidePanorama.FindNearbyAsync(cityCenter); if (panoramaNearCity != null) { StreetsideExperience ssView = new StreetsideExperience(panoramaNearCity); ssView.OverviewMapVisible = true; MapControl1.CustomExperience = ssView; } } else { ContentDialog viewNotSupportedDialog = new ContentDialog() { Title = "Streetside is not supported", Content = "\nStreetside views are not supported on this device.", PrimaryButtonText = "OK" }; await viewNotSupportedDialog.ShowAsync(); } }
public async void ShowNoAccessDialog() { AccessStatus = await RequestAccess(); if (AccessStatus == GeolocationAccessStatus.Allowed) { return; } TextBlock content = new TextBlock { Text = "ERROR_NO_LOCTION_ACCESS_DisplayMessage".t(R.File.CORTANA), TextAlignment = Windows.UI.Xaml.TextAlignment.Center, Margin = new Windows.UI.Xaml.Thickness { Bottom = 10, Left = 10, Top = 10, Right = 10}, TextWrapping = Windows.UI.Xaml.TextWrapping.WrapWholeWords, HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center, VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center, }; ContentDialog dialog = new ContentDialog() { Content = content }; dialog.SecondaryButtonText = "DIALOG_NO_LOCATION_ACCESS_CANCEL".t(); dialog.PrimaryButtonText = "DIALOG_NO_LOCATION_ACCESS_SETTINGS_BUTTON_TEXT".t(); dialog.PrimaryButtonClick += (d, _) => { ShowLocationSettingsPage().Forget(); }; await dialog.ShowAsync(); }
private async void Button_Click(object sender, RoutedEventArgs e) { ContentDialog d = new ContentDialog(); d.Title = "Not implemented"; d.Content = "The buttons are for illustrative purposes only and do not perform any action"; d.PrimaryButtonText = "OK"; await d.ShowAsync(); }
private async void OnShowDialog(object sender, RoutedEventArgs e) { ContentDialog noWifiDialog = new ContentDialog() { Title = "No wifi connection", Content = "Check connection and try again", PrimaryButtonText = "OK" }; await noWifiDialog.ShowAsync(); }
public async void OnListItemClicked(object sender, ItemClickEventArgs e) { var messageDialog = new ContentDialog(); messageDialog.IsPrimaryButtonEnabled = true; messageDialog.PrimaryButtonText = "是"; messageDialog.SecondaryButtonText = "否"; messageDialog.Content = $"{e.ClickedItem}"; await messageDialog.ShowAsync(); }
private async void ButtonSubmit_Click(object sender, RoutedEventArgs e) { var dialog = new ContentDialog() { Title = "Your from submission", Content = $"Hello {TextBoxFirstName.Text} {TextBoxLastName.Text}. Your EmaiL: {TextBoxEmail.Text}", PrimaryButtonText = "Ok" }; await dialog.ShowAsync(); }
private async void showMessage(object sender, RoutedEventArgs e) { var dialog = new ContentDialog(); var resourcesLoader = new Windows.ApplicationModel.Resources.ResourceLoader(); dialog.Content = resourcesLoader.GetString("Mensaje"); await dialog.ShowAsync(); }
private async void listHadith_SelectionChanged(object sender, SelectionChangedEventArgs e) { var hadith = listHadith.SelectedItem.ToString(); var cd = new ContentDialog(); cd.Title = "الحديث"; cd.Content = hadith; cd.PrimaryButtonText = "تم"; cd.SecondaryButtonText = "مشاركة"; await cd.ShowAsync(); }
async private void Button1_Click(object sender, RoutedEventArgs e) { ContentDialog dialog = new ContentDialog(); dialog.Title = "编程小梦"; dialog.Content = "专注开发Windows phone应用"; dialog.PrimaryButtonText = "赞一个"; dialog.SecondaryButtonText="顶一个"; dialog.FullSizeDesired = true; await dialog.ShowAsync(); }
public object Execute(object sender, object parameter) { var d = new ContentDialog { Title = Title, Content = Content, PrimaryButtonText = OkText }; Task.Run(async () => { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => await d.ShowAsync()); }); return this; }
public static async void showMessage(string title, string msg, bool fullScreen) { //MessageDialog message = new MessageDialog(msg); //await message.ShowAsync(); ContentDialog contentDialog = new ContentDialog(); contentDialog.FullSizeDesired = fullScreen; contentDialog.Title = title; contentDialog.Content = msg; contentDialog.PrimaryButtonText = "OK"; await contentDialog.ShowAsync(); }
private async void Button_Click(object sender, RoutedEventArgs e) { ContentDialog d = new ContentDialog(); d.Title = "Not implemented"; d.Content = "The buttons are for illustrative purposes only and do not perform any action"; d.PrimaryButtonText = "OK"; await d.ShowAsync(); //ResourceLoader resourceLoader = new ResourceLoader("Resources"); //var resDisclaimerTitle = resourceLoader.GetString("demo"); //var sdsd = "dsds"; }
private async void WifiConnectionLost() { ContentDialog noWifiDialog = new ContentDialog() { Title = "No wifi connection", Content = "Check connection and try again", PrimaryButtonText = "Ok" }; noWifiDialog.ShowAsync(); //await noWifiDialog.ShowAsync(); }
private async void OnAction(object sender, RoutedEventArgs e) { _telemetry.TrackEvent("OnAction", properties: new Dictionary<string, string>() { ["data"] = sampleDataText.Text }); var dialog = new ContentDialog { Title = "Sample", Content = $"You entered {sampleDataText.Text}", PrimaryButtonText = "Ok" }; await dialog.ShowAsync(); }
public async static void about() { var gg = new About(); ContentDialog tt = new ContentDialog(); tt.PrimaryButtonText = "ok"; tt.PrimaryButtonClick += Ok_Click; tt.SecondaryButtonText = "Rate Us"; tt.SecondaryButtonClick += Rate_Click; tt.Title = "العبقرى"; tt.Content = gg; await tt.ShowAsync(); }
private async void login_Click(object sender, RoutedEventArgs e) { Client.Authenticate(emailBox.Text.ToLower(), passwordBox.Password); ContentDialog test = new ContentDialog() { Title = "Test", Content = User.Email, PrimaryButtonText = "Ok" }; await test.ShowAsync(); }
private async void interstitialAd_ErrorOccurred(object sender, AdErrorEventArgs e) { // handle errors here var dialog = new ContentDialog { Title = "An Error", Content = e.ErrorMessage, PrimaryButtonText = "OK", IsPrimaryButtonEnabled = true }; await dialog.ShowAsync(); }
public async void HiglightSreen() { Grid contentGrid = new Grid { Height = Window.Current.Bounds.Height, Width = Window.Current.Bounds.Width }; ContentDialog dlg = new ContentDialog { Content = contentGrid }; SolidColorBrush color = new SolidColorBrush(Colors.White) { Opacity = 1 }; dlg.Background = color; await dlg.ShowAsync(); }
public static async Task <AuthResponse> RefreshAccesTokenAsync(string refreshToken, ContentDialog errorHttpDialog = null) { var pairs = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("client_id", Client.ClientId), new KeyValuePair <string, string>("client_secret", Client.ClientSecret), new KeyValuePair <string, string>("refresh_token", refreshToken), new KeyValuePair <string, string>("grant_type", "refresh_token") }; var httpClient = new HttpClient(); var httpContent = new HttpFormUrlEncodedContent(pairs); try { var httpResponse = await httpClient.PostAsync(Client.TokenUri, httpContent); if (httpResponse.IsSuccessStatusCode) { string contentResponse = await httpResponse.Content.ReadAsStringAsync(); var authResponse = JsonConvert.DeserializeObject <AuthResponse>(contentResponse); return(authResponse); } else { await errorHttpDialog?.ShowAsync(); } } catch { await errorHttpDialog?.ShowAsync(); } return(null); }
public async void DuplicateSelected(object sender, ItemClickEventArgs e) { if (e.ClickedItem is DuplicateMediaEntry duplicateEntry) { // Prompt user for confirmation. _selectConfirmDialog = new ContentDialog() { Title = "Delete all other duplicates?", Content = "Cannot be undone.", PrimaryButtonText = "Cancel", DefaultButton = ContentDialogButton.Secondary, CloseButtonText = "Delete", CloseButtonCommand = DuplicateSelectCommand, CloseButtonCommandParameter = duplicateEntry, }; await _selectConfirmDialog?.ShowAsync(); } }
async void OnPageActionSheet(Page sender, ActionSheetArguments options) { List <string> buttons = options.Buttons.ToList(); var list = new Windows.UI.Xaml.Controls.ListView { Style = (Windows.UI.Xaml.Style)Windows.UI.Xaml.Application.Current.Resources["ActionSheetList"], ItemsSource = buttons, IsItemClickEnabled = true }; var dialog = new ContentDialog { Template = (Windows.UI.Xaml.Controls.ControlTemplate)Windows.UI.Xaml.Application.Current.Resources["MyContentDialogControlTemplate"], Content = list, Style = (Windows.UI.Xaml.Style)Windows.UI.Xaml.Application.Current.Resources["ActionSheetStyle"] }; if (options.Title != null) { dialog.Title = options.Title; } list.ItemClick += (s, e) => { dialog.Hide(); options.SetResult((string)e.ClickedItem); }; TypedEventHandler <CoreWindow, CharacterReceivedEventArgs> onEscapeButtonPressed = delegate(CoreWindow window, CharacterReceivedEventArgs args) { if (args.KeyCode == 27) { dialog.Hide(); options.SetResult(ContentDialogResult.None.ToString()); } }; Window.Current.CoreWindow.CharacterReceived += onEscapeButtonPressed; _actionSheetOptions = options; if (options.Cancel != null) { dialog.SecondaryButtonText = options.Cancel; } if (options.Destruction != null) { dialog.PrimaryButtonText = options.Destruction; } ContentDialogResult result = await dialog.ShowAsync(); if (result == ContentDialogResult.Secondary) { options.SetResult(options.Cancel); } else if (result == ContentDialogResult.Primary) { options.SetResult(options.Destruction); } Window.Current.CoreWindow.CharacterReceived -= onEscapeButtonPressed; }
private async void Popup_CommandHandler_Export(FlyoutCommand command) { var part = _editor.Part; if (part == null) { return; } using (var rootBlock = _editor.GetRootBlock()) { var onRawContent = part.Type == "Raw Content"; var contentBlock = onRawContent ? rootBlock : _lastSelectedBlock; if (contentBlock == null) { return; } var mimeTypes = _editor.GetSupportedExportMimeTypes(contentBlock); if (mimeTypes == null) { return; } if (mimeTypes.Count() == 0) { return; } // Show export dialog var fileName = await ChooseExportFilename(mimeTypes); if (!string.IsNullOrEmpty(fileName)) { var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; var item = await localFolder.TryGetItemAsync(fileName); string filePath = null; if (item != null) { ContentDialog overwriteDialog = new ContentDialog { Title = "File Already Exists", Content = "A file with that name already exists, overwrite it?", PrimaryButtonText = "Cancel", SecondaryButtonText = "Overwrite" }; ContentDialogResult result = await overwriteDialog.ShowAsync(); if (result == ContentDialogResult.Primary) { return; } filePath = item.Path.ToString(); } else { filePath = System.IO.Path.Combine(localFolder.Path.ToString(), fileName); } try { var drawer = new ImageDrawer(); drawer.ImageLoader = UcEditor.ImageLoader; _editor.WaitForIdle(); _editor.Export_(contentBlock, filePath, drawer); var file = await StorageFile.GetFileFromPathAsync(filePath); await Windows.System.Launcher.LaunchFileAsync(file); } catch (Exception ex) { var msgDialog = new MessageDialog(ex.ToString()); await msgDialog.ShowAsync(); } } } }
private async void changePassBtn_Click(object sender, RoutedEventArgs e) { try { if (currentPass.Password == App.Admin.Password && username.Text == App.Admin.Username && newPass.Password != string.Empty) { App.Admin.Password = newPass.Password; await App.MobileService.GetTable <Admin>().UpdateAsync(App.Admin); ContentDialog confirmDialog = new ContentDialog() { Title = "Success", Content = "Password has been changed", PrimaryButtonText = "Sign out" }; await confirmDialog.ShowAsync(); (Window.Current.Content as Frame).Navigate(typeof(MainPage)); } else { ContentDialog confirmDialog = new ContentDialog() { Title = "Failed", Content = "Incorrect username and password", PrimaryButtonText = "Ok" }; await confirmDialog.ShowAsync(); } } catch { MobileServiceCollection <Admin, Admin> items = await App.MobileService.GetTable <Admin>().Where(a => a.Username == username.Text).ToCollectionAsync(); App.Admin = items.FirstOrDefault(); if ((App.Admin != null) && newPass.Password != string.Empty) { App.Admin.Password = newPass.Password; await App.MobileService.GetTable <Admin>().UpdateAsync(App.Admin); ContentDialog confirmDialog = new ContentDialog() { Title = "Success", Content = "Password has been changed", PrimaryButtonText = "Ok" }; await confirmDialog.ShowAsync(); (Window.Current.Content as Frame).Navigate(typeof(MainPage)); } else { ContentDialog confirmDialog = new ContentDialog() { Title = "Failed", Content = "Incorrect username", PrimaryButtonText = "Ok" }; await confirmDialog.ShowAsync(); } } }
private async void AppBar_OpenPackageButton_Click(object sender, RoutedEventArgs e) { List <string> files = new List <string>(); // List iink files inside LocalFolders var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; var items = await localFolder.GetItemsAsync(); foreach (var item in items) { if (item.IsOfType(StorageItemTypes.File) && item.Path.EndsWith(".iink")) { files.Add(item.Name.ToString()); } } if (files.Count == 0) { return; } // Display file list ListBox fileList = new ListBox { ItemsSource = files, SelectedIndex = 0 }; ContentDialog fileNameDialog = new ContentDialog { Title = "Select Package Name", Content = fileList, IsSecondaryButtonEnabled = true, PrimaryButtonText = "Ok", SecondaryButtonText = "Cancel", }; if (await fileNameDialog.ShowAsync() == ContentDialogResult.Secondary) { return; } var fileName = fileList.SelectedValue.ToString(); var filePath = System.IO.Path.Combine(localFolder.Path.ToString(), fileName); // Close current package _lastSelectedBlock?.Dispose(); _lastSelectedBlock = null; if (_editor.Part != null) { var part = _editor.Part; var package = part?.Package; _editor.Part = null; part?.Dispose(); package?.Dispose(); } // Reset viewing parameters UcEditor.ResetView(false); // Open package and select first part { var package = _engine.OpenPackage(filePath); var part = package.GetPart(0); _editor.Part = part; _packageName = fileName; Title.Text = _packageName + " - " + part.Type; } }
private async void AppBar_SaveAsButton_Click(object sender, RoutedEventArgs e) { var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; // Show file name input dialog TextBox inputTextBox = new TextBox { AcceptsReturn = false, Height = 32 }; ContentDialog fileNameDialog = new ContentDialog { Title = "Enter New Package Name", Content = inputTextBox, IsSecondaryButtonEnabled = true, PrimaryButtonText = "Ok", SecondaryButtonText = "Cancel", }; if (await fileNameDialog.ShowAsync() == ContentDialogResult.Secondary) { return; } var fileName = inputTextBox.Text; if (fileName == null || fileName == "") { return; } // Add iink extension if needed if (!fileName.EndsWith(".iink")) { fileName = fileName + ".iink"; } // Display overwrite dialog (if needed) string filePath = null; var item = await localFolder.TryGetItemAsync(fileName); if (item != null) { ContentDialog overwriteDialog = new ContentDialog { Title = "File Already Exists", Content = "A file with that name already exists, overwrite it?", PrimaryButtonText = "Cancel", SecondaryButtonText = "Overwrite" }; ContentDialogResult result = await overwriteDialog.ShowAsync(); if (result == ContentDialogResult.Primary) { return; } filePath = item.Path.ToString(); } else { filePath = System.IO.Path.Combine(localFolder.Path.ToString(), fileName); } // Get current package var part = _editor.Part; if (part == null) { return; } var package = part.Package; // Save Package with new name package.SaveAs(filePath); // Update internals _packageName = fileName; Title.Text = _packageName + " - " + part.Type; }
public async Task PasteItems(DataPackageView packageView, string destinationPath, DataPackageOperation acceptedOperation) { itemsToPaste = await packageView.GetStorageItemsAsync(); HashSet <IStorageItem> pastedItems = new HashSet <IStorageItem>(); itemsPasted = 0; if (itemsToPaste.Count > 3) { (App.CurrentInstance as ModernShellPage).UpdateProgressFlyout(InteractionOperationType.PasteItems, itemsPasted, itemsToPaste.Count); } foreach (IStorageItem item in itemsToPaste) { if (item.IsOfType(StorageItemTypes.Folder)) { if (destinationPath.IsSubPathOf(item.Path)) { ImpossibleActionResponseTypes responseType = ImpossibleActionResponseTypes.Abort; Binding themeBind = new Binding(); themeBind.Source = ThemeHelper.RootTheme; ContentDialog dialog = new ContentDialog() { Title = ResourceController.GetTranslation("ErrorDialogThisActionCannotBeDone"), Content = ResourceController.GetTranslation("ErrorDialogTheDestinationFolder") + " (" + destinationPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last() + ") " + ResourceController.GetTranslation("ErrorDialogIsASubfolder") + " (" + item.Name + ")", PrimaryButtonText = ResourceController.GetTranslation("ErrorDialogSkip"), CloseButtonText = ResourceController.GetTranslation("ErrorDialogCancel"), PrimaryButtonCommand = new RelayCommand(() => { responseType = ImpossibleActionResponseTypes.Skip; }), CloseButtonCommand = new RelayCommand(() => { responseType = ImpossibleActionResponseTypes.Abort; }) }; BindingOperations.SetBinding(dialog, FrameworkElement.RequestedThemeProperty, themeBind); await dialog.ShowAsync(); if (responseType == ImpossibleActionResponseTypes.Skip) { continue; } else if (responseType == ImpossibleActionResponseTypes.Abort) { return; } } else { StorageFolder pastedFolder = await CloneDirectoryAsync(item.Path, destinationPath, item.Name, false); pastedItems.Add(pastedFolder); if (destinationPath == CurrentInstance.ViewModel.WorkingDirectory) { CurrentInstance.ViewModel.AddFolder(pastedFolder.Path); } } } else if (item.IsOfType(StorageItemTypes.File)) { if (itemsToPaste.Count > 3) { (App.CurrentInstance as ModernShellPage).UpdateProgressFlyout(InteractionOperationType.PasteItems, ++itemsPasted, itemsToPaste.Count); } StorageFile clipboardFile = await StorageFile.GetFileFromPathAsync(item.Path); StorageFile pastedFile = await clipboardFile.CopyAsync(await StorageFolder.GetFolderFromPathAsync(destinationPath), item.Name, NameCollisionOption.GenerateUniqueName); pastedItems.Add(pastedFile); if (destinationPath == CurrentInstance.ViewModel.WorkingDirectory) { CurrentInstance.ViewModel.AddFile(pastedFile.Path); } } } if (acceptedOperation == DataPackageOperation.Move) { foreach (IStorageItem item in itemsToPaste) { if (item.IsOfType(StorageItemTypes.File)) { StorageFile file = await StorageFile.GetFileFromPathAsync(item.Path); await file.DeleteAsync(); } else if (item.IsOfType(StorageItemTypes.Folder)) { StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(item.Path); await folder.DeleteAsync(); } ListedItem listedItem = CurrentInstance.ViewModel.FilesAndFolders.FirstOrDefault(listedItem => listedItem.ItemPath.Equals(item.Path, StringComparison.OrdinalIgnoreCase)); if (listedItem != null) { CurrentInstance.ViewModel.RemoveFileOrFolder(listedItem); } } } if (destinationPath == CurrentInstance.ViewModel.WorkingDirectory) { List <string> pastedItemPaths = pastedItems.Select(item => item.Path).ToList(); List <ListedItem> copiedItems = CurrentInstance.ViewModel.FilesAndFolders.Where(listedItem => pastedItemPaths.Contains(listedItem.ItemPath)).ToList(); CurrentInstance.ContentPage.SetSelectedItemsOnUi(copiedItems); CurrentInstance.ContentPage.FocusSelectedItems(); } packageView.ReportOperationCompleted(acceptedOperation); }
private async System.Threading.Tasks.Task <string> ChooseExportFilename(MimeType[] mimeTypes) { var mimeTypeTextBlock = new TextBlock { Text = "Choose a mime type", MaxLines = 1, TextWrapping = TextWrapping.NoWrap, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 0, 0), Width = 300, }; var mimeTypeComboBox = new ComboBox { IsTextSearchEnabled = true, SelectedIndex = -1, Margin = new Thickness(0, 5, 0, 0), Width = 300 }; foreach (var mimeType in mimeTypes) { mimeTypeComboBox.Items.Add(MimeTypeF.GetTypeName(mimeType)); } mimeTypeComboBox.SelectedIndex = 0; var nameTextBlock = new TextBlock { Text = "Enter Export File Name", MaxLines = 1, TextWrapping = TextWrapping.NoWrap, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 10, 0, 0), Width = 300 }; var nameTextBox = new TextBox { Text = "", AcceptsReturn = false, MaxLength = 1024 * 1024, TextWrapping = TextWrapping.NoWrap, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 5, 0, 10), Width = 300 }; var panel = new StackPanel { Margin = new Thickness(10), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, }; panel.Children.Add(mimeTypeTextBlock); panel.Children.Add(mimeTypeComboBox); panel.Children.Add(nameTextBlock); panel.Children.Add(nameTextBox); var dialog = new ContentDialog { Title = "Export", Content = panel, PrimaryButtonText = "OK", SecondaryButtonText = "Cancel", IsPrimaryButtonEnabled = true, IsSecondaryButtonEnabled = true }; var result = await dialog.ShowAsync(); if (result == ContentDialogResult.Primary) { var fileName = nameTextBox.Text; var extIndex = mimeTypeComboBox.SelectedIndex; var extensions = MimeTypeF.GetFileExtensions(mimeTypes[extIndex]).Split(','); int ext; for (ext = 0; ext < extensions.Count(); ++ext) { if (fileName.EndsWith(extensions[ext], StringComparison.OrdinalIgnoreCase)) { break; } } if (ext >= extensions.Count()) { fileName += extensions[0]; } return(fileName); } return(null); }
// The code to do actual login is here. To be moved to PayrollCore when // The Graph controls are compatible with .NET Standard 2.0 private async void LoadTimer_Tick(object sender, object e) { loadTimer.Stop(); User user; if (upn != null) { user = await SettingsHelper.Instance.op2.GetUserById(upn); if (user != null) { pageTitle.Text = user.fullName; progText.Text = "Syncing account data..."; // User is already registered. Proceed to check if it is from AD and sync their Allow Login status if does not contains TP. if (user.fromAD == true && !user.userID.Contains("TP")) { bool IsEnabledInAd = await IsUserEnabledAD(upn); user.isDisabled = !IsEnabledInAd; Debug.WriteLine(user.isDisabled.ToString()); await SettingsHelper.Instance.op2.UpdateUser(user); } progText.Text = "Logging you in..."; if (user.isDisabled == false) { bool IsSuccess = await SettingsHelper.Instance.UpdateUserState(user); if (IsSuccess) { if (user.IsNewUser == true && SettingsHelper.Instance.userState.user.userGroup.EnableFaceRec == true) { this.Frame.Navigate(typeof(FaceRecIntroPage), null, new SlideNavigationTransitionInfo() { Effect = SlideNavigationTransitionEffect.FromRight }); } else { this.Frame.Navigate(typeof(UserProfile.UserProfilePage), null, new SlideNavigationTransitionInfo() { Effect = SlideNavigationTransitionEffect.FromRight }); } return; } else { ContentDialog contentDialog = new ContentDialog { Title = "Unable to login", Content = "There's a problem that prevents us to log you in. Please try again later. If the problem persists, contact Chiefs or HR Functional Unit to help you sign in.", PrimaryButtonText = "Ok" }; await contentDialog.ShowAsync(); } } else { ContentDialog contentDialog = new ContentDialog { Title = "Your account is disabled.", Content = "If you believe that your account has been disabled by mistake, contact TA Supervisor, Chiefs, or TA HR Functional Unit to enable your account.", PrimaryButtonText = "Ok" }; await contentDialog.ShowAsync(); } } else { // User not registered in system yet, proceed to set up user account. progText.Text = "Setting up your account..."; User newUser = await GetUserFromAD(upn); if (newUser != null) { newUser.IsNewUser = true; bool IsSuccess = await SettingsHelper.Instance.op2.AddUser(newUser); if (IsSuccess) { loadTimer.Start(); return; } else { ContentDialog contentDialog = new ContentDialog { Title = "Unable to register your account.", Content = "There's a problem in creating your account. Please try again later. If the problem persists, please contact Chiefs or HR Functional Unit to help you login.", PrimaryButtonText = "Ok" }; await contentDialog.ShowAsync(); } } else { ContentDialog contentDialog = new ContentDialog { Title = "Unable to create your account", Content = "There is a problem in creating your account. Please make sure that your AD account is enabled. Please contact Chiefs or HR Functional Unit to get help.", PrimaryButtonText = "Ok" }; await contentDialog.ShowAsync(); } } } this.Frame.Navigate(typeof(LoginPagev2), null, new SlideNavigationTransitionInfo() { Effect = SlideNavigationTransitionEffect.FromLeft }); }
private async void ShellMenuItemClick_File_Load(object sender, RoutedEventArgs e) { if (NavigationService.Frame.Content is MasterDetailPage) { ContentDialog loadFileDialog = new ContentDialog { Title = "Load instruction?", Content = "Unsaved changes will be lost. Export your instruction before loading a new one.", PrimaryButtonText = "Load instruction", CloseButtonText = "Cancel" }; ContentDialogResult result = await loadFileDialog.ShowAsync(); if (result == ContentDialogResult.Primary) { var page = NavigationService.Frame.Content as MasterDetailPage; if (page != null) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; picker.FileTypeFilter.Add(".zip"); StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { using (Stream zipToOpen = await file.OpenStreamForReadAsync()) { await InstructionDataProvider.LoadDataFromZipAsync(zipToOpen, Path.Combine(ApplicationData.Current.TemporaryFolder.Path, file.DisplayName + ".save")); } page.Reset(false); } } } else { return; } } else { if (NavigationService.Frame.Content is StartPage) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; picker.FileTypeFilter.Add(".zip"); StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { var page = NavigationService.Frame.Content as StartPage; page.loading = true; using (Stream zipToOpen = await file.OpenStreamForReadAsync()) { await InstructionDataProvider.LoadDataFromZipAsync(zipToOpen, Path.Combine(ApplicationData.Current.TemporaryFolder.Path, file.DisplayName + ".save")); } NavigationService.Navigate<MasterDetailPage>(); } } } }
public static async Task <ContentDialogResult> ShowAsyncEx(this ContentDialog contentDialog, IDispatcherWrapper dispatcher = null) => await ShowAsync(async() => await contentDialog.ShowAsync(), dispatcher);
private async void Begin_Game() { await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { while (pretzelCount <= 100 && pretzelLoss <= 50) { int left = (new Random()).Next(0, (int)Math.Floor(0.96 * ((Frame)Window.Current.Content).ActualWidth)); Button pretzelButton = new Button { Name = "pretzel" + pretzelCount, Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)), Height = 61, Width = 73, Margin = new Thickness { Top = -0.8 * ((Frame)Window.Current.Content).ActualHeight, Left = left }, }; pretzelButton.Click += async(sender, e) => { pretzelCount--; score++; Pretzel_Click(pretzelButton); var pretzelSound = new MediaElement(); pretzelSound.Stop(); var folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets"); var file = await folder.GetFileAsync("pretzel.mp4"); var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); pretzelSound.SetSource(stream, ""); pretzelSound.Play(); await Task.Delay(250); pretzelSound.Stop(); }; Image pretzelImage = new Image { Source = new BitmapImage(new Uri("ms-appx:///Assets/pretzel.png", UriKind.Absolute)), Stretch = Stretch.UniformToFill, }; pretzelButton.Content = pretzelImage; Pretzels_Stack.Children.Add(pretzelButton); Debug.WriteLine("Added pretzel #" + pretzelCount); Pretzel_Move(pretzelButton); pretzelCount++; await Task.Delay(250); } if (pretzelLoss >= 50) { Debug.WriteLine("Game over!"); ContentDialog deleteFileDialog = new ContentDialog { Title = "Game over!", Content = "Game over! Your score was: " + score + "! Would you like to play again?", PrimaryButtonText = "Play Again", CloseButtonText = "Return to Home Screen" }; ContentDialogResult result = await deleteFileDialog.ShowAsync(); if (result == ContentDialogResult.Primary) { score = 0; pretzelCount = 0; pretzelLoss = 0; Pretzels_Stack.Children.Clear(); await Task.Delay(500); Begin_Game(); } else { this.Frame.Navigate(typeof(MainPage)); } } }); }
/// <inheritdoc /> public async Task PointerPressedExecuteAsync() { // Check where the click was executed Point pointer = PointerEventArgs.GetCurrentPoint(Canvas).Position; // Querry a list of selected items List <PaintBase> selected = ShapeList.Where(pb => pb.Selected).ToList(); // Check // if only one item is selected if (selected.Count == 1) { PaintBase paintBase = selected.First(); // Check if the selected item is a decorator if (paintBase is TextDecoration decoration) { // Check if a decorator was clicked TextDecoration deco = decoration.GetClickedDecoration(pointer.X, pointer.Y); if (deco != null) { // Create dialog for Decorator editing DecoratorDialog dialog = new DecoratorDialog(deco.DecorationText, deco.GetDecoratorPosition()); // When editing add a delete button dialog.SecondaryButtonText = "Delete"; ContentDialogResult result = await dialog.ShowAsync(); if (result == ContentDialogResult.Primary) { deco.DecorationText = dialog.Decoration; AddUndoEntry(); // Check if decorator should be moved if (dialog.Position != GetDecoratorPosition(deco)) { TextDecoration newDecoration = decoration.MovePosition(deco, dialog.Position); ReplaceShapelistEntry(decoration, newDecoration); } _page.Draw(); _page.UpdateList(); // Return to prevent 2 decorations in one action return; } else if (result == ContentDialogResult.Secondary) { AddUndoEntry(); PaintBase newElement = decoration.RemoveDecorator(deco); ReplaceShapelistEntry(decoration, newElement); _page.Draw(); _page.UpdateList(); } } } // when the item itself is clicked, add a new decorator if ((pointer.X > paintBase.X && pointer.X < paintBase.X + paintBase.Width) && (pointer.Y > paintBase.Y && pointer.Y < paintBase.Y + paintBase.Height)) { AddUndoEntry(); await AddNewDecorator(paintBase); _page.Draw(); _page.UpdateList(); } } else { // Show error ContentDialog dialog = new ContentDialog() { Title = "Failed adding decorator", Content = "You may only select one item to add a decorator to", CloseButtonText = "Ok" }; await dialog.ShowAsync(); } }
// Button private async void lvMasterChats_ItemClick(object sender, ItemClickEventArgs e) { prgSendStatus.Value = 0; // Show dialog ContentDialog openShareDialog = new ContentDialog() { Title = "Share", Content = "Share with this chat?", PrimaryButtonText = "Yes", SecondaryButtonText = "No" }; ContentDialogResult result = await openShareDialog.ShowAsync(); if (result == ContentDialogResult.Primary) { // TODO: disable user interaction // TODO: Rework entire sending mechanism prgSendStatus.Value = 10; var dialog = e.ClickedItem as TLDialog; var manualResetEvent = new ManualResetEvent(false); var cacheService = UnigramContainer.Current.ResolveType <ICacheService>(); var protoService = UnigramContainer.Current.ResolveType <IMTProtoService>() as MTProtoService; prgSendStatus.Value = 20; protoService.Initialized += (s, args) => { prgSendStatus.Value = 30; // Now, prepare the message with the correct date and message itself. var date = TLUtils.DateToUniversalTimeTLInt(protoService.ClientTicksDelta, DateTime.Now); prgSendStatus.Value = 40; // Send the correct message according to the send content var message = TLUtils.GetMessage(SettingsHelper.UserId, dialog.Peer, TLMessageState.Sending, true, true, date, TextField.Text.Trim(), new TLMessageMediaEmpty(), TLLong.Random(), 0); prgSendStatus.Value = 50; cacheService.SyncSendingMessage(message, null, async(m) => { await protoService.SendMessageAsync(message, () => { // TODO: fast callback }); manualResetEvent.Set(); prgSendStatus.Value = 60; }); prgSendStatus.Value = 70; }; protoService.InitializationFailed += (s, args) => { manualResetEvent.Set(); }; cacheService.Init(); prgSendStatus.Value = 80; protoService.Initialize(); prgSendStatus.Value = 90; manualResetEvent.WaitOne(4000); prgSendStatus.Value = 100; // Now close the shareoperation sth.CloseShareTarget(); } }
private async void ClearDataBTN_Click(object sender, RoutedEventArgs e) { var clearData = new ContentDialog() { Title = "Clear selected content only" }; var panel = new StackPanel(); var History = new CheckBox(); History.Content = "Browsing History"; panel.Children.Add(History); History.IsChecked = true; var Cookies = new CheckBox(); Cookies.Content = "Cookies and saved website data"; panel.Children.Add(Cookies); Cookies.IsChecked = true; var DownloadHistory = new CheckBox(); DownloadHistory.Content = "Downloads History"; panel.Children.Add(DownloadHistory); var Passwords = new CheckBox(); Passwords.Content = "Passwords"; panel.Children.Add(Passwords); clearData.Content = panel; clearData.PrimaryButtonText = "Clear"; clearData.SecondaryButtonText = "Cancel"; var resultOfClearDialog = await clearData.ShowAsync(); if (resultOfClearDialog == ContentDialogResult.Primary) { if (History.IsChecked == true) { StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;//open app temp folder StorageFile HistoryFile = await tempFolder.CreateFileAsync("bHistoryURL.txt", CreationCollisionOption.OpenIfExists); await HistoryFile.DeleteAsync(); HistoryFile = await tempFolder.CreateFileAsync("bHistoryName.txt", CreationCollisionOption.OpenIfExists); await HistoryFile.DeleteAsync(); } if (Cookies.IsChecked == true) { } if (DownloadHistory.IsChecked == true) { } if (Passwords.IsChecked == true) { } clearData.Hide(); } else { clearData.Hide(); } }
public async void CheckPathInput(ItemViewModel instance, string CurrentInput) { if (CurrentInput != instance.WorkingDirectory || App.CurrentInstance.ContentFrame.CurrentSourcePageType == typeof(YourHome)) { //(App.CurrentInstance.OperationsControl as RibbonArea).RibbonViewModel.HomeItems.isEnabled = false; //(App.CurrentInstance.OperationsControl as RibbonArea).RibbonViewModel.ShareItems.isEnabled = false; if (CurrentInput.Equals("Home", StringComparison.OrdinalIgnoreCase) || CurrentInput.Equals(ResourceController.GetTranslation("NewTab"), StringComparison.OrdinalIgnoreCase)) { await App.CurrentInstance.FilesystemViewModel.SetWorkingDirectory(ResourceController.GetTranslation("NewTab")); App.CurrentInstance.ContentFrame.Navigate(typeof(YourHome), ResourceController.GetTranslation("NewTab"), new SuppressNavigationTransitionInfo()); } else { switch (CurrentInput.ToLower()) { case "%temp%": CurrentInput = AppSettings.TempPath; break; case "%appdata": CurrentInput = AppSettings.AppDataPath; break; case "%homepath%": CurrentInput = AppSettings.HomePath; break; case "%windir%": CurrentInput = AppSettings.WinDirPath; break; } try { var item = await DrivesManager.GetRootFromPath(CurrentInput); await StorageFileExtensions.GetFolderFromPathAsync(CurrentInput, item); App.CurrentInstance.ContentFrame.Navigate(AppSettings.GetLayoutType(), CurrentInput); // navigate to folder } catch (Exception) // Not a folder or inaccessible { try { var item = await DrivesManager.GetRootFromPath(CurrentInput); await StorageFileExtensions.GetFileFromPathAsync(CurrentInput, item); await Interaction.InvokeWin32Component(CurrentInput); } catch (Exception ex) // Not a file or not accessible { // Launch terminal application if possible foreach (var item in AppSettings.TerminalsModel.Terminals) { if (item.Path.Equals(CurrentInput, StringComparison.OrdinalIgnoreCase) || item.Path.Equals(CurrentInput + ".exe", StringComparison.OrdinalIgnoreCase)) { if (App.Connection != null) { var value = new ValueSet(); value.Add("Application", item.Path); value.Add("Arguments", String.Format(item.Arguments, App.CurrentInstance.FilesystemViewModel.WorkingDirectory)); await App.Connection.SendMessageAsync(value); } return; } } var dialog = new ContentDialog() { Title = "Invalid item", Content = "The item referenced is either invalid or inaccessible.\nMessage:\n\n" + ex.Message, CloseButtonText = "OK" }; await dialog.ShowAsync(); } } } App.CurrentInstance.NavigationToolbar.PathControlDisplayText = App.CurrentInstance.FilesystemViewModel.WorkingDirectory; } }
private async System.Threading.Tasks.Task <Tuple <int, string> > EnterImportData(string title, MimeType[] mimeTypes) { const bool defaultWrapping = false; const double defaultWidth = 400; var mimeTypeTextBlock = new TextBlock { Text = "Choose a mime type", MaxLines = 1, TextWrapping = TextWrapping.NoWrap, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 0, 0), Width = defaultWidth, }; var mimeTypeComboBox = new ComboBox { IsTextSearchEnabled = true, SelectedIndex = -1, Margin = new Thickness(0, 5, 0, 5), Width = defaultWidth }; foreach (var mimeType in mimeTypes) { mimeTypeComboBox.Items.Add(MimeTypeF.GetTypeName(mimeType)); } mimeTypeComboBox.SelectedIndex = 0; var dataTextBlock = new TextBlock { Text = "Enter some text", MaxLines = 1, TextWrapping = TextWrapping.NoWrap, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 5, 0, 0), Width = defaultWidth }; var dataTextBox = new TextBox { Text = "", AcceptsReturn = true, TextWrapping = (defaultWrapping ? TextWrapping.Wrap : TextWrapping.NoWrap), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center, FontSize = 12, Margin = new Thickness(0), Width = defaultWidth, Height = 200, }; ScrollViewer.SetVerticalScrollBarVisibility(dataTextBox, ScrollBarVisibility.Auto); ScrollViewer.SetHorizontalScrollBarVisibility(dataTextBox, ScrollBarVisibility.Auto); var dataWrappingCheckBox = new CheckBox { Content = "Wrapping", HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 0, 5), Width = defaultWidth, IsChecked = defaultWrapping, }; dataWrappingCheckBox.Checked += new RoutedEventHandler((sender, e) => { dataTextBox.TextWrapping = TextWrapping.Wrap; }); dataWrappingCheckBox.Unchecked += new RoutedEventHandler((sender, e) => { dataTextBox.TextWrapping = TextWrapping.NoWrap; }); var panel = new StackPanel { Margin = new Thickness(10), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, }; panel.Children.Add(mimeTypeTextBlock); panel.Children.Add(mimeTypeComboBox); panel.Children.Add(dataTextBlock); panel.Children.Add(dataTextBox); panel.Children.Add(dataWrappingCheckBox); var dialog = new ContentDialog { Title = title, Content = panel, PrimaryButtonText = "OK", SecondaryButtonText = "Cancel", IsPrimaryButtonEnabled = true, IsSecondaryButtonEnabled = true }; var result = await dialog.ShowAsync(); if (result == ContentDialogResult.Primary) { // Convert '\r' to '\n' // https://stackoverflow.com/questions/42867242/uwp-textbox-puts-r-only-how-to-set-linebreak var text = dataTextBox.Text.Replace('\r', '\n'); return(new Tuple <int, string>(mimeTypeComboBox.SelectedIndex, text)); } return(null); }
private async void ButUserChg_Click(object sender, RoutedEventArgs e) { ContentDialogResult res; StackPanel konteyner = new StackPanel(); groupsbox = new ComboBox(); ComboBox typeuser = new ComboBox(); konteyner.Children.Add(new TextBox() { PlaceholderText = "Login of user..." }); konteyner.Children.Add(new TextBox() { PlaceholderText = "New login of user..." }); konteyner.Children.Add(new TextBox() { PlaceholderText = "New password of user..." }); konteyner.Children.Add(typeuser); konteyner.Children.Add(groupsbox); groupsbox.Items.Clear(); groupsbox.IsEnabled = false; if (listGroups.Count > 0) { for (int count = 0; count < listGroups.Count; count++) { groupsbox.Items.Add(listGroups[count].Name); } groupsbox.SelectedIndex = 0; } else { groupsbox.PlaceholderText = "Groups are not found!"; } typeuser.Items.Add("Adm"); typeuser.Items.Add("Teacher"); typeuser.Items.Add("Student"); typeuser.SelectedIndex = 0; typeuser.DropDownClosed += Typeuser_DropDownClosed; ContentDialog dialog = new ContentDialog() { Title = "Change user data", Content = konteyner, PrimaryButtonText = "Change" }; res = await dialog.ShowAsync(); if (res == ContentDialogResult.Primary) { if (typeuser.SelectedItem.ToString() == "Student") { changer_users(((konteyner.Children[0]) as TextBox).Text, ((konteyner.Children[1]) as TextBox).Text, Crypt(((konteyner.Children[2]) as TextBox).Text), ((konteyner.Children[3]) as ComboBox).SelectedItem.ToString(), ((konteyner.Children[4]) as ComboBox).SelectedItem.ToString()); } else { changer_users(((konteyner.Children[0]) as TextBox).Text, ((konteyner.Children[1]) as TextBox).Text, Crypt(((konteyner.Children[2]) as TextBox).Text), ((konteyner.Children[3]) as ComboBox).SelectedItem.ToString(), "null"); } } }
public async Task <bool> RenameFileItem(ListedItem item, string oldName, string newName) { if (oldName == newName) { return(true); } if (!string.IsNullOrWhiteSpace(newName)) { try { if (item.PrimaryItemAttribute == StorageItemTypes.Folder) { var folder = await StorageFolder.GetFolderFromPathAsync(item.ItemPath); await folder.RenameAsync(newName, NameCollisionOption.FailIfExists); } else { var file = await StorageFile.GetFileFromPathAsync(item.ItemPath); await file.RenameAsync(newName, NameCollisionOption.FailIfExists); } } catch (Exception) { var ItemAlreadyExistsDialog = new ContentDialog() { Title = ResourceController.GetTranslation("ItemAlreadyExistsDialogTitle"), Content = ResourceController.GetTranslation("ItemAlreadyExistsDialogContent"), PrimaryButtonText = ResourceController.GetTranslation("ItemAlreadyExistsDialogPrimaryButtonText"), SecondaryButtonText = ResourceController.GetTranslation("ItemAlreadyExistsDialogSecondaryButtonText") }; ContentDialogResult result = await ItemAlreadyExistsDialog.ShowAsync(); if (result == ContentDialogResult.Primary) { if (item.PrimaryItemAttribute == StorageItemTypes.Folder) { var folder = await StorageFolder.GetFolderFromPathAsync(item.ItemPath); await folder.RenameAsync(newName, NameCollisionOption.GenerateUniqueName); } else { var file = await StorageFile.GetFileFromPathAsync(item.ItemPath); await file.RenameAsync(newName, NameCollisionOption.GenerateUniqueName); } } else if (result == ContentDialogResult.Secondary) { if (item.PrimaryItemAttribute == StorageItemTypes.Folder) { var folder = await StorageFolder.GetFolderFromPathAsync(item.ItemPath); await folder.RenameAsync(newName, NameCollisionOption.ReplaceExisting); } else { var file = await StorageFile.GetFileFromPathAsync(item.ItemPath); await file.RenameAsync(newName, NameCollisionOption.ReplaceExisting); } } } } CurrentInstance.NavigationToolbar.CanGoForward = false; return(true); }
private async void guardarPersonaCommand_Executed() { int filasAfectadas = -1; clsManejadoraPersona_BL manejadoraBL = new clsManejadoraPersona_BL(); ContentDialog mensajePopUp = new ContentDialog(); try { if (personaSeleccionada.idPersona == 0) { filasAfectadas = manejadoraBL.crearPersona_BL(personaSeleccionada); //actualizarListadoCommand_Executed(); if (filasAfectadas == 1) { //actualizarListadoCommand_Executed(); mensajePopUp.Title = "Creacion exitosa"; mensajePopUp.Content = "La persona ha sido creada correctamente"; mensajePopUp.PrimaryButtonText = "Aceptar"; } else { //actualizarListadoCommand_Executed(); mensajePopUp.Title = "Creacion fallida"; mensajePopUp.Content = "La persona no ha podido ser creada"; mensajePopUp.PrimaryButtonText = "Aceptar :("; } } else { filasAfectadas = manejadoraBL.editarPersona_BL(personaSeleccionada); //actualizarListadoCommand_Executed(); if (filasAfectadas == 1) { mensajePopUp.Title = "Creacion exitosa"; mensajePopUp.Content = "La persona ha sido editada correctamente"; mensajePopUp.PrimaryButtonText = "Aceptar"; } else { mensajePopUp.Title = "Creacion fallida"; mensajePopUp.Content = "La persona no ha podido ser creada"; mensajePopUp.PrimaryButtonText = "Aceptar :("; } } actualizarListadoCommand_Executed(); await mensajePopUp.ShowAsync(); } catch (Exception e) { mensajePopUp.Title = "Error"; mensajePopUp.Content = "Se ha producido un error"; mensajePopUp.PrimaryButtonText = "Aceptar"; await mensajePopUp.ShowAsync(); } }
private async void AddCommand_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { // Define Combobox for Display in ContentDialog ComboBox comboBox = new ComboBox() { HorizontalAlignment = HorizontalAlignment.Stretch, Header = "Select CT log Here" }; // Fill only those names that are not not yet added in course foreach (var x in (from a in AllStudents.lists where !ViewList.Items.Contains(a.GetView) select a.Name)) { comboBox.Items.Add(x); } // Instance of Content Dialog thaat will be displayed ContentDialog contentDialog = new ContentDialog() { PrimaryButtonText = "Add", CloseButtonText = "Cancel", Title = "Add New Item", Content = comboBox }; // If no student if left if (comboBox.Items.Count == 0) { comboBox.IsEnabled = false; contentDialog.IsPrimaryButtonEnabled = false; } else { comboBox.SelectedItem = comboBox.Items.First(); } switch (await contentDialog.ShowAsync()) { // Add case ContentDialogResult.Primary: // Find the selected student foreach (var x in AllStudents.lists) { if (x.Name == comboBox.SelectedItem.ToString()) { ctLog.lists.AddLast(x); break; } } // Sort ctLog List <EStudentEntry> v = ctLog.lists.OrderBy(a => a.Name).ToList(); ctLog.lists.Clear(); foreach (var x in v) { ctLog.lists.AddLast(x); } // Fill ViewList with new sorted order ViewList.Items.Clear(); foreach (var a in ctLog.lists) { if (a.GetView == null) { a.InitializeStudent(); } ViewList.Items.Add(a.GetView); } break; } }
private async void ShowDialogAsync(bool fault) { var dialog = new ContentDialog() { Title = "Login", FullSizeDesired = false, MaxWidth = this.ActualWidth // Required for Mobile! }; StackPanel panel = new StackPanel(); Grid myGrid = new Grid(); myGrid.Width = 350; myGrid.Height = 150; // Define the Columns ColumnDefinition colDef1 = new ColumnDefinition(); ColumnDefinition colDef2 = new ColumnDefinition(); myGrid.ColumnDefinitions.Add(colDef1); myGrid.ColumnDefinitions.Add(colDef2); // Define the Rows RowDefinition rowDef1 = new RowDefinition(); RowDefinition rowDef2 = new RowDefinition(); RowDefinition rowDef3 = new RowDefinition(); myGrid.RowDefinitions.Add(rowDef1); myGrid.RowDefinitions.Add(rowDef2); myGrid.RowDefinitions.Add(rowDef3); // Add the first text cell to the Grid TextBlock txt1 = new TextBlock(); txt1.VerticalAlignment = VerticalAlignment.Center; txt1.Text = "Gebruikersnaam:"; txt1.FontSize = 15; txt1.Margin = new Thickness(5); Grid.SetColumn(txt1, 0); Grid.SetRow(txt1, 0); TextBox box1 = new TextBox(); box1.Margin = new Thickness(5); box1.Height = 8; Grid.SetColumn(box1, 1); Grid.SetRow(box1, 0); // Add the second text cell to the Grid TextBlock txt2 = new TextBlock(); txt2.Text = "Wachtwoord:"; txt2.VerticalAlignment = VerticalAlignment.Center; txt2.FontSize = 15; txt2.Margin = new Thickness(5); Grid.SetColumn(txt2, 0); Grid.SetRow(txt2, 1); PasswordBox box2 = new PasswordBox(); box2.Margin = new Thickness(5); box2.Height = 8; Grid.SetColumn(box2, 1); Grid.SetRow(box2, 1); myGrid.Children.Add(txt1); myGrid.Children.Add(box1); myGrid.Children.Add(txt2); myGrid.Children.Add(box2); panel.Children.Add(myGrid); if (fault == true) { TextBlock txt3 = new TextBlock(); txt3.Text = "Wachtwoord of Gebruikersnaam fout"; txt3.VerticalAlignment = VerticalAlignment.Center; txt3.FontSize = 15; txt3.Foreground = new SolidColorBrush(Colors.Red); txt3.Margin = new Thickness(5); // Grid.SetColumn(txt3, 0); //Grid.SetRow(txt3, 2); panel.Children.Add(txt3); } dialog.Content = panel; dialog.CloseButtonText = "Close"; dialog.SecondaryButtonText = "Submit"; var resultGebruiker = ""; ContentDialogResult result = await dialog.ShowAsync(); if (result == ContentDialogResult.Secondary) { if (box1.Text.Trim().Equals("") || box2.Password.ToString().Trim().Equals("")) { } else { resultGebruiker = await gebruikerViewModel.LogInAsync(box1.Text, box2.Password.ToString()); } string[] tokens = resultGebruiker.Split('"'); tokens[1] = ""; if (tokens[5] == "token_type") { var token = tokens[4]; Gebruiker user = new Gebruiker(Int32.Parse(tokens[21].ToString()), tokens[13].ToString(), tokens[17].ToString()); ((App)Application.Current).gebruiker = user; GlobalToken.Token = tokens[3].ToString(); this.Frame.Navigate(typeof(OndernemingenPage)); ToastTemplateType toastTemplate = ToastTemplateType.ToastText02; XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate); XmlNodeList toastTekstElementen = toastXml.GetElementsByTagName("text"); toastTekstElementen[0].AppendChild(toastXml.CreateTextNode("Welkom " + user.Gebruikersnaam + " :)")); IXmlNode toastNode = toastXml.SelectSingleNode("/toast"); ((XmlElement)toastNode).SetAttribute("duration", "long"); ToastNotification toast = new ToastNotification(toastXml); ToastNotificationManager.CreateToastNotifier().Show(toast); } else { ShowDialogAsync(true); } // Terms of use were accepted. } }
protected async override void OnNavigatedTo(NavigationEventArgs e) { if (SettingHelper.IsPc()) { sp_View.DisplayMode = SplitViewDisplayMode.CompactOverlay; } else { sp_View.DisplayMode = SplitViewDisplayMode.Overlay; } ChangeTheme(); timer = new DispatcherTimer(); timer.Interval = new TimeSpan(0, 0, 5); timer.Start(); timer.Tick += Timer_Tick; MessageCenter.ChanageThemeEvent += MessageCenter_ChanageThemeEvent; MessageCenter.MianNavigateToEvent += MessageCenter_MianNavigateToEvent; MessageCenter.InfoNavigateToEvent += MessageCenter_InfoNavigateToEvent; MessageCenter.PlayNavigateToEvent += MessageCenter_PlayNavigateToEvent; MessageCenter.HomeNavigateToEvent += MessageCenter_HomeNavigateToEvent; MessageCenter.BgNavigateToEvent += MessageCenter_BgNavigateToEvent;; MessageCenter.Logined += MessageCenter_Logined; MessageCenter.ChangeBg += MessageCenter_ChangeBg; //main_frame.Navigate(typeof(HomePage)); MessageCenter_ChangeBg(); main_frame.Visibility = Visibility.Visible; menu_List.SelectedIndex = 0; Can_Nav = false; Can_Nav = true; frame.Visibility = Visibility.Visible; frame.Navigate(typeof(BlankPage)); play_frame.Visibility = Visibility.Visible; play_frame.Navigate(typeof(BlankPage)); //LoadPlayApiInfo(); if (e.Parameter != null) { var m = e.Parameter as StartModel; switch (m.StartType) { case StartTypes.None: break; case StartTypes.Video: MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(VideoViewPage), m.Par1); break; case StartTypes.Live: MessageCenter.SendNavigateTo(NavigateMode.Play, typeof(LiveRoomPage), m.Par1); break; case StartTypes.Bangumi: MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(BanInfoPage), m.Par1); break; case StartTypes.MiniVideo: MessageCenter.ShowMiniVideo(m.Par1); //MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(WebPage), "http://vc.bilibili.com/mobile/detail?vc=" + m.Par1); break; case StartTypes.Web: MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(WebPage), m.Par1); break; case StartTypes.Album: MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(DynamicInfoPage), m.Par1); break; case StartTypes.Article: MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(ArticleContentPage), m.Par1); break; case StartTypes.Music: MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(MusicInfoPage), m.Par1); break; case StartTypes.User: MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(UserInfoPage), m.Par1); break; case StartTypes.File: var files = m.Par3 as IReadOnlyList <IStorageItem>; List <PlayerModel> ls = new List <PlayerModel>(); int i = 1; foreach (StorageFile file in files) { ls.Add(new PlayerModel() { Mode = PlayMode.FormLocal, No = i.ToString(), VideoTitle = "", Title = file.DisplayName, Parameter = file, Aid = file.DisplayName, Mid = file.Path }); i++; } play_frame.Navigate(typeof(PlayerPage), new object[] { ls, 0 }); // MessageCenter.SendNavigateTo(NavigateMode.Play, typeof(PlayerPage), new object[] { ls, 0 }); break; case StartTypes.HandelUri: if (!await MessageCenter.HandelUrl(m.Par1)) { ContentDialog contentDialog = new ContentDialog() { PrimaryButtonText = "确定", Title = "不支持跳转的地址" }; TextBlock textBlock = new TextBlock() { Text = m.Par1, IsTextSelectionEnabled = true }; contentDialog.Content = textBlock; contentDialog.ShowAsync(); } break; default: break; } } if (SettingHelper.Get_First()) { TextBlock tx = new TextBlock() { Text = string.Format(@"{0}", AppHelper.GetLastVersionStr()), IsTextSelectionEnabled = true, TextWrapping = TextWrapping.Wrap }; await new ContentDialog() { Content = tx, PrimaryButtonText = "知道了" }.ShowAsync(); SettingHelper.Set_First(false); } new AppHelper().GetDeveloperMessage(); account = new Account(); //检查登录状态 if (SettingHelper.Get_Access_key() != "") { if ((await account.CheckLoginState(ApiHelper.access_key)).success) { MessageCenter_Logined(); await account.SSO(ApiHelper.access_key); } else { var data = await account.RefreshToken(SettingHelper.Get_Access_key(), SettingHelper.Get_Refresh_Token()); if (!data.success) { Utils.ShowMessageToast("登录过期,请重新登录"); await Utils.ShowLoginDialog(); } } } }
static async Task <bool> ShowAlert(ContentDialog alert) { ContentDialogResult result = await alert.ShowAsync(); return(result == ContentDialogResult.Primary); }
private async void PrintJournal_Click(object sender, RoutedEventArgs e) { ToastNotifier toast = ToastNotificationManager.CreateToastNotifier(); Windows.Data.Xml.Dom.XmlDocument toastxml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText02); Windows.Data.Xml.Dom.XmlNodeList toastnodelist = toastxml.GetElementsByTagName("text"); ToastNotification toastNotification; ComboBox gBox = new ComboBox(); int kol = 0; FileInfo fi; List <TeacherRecord> records = new List <TeacherRecord>(); ContentDialog dialog = new ContentDialog() { Title = "Export data", Content = gBox, PrimaryButtonText = "Export" }; for (int count = 0; count < listGroups.Count; count++) { gBox.Items.Add(listGroups[count].Name); } if (gBox.Items.Count > 0) { gBox.SelectedIndex = 0; } else { gBox.PlaceholderText = "Groups are not found!"; } ContentDialogResult res = await dialog.ShowAsync(); if (res == ContentDialogResult.Primary) { if (gBox.Items.Count == 0) { return; } using (ExcelPackage excel = new ExcelPackage()) { excel.Workbook.Properties.Title = "Export"; ExcelWorksheet worksheet = excel.Workbook.Worksheets.Add(gBox.SelectedItem.ToString()); for (int count = 0; count < listrecords.Count; count++) { if (listrecords[count].group == gBox.SelectedItem.ToString()) { records.Add(listrecords[count]); } } for (int count = 0; count < records.Count; count++) { { for (int count2 = 0; count2 < 5; count2++) { switch (count2) { case 0: { worksheet.Cells[count + 1, count2 + 1].Value = listrecords[count].data; break; } case 1: { worksheet.Cells[count + 1, count2 + 1].Value = listrecords[count].subject; break; } case 2: { worksheet.Cells[count + 1, count2 + 1].Value = listrecords[count].group; break; } case 3: { worksheet.Cells[count + 1, count2 + 1].Value = listrecords[count].student; break; } case 4: { worksheet.Cells[count + 1, count2 + 1].Value = listrecords[count].value; break; } } kol++; } } } if (kol == 0) { worksheet.Cells[1, 1].Value = "Records are not found!"; } fi = new FileInfo(ApplicationData.Current.LocalFolder.Path + @"\" + "Export" + " group " + gBox.SelectedItem.ToString() + ".xlsx"); try { excel.SaveAs(fi); } catch (Exception ex) { toastnodelist.Item(0).AppendChild(toastxml.CreateTextNode("Exception!")); toastnodelist.Item(1).AppendChild(toastxml.CreateTextNode(e.ToString())); toastNotification = new ToastNotification(toastxml); toastNotification.ExpirationTime = DateTime.Now.AddSeconds(4); toast.Show(toastNotification); return; } finally { toastnodelist.Item(0).AppendChild(toastxml.CreateTextNode("Success!")); toastnodelist.Item(1).AppendChild(toastxml.CreateTextNode(ApplicationData.Current.LocalFolder.Path + @"\" + "Export" + " group " + gBox.SelectedItem.ToString() + ".xlsx")); toastNotification = new ToastNotification(toastxml); toastNotification.ExpirationTime = DateTime.Now.AddSeconds(4); toast.Show(toastNotification); } //var msg = await new MessageDialog(ApplicationData.Current.LocalFolder.Path + @"\" + "Export" + " group " + gBox.SelectedItem.ToString() + ".xlsx").ShowAsync(); } } }
private async void MakeNewPromoButton(object sender, RoutedEventArgs e) { if (String.IsNullOrEmpty(uxDescriptionBox.Text) || uxRequiredItemsList.SelectedItems.Count == 0 || uxAppliedItemsList.SelectedItems.Count == 0 || String.IsNullOrEmpty(uxPercentageBox.Text.ToString())) { ContentDialog responseAlert = new ContentDialog { Title = "Required fields are missing", Content = "Please make sure that all fields are filled out", CloseButtonText = "Ok" }; ContentDialogResult result = await responseAlert.ShowAsync(); } else { List <MenuItem> required = new List <MenuItem>(); foreach (object o in uxRequiredItemsList.SelectedItems) { required.Add((MenuItem)o); } List <MenuItem> applied = new List <MenuItem>(); foreach (object o in uxAppliedItemsList.SelectedItems) { applied.Add((MenuItem)o); } var validMakeNewPromo = await MakeNewPromo.SendMakeNewPromo("Customer", uxDescriptionBox.Text, required, applied, uxPercentageBox.Text.ToString(), uxActiveChoice.IsEnabled.ToString(), uxRepeatableChoice.IsEnabled.ToString()); if (validMakeNewPromo != null) { ContentDialog responseAlert = new ContentDialog { Title = "Successful", Content = "Promotion was successfully added to the database", CloseButtonText = "Ok" }; ContentDialogResult result = await responseAlert.ShowAsync(); var writer = new ZXing.BarcodeWriter(); writer.Format = ZXing.BarcodeFormat.QR_CODE; writer.Options = new ZXing.Common.EncodingOptions() { Height = 300, Width = 300, PureBarcode = true }; QRCode.Source = writer.Write(validMakeNewPromo); uxDiscountPopup.IsOpen = false; uxDiscountButton.Visibility = Visibility.Collapsed; // Remove option to bring back this screen } else { ContentDialog responseAlert = new ContentDialog { Title = "Unsuccessful", Content = "Promotion was not successfully added to the database", CloseButtonText = "Ok" }; ContentDialogResult result = await responseAlert.ShowAsync(); } } }
async void Login() { string studata = ""; string studataOld = ""; App.isMainPageFirstTimeInit = false; // get account info string username = UsernameTextBox.Text; string password = PasswordTextBox.Password; localSettings.Values["UsrName"] = username; localSettings.Values["Passwd"] = password; // when empty box if (username == "" || password == "") { ContentDialog ErrorEmptyContentDialog = new ContentDialog { Title = LocalizedResources.GetString("/Text"), Content = LocalizedResources.GetString("pleaseInput/Text"), CloseButtonText = LocalizedResources.GetString("yesInput/Text"), }; ContentDialogResult result = await ErrorEmptyContentDialog.ShowAsync(); } // load else { App.SetTitleBarUI(Windows.UI.Color.FromArgb(255, 0, 99, 177), Windows.UI.Color.FromArgb(0, 25, 114, 184)); // kissing Views.Busy.SetBusy(true, "Purr ..."); try { studata = await StudentData.Kissing(username, password, true); } catch (Exception) { } // bad network or server if (studata == "") { ContentDialog ErrorContentDialog = new ContentDialog { Title = LocalizedResources.GetString("error/Text"), Content = LocalizedResources.GetString("netError/Text"), CloseButtonText = LocalizedResources.GetString("yesNet/Text"), }; await ErrorContentDialog.ShowAsync(); } // wrong account info else if (studata.Contains("Something went wrong!")) { PasswordTextBox.PlaceholderText = ""; ContentDialog ErrorContentDialog = new ContentDialog { Title = LocalizedResources.GetString("error/Text"), Content = LocalizedResources.GetString("someError/Text"), CloseButtonText = LocalizedResources.GetString("yesAcc/Text"), }; ContentDialogResult result = await ErrorContentDialog.ShowAsync(); } else { // save student data to new studataOld = studata; await StudentData.SaveStudentData(studata, StudentData.NewOrOld.New); if (System.Diagnostics.Debugger.IsAttached) { // new StudentData StudentData studentData = new StudentData(StudentData.ParseJSON(studata), StudentData.ParseJSON(studataOld)); StudentData.SaveHistoryData(StudentData.CollectCurrentHistoryData()); // navigate Frame.Navigate(typeof(SubjectsAssignmentsPage)); if (StudentData.DisabledMsgDialog != null) { await StudentData.DisabledMsgDialog.ShowAsync(); } } else { try { // new StudentData StudentData studentData = new StudentData(StudentData.ParseJSON(studata), StudentData.ParseJSON(studataOld)); StudentData.SaveHistoryData(StudentData.CollectCurrentHistoryData()); // navigate Frame.Navigate(typeof(SubjectsAssignmentsPage)); if (StudentData.DisabledMsgDialog != null) { await StudentData.DisabledMsgDialog.ShowAsync(); } } catch (Exception e) { await Windows.Storage.ApplicationData.Current.ClearAsync(); localSettings.Values["UsrName"] = username; localSettings.Values["Passwd"] = password; ContentDialog ErrorContentDialog = new ContentDialog { Title = "ERROR", Content = e.ToString(), CloseButtonText = "哦。", }; ContentDialogResult result = await ErrorContentDialog.ShowAsync(); } } } Views.Busy.SetBusy(false); } }
// rename line private async void RenameLine(object s, RoutedEventArgs ev, Card sender) { int error = 0; var dialog = new ContentDialog() { Title = resourceLoader.GetString("Linename") }; TextBox namebox = new TextBox(); namebox.Text = sender.ParentLine.Name; namebox.Height = 32; namebox.SelectionStart = namebox.Text.Length; namebox.KeyDown += async(sndr, args) => { if (args.Key == Windows.System.VirtualKey.Enter) { if (namebox.Text.Trim() == "") { dialog.Title = resourceLoader.GetString("LinenameError"); } else if (namebox.Text.Trim().Length > 30) { dialog.Title = resourceLoader.GetString("LinenameLengthError"); } else { dialog.Hide(); error = 0; sender.ParentLine.Name = namebox.Text.Trim(); await lineSerializer.saveLine(sender.ParentLine); await getSavedData(); } } }; dialog.Content = namebox; dialog.PrimaryButtonText = "OK"; dialog.PrimaryButtonClick += async delegate { if (namebox.Text.Trim() == "") { error = 1; } else if (namebox.Text.Trim().Length > 30) { error = 2; } else { error = 0; sender.ParentLine.Name = namebox.Text.Trim(); await lineSerializer.saveLine(sender.ParentLine); await getSavedData(); } }; var result = await dialog.ShowAsync(); if (result == ContentDialogResult.None) { error = 0; } while (error != 0) { if (error == 1) { dialog.Title = resourceLoader.GetString("LinenameError"); } if (error == 2) { dialog.Title = resourceLoader.GetString("LinenameLengthError"); } result = await dialog.ShowAsync(); if (result == ContentDialogResult.None) { error = 0; } } }
private async void RegLogButton_Click(object sender, RoutedEventArgs e) //Кнопка входа/регистрации { if (RegGrid.Visibility == Visibility.Visible) //Действия для регистрации { if (RegTextBox.Text != "") { if (RegPasswordbx.Password != "") { string passw = Cypher.GetMd5Hash(RegPasswordbx.Password); if (RegNameBox.Text != "") { if (RegSurNameBox.Text != "") { if (RegTypeBox.SelectedIndex != -1) { UserData us = new UserData(RegTextBox.Text, passw, RegNameBox.Text, RegSurNameBox.Text, RegTypeBox.SelectedIndex, RegTextBlock.Text); users.Add(us); De_Serialization.Serialization <List <UserData> >("UserData.xml", CreationCollisionOption.OpenIfExists, users); RegGrid.Visibility = Visibility.Collapsed; LoginGrid.Visibility = Visibility.Visible; RegLogButton.Content = "Войти"; } } } } } //Ошибки if (RegTextBox.Text == "" || RegPasswordbx.Password == "" || RegNameBox.Text == "" || RegSurNameBox.Text == "" || RegTypeBox.SelectedIndex == -1) { ContentDialog prog = new ContentDialog() { Title = "Ошибка", Content = "Одно или несколько полей пустые", PrimaryButtonText = "OK" }; await prog.ShowAsync(); } } else //Действия для входа { if (users.Count != 0 && LoginTextBox.Text != "" && Passwordbx.Password != "") { string passw = Cypher.GetMd5Hash(Passwordbx.Password); bool confirmed = true; for (int i = 0; i < users.Count; i++) { if (LoginTextBox.Text == users[i].Login && passw == users[i].Password) { List <string> us = new List <string>() { users[i].Login, passw, users[i].Name, users[i].Surname, users[i].AccountType.ToString(), users[i].DisciplineType }; De_Serialization.Serialization <List <string> >("LoginData.xml", CreationCollisionOption.ReplaceExisting, us); confirmed = true; if (users[i].AccountType == 0) { this.Frame.Navigate(typeof(StudentPage)); } if (users[i].AccountType == 1) { this.Frame.Navigate(typeof(TeacherPage)); } if (users[i].AccountType == 2) { this.Frame.Navigate(typeof(AdminPage)); } break; } else { confirmed = false; } } if (!confirmed) { ContentDialog prog = new ContentDialog() { Title = "Ошибка", Content = "Неверный логин или пароль", PrimaryButtonText = "OK" }; await prog.ShowAsync(); } } } }