/// <summary>
 /// Hides the dialog, and sets the Result property
 /// </summary>
 /// <param name="result"></param>
 public void Close(ContentDialogResult result)
 {
     // Set the return value
     Result = result;
     // Hide the dialog window
     Hide();
 }
Example #2
0
        public async void ReturnBookCommand(string bookid)
        {
            int    booksissueed = 0, issueduration = 0;
            double days = 0.0, fine = 0.0;
            string bookstatus = string.Empty, IssuedMem = string.Empty;
            await ApplicationData.Current.LocalFolder.CreateFileAsync("University.db", CreationCollisionOption.OpenIfExists);

            string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "University.db");

            using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
            {
                db.Open();
                string BookStatusCommand = "Select Status, IssuedTo, (julianday() - julianday(IssueDate, 'utc')) from books" +
                                           $" WHERE BookID = '{bookid}'";
                try
                {
                    SqliteCommand    bookcmd    = new SqliteCommand(BookStatusCommand, db);
                    SqliteDataReader BookResult = bookcmd.ExecuteReader();

                    while (BookResult.Read())
                    {
                        bookstatus = BookResult.GetString(0);
                    }

                    if (string.Equals(bookstatus, "Issued"))
                    {
                        while (BookResult.Read())
                        {
                            IssuedMem = BookResult.GetString(1);
                            days      = double.Parse(BookResult.GetString(2));
                        }
                        String GetUserCommand = "Select BooksIssued, IssueMonthDuration from users" +
                                                $" WHERE ID = '{IssuedMem}'";

                        SqliteCommand usercmd = new SqliteCommand(GetUserCommand, db);

                        SqliteDataReader UserResult = usercmd.ExecuteReader();
                        while (UserResult.Read())
                        {
                            booksissueed  = int.Parse(UserResult.GetString(0));
                            issueduration = int.Parse(UserResult.GetString(1));
                        }
                        if ((issueduration * 30) - days < 0)
                        {
                            fine = CalculateFine(days - issueduration);
                            ContentDialog FineDialog = new ContentDialog
                            {
                                Title               = $"Collect Fine Rs.{fine}",
                                Content             = "Close only aftercollecting fine",
                                PrimaryButtonText   = "Fine Paid",
                                SecondaryButtonText = "Fine not Paid"
                            };
                            ContentDialogResult res = await FineDialog.ShowAsync();

                            if (res == ContentDialogResult.Primary)
                            {
                                goto returnprocess;
                            }
                            else if (res == ContentDialogResult.Secondary)
                            {
                                await ShowDialogBox("Fine not paid. Book is not returned.");

                                goto dbclose;
                            }
                        }
returnprocess:

                        CreateBill(bookid, IssuedMem, fine);
                        string returnbookquery = $"UPDATE books SET Status = 'Available', IssuedTo = 'None'," +
                                                 " IssueDate = 'None'" +
                                                 $" WHERE BookID = '{bookid}'";
                        SqliteCommand    returnbookcmd = new SqliteCommand(returnbookquery, db);
                        SqliteDataReader ReturnResult  = returnbookcmd.ExecuteReader();

                        string decuserbooknoquery = $"UPDATE users SET BooksIssued = {booksissueed - 1} " +
                                                    $" WHERE ID = '{IssuedMem}'";
                        SqliteCommand    decuserbookcmd   = new SqliteCommand(decuserbooknoquery, db);
                        SqliteDataReader DecMembookResult = decuserbookcmd.ExecuteReader();

                        if (ReturnResult.RecordsAffected > 0 && DecMembookResult.RecordsAffected > 0)
                        {
                            await ShowDialogBox("Book Returned");
                        }
                        else
                        {
                            await ShowDialogBox("Book Not Returned");
                        }
                    }
                    else
                    {
                        await ShowDialogBox("Book is not issued to anyone.");
                    }
                }
                catch (Exception e)
                {
                    await ShowDialogBox($"Book Not Issued \n{e.Message}");

                    goto dbclose;
                }


dbclose:
                db.Close();
            }
        }
Example #3
0
        //ContentDialog Fin de Partida
        /// <summary>
        /// Método que muestra un ContenDialog al final de la partida para que el usuario introduzca su nick y se guarde
        /// en la BD de forma que aparezca en el ranking
        /// </summary>
        public async void MostrarMensajeFinPartida()
        {
            /*Help for InputDialog:
             * https://comentsys.wordpress.com/2018/05/04/uwp-input-dialog/
             */

            //Se para el sonido
            hacerSonidos.Stop();
            //Creo TextBox para introducir nombre de usuario
            TextBox input = new TextBox();

            input.Height = (double)App.Current.Resources["TextControlThemeMinHeight"];

            //Si se repite el contentDialog porque se pasaron los 20 caracteres
            if (repeticionDialog < 1)
            {
                input.PlaceholderText = "Introduce tu nick";
            }
            else
            {
                input.PlaceholderText = "Nick debe ser menor a 20 caracteres";
            }

            ContentDialog dialog = new ContentDialog()
            {
                Title             = "¡¡¡Fin de la partida!!!",
                PrimaryButtonText = "Guardar",
                //Asigno como contenido el TextBox para introducir nick de usuario
                Content = input
            };

            ContentDialogResult result = await dialog.ShowAsync();

            if (result == ContentDialogResult.Primary)
            {
                if (input.Text.Length <= 20)
                {
                    //Volver a inicio
                    Frame frame = (Frame)Window.Current.Content;

                    frame.Navigate(typeof(MainPage));

                    //Asigno a objJugador el nick del jugador actual
                    objJugador.NombreJugador = input.Text;
                    //Guardo nick y puntuación del jugador en BD
                    try
                    {
                        clsOperacionesJugadorBL operacionBL = new clsOperacionesJugadorBL();
                        operacionBL.InsertNuevoJugador(objJugador);
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }

                    //repeticionDialog = 0;
                }
                else
                {
                    //MostrarMensajeErrorInput();

                    repeticionDialog++;
                    MostrarMensajeFinPartida();
                }
            }
        }
Example #4
0
        private async void LSTVWinfo_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch ((e.ClickedItem as UsualItemData).ID)
            {
            case 0:
            {
                FRAMEdetail.Navigate(typeof(ImageShowPage), new Parameters("北大地图", "ms-appx:///Assets/pkumap.jpg"));
                if (VSGinfo.CurrentState == narrow)
                {
                    UpdateVisualState(narrow, null);
                }
            } break;

            case 1:
            {
                FRAMEdetail.Navigate(typeof(ImageShowPage), new Parameters("北京地铁图", "ms-appx:///Assets/subwaymap.jpg"));
                if (VSGinfo.CurrentState == narrow)
                {
                    UpdateVisualState(narrow, null);
                }
            } break;

            case 2:
            {
                PRGRSinfo.ProgressStart();
                await InfoUtil.GetCardAmount();

                PRGRSinfo.ProgressEnd();
            } break;

            case 3:
            {
                first : BitmapImage bmp = new BitmapImage();
                Stream stream = await WebConnection.Connect_for_stream("http://dean.pku.edu.cn/student/yanzheng.php?act=init");

                if (stream == null)
                {
                    Constants.BoxPage.ShowMessage("获取验证码失败!");
                    return;
                }
                var ran_stream = await Util.StreamToRandomAccessStream(stream);

                bmp.SetSource(ran_stream);

                IMGverify.Source = bmp;
                if (DLGshowing)
                {
                    return;
                }
                ContentDialogResult res = await DLGverify.ShowAsync();

                if (res == ContentDialogResult.Primary)
                {
                    String phpsessid = await Dean.get_session_id(verifyCode);

                    if (phpsessid == "")
                    {
                        goto first;
                    }
                    PRGRSinfo.ProgressStart();
                    Parameters parameters = await WebConnection.Connect(Constants.domain + "/services/pkuhelper/allGrade.php?phpsessid=" + phpsessid, null);

                    if (parameters.name != "200")
                    {
                        Util.DealWithDisconnect(parameters);
                        PRGRSinfo.ProgressEnd();
                    }
                    else
                    {
                        PRGRSinfo.ProgressEnd();
                        FRAMEdetail.Navigate(typeof(GradePage), parameters.value);
                        if (VSGinfo.CurrentState == narrow)
                        {
                            UpdateVisualState(narrow, null);
                        }
                    }
                }
            } break;

            case 4:
            {
                FRAMEdetail.Navigate(typeof(SchoolCalendarPage));
                if (VSGinfo.CurrentState == narrow)
                {
                    UpdateVisualState(narrow, null);
                }
            }
            break;

            case 5:
            {
                FRAMEdetail.Navigate(typeof(PhoneList));
                if (VSGinfo.CurrentState == narrow)
                {
                    UpdateVisualState(narrow, null);
                }
            }
            break;
            }
        }
Example #5
0
 private void ContentDialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
 {
     Result = ContentDialogResult.Cancel;
 }
        private async void Calculate(object sender, RoutedEventArgs e)
        {
            try
            {
                char[]    message      = messageTextBox.Text.ToCharArray();
                Interval  interval     = new Interval();
                TextBox[] probablities = new TextBox[itemsNumber];
                char[]    letters      = new char[itemsNumber];
                for (int i = 0; i < itemsNumber; i++)
                {
                    probablities[i] = alphabet[i, 1];
                    var characters = alphabet[i, 0].Text.ToCharArray();
                    letters[i] = characters[0];
                }
                bool isMessageInAlphabet = false;
                for (int i = 0; i < message.Length; i++)
                {
                    isMessageInAlphabet = checkLetterInAlphabet(message[i], letters);
                    if (!isMessageInAlphabet)
                    {
                        break;
                    }
                }
                if (!isMessageInAlphabet)
                {
                    ContentDialog dialog = new ContentDialog {
                        Title = "Error", Content = "Wiadomość niepoprawna", CloseButtonText = "ok"
                    };
                    ContentDialogResult result = await dialog.ShowAsync();

                    return;
                }


                try
                {
                    subIntervalsGrid.Children.Clear();
                    checkProbability(probablities);
                    decimal[] probs = parseProbabilities(probablities);
                    probs = ArithmeticCoding.MakeProportions(probs);
                    for (int p = 0; p < message.GetLength(0); p++)
                    {
                        Interval[] intervals = ArithmeticCoding.MakeSubintervals(interval, probs);
                        addSubinterval(intervals, message[p], letters);
                        interval = ArithmeticCoding.SetCurrentInterval(intervals, letters, message[p]);
                    }
                    resultCodingGrid.Visibility        = Visibility.Visible;
                    resultCodingGrid.Opacity           = 0;
                    resultCodingGrid.OpacityTransition = new ScalarTransition()
                    {
                        Duration = new TimeSpan(0, 0, 0, 0, 500)
                    };
                    resultCodingGrid.Opacity           = 1;
                    resultCodingTextBlock.Text         = "Wynik: " + ((interval.l + interval.r) / 2).ToString();
                    subIntervalsGrid.Visibility        = Visibility.Visible;
                    subIntervalsGrid.Opacity           = 0;
                    subIntervalsGrid.OpacityTransition = new ScalarTransition()
                    {
                        Duration = new TimeSpan(0, 0, 0, 0, 500)
                    };
                    subIntervalsGrid.Opacity = 1;
                }
                catch (Exception ex)
                {
                    ContentDialog dialog = new ContentDialog {
                        Title = "Error", Content = ex.Message, CloseButtonText = "ok"
                    };
                    ContentDialogResult result = await dialog.ShowAsync();
                }
            }
            catch (Exception ex)
            {
                ContentDialog dialog = new ContentDialog {
                    Title = "Error", Content = ex.Message, CloseButtonText = "ok"
                };
                ContentDialogResult result = await dialog.ShowAsync();
            }
        }
Example #7
0
 private void CancelButton_Click(object sender, RoutedEventArgs e)
 {
     result = ContentDialogResult.None;
     dialog.Hide();
 }
Example #8
0
 private void YesButton_Click(object sender, RoutedEventArgs e)
 {
     result = ContentDialogResult.Primary;
     dialog.Hide();
 }
        private async void BtnEnvoyerMaCandidature_Click(object sender, RoutedEventArgs e)
        {
            if (cboResto.SelectedItem == null)
            {
                var message = new MessageDialog("Veuillez choisir un restaurant.");
                await message.ShowAsync();;
            }
            else if (cboPostes.SelectedItem == null)
            {
                var message = new MessageDialog("Veuillez choisir un poste.");
                await message.ShowAsync();;
            }
            else if (txtMotivations.Text == "")
            {
                var message = new MessageDialog("Veuillez entrer vos motivations.");
                await message.ShowAsync();;
            }
            else
            {
                // action=newCandidature&idCandidat={idCandidat}&idResto={idResto}&idPoste={idPoste}&motivations={motivations}
                // récupération des données candidature
                string        idCandidat           = lutilisateurActuellement.IdUtilisateur.ToString();
                Poste         lePosteChoisi        = (cboPostes.SelectedItem as Poste);
                string        idPoste              = lePosteChoisi.IdPoste.ToString();
                Restaurant    leRestoChoisi        = (cboResto.SelectedItem as Restaurant);
                string        idResto              = leRestoChoisi.IdResto.ToString();
                string        motivations          = txtMotivations.Text;
                ContentDialog newCandidatureDialog = new ContentDialog
                {
                    Title   = "Attention !",
                    Content = "Faites attention à bien vous relire afin de ne pas faire d'erreur.\n" +
                              "Êtes-vous sûr(e) de vouloir postuler au restaurant " + leRestoChoisi.LibelleResto +
                              " au poste de " + lePosteChoisi.LibellePoste + " ?",
                    PrimaryButtonText = "Oui",
                    CloseButtonText   = "Non"
                };

                ContentDialogResult result = await newCandidatureDialog.ShowAsync();

                // Créer la candidature si l'utilisateur a cliqué sur le bouton principal ("oui")
                // Sinon, rien faire.
                if (result == ContentDialogResult.Primary)
                {
                    // Créer la candidature
                    // L'api permet de vérifier si la candidature existe déjà à l'aide de l'utilisateur et l'id du resto
                    // Si elle n'existe pas déjà, on la créée.
                    var reponse = await hc.GetStringAsync("http://localhost/recru_eatgood_api/index_candidat.php?" +
                                                          "action=newCandidature" +
                                                          "&idCandidat=" + idCandidat +
                                                          "&idResto=" + idResto +
                                                          "&idPoste=" + idPoste +
                                                          "&motivations=" + motivations);

                    var donnees  = JsonConvert.DeserializeObject <dynamic>(reponse);
                    var resultat = donnees["Success"];
                    if (resultat == "false")
                    {
                        var message = new MessageDialog("Vous avez déjà candidaté pour le restaurant " + leRestoChoisi.LibelleResto);
                        await message.ShowAsync();

                        cboResto.SelectedItem = null;;
                    }
                    else
                    {
                        var message = new MessageDialog("Vous avez bien candidaté pour le restaurant " +
                                                        leRestoChoisi.LibelleResto + " au poste de " + lePosteChoisi.LibellePoste);
                        await message.ShowAsync();

                        cboResto.SelectedItem  = null;
                        cboPostes.SelectedItem = null;
                        txtMotivations.Text    = "";
                        await lesDonnees.ChargerLesDonnees();

                        this.Frame.Navigate(typeof(Page_Accueil), lesDonnees);
                    }
                }
                else
                {
                    // Ne pas créer la candidature
                }
            }
        }
Example #10
0
 private async void ShareAppBarButton_Tapped(object sender, TappedRoutedEventArgs e)
 {
     ShareDialog.Default.Init(this.NewsBodyViewModel.News.NewsUrl, this.NewsBodyViewModel.News.Title);
     ContentDialogResult result = await ShareDialog.Default.ShowAsync();
 }
Example #11
0
        //Handels playlist list item click event to show songds of the playlist in dialog box.
        private async void PlaylistList_ItemClick(object sender, ItemClickEventArgs e)
        {
            queue.Clear();
            PlaylistSongs.Items.Clear();
            const ThumbnailMode thumbnailMode = ThumbnailMode.MusicView;

            Model.Playlist playlistToShow = (Model.Playlist)e.ClickedItem;
            var            fileToShow     = fileList.Where(f => f.Name == playlistToShow.Name).FirstOrDefault();

            Windows.Media.Playlists.Playlist playlist = await Windows.Media.Playlists.Playlist.LoadAsync(fileToShow);

            foreach (var s in playlist.Files)
            {
                var        af   = songFileList.Where(sf => sf.Name == s.Name).FirstOrDefault();
                const uint size = 100;
                using (StorageItemThumbnail thumbnail = await s.GetThumbnailAsync(thumbnailMode, size))
                {
                    if (thumbnail != null && (thumbnail.Type == ThumbnailType.Image || thumbnail.Type == ThumbnailType.Icon))
                    {
                        BitmapImage bitmapImage = new BitmapImage();
                        bitmapImage.SetSource(thumbnail);
                        Model.MediaFile o1 = new Model.AudioFile();
                        Image           i  = new Image();
                        MusicProperties musicProperties = await s.Properties.GetMusicPropertiesAsync();

                        i.Source = bitmapImage;
                        o1.Thumb = i;
                        o1.Title = s.Name;
                        if (musicProperties.Title != "")
                        {
                            o1.Title = musicProperties.Title;
                        }
                        o1.Name = s.Name;
                        o1.Path = s.Path;
                        PlaylistSongs.Items.Add(o1);
                    }
                }
            }
            SonglistView.Title = fileToShow.Name.Replace(".wpl", "");
            SonglistView.IsPrimaryButtonEnabled = true;
            SonglistView.PrimaryButtonText      = "Save";
            PlaylistSongs.CanDragItems          = true;
            PlaylistSongs.CanReorderItems       = true;
            PlaylistSongs.AllowDrop             = true;
            ContentDialogResult contentDialogResult = await SonglistView.ShowAsync();

            if (contentDialogResult == ContentDialogResult.Primary)
            {
                playlist.Files.Clear();
                StorageFolder       sf = KnownFolders.MusicLibrary;
                NameCollisionOption collisionOption = NameCollisionOption.ReplaceExisting;
                PlaylistFormat      format          = PlaylistFormat.WindowsMedia;
                foreach (Model.MediaFile item in PlaylistSongs.Items)
                {
                    StorageFile storageFile = await StorageFile.GetFileFromPathAsync(item.Path);

                    playlist.Files.Add(storageFile);
                    Debug.WriteLine(item.Name);
                }
                StorageFile savedFile = await playlist.SaveAsAsync(sf, fileToShow.Name.Replace(".wpl", ""), collisionOption, format);
            }
            else if (contentDialogResult == ContentDialogResult.Secondary)
            {
                Play_From_Playlist(playlistToShow.Name);
            }
        }
Example #12
0
        public async Task <IStorageHistory> RenameAsync(IStorageItemWithPath source,
                                                        string newName,
                                                        NameCollisionOption collision,
                                                        IProgress <FilesystemErrorCode> errorCode,
                                                        CancellationToken cancellationToken)
        {
            if (Path.GetFileName(source.Path) == newName && collision == NameCollisionOption.FailIfExists)
            {
                errorCode?.Report(FilesystemErrorCode.ERROR_ALREADYEXIST);
                return(null);
            }

            if (!string.IsNullOrWhiteSpace(newName) &&
                !FilesystemHelpers.ContainsRestrictedCharacters(newName) &&
                !FilesystemHelpers.ContainsRestrictedFileName(newName))
            {
                var renamed = await source.ToStorageItemResult(associatedInstance)
                              .OnSuccess(async(t) =>
                {
                    await t.RenameAsync(newName, collision);
                    return(t);
                });

                if (renamed)
                {
                    errorCode?.Report(FilesystemErrorCode.ERROR_SUCCESS);
                    return(new StorageHistory(FileOperationType.Rename, source, renamed.Result.FromStorageItem()));
                }
                else if (renamed == FilesystemErrorCode.ERROR_UNAUTHORIZED)
                {
                    // Try again with MoveFileFromApp
                    var destination = Path.Combine(Path.GetDirectoryName(source.Path), newName);
                    if (NativeFileOperationsHelper.MoveFileFromApp(source.Path, destination))
                    {
                        errorCode?.Report(FilesystemErrorCode.ERROR_SUCCESS);
                        return(new StorageHistory(FileOperationType.Rename, source, StorageItemHelpers.FromPathAndType(destination, source.ItemType)));
                    }
                    else
                    {
                        Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
                    }
                }
                else if (renamed == FilesystemErrorCode.ERROR_NOTAFILE || renamed == FilesystemErrorCode.ERROR_NOTAFOLDER)
                {
                    await DialogDisplayHelper.ShowDialogAsync("RenameError/NameInvalid/Title".GetLocalized(), "RenameError/NameInvalid/Text".GetLocalized());
                }
                else if (renamed == FilesystemErrorCode.ERROR_NAMETOOLONG)
                {
                    await DialogDisplayHelper.ShowDialogAsync("RenameError/TooLong/Title".GetLocalized(), "RenameError/TooLong/Text".GetLocalized());
                }
                else if (renamed == FilesystemErrorCode.ERROR_INUSE)
                {
                    // TODO: proper dialog, retry
                    await DialogDisplayHelper.ShowDialogAsync("FileInUseDeleteDialog/Title".GetLocalized(), "");
                }
                else if (renamed == FilesystemErrorCode.ERROR_NOTFOUND)
                {
                    await DialogDisplayHelper.ShowDialogAsync("RenameError/ItemDeleted/Title".GetLocalized(), "RenameError/ItemDeleted/Text".GetLocalized());
                }
                else if (renamed == FilesystemErrorCode.ERROR_ALREADYEXIST)
                {
                    var ItemAlreadyExistsDialog = new ContentDialog()
                    {
                        Title               = "ItemAlreadyExistsDialogTitle".GetLocalized(),
                        Content             = "ItemAlreadyExistsDialogContent".GetLocalized(),
                        PrimaryButtonText   = "ItemAlreadyExistsDialogPrimaryButtonText".GetLocalized(),
                        SecondaryButtonText = "ItemAlreadyExistsDialogSecondaryButtonText".GetLocalized(),
                        CloseButtonText     = "ItemAlreadyExistsDialogCloseButtonText".GetLocalized()
                    };

                    ContentDialogResult result = await ItemAlreadyExistsDialog.ShowAsync();

                    if (result == ContentDialogResult.Primary)
                    {
                        return(await RenameAsync(source, newName, NameCollisionOption.GenerateUniqueName, errorCode, cancellationToken));
                    }
                    else if (result == ContentDialogResult.Secondary)
                    {
                        return(await RenameAsync(source, newName, NameCollisionOption.ReplaceExisting, errorCode, cancellationToken));
                    }
                }
                errorCode?.Report(renamed);
            }

            return(null);
        }
Example #13
0
        public async Task <IStorageHistory> CopyAsync(IStorageItemWithPath source,
                                                      string destination,
                                                      IProgress <float> progress,
                                                      IProgress <FilesystemErrorCode> errorCode,
                                                      CancellationToken cancellationToken)
        {
            if (associatedInstance.FilesystemViewModel.WorkingDirectory.StartsWith(App.AppSettings.RecycleBinPath))
            {
                errorCode?.Report(FilesystemErrorCode.ERROR_UNAUTHORIZED);
                progress?.Report(100.0f);

                // Do not paste files and folders inside the recycle bin
                await DialogDisplayHelper.ShowDialogAsync(
                    "ErrorDialogThisActionCannotBeDone".GetLocalized(),
                    "ErrorDialogUnsupportedOperation".GetLocalized());

                return(null);
            }

            IStorageItem copiedItem = null;

            //long itemSize = await FilesystemHelpers.GetItemSize(await source.ToStorageItem(associatedInstance));

            if (source.ItemType == FilesystemItemType.Directory)
            {
                if (!string.IsNullOrWhiteSpace(source.Path) &&
                    Path.GetDirectoryName(destination).IsSubPathOf(source.Path)) // We check if user tried to copy anything above the source.ItemPath
                {
                    var           destinationName = destination.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last();
                    var           sourceName      = source.Path.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last();
                    ContentDialog dialog          = new ContentDialog()
                    {
                        Title   = "ErrorDialogThisActionCannotBeDone".GetLocalized(),
                        Content = "ErrorDialogTheDestinationFolder".GetLocalized() + " (" + destinationName + ") " + "ErrorDialogIsASubfolder".GetLocalized() + " (" + sourceName + ")",
                        //PrimaryButtonText = "ErrorDialogSkip".GetLocalized(),
                        CloseButtonText = "ErrorDialogCancel".GetLocalized()
                    };

                    ContentDialogResult result = await dialog.ShowAsync();

                    if (result == ContentDialogResult.Primary)
                    {
                        progress?.Report(100.0f);
                        errorCode?.Report(FilesystemErrorCode.ERROR_INPROGRESS | FilesystemErrorCode.ERROR_SUCCESS);
                    }
                    else
                    {
                        progress?.Report(100.0f);
                        errorCode?.Report(FilesystemErrorCode.ERROR_INPROGRESS | FilesystemErrorCode.ERROR_GENERIC);
                    }
                    return(null);
                }
                else
                {
                    var fsSourceFolder = await source.ToStorageItemResult(associatedInstance);

                    var fsDestinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination));

                    var fsResult = (FilesystemResult)(fsSourceFolder.ErrorCode | fsDestinationFolder.ErrorCode);

                    if (fsResult)
                    {
                        var fsCopyResult = await FilesystemTasks.Wrap(() => CloneDirectoryAsync((StorageFolder)fsSourceFolder, (StorageFolder)fsDestinationFolder, fsSourceFolder.Result.Name, CreationCollisionOption.FailIfExists));

                        if (fsCopyResult == FilesystemErrorCode.ERROR_ALREADYEXIST)
                        {
                            var ItemAlreadyExistsDialog = new ContentDialog()
                            {
                                Title               = "ItemAlreadyExistsDialogTitle".GetLocalized(),
                                Content             = "ItemAlreadyExistsDialogContent".GetLocalized(),
                                PrimaryButtonText   = "ItemAlreadyExistsDialogPrimaryButtonText".GetLocalized(),
                                SecondaryButtonText = "ItemAlreadyExistsDialogSecondaryButtonText".GetLocalized(),
                                CloseButtonText     = "ItemAlreadyExistsDialogCloseButtonText".GetLocalized()
                            };

                            ContentDialogResult result = await ItemAlreadyExistsDialog.ShowAsync();

                            if (result == ContentDialogResult.Primary)
                            {
                                fsCopyResult = await FilesystemTasks.Wrap(() => CloneDirectoryAsync((StorageFolder)fsSourceFolder, (StorageFolder)fsDestinationFolder, fsSourceFolder.Result.Name, CreationCollisionOption.GenerateUniqueName));
                            }
                            else if (result == ContentDialogResult.Secondary)
                            {
                                fsCopyResult = await FilesystemTasks.Wrap(() => CloneDirectoryAsync((StorageFolder)fsSourceFolder, (StorageFolder)fsDestinationFolder, fsSourceFolder.Result.Name, CreationCollisionOption.ReplaceExisting));

                                return(null); // Cannot undo overwrite operation
                            }
                            else
                            {
                                return(null);
                            }
                        }
                        if (fsCopyResult)
                        {
                            if (associatedInstance.FilesystemViewModel.CheckFolderForHiddenAttribute(source.Path))
                            {
                                // The source folder was hidden, apply hidden attribute to destination
                                NativeFileOperationsHelper.SetFileAttribute(fsCopyResult.Result.Path, FileAttributes.Hidden);
                            }
                            copiedItem = (StorageFolder)fsCopyResult;
                        }
                        fsResult = fsCopyResult;
                    }
                    errorCode?.Report(fsResult.ErrorCode);
                }
            }
            else if (source.ItemType == FilesystemItemType.File)
            {
                FilesystemResult <StorageFolder> destinationResult = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination));

                var sourceResult = await source.ToStorageItemResult(associatedInstance);

                var fsResult = (FilesystemResult)(sourceResult.ErrorCode | destinationResult.ErrorCode);

                if (fsResult)
                {
                    var file         = (StorageFile)sourceResult;
                    var fsResultCopy = await FilesystemTasks.Wrap(() => file.CopyAsync(destinationResult.Result, Path.GetFileName(file.Name), NameCollisionOption.FailIfExists).AsTask());

                    if (fsResultCopy == FilesystemErrorCode.ERROR_ALREADYEXIST)
                    {
                        var ItemAlreadyExistsDialog = new ContentDialog()
                        {
                            Title               = "ItemAlreadyExistsDialogTitle".GetLocalized(),
                            Content             = "ItemAlreadyExistsDialogContent".GetLocalized(),
                            PrimaryButtonText   = "ItemAlreadyExistsDialogPrimaryButtonText".GetLocalized(),
                            SecondaryButtonText = "ItemAlreadyExistsDialogSecondaryButtonText".GetLocalized(),
                            CloseButtonText     = "ItemAlreadyExistsDialogCloseButtonText".GetLocalized()
                        };

                        ContentDialogResult result = await ItemAlreadyExistsDialog.ShowAsync();

                        if (result == ContentDialogResult.Primary)
                        {
                            fsResultCopy = await FilesystemTasks.Wrap(() => file.CopyAsync(destinationResult.Result, Path.GetFileName(file.Name), NameCollisionOption.GenerateUniqueName).AsTask());
                        }
                        else if (result == ContentDialogResult.Secondary)
                        {
                            fsResultCopy = await FilesystemTasks.Wrap(() => file.CopyAsync(destinationResult.Result, Path.GetFileName(file.Name), NameCollisionOption.ReplaceExisting).AsTask());

                            return(null); // Cannot undo overwrite operation
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    if (fsResultCopy)
                    {
                        copiedItem = fsResultCopy.Result;
                    }
                    fsResult = fsResultCopy;
                }
                if (fsResult == FilesystemErrorCode.ERROR_UNAUTHORIZED || fsResult == FilesystemErrorCode.ERROR_GENERIC)
                {
                    // Try again with CopyFileFromApp
                    if (NativeFileOperationsHelper.CopyFileFromApp(source.Path, destination, true))
                    {
                        fsResult = (FilesystemResult)true;
                    }
                    else
                    {
                        Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
                    }
                }
                errorCode?.Report(fsResult.ErrorCode);
            }

            if (Path.GetDirectoryName(destination) == associatedInstance.FilesystemViewModel.WorkingDirectory)
            {
                if (copiedItem != null)
                {
                    List <ListedItem> copiedListedItems = associatedInstance.FilesystemViewModel.FilesAndFolders
                                                          .Where(listedItem => copiedItem.Path.Contains(listedItem.ItemPath)).ToList();

                    if (copiedListedItems.Count > 0)
                    {
                        associatedInstance.ContentPage.AddSelectedItemsOnUi(copiedListedItems);
                        associatedInstance.ContentPage.FocusSelectedItems();
                    }
                }
            }

            progress?.Report(100.0f);

            var pathWithType = copiedItem.FromStorageItem(destination, source.ItemType);

            return(new StorageHistory(FileOperationType.Copy, source, pathWithType));
        }
Example #14
0
        private async void SecureArea_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (ApplicationData.Current.LocalSettings.Values.ContainsKey("IsFirstEnterSecureArea"))
                {
                    UnlockPassword       = CredentialProtector.GetPasswordFromProtector("SecureAreaPrimaryPassword");
                    FileEncryptionAesKey = KeyGenerator.GetMD5FromKey(UnlockPassword, 16);
                    AESKeySize           = Convert.ToInt32(ApplicationData.Current.LocalSettings.Values["SecureAreaAESKeySize"]);

                    if (!(ApplicationData.Current.LocalSettings.Values["SecureAreaLockMode"] is string LockMode) || LockMode != nameof(CloseLockMode) || IsNewStart)
                    {
                        if (Convert.ToBoolean(ApplicationData.Current.LocalSettings.Values["SecureAreaEnableWindowsHello"]))
                        {
RETRY:
                            switch (await WindowsHelloAuthenticator.VerifyUserAsync().ConfigureAwait(true))
                            {
                            case AuthenticatorState.VerifyPassed:
                            {
                                break;
                            }

                            case AuthenticatorState.UnknownError:
                            case AuthenticatorState.VerifyFailed:
                            {
                                QueueContentDialog Dialog = new QueueContentDialog
                                {
                                    Title               = Globalization.GetString("Common_Dialog_ErrorTitle"),
                                    Content             = Globalization.GetString("QueueDialog_WinHelloAuthFail_Content"),
                                    PrimaryButtonText   = Globalization.GetString("Common_Dialog_TryAgain"),
                                    SecondaryButtonText = Globalization.GetString("Common_Dialog_UsePassword"),
                                    CloseButtonText     = Globalization.GetString("Common_Dialog_GoBack")
                                };

                                ContentDialogResult Result = await Dialog.ShowAsync().ConfigureAwait(true);

                                if (Result == ContentDialogResult.Primary)
                                {
                                    goto RETRY;
                                }
                                else if (Result == ContentDialogResult.Secondary)
                                {
                                    if (!await EnterByPassword().ConfigureAwait(true))
                                    {
                                        return;
                                    }
                                }
                                else
                                {
                                    GoBack();
                                    return;
                                }
                                break;
                            }

                            case AuthenticatorState.UserNotRegistered:
                            case AuthenticatorState.CredentialNotFound:
                            {
                                QueueContentDialog Dialog = new QueueContentDialog
                                {
                                    Title           = Globalization.GetString("Common_Dialog_ErrorTitle"),
                                    Content         = Globalization.GetString("QueueDialog_WinHelloCredentialLost_Content"),
                                    CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                                };
                                _ = await Dialog.ShowAsync().ConfigureAwait(true);

                                ApplicationData.Current.LocalSettings.Values["SecureAreaEnableWindowsHello"] = false;

                                if (!await EnterByPassword().ConfigureAwait(true))
                                {
                                    return;
                                }
                                break;
                            }

                            case AuthenticatorState.WindowsHelloUnsupport:
                            {
                                QueueContentDialog Dialog = new QueueContentDialog
                                {
                                    Title             = Globalization.GetString("Common_Dialog_WarningTitle"),
                                    Content           = Globalization.GetString("QueueDialog_WinHelloDisable_Content"),
                                    PrimaryButtonText = Globalization.GetString("Common_Dialog_UsePassword"),
                                    CloseButtonText   = Globalization.GetString("Common_Dialog_GoBack")
                                };

                                ApplicationData.Current.LocalSettings.Values["SecureAreaEnableWindowsHello"] = false;

                                if ((await Dialog.ShowAsync().ConfigureAwait(true)) == ContentDialogResult.Primary)
                                {
                                    if (!await EnterByPassword().ConfigureAwait(true))
                                    {
                                        return;
                                    }
                                }
                                else
                                {
                                    GoBack();
                                    return;
                                }
                                break;
                            }
                            }
                        }
                        else
                        {
                            if (!await EnterByPassword().ConfigureAwait(true))
                            {
                                return;
                            }
                        }
                    }
                }
                else
                {
                    if (!ApplicationData.Current.LocalSettings.Values.ContainsKey("SecureAreaUsePermission"))
                    {
                        try
                        {
                            LoadingText.Text                   = Globalization.GetString("Progress_Tip_CheckingLicense");
                            CancelButton.Visibility            = Visibility.Collapsed;
                            LoadingControl.IsLoading           = true;
                            MainPage.ThisPage.IsAnyTaskRunning = true;

                            if (await CheckPurchaseStatusAsync().ConfigureAwait(true))
                            {
                                if (MainPage.ThisPage.Nav.CurrentSourcePageType.Name != nameof(SecureArea))
                                {
                                    GoBack();
                                    return;
                                }

                                ApplicationData.Current.LocalSettings.Values["SecureAreaUsePermission"] = true;
                                await Task.Delay(500).ConfigureAwait(true);
                            }
                            else
                            {
                                if (MainPage.ThisPage.Nav.CurrentSourcePageType.Name != nameof(SecureArea))
                                {
                                    GoBack();
                                    return;
                                }

                                SecureAreaIntroDialog IntroDialog = new SecureAreaIntroDialog();
                                if ((await IntroDialog.ShowAsync().ConfigureAwait(true)) == ContentDialogResult.Primary)
                                {
                                    if (await PurchaseAsync().ConfigureAwait(true))
                                    {
                                        ApplicationData.Current.LocalSettings.Values["SecureAreaUsePermission"] = true;

                                        QueueContentDialog SuccessDialog = new QueueContentDialog
                                        {
                                            Title           = Globalization.GetString("Common_Dialog_WarningTitle"),
                                            Content         = Globalization.GetString("QueueDialog_SecureAreaUnlock_Content"),
                                            CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                                        };
                                        _ = await SuccessDialog.ShowAsync().ConfigureAwait(true);
                                    }
                                    else
                                    {
                                        GoBack();
                                        return;
                                    }
                                }
                                else
                                {
                                    GoBack();
                                    return;
                                }
                            }
                        }
                        catch (NetworkException)
                        {
                            QueueContentDialog ErrorDialog = new QueueContentDialog
                            {
                                Title           = Globalization.GetString("Common_Dialog_ErrorTitle"),
                                Content         = Globalization.GetString("QueueDialog_SecureAreaNetworkUnavailable_Content"),
                                CloseButtonText = Globalization.GetString("Common_Dialog_GoBack")
                            };
                            _ = await ErrorDialog.ShowAsync().ConfigureAwait(true);

                            GoBack();
                            return;
                        }
                        finally
                        {
                            await Task.Delay(500).ConfigureAwait(true);

                            LoadingControl.IsLoading           = false;
                            MainPage.ThisPage.IsAnyTaskRunning = false;
                        }
                    }

                    SecureAreaWelcomeDialog Dialog = new SecureAreaWelcomeDialog();
                    if ((await Dialog.ShowAsync().ConfigureAwait(true)) == ContentDialogResult.Primary)
                    {
                        AESKeySize           = Dialog.AESKeySize;
                        UnlockPassword       = Dialog.Password;
                        FileEncryptionAesKey = KeyGenerator.GetMD5FromKey(UnlockPassword, 16);
                        CredentialProtector.RequestProtectPassword("SecureAreaPrimaryPassword", UnlockPassword);

                        ApplicationData.Current.LocalSettings.Values["SecureAreaAESKeySize"]         = Dialog.AESKeySize;
                        ApplicationData.Current.LocalSettings.Values["SecureAreaEnableWindowsHello"] = Dialog.IsEnableWindowsHello;
                        ApplicationData.Current.LocalSettings.Values["IsFirstEnterSecureArea"]       = false;
                    }
                    else
                    {
                        if (Dialog.IsEnableWindowsHello)
                        {
                            await WindowsHelloAuthenticator.DeleteUserAsync().ConfigureAwait(true);
                        }

                        GoBack();

                        return;
                    }
                }

                await StartLoadFile().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                LogTracer.LeadToBlueScreen(ex);
            }
        }
Example #15
0
        public async void DecompressArchive()
        {
            BaseStorageFile archive = await StorageItemHelpers.ToStorageItem <BaseStorageFile>(associatedInstance.SlimContentPage.SelectedItem.ItemPath);

            if (archive != null)
            {
                DecompressArchiveDialog          decompressArchiveDialog    = new DecompressArchiveDialog();
                DecompressArchiveDialogViewModel decompressArchiveViewModel = new DecompressArchiveDialogViewModel(archive);
                decompressArchiveDialog.ViewModel = decompressArchiveViewModel;

                ContentDialogResult option = await decompressArchiveDialog.ShowAsync();

                if (option == ContentDialogResult.Primary)
                {
                    // Check if archive still exists
                    if (!StorageItemHelpers.Exists(archive.Path))
                    {
                        return;
                    }

                    CancellationTokenSource extractCancellation = new CancellationTokenSource();
                    PostedStatusBanner      banner = App.OngoingTasksViewModel.PostOperationBanner(
                        string.Empty,
                        "ExtractingArchiveText".GetLocalized(),
                        0,
                        ReturnResult.InProgress,
                        FileOperationType.Extract,
                        extractCancellation);

                    BaseStorageFolder destinationFolder     = decompressArchiveViewModel.DestinationFolder;
                    string            destinationFolderPath = decompressArchiveViewModel.DestinationFolderPath;

                    if (destinationFolder == null)
                    {
                        BaseStorageFolder parentFolder = await StorageItemHelpers.ToStorageItem <BaseStorageFolder>(Path.GetDirectoryName(archive.Path));

                        destinationFolder = await FilesystemTasks.Wrap(() => parentFolder.CreateFolderAsync(Path.GetFileName(destinationFolderPath), CreationCollisionOption.GenerateUniqueName).AsTask());
                    }
                    if (destinationFolder == null)
                    {
                        return; // Could not create dest folder
                    }

                    Stopwatch sw = new Stopwatch();
                    sw.Start();

                    await ZipHelpers.ExtractArchive(archive, destinationFolder, banner.Progress, extractCancellation.Token);

                    sw.Stop();
                    banner.Remove();

                    if (sw.Elapsed.TotalSeconds >= 6)
                    {
                        App.OngoingTasksViewModel.PostBanner(
                            "ExtractingCompleteText".GetLocalized(),
                            "ArchiveExtractionCompletedSuccessfullyText".GetLocalized(),
                            0,
                            ReturnResult.Success,
                            FileOperationType.Extract);
                    }

                    if (decompressArchiveViewModel.OpenDestinationFolderOnCompletion)
                    {
                        await NavigationHelpers.OpenPath(destinationFolderPath, associatedInstance, FilesystemItemType.Directory);
                    }
                }
            }
        }
        /// <summary>
        /// Shows the details of an item clicked on in the <see cref="ItemPage"/>
        /// </summary>
        private async void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            //var itemId = ((SampleDataItem)e.ClickedItem).UniqueId;
            //if (!Frame.Navigate(typeof(ItemPage), itemId))
            //{
            //    throw new Exception(this.resourceLoader.GetString("NavigationFailedExceptionMessage"));
            //}
            Exception exception = null;

            try
            {
                var passphraseDialog = new PassphraseInputDialog();
                ContentDialogResult passphraseDialogResult = await passphraseDialog.ShowAsync();

                if (passphraseDialogResult == ContentDialogResult.Primary)
                {
                    var passphrase = passphraseDialog.Passphrase;
                    var fileData   = (YCFileData)e.ClickedItem;

                    StorageFolder tempFolder    = Windows.Storage.ApplicationData.Current.LocalCacheFolder;
                    StorageFile   encryptedFile = await tempFolder.CreateFileAsync(fileData.InternalName, CreationCollisionOption.ReplaceExisting);

                    StorageFile decryptedFile = await tempFolder.CreateFileAsync(fileData.FileName, CreationCollisionOption.ReplaceExisting);

                    using (var encryptedFileStream = await encryptedFile.OpenStreamForWriteAsync())
                    {
                        await client.GetFile(fileData.InternalName, encryptedFileStream);

                        // reset encrypted file tape head
                        encryptedFileStream.Seek(0, SeekOrigin.Begin);

                        using (var decryptedFileStream = await decryptedFile.OpenStreamForWriteAsync())
                        {
                            engine.DecryptFile(encryptedFileStream, decryptedFileStream, passphrase);
                        }
                    }
                    //No further use for the local encrypted file
                    await encryptedFile.DeleteAsync(StorageDeleteOption.PermanentDelete);

                    // Lift Off!
                    //var launcherOpts = new LauncherOptions()
                    //{
                    //    DisplayApplicationPicker = false
                    //};
                    await Launcher.LaunchFileAsync(decryptedFile);

                    //Burn after reading!
                    //await decryptedFile.DeleteAsync();
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            if (exception != null)
            {
                var dialog = new MessageDialog("An exception was thrown:" + Environment.NewLine + exception.Message, "Oh noes!");
                await dialog.ShowAsync();
            }
        }
Example #17
0
        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;
        }
Example #18
0
 private void NoButton_Click(object sender, RoutedEventArgs e)
 {
     result = ContentDialogResult.Secondary;
     dialog.Hide();
 }
Example #19
0
        public async Task ShowAsync(object context)
        {
            OutcomeParameter parameter = (OutcomeParameter)context;

            decimal  amount      = 0;
            string   currency    = null;
            string   description = String.Empty;
            DateTime when        = DateTime.Now;
            IKey     categoryKey = parameter.CategoryKey;

            // Initiate categories loading...
            CategoryPicker categoryDialog = new CategoryPicker();

            OutcomeAmount amountDialog = new OutcomeAmount(queryDispatcher);

            amountDialog.PrimaryButtonText = "Next";

            if (parameter.CategoryKey.IsEmpty)
            {
                amountDialog.SecondaryButtonText = String.Empty;
            }
            else
            {
                amountDialog.SecondaryButtonText = "Create today";
            }

            if (parameter.Amount != null)
            {
                amountDialog.Value    = parameter.Amount.Value;
                amountDialog.Currency = parameter.Amount.Currency;
            }

            ContentDialogResult result = await amountDialog.ShowAsync(false);

            amount   = amountDialog.Value;
            currency = amountDialog.Currency;
            if (result == ContentDialogResult.None)
            {
                return;
            }
            else if (result == ContentDialogResult.Primary)
            {
                categoryDialog.PrimaryButtonText   = "Next";
                categoryDialog.SecondaryButtonText = "Create today";
                if (!parameter.CategoryKey.IsEmpty)
                {
                    categoryDialog.SelectedKey = parameter.CategoryKey;
                }

                result = await categoryDialog.ShowAsync();

                if (result == ContentDialogResult.None)
                {
                    return;
                }

                categoryKey = categoryDialog.SelectedKey;
                if (result == ContentDialogResult.Primary)
                {
                    OutcomeDescription descriptionDialog = new OutcomeDescription();
                    descriptionDialog.PrimaryButtonText   = "Next";
                    descriptionDialog.SecondaryButtonText = "Create today";

                    result = await descriptionDialog.ShowAsync();

                    if (result == ContentDialogResult.None && !descriptionDialog.IsEnterPressed)
                    {
                        return;
                    }

                    description = descriptionDialog.Value;

                    if (result == ContentDialogResult.Primary || descriptionDialog.IsEnterPressed)
                    {
                        OutcomeWhen whenDialog = new OutcomeWhen();
                        whenDialog.PrimaryButtonText   = "Create";
                        whenDialog.SecondaryButtonText = "Cancel";
                        whenDialog.Value = when;

                        result = await whenDialog.ShowAsync();

                        if (result != ContentDialogResult.Primary)
                        {
                            return;
                        }

                        when = whenDialog.Value;
                    }
                }
            }

            await commandDispatcher.HandleAsync(new CreateOutcome(
                                                    new Price(amount, currency),
                                                    description,
                                                    when,
                                                    categoryKey
                                                    ));
        }
Example #20
0
        /// <summary>
        /// Will save a field work copy, from local state folder to the my document folder of current user and will prompt a message when done.
        /// </summary>
        public async void QuickBackupAsync()
        {
            //Variables
            List <StorageFile> FilesToBackup     = new List <StorageFile>();
            FileServices       fs                = new FileServices();
            int            photoCount            = 0;
            bool           hasPhotos             = false;                   // Will prevent warning message of no backuped photo showing when no photos were taken on the device
            DateTimeOffset youngestPhoto         = DateTimeOffset.MinValue; //Default for current
            DateTimeOffset inMemoryYoungestPhoto = DateTimeOffset.MinValue;
            string         projectName           = string.Empty;

            if (localSetting.GetSettingValue(Dictionaries.ApplicationLiterals.KeywordBackupPhotoYoungest) != null)
            {
                inMemoryYoungestPhoto = (DateTimeOffset)localSetting.GetSettingValue(Dictionaries.ApplicationLiterals.KeywordBackupPhotoYoungest);
            }
            if (localSetting.GetSettingValue(Dictionaries.DatabaseLiterals.FieldUserInfoPName) != null)
            {
                projectName = localSetting.GetSettingValue(Dictionaries.DatabaseLiterals.FieldUserInfoPName).ToString();
            }

            //calculate new name for output database in the archive
            string       uCode    = currentLocalSettings.Containers[ApplicationLiterals.LocalSettingMainContainer].Values[Dictionaries.DatabaseLiterals.FieldUserInfoUCode].ToString();
            FileServices fService = new FileServices();
            string       newName  = fService.CalculateDBCopyName(uCode) + ".sqlite";

            //Iterate through field book folder files
            string        _fieldBooLocalPath = localSetting.GetSettingValue(Dictionaries.ApplicationLiterals.KeywordFieldProject).ToString();
            StorageFolder fieldBook          = await StorageFolder.GetFolderFromPathAsync(_fieldBooLocalPath);

            //Get a list of files from field book
            IReadOnlyList <StorageFile> fieldBookPhotosRO = await fieldBook.GetFilesAsync();

            //Get a list of photos only
            foreach (StorageFile files in fieldBookPhotosRO)
            {
                //Get databases
                if (files.Name.ToLower().Contains(".sqlite") && files.Name.Contains(Dictionaries.DatabaseLiterals.DBName))
                {
                    FilesToBackup.Add(files);
                }

                //Get photos
                if (files.Name.ToLower().Contains(".jpg"))
                {
                    hasPhotos = true;
                    if (files.DateCreated >= inMemoryYoungestPhoto)
                    {
                        //Copy all photos
                        FilesToBackup.Add(files);

                        //Keep youngest photo for futur backup
                        if (files.DateCreated > youngestPhoto)
                        {
                            youngestPhoto = files.DateCreated;
                        }

                        photoCount++;
                    }
                }
            }

            //If any photos needs to be copied, else show warning
            if (FilesToBackup.Count > 1)
            {
                //Copy database and rename it
                List <StorageFile> newList = new List <StorageFile>();
                foreach (StorageFile sf in FilesToBackup)
                {
                    if (sf.Name.Contains(Dictionaries.DatabaseLiterals.DBName))
                    {
                        StorageFile newFile = await sf.CopyAsync(fieldBook, newName);

                        newList.Add(newFile);
                    }
                    else
                    {
                        newList.Add(sf);
                    }
                }

                //Zip
                string outputArchivePath = await fs.AddFilesToZip(newList);

                //Keep youngest photo in memory
                localSetting.SetSettingValue(Dictionaries.ApplicationLiterals.KeywordBackupPhotoYoungest, youngestPhoto);

                //Copy
                await fs.SaveArchiveCopy(newList, "", "", projectName + "_");

                //Delete renamed copy
                foreach (StorageFile fsToDelete in newList)
                {
                    if (fsToDelete.Name.Contains(newName))
                    {
                        await fsToDelete.DeleteAsync();

                        break;
                    }
                }
            }
            else if (FilesToBackup.Count == 1 && FilesToBackup[0].Name.Contains(".sqlite"))
            {
                //Do not zip, only output sqlite
                try
                {
                    await fs.SaveDBCopy();
                }
                catch (Exception)
                {
                    //Show error message
                    var           loadLocalization = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();
                    ContentDialog endProcessDialog = new ContentDialog()
                    {
                        Title             = loadLocalization.GetString("SaveDBDialogTitle"),
                        Content           = loadLocalization.GetString("SaveDBDialogContentError"),
                        PrimaryButtonText = loadLocalization.GetString("LoadDataButtonProcessEndMessageOk")
                    };

                    endProcessDialog.Style = (Style)Application.Current.Resources["DeleteDialog"];
                    ContentDialogResult cdr = await endProcessDialog.ShowAsync();
                }
            }
            else if (FilesToBackup.Count == 0)
            {
                //Show empty archive warning
                var           loadLocalization     = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();
                ContentDialog warningNoPhotoBackup = new ContentDialog()
                {
                    Title             = loadLocalization.GetString("ShellBackupEmptyTitle"),
                    Content           = loadLocalization.GetString("ShellBackupEmptyMessage/Text"),
                    PrimaryButtonText = loadLocalization.GetString("GenericDialog_ButtonOK")
                };
                warningNoPhotoBackup.Style = (Style)Application.Current.Resources["WarningDialog"];
                ContentDialogResult cdr = await warningNoPhotoBackup.ShowAsync();
            }

            //Show empty backed up photo warning
            if (photoCount == 0 && hasPhotos)
            {
                var           loadLocalization     = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();
                ContentDialog warningNoPhotoBackup = new ContentDialog()
                {
                    Title             = loadLocalization.GetString("ShellBackupPhotoEmptyTitle"),
                    Content           = loadLocalization.GetString("ShellBackupPhotoEmptyMessage/Text"),
                    PrimaryButtonText = loadLocalization.GetString("GenericDialog_ButtonOK")
                };
                warningNoPhotoBackup.Style = (Style)Application.Current.Resources["WarningDialog"];
                ContentDialogResult cdr = await warningNoPhotoBackup.ShowAsync();
            }
        }
Example #21
0
        public async void PrintList(string Type, List <string> list)//type是内容类型(history/practice)
        {
            string writingData = "";

            foreach (string piece in list)
            {
                writingData += piece + "\n";
            }


            FileSavePicker savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            // Dropdown of file types the user can save the file as
            savePicker.FileTypeChoices.Add("文本文件", new List <string>()
            {
                ".txt"
            });
            // Default file name if the user does not type one in or select a file to replace
            savePicker.SuggestedFileName = Type + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day;

            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                // Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
                CachedFileManager.DeferUpdates(file);
                // write to file
                await FileIO.WriteTextAsync(file, writingData);

                // Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
                // Completing updates may require Windows to ask for user input.
                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                if (status == FileUpdateStatus.Complete)
                {
                    //"File was saved."
                    ContentDialog SavedDialog = new ContentDialog
                    {
                        Title           = "已保存",
                        Content         = "已保存" + file.Path,
                        CloseButtonText = "好"
                    };

                    ContentDialogResult result = await SavedDialog.ShowAsync();
                }
                else
                {
                    //couldn't be saved.";
                    ContentDialog ErrorDialog = new ContentDialog
                    {
                        Title           = "无法保存",
                        Content         = "无法保存到" + file.Path,
                        CloseButtonText = "好"
                    };

                    ContentDialogResult result = await ErrorDialog.ShowAsync();
                }
            }
            else
            {
                ContentDialog CancelledDialog = new ContentDialog
                {
                    Title           = "已取消",
                    Content         = "操作已被取消",
                    CloseButtonText = "好"
                };

                ContentDialogResult result = await CancelledDialog.ShowAsync();
            }
        }
Example #22
0
 private async void AppBarButton_Tapped(object sender, TappedRoutedEventArgs e)
 {
     RoomViewModel.Room = new Room();
     RoomContentDialog   pd  = new RoomContentDialog(RoomViewModel);
     ContentDialogResult cdr = await pd.ShowAsync();
 }
Example #23
0
 public UserLogIn()
 {
     this.InitializeComponent();
     Result = ContentDialogResult.Nothing;
 }