using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tango.Console; using Tango.Console.Network; using Tango.Core.DI; using Tango.FSE.Common; using Tango.FSE.Common.Console; using Tango.Transport; namespace Tango.FSE.PPCConsole.ViewModels { /// /// Represents the command prompt console view model. /// /// public class ConsoleViewVM : FSEViewModel { private List _lastSuggestions; /// /// Gets or sets the console provider. /// [TangoInject] public IConsolProvider ConsoleProvider { get; set; } private ConsoleControlVM _consoleVM; /// /// Gets or sets the console control view model. /// public ConsoleControlVM ConsoleVM { get { return _consoleVM; } set { _consoleVM = value; RaisePropertyChangedAuto(); } } private int _timeout; /// /// Gets or sets the command timeout. /// public int Timeout { get { return _timeout; } set { _timeout = value; RaisePropertyChangedAuto(); } } private bool _runAsAdministrator; /// /// Gets or sets a value indicating whether to run the next command as an administrator. /// public bool RunAsAdministrator { get { return _runAsAdministrator; } set { _runAsAdministrator = value; RaisePropertyChangedAuto(); } } /// /// Initializes a new instance of the class. /// public ConsoleViewVM() { _lastSuggestions = new List(); ConsoleVM = new ConsoleControlVM(); ConsoleVM.CommandExecuting += ConsoleVM_CommandExecuting; ConsoleVM.Clear(); Timeout = 30; } /// /// Called when the application has been started. /// public override void OnApplicationStarted() { ConsoleProvider.Initialized += ConsoleService_Initialized; } private void ConsoleService_Initialized(object sender, GetCurrentDirectoryResponse e) { ConsoleVM.Clear(); ConsoleVM.CurrentCommand.WorkingFolder = e.CurrentDirectory; ConsoleVM.AppendSuggestions(e.Suggestions); } private async void ConsoleVM_CommandExecuting(object sender, ConsoleCommandExecutingEventArgs e) { try { var response = await ConsoleProvider.ExecuteCommand(new ConsoleCommandRequest() { Command = e.Command.CommandText, WorkingFolder = e.Command.WorkingFolder, RunAsAdministrator = RunAsAdministrator }, TimeSpan.FromSeconds(Timeout)); _lastSuggestions = response.Suggestions; e.Complete(new ConsoleCommandExecutionResult() { Output = response.Output, Suggestions = response.Suggestions, WorkingFolder = response.WorkingFolder }); } catch (TransporterDisconnectedException) { e.Complete(new ConsoleCommandExecutionResult() { Output = "Please connect to a machine before attempting to execute a command.", WorkingFolder = e.Command.WorkingFolder, Suggestions = _lastSuggestions }); } catch (Exception ex) { e.Complete(new ConsoleCommandExecutionResult() { Output = ex.FlattenMessage(), WorkingFolder = e.Command.WorkingFolder, Suggestions = _lastSuggestions }); } } } }