Skip to content
This repository has been archived by the owner on Dec 21, 2024. It is now read-only.

Commit

Permalink
Several changes to nullability
Browse files Browse the repository at this point in the history
  • Loading branch information
StrangeRanger committed Mar 21, 2024
1 parent 4cb30dd commit 800adf0
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ private async Task LoadAvailableParametersCore(Command? psCommand, bool isAsync)
_availableParameters.Add("No valid command provided");
return;
}

if (_availableParameters.Count == 0)
{
using var powerShell = System.Management.Automation.PowerShell.Create();
Expand Down
111 changes: 49 additions & 62 deletions ActiveDirectoryQuerier/MainWindowViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ public sealed class MainWindowViewModel : INotifyPropertyChanged
// [ Properties ] --------------------------------------------------------------- //
// [[ Properties for backing fields ]] ------------------------------------------ //

public ObservableCollection<Button> QueryButtonStackPanel => _queryButtonStackPanel ??= new ObservableCollection<Button>();
public ObservableCollection<Button> QueryButtonStackPanel => _queryButtonStackPanel ??=
new ObservableCollection<Button>();

public ConsoleViewModel ConsoleViewModelOutputInQueryBuilder
{
Expand Down Expand Up @@ -100,8 +101,7 @@ public string QueryDescription
public Command? SelectedCommandInQueryBuilder
{
get => _selectedCommandInQueryBuilder;
set
{
set {
if (_selectedCommandInQueryBuilder != value)
{
_selectedCommandInQueryBuilder = value;
Expand Down Expand Up @@ -160,7 +160,7 @@ public bool IsQueryEditingEnabled

// [[ GUI element relays ]] ----------------------------------------------------- //
// [[[ Dynamically created elements ]]] ----------------------------------------- //

private ICommand EditQueryFromQueryStackPanelRelay { get; }
private ICommand DeleteQueryFromQueryStackPanelRelay { get; }
private ICommand ExecuteQueryFromQueryStackPanelRelay { get; }
Expand All @@ -180,7 +180,6 @@ public bool IsQueryEditingEnabled
public ICommand ClearConsoleOutputInQueryBuilderRelay { get; }
public ICommand ImportQueryFileRelay { get; }
public ICommand CreateNewQueryFileRelay { get; }
public ICommand ClearConsoleOutputInActiveDirectoryInfoRelay { get; }

// [ Constructor ] ------------------------------------------------------------- //

Expand Down Expand Up @@ -216,16 +215,14 @@ public MainWindowViewModel()
ExecuteQueryFromQueryStackPanelRelay = new RelayCommand(ExecuteQueryFromQueryStackPanel);
ClearConsoleOutputInQueryBuilderRelay = new RelayCommand(
_ => ClearConsoleOutput(_consoleOutputInQueryBuilder));
ClearConsoleOutputInActiveDirectoryInfoRelay = new RelayCommand(
_ => ClearConsoleOutput(_consoleOutputInActiveDirectoryInfo));
ClearQueryBuilderRelay = new RelayCommand(ClearQueryBuilder);

Task.Run(InitializeActiveDirectoryCommandsAsync);
LoadSavedQueriesFromFile(); // Calls method to deserialize and load buttons.
}

// [ Methods ] ----------------------------------------------------------------- //

/// <remarks>
/// The use of the <c>command</c> parameter indicates that the method can be called from the Query Stack Panel.
/// On the other hand, the absence of the <c>command</c> parameter and use of the
Expand All @@ -237,9 +234,9 @@ private async Task ExecuteQueryAsync(ConsoleViewModel consoleOutput, Command? co
{
Trace.WriteLine("No command selected.");
MessageBox.Show("To execute a command, you must first select a command.",
"Warning",
MessageBoxButton.OK,
MessageBoxImage.Warning);
"Warning",
MessageBoxButton.OK,
MessageBoxImage.Warning);
return;
}

Expand All @@ -252,9 +249,11 @@ private async Task ExecuteQueryAsync(ConsoleViewModel consoleOutput, Command? co
}
else
{
// Add selected parameters and their values to the command.
UpdateSelectedCommand();
result = await _psExecutor.ExecuteAsync(SelectedCommandInQueryBuilder);
UpdateCommandWithSelectedParameters();
// Null forgiveness operator is used because if command is not null, this line will never be reached.
// If it is null, that must mean that SelectedCommandInQueryBuilder is not null, else the return
// statement above would have been executed.
result = await _psExecutor.ExecuteAsync(SelectedCommandInQueryBuilder!);
}

if (result.HadErrors)
Expand All @@ -265,28 +264,28 @@ private async Task ExecuteQueryAsync(ConsoleViewModel consoleOutput, Command? co

consoleOutput.Append(result.StdOut);
}
catch (Exception ex)
catch (Exception exception)
{
consoleOutput.Append($"Error executing command: {ex.Message}" + ex.Message);
consoleOutput.Append($"Error executing command: {exception.Message}");
}
}

private void ClearConsoleOutput(ConsoleViewModel consoleOutput)
{
if (consoleOutput.ConsoleOutput.Length == 0)
{
MessageBox.Show("The console is already clear.",
"Information",
MessageBoxButton.OK,
MessageBoxImage.Information);
"Information",
MessageBoxButton.OK,
MessageBoxImage.Information);
return;
}

MessageBoxResult result = MessageBox.Show("Are you sure you want to clear the console output?",
"Warning",
MessageBoxButton.YesNo,
MessageBoxImage.Warning,
MessageBoxResult.No);
"Warning",
MessageBoxButton.YesNo,
MessageBoxImage.Warning,
MessageBoxResult.No);

if (result == MessageBoxResult.Yes)
{
Expand All @@ -306,18 +305,16 @@ private async void ExecuteSelectedQueryInADInfo(object _)
return;
}

string selectedOption = SelectedQueryInActiveDirectoryInfo;
if (_activeDirectoryInfo.AvailableOptions.TryGetValue(selectedOption, out var method))
if (_activeDirectoryInfo.AvailableOptions.TryGetValue(SelectedQueryInActiveDirectoryInfo, out var method))
{
PSOutput result = await method.Invoke();

ConsoleViewModelOutputInActiveDirectoryInfo.Append(result.HadErrors ? result.StdErr : result.StdOut);
}
// This is an internal error to ensure that if the selected option is not found, the program will not continue.
else
{
var errorMessage = "Internal Error: The selected option was not found in the dictionary: " +
$"{selectedOption}";
var errorMessage = "Internal Error: The selected option was not found in the dictionary: " +
$"{SelectedQueryInActiveDirectoryInfo}";
MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
throw new KeyNotFoundException("The selected option was not found in the dictionary.");
}
Expand All @@ -326,18 +323,17 @@ private async void ExecuteSelectedQueryInADInfo(object _)
private void EditQueryFromQueryStackPanel(object queryButton)
{
var currentQuery = (Query)((Button)queryButton).Tag;
Command chosenCommand = ADCommands.FirstOrDefault(item => item.CommandText == currentQuery.PSCommandName)!;
ADCommandParameters adCommandParameters = new();

_queryBeingEdited = currentQuery;
IsQueryEditingEnabled = true;
QueryName = currentQuery.QueryName;
QueryDescription = currentQuery.QueryDescription;

// Fill in the commandName
Command chosenCommand = ADCommands.FirstOrDefault(item => item.CommandText == currentQuery.PSCommandName)!;
SelectedCommandInQueryBuilder = chosenCommand;

// Load the Possible Parameters Synchronously
ADCommandParameters adCommandParameters = new();
adCommandParameters.LoadAvailableParameters(SelectedCommandInQueryBuilder);
AvailableADCommandParameters = new ObservableCollection<string>(adCommandParameters.AvailableParameters);
OnPropertyChanged(nameof(AvailableADCommandParameters));
Expand All @@ -349,7 +345,6 @@ private void EditQueryFromQueryStackPanel(object queryButton)
DynamicallyAvailableADCommandParameterValueTextBoxes.Clear();
}

// TODO: Fix nullability warning.
// Fill in Parameters and values
for (var i = 0; i < currentQuery.PSCommandParameters.Length; i++)
{
Expand Down Expand Up @@ -485,7 +480,7 @@ private async Task LoadCommandParametersAsync(Command? selectedCommand)

// Update the possible properties of the ComboBoxParameterViewModels.
foreach (ComboBoxParameterViewModel comboBoxParameterViewModel in
DynamicallyAvailableADCommandParameterComboBoxes)
DynamicallyAvailableADCommandParameterComboBoxes)
{
comboBoxParameterViewModel.AvailableParameters = AvailableADCommandParameters;
}
Expand Down Expand Up @@ -614,11 +609,8 @@ private void ExportConsoleOutputToFile(object _)
ConsoleViewModelOutputInQueryBuilder.ExportToTextFile(filename);
}
}

/// <summary>
/// This method is for getting the currently selected command at anytime
/// </summary>
private void UpdateSelectedCommand()

private void UpdateCommandWithSelectedParameters()
{
if (SelectedCommandInQueryBuilder is null)
{
Expand All @@ -629,21 +621,14 @@ private void UpdateSelectedCommand()
MessageBoxImage.Warning);
return;
}

// Try to get the content within the drop downs
try
{
SelectedCommandInQueryBuilder.Parameters.Clear();
for (int i = 0; i < DynamicallyAvailableADCommandParameterComboBoxes.Count; i++)
{
SelectedCommandInQueryBuilder.Parameters.Add(
new CommandParameter(DynamicallyAvailableADCommandParameterComboBoxes[i].SelectedParameter,
DynamicallyAvailableADCommandParameterValueTextBoxes[i].SelectedParameterValue));
}
}
catch (Exception ex)

SelectedCommandInQueryBuilder.Parameters.Clear();
// Loop through the ComboBoxes and add the selected parameters to the command.
for (var i = 0; i < DynamicallyAvailableADCommandParameterComboBoxes.Count; i++)
{
Console.Write(ex);
SelectedCommandInQueryBuilder.Parameters.Add(new CommandParameter(
DynamicallyAvailableADCommandParameterComboBoxes[i].SelectedParameter,
DynamicallyAvailableADCommandParameterValueTextBoxes[i].SelectedParameterValue));
}
}

Expand All @@ -652,7 +637,7 @@ private void UpdateSelectedCommand()
/// </summary>
private void GetCurrentQuery()
{
UpdateSelectedCommand();
UpdateCommandWithSelectedParameters();

if (SelectedCommandInQueryBuilder?.Parameters == null)
{
Expand Down Expand Up @@ -721,7 +706,7 @@ private void SaveCurrentQuery(object commandParameter)
// Try to get the content within the drop downs
try
{
UpdateSelectedCommand();
UpdateCommandWithSelectedParameters();

_queryManager.ConvertCommandToQueryAndSave(SelectedCommandInQueryBuilder, QueryName, QueryDescription);

Expand Down Expand Up @@ -757,8 +742,8 @@ private void ClearQueryBuilder(object _)
// If the user selects yes, clear the consoleOutput
if (result == MessageBoxResult.Yes)
{
QueryName = "";
QueryDescription = "";
QueryName = string.Empty;
QueryDescription = string.Empty;
SelectedCommandInQueryBuilder = null;
DynamicallyAvailableADCommandParameterComboBoxes.Clear();
DynamicallyAvailableADCommandParameterValueTextBoxes.Clear();
Expand Down Expand Up @@ -799,10 +784,12 @@ private Button CreateQueryButtonInStackPanel(Query? query = null)
MenuItem menuItem1 =
new() { Header = "Execute", Command = ExecuteQueryFromQueryStackPanelRelay, CommandParameter = newButton };

MenuItem outputToCsv =
new() { Header = "Output to CSV", Command = OutputExecutionResultsToCsvFileRelay, CommandParameter = newButton };
MenuItem outputToText =
new() { Header = "Output to Text", Command = OutputExecutionResultsToTextFileRelay, CommandParameter = newButton };
MenuItem outputToCsv = new() { Header = "Output to CSV",
Command = OutputExecutionResultsToCsvFileRelay,
CommandParameter = newButton };
MenuItem outputToText = new() { Header = "Output to Text",
Command = OutputExecutionResultsToTextFileRelay,
CommandParameter = newButton };
MenuItem outputToConsole = new() { Header = "Execute to Console",
Command = ExecuteQueryFromQueryStackPanelRelay,
CommandParameter = newButton };
Expand Down
6 changes: 3 additions & 3 deletions ActiveDirectoryQuerier/Queries/Query.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ public class Query
/// Used for Serializing the Commands parameters
/// </summary>
// ReSharper disable once InconsistentNaming
public string[]? PSCommandParameters { get; set; }
public string[] PSCommandParameters { get; set; } = Array.Empty<string>();

/// <summary>
/// Used for Serializing the Commands parameters
/// </summary>
// ReSharper disable once InconsistentNaming
public string[]? PSCommandParameterValues { get; set; }
public string[] PSCommandParameterValues { get; set; } = Array.Empty<string>();

/// <summary>
/// Command that should help with Binding the command to the query for the buttons sake
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion ActiveDirectoryQuerier/ViewModels/ConsoleViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public void Append(IEnumerable<string> outputText)
// TODO: Add a newline character to the end of the outputText.
ConsoleOutput += string.Join(Environment.NewLine, outputText);
}

public void Append(string outputText)
{
// TODO: Add a newline character to the end of the outputText.
Expand Down
4 changes: 2 additions & 2 deletions ActiveDirectoryQuerier/ViewModels/TextBoxViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ namespace ActiveDirectoryQuerier.ViewModels;
public sealed class TextBoxViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
private string? _selectedParameterValue;
private string _selectedParameterValue = string.Empty;

public string? SelectedParameterValue
public string SelectedParameterValue
{
get => _selectedParameterValue;
set {
Expand Down

0 comments on commit 800adf0

Please sign in to comment.