open MainWindow after auth?

JasonMcMahan

New member
Joined
Sep 12, 2023
Messages
3
Programming Experience
Beginner
Good day, I am extremely new to programming in general as i started as an admin and moved into scripting with powershell, some python and bash.
I recently am in process trying to learn to create a wpf. This will be a gui front end using cloud foundry cli to connect, authenticate, and perform specific tasks that are not available within the gui.
The LogonWindow works as expected, opening at start, accepting user credentials and region information, but once authenticated it should open MainWindow with a listbox that is populated from the available organizations. I see the list populated but the MainWindow is never loaded, and i dont see any errors.
MainWindow.xaml
MainWindow.xaml:
<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:BtpAdmin"
        xmlns:vm="clr-namespace:BtpAdmin"
        xmlns:av="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="av" x:Class="BtpAdmin.MainWindow"
        Title="MainWindow" Height="450" Width="600" Background="#FFF6E705">
    <Grid>
        <Label x:Name="lblCurrenStatus" Content="Status:" HorizontalAlignment="Left"
               Margin="10,18,0,0"  VerticalAlignment="Top" Height="34" Width="72"
               FontSize="14" RenderTransformOrigin="3.893,5.368"
               Background="{x:Null}"/>
        <ListBox x:Name="orgListBox" SelectionChanged="OrgListBox_SelectionChanged"
                 Margin="10,155,343,95" av:ItemsSource="{av:SampleData ItemCount=5}"/>
    </Grid>
</Window>

MainWindow.xaml.cs:
using BtpAdmin.CloudFoundry;
using BtpAdmin.Views;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BtpAdmin
{
    public partial class MainWindow : Window
    {
        private List<string> _availableOrgs;
        private Process _cfProcess;

        public MainWindow(List<string> availableOrgs, Process cfProcess)
        {
            InitializeComponent();
            Debug.WriteLine("MainWindow initialized"); // Add debug message

            _availableOrgs = availableOrgs;
            _cfProcess = cfProcess; // Store the provided cfProcess

            // Populate the orgListBox when the MainWindow is loaded
            //Loaded += MainWindow_Loaded;

            Debug.WriteLine("MainWindow Loaded event subscribed"); // Add debug message
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("MainWindow_Loaded event handler called"); // Add debug message

            // Populate the orgListBox with available organizations
            PopulateOrgsListBox(_availableOrgs);

            Debug.WriteLine("orgListBox populated"); // Add debug message
        }


        public void PopulateOrgsListBox(List<string> orgs)
        {
            orgListBox.Items.Clear();
            foreach (string org in orgs)
            {
                orgListBox.Items.Add(org);
            }
        }

        private void OrgListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (orgListBox.SelectedItem != null)
            {
                string selectedOrg = orgListBox.SelectedItem.ToString();

                // Execute the 'cf target -o organization' command using the existing _cfProcess
                string command = $"target -o {selectedOrg}";
                string commandOutput = CloudFoundryApi.ExecuteCommand(_cfProcess, command);

            }
        }
    }
}
App.xaml.cs:
using BtpAdmin.CloudFoundry;
using BtpAdmin.Views;
using System;
using System.ComponentModel;
using System.IO;
using System.Security;
using System.Diagnostics;
using System.Windows;
using System.Collections.Generic;

namespace BtpAdmin
{
    public partial class App : Application
    {
        public static Process CfProcess { get; private set; } // Declare a static property to store the cfProcess instance

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            LogonWindow logonWindow = new LogonWindow();
            logonWindow.CenterWindowOnActiveScreen();
            if (logonWindow.ShowDialog() != true)
            {
                // User canceled logon
                Shutdown();
                return;
            }

            if (logonWindow.EnteredPassword != null)
            {
                string cfExePath = CloudFoundryApi.FindCFExePath();
                if (!string.IsNullOrEmpty(cfExePath) && File.Exists(cfExePath))
                {
                    if (CloudFoundryApi.IsCFInstalled(cfExePath))
                    {
                        // Create a Cloud Foundry process for the application's lifecycle
                        CfProcess = CloudFoundryApi.StartCFLoginProcess(cfExePath, logonWindow.ApiEndPoint, logonWindow.Username, ConvertToString(logonWindow.EnteredPassword));
                        CfProcess.StartInfo.RedirectStandardOutput = true;
                        CfProcess.StartInfo.RedirectStandardError = true;
                        string output = CfProcess.StandardOutput.ReadToEnd();
                        string errorOutput = CfProcess.StandardError.ReadToEnd();
                        CfProcess.WaitForExit();

                        if (CfProcess.ExitCode == 0) // Check if login was successful
                        {
                            // Reuse the same CfProcess for 'cf orgs'
                            CfProcess.StartInfo.FileName = cfExePath;
                            CfProcess.StartInfo.Arguments = "orgs";
                            CfProcess.StartInfo.RedirectStandardOutput = true;
                            CfProcess.StartInfo.UseShellExecute = false;
                            CfProcess.StartInfo.CreateNoWindow = true; // Hide the command window
                            CfProcess.Start();

                            // Read the output of 'cf orgs' process
                            string orgsOutput = CfProcess.StandardOutput.ReadToEnd();
                            CfProcess.WaitForExit();

                            // Process the 'cf orgs' output and display it in your UI
                            List<string> availableOrgs = CloudFoundryApi.ParseOrgsFromOutput(orgsOutput);

                            // Open the MainWindow and pass the availableOrgs list
                            MainWindow mainWindow = new MainWindow(availableOrgs, CfProcess);
                            mainWindow.Show();
                        }
                        else
                        {
                            MessageBox.Show("Login to CF CLI failed. Please check your credentials.");
                            Shutdown();
                        }
                    }
                    else
                    {
                        MessageBox.Show("CF CLI is not installed. Please install it before using the application.");
                        Shutdown();
                    }
                }
                else
                {
                    MessageBox.Show("CF CLI executable not found or invalid path. Please check your installation.");
                    Shutdown();
                }
            }
            else
            {
                // Handle case where password is null
                MessageBox.Show("Password cannot be null. Please enter a valid password.");
                Shutdown();
            }
        }


        private string ConvertToString(SecureString secureString)
        {
            IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(secureString);
            try
            {
                return System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
            }
        }
    }
}


Any help or suggestions to figure out why the window is not loading, nothing in debug shows any issues or errors that i can see.
Its just like it PopulateOrgsListBox(_availableOrgs); then goes through the logic without ever displaying MainWindow.

Thank you
 
How did you determine that the correct way to override the main window with your login window before showing the main window should be done by overriding the OnStartUp() method? How did you determine that instantiating the main window and calling Show() would do the right thing?
 
How did you determine that the correct way to override the main window with your login window before showing the main window should be done by overriding the OnStartUp() method? How did you determine that instantiating the main window and calling Show() would do the right thing?
I started working on this project by googling what i could, using chatgpt for reference and dev co-workers when able.
I even was able to get a dev lead to give what i have thus far a look over and he wasnt sure what was going on but couldn't look overly in depth.

Thank you for the reply and any help suggestion would be appreciated because i see nothing in debug, or errors and am quite lost.
 
I know this has been awhile, but is there any chance someone may feel giving during this season and have suggestion or ideas for me to try and move this further? THank you for any help or suggestions.
 
Do you know how to use breakpoints for debugging? You could set breakpoints to determine if something is executed. You have many Debug.WriteLine calls and that is good, usually they can be used for determining if execution reaches code. Breakpoints have the additional benefit of being able to single-step through the execution.

Do you get the Debug.WriteLine saying MainWindow initialized? What other messages do you get?

Is there any possibility that the user(s) will want to logout and login with different credentials? If so then the application can go directly to the main window then show a login form from there.

I think people will need more information to be able to help you.

Something I would do, and please believe me, I do this type of thing often for my projects, I would create another project that only has the code that duplicates the problem. Then if I cannot solve the problem myself, I can post just the minimum amount of code to show the problem. I am doing that now with a problem I have.
 

Latest posts

Back
Top Bottom