Navigation when crating account

Eduardo Gomez 3,416 Reputation points
2023-02-08T16:00:27.8666667+00:00

I have my ViewModel for the main window, with the navigation

   public string UserId { get; set; }

        public Command SelectedPageCommand { get; set; }

        public NavButton? SelectedItem { get; set; }

        public MainWindowViewModel(string userID) {

            UserId = userID;

            SelectedPageCommand = new Command<ModernWpf.Controls.Frame>(PasgeSelectionItem);
        }

        private void PasgeSelectionItem(ModernWpf.Controls.Frame frame) {
            frame?.Navigate(SelectedItem?.NavLink);

            if (SelectedItem!.Name.Equals("CntactUS")) {
                SendEmail();
            }
            if (SelectedItem.Name.Equals("acc")) {
                if (!string.IsNullOrEmpty(UserId)) {
                    if (frame != null) {
                        frame.LoadCompleted += (sender, eventArgs) => {
                            if (eventArgs.Content is ProfilePage page) {
                                page.DataContext = new ProfilePageViewModel(UserId);
                            }
                        };
                        frame.Navigate(SelectedItem.NavLink);
                    }
                }
            }
        }

        private static void SendEmail() {

            var destinationurl = $"mailto:egomezr@outlook.com?Subject=IMPORTANT&body=";
            var sInfo = new ProcessStartInfo(destinationurl) {
                UseShellExecute = true,
                WindowStyle = ProcessWindowStyle.Minimized
            };
            Process.Start(sInfo);
        }

Everything works and I can navigate within my pages, but if I create an account for the first time, I cannot navigate.

So, the only way I can navigate is if I log in, in because if I just created an account, there is no navigation

demo:

https://reccloud.com/u/5uf192w

code:

https://github.com/eduardoagr/TranscribeMe

This bug is very stage
appStartup


        SyncfusionLicenseProvider.RegisterLicense(ConstantsHelpers.SYNCFUSION_KEY);

        _host = Host.CreateDefaultBuilder()
            .ConfigureServices((context, services) => {

                string? FireDomain = context.Configuration.GetValue<string>("FIREBASE_DOMAIN");
                string? FireKey = context.Configuration.GetValue<string>("FIREBASE_KEY");

                var config = new FirebaseAuthConfig {
                    ApiKey = FireKey,
                    AuthDomain = FireDomain,
                    Providers = new FirebaseAuthProvider[] {
                      new EmailProvider()
                    }
                };

                services.AddSingleton<IFirebaseAuthClient>(new FirebaseAuthClient(config));
                var serviceProvider = services.BuildServiceProvider();
                var firebaseAuthClient = serviceProvider.GetRequiredService<IFirebaseAuthClient>();
                if (firebaseAuthClient == null) {
                    throw new InvalidOperationException("IFirebaseAuthClient is not registered with the container.");
                }
                services.AddSingleton((services) => new SignUpLoginWondow(firebaseAuthClient));
                // Register another window
                services.AddSingleton((services) => new MainWindow());
            })
            .Build();
    }

    protected override void OnStartup(StartupEventArgs e) {

        if (LoginWithSavedData()) {
            MainWindow = _host.Services.GetRequiredService<MainWindow>();
        } else {
            MainWindow = _host.Services.GetRequiredService<SignUpLoginWondow>();
        }


        MainWindow.Show();
        base.OnStartup(e);
    }

    private static bool LoginWithSavedData() {
        string userDataFile = Path.Combine(
                        Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                        "userdata.json");

        if (File.Exists(userDataFile)) {
            var json = File.ReadAllText(userDataFile);
            var savedUser = JsonSerializer.Deserialize<UserData>(json);
            if (savedUser != null && !string.IsNullOrEmpty(savedUser.Object.Id)) {
                return true;
            }
        }

        return false;
    }

and this is my SignUp/login vm

   private async Task RegisterActionAsync() {

            try {
                isButtonVisible = Visibility.Collapsed;
                isBusy = true;
                var result = await _firebaseAuthClient.CreateUserWithEmailAndPasswordAsync
                    (User.Email, User.Password, User.Username);
                if (result.User != null) {

                    await GetGeoData();

                    var firebase = new FirebaseClient(
                        DatabaseURL);

                    var newUser =
                        await firebase.Child("Users").
                        PostAsync(
                            new LocalUser(result.User.Uid,
                            GetAge(User.DateOfBirth),
                            result.User.Info.DisplayName,
                            User.FirstName!,
                            User.LastName,
                            User.PhotoUrl,
                            result.User.Info.Email,
                            _currentCity?.address!.country,
                            _currentCity!.address!.city,
                            User.HasPaid, User.IsActive,
                            User.DateOfBirth,
                            new DateTime(),
                            new DateTime()));

                    // Add the password to the newUser object
                    newUser.Object.Password = User.Password;

                    // Save user data in a local file
                    string userDataFile = Path.Combine(
                        Environment.GetFolderPath(
                            Environment.SpecialFolder.LocalApplicationData),
                            "userdata.json");

                    File.WriteAllText(userDataFile, JsonSerializer.Serialize(newUser));

                    MainWindow mainWindow = new();
                    mainWindow.Show();
                    Application.Current.Windows[0].Close();

                }
            } catch (FirebaseAuthException ex) {
                await ExceptionAsync(ex);
            }
        }

        private async Task LoginAction() {

            try {
                isButtonVisible = Visibility.Collapsed;
                isBusy = true;
                var result = await _firebaseAuthClient.SignInWithEmailAndPasswordAsync(
                    User.Email, User.Password);
                if (result.User != null && !string.IsNullOrEmpty(result.User.Uid)) {

                    MainWindow mainWindow = new() {
                        DataContext = new MainWindowViewModel(result.User.Uid, DatabaseURL)
                    };
                    mainWindow.Show();
                    Application.Current.Windows[0].Close();
                }
            } catch (FirebaseAuthException ex) {
                await ExceptionAsync(ex);

            }
        }
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,671 questions
{count} votes

Accepted answer
  1. Peter Fleischer (former MVP) 19,231 Reputation points
    2023-02-10T06:01:20.9333333+00:00

    HI,
    I cannot reproduce your problem -> I delete my image, because now I can reproduce your problem with 6 letter password.

    In reproducing your problem, I found the cause. MainWindow has no DataContext (MainWindowVieModel instance).

    In RegisterLicense you create new MainWindow without DataContext. Try this:

                    services.AddSingleton((services) => new MainWindow() { DataContext=new MainWindowViewModel(null)});
    
    

0 additional answers

Sort by: Most helpful