private static void DisplayErrorMessageAndExit(string errorMessage, ExitCode errorCode) { Console.WriteLine(Environment.NewLine); Console.WriteLine(String.Format("* ERROR: {0}", errorMessage)); _logger.Error(errorMessage); Environment.Exit((int) errorCode); }
private void TestSqlServer(string regPath, string serviceName, string serverName) { var registryValue = (string)Registry.GetValue(regPath, "", ""); if (registryValue == null) { Output.WriteError(string.Format("The {0} is not installed", serverName)); exitCode = ExitCode.FAIL; } else { ServiceControllerExt sc = new ServiceControllerExt(serviceName); if (sc.Status != System.ServiceProcess.ServiceControllerStatus.Stopped) { Output.WriteError(string.Format("The {0} service {1} is running.", serverName, serviceName)); exitCode = ExitCode.FAIL; } if (sc.GetStartupType().ToLower() != "disabled") { Output.WriteError(string.Format("The {0} service {1} is not disabled.", serverName, serviceName)); exitCode = ExitCode.FAIL; } } }
public void Run() { Output.WriteDebug("Checking Uhuru Prison users existence"); Prison.Prison[] prisonUsers = Prison.Prison.Load(); List<string> notExistingUsers = new List<string>(); Output.WriteDebug(string.Format("Found {0} prison users on the system", prisonUsers.Count())); foreach (var prisonUser in prisonUsers) { Output.WriteDebug(string.Format("Testing user {0}", prisonUser.User.Username)); using (PrincipalContext principalContext = new PrincipalContext(ContextType.Machine)) { UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, prisonUser.User.Username); if (userPrincipal == null) { notExistingUsers.Add(prisonUser.User.Username); Output.WriteDebug(string.Format("User {0} does not exist on the system", prisonUser.User.Username)); } } } if (notExistingUsers.Count > 0) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("The following prison users do not exist on the local system"); stringBuilder.AppendLine(String.Join(", ", notExistingUsers)); Output.WriteWarn(stringBuilder.ToString()); exitCode = ExitCode.WARNING; } }
public void Run() { Output.WriteDebug("Testing local user consistency"); List<string> localUsers = GetLocalUsers(); Output.WriteDebug(string.Format("Found {0} local users", localUsers.Count)); Prison.Prison[] prisonUsers = Prison.Prison.Load(); List<string> usersNotInPrison = new List<string>(); foreach (string localUser in localUsers) { if (!localUser.StartsWith("prison_")) { //Skipping non prison users continue; } Output.WriteDebug(string.Format("Testing local user {0}", localUser)); if (prisonUsers.Where(p => p.User.Username == localUser).Count() ==0) { usersNotInPrison.Add(localUser); } } if (usersNotInPrison.Count > 0) { StringBuilder sb = new StringBuilder(); sb.AppendLine("The following user(s)"); sb.AppendLine(String.Join(", ", usersNotInPrison)); sb.AppendLine("exists on the local system but there is no prison associated to them"); Output.WriteWarn(sb.ToString()); exitcode = ExitCode.WARNING; } }
public void Run() { Output.WriteDebug("Testing if firewall is enabled"); Type netFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false); INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(netFwMgrType); bool firewallEnabled = mgr.LocalPolicy.CurrentProfile.FirewallEnabled; if (!firewallEnabled) { Output.WriteWarn("The windows firewall is disabled on the local machine"); exitCode = ExitCode.WARNING; return; } Output.WriteDebug("Testing if ssh port is opened"); CheckRule(SSHDFWRULENAME, 22); Output.WriteDebug("Testing prison firewall rules"); Prison.Prison[] prisonUsers = Prison.Prison.Load(); foreach (var prisonUser in prisonUsers) { string firewallRuleName = prisonUser.ID.ToString().TrimStart('0').Replace("-", ""); Output.WriteDebug(string.Format("Testing firewall for user {0}", firewallRuleName)); int firewallPort = prisonUser.Rules.UrlPortAccess; CheckRule(firewallRuleName, firewallPort); } }
private void CheckRule(string ruleName, int port) { string output = string.Empty; Type netFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2", false); INetFwPolicy2 fwpol = (INetFwPolicy2)Activator.CreateInstance(netFwPolicy2); try { INetFwRule rule = fwpol.Rules.Item(ruleName); string localPort = rule.LocalPorts; if (localPort != port.ToString()) { StringBuilder sb = new StringBuilder(); sb.AppendLine(string.Format("Incorrect Local Port setup for rule {0}", ruleName)); sb.AppendLine(string.Format("Expected {0} but is {1}", port, localPort)); output = sb.ToString(); } } catch (FileNotFoundException) { output = string.Format("Rule {0} does not exist", ruleName); } if (!string.IsNullOrEmpty(output)) { Output.WriteWarn(output); exitCode = ExitCode.WARNING; } }
public void Run() { Output.WriteDebug("Checking that required services are running now"); List<string> missingServices = new List<string>(); List<string> stoppedServices = new List<string>(); List<string> noBoot = new List<string>(); foreach (string serviceName in SERVICES) { ServiceControllerExt sc = new ServiceControllerExt(serviceName); try { if (sc.Status != ServiceControllerStatus.Running) { stoppedServices.Add(serviceName); } if (sc.GetStartupType().ToLower() != "auto") { noBoot.Add(serviceName); } } catch (InvalidOperationException) { missingServices.Add(serviceName); } } if (missingServices.Count != 0) { StringBuilder sb = new StringBuilder(); sb.AppendLine("The following service(s) are missing:"); sb.AppendLine(String.Join(", ", missingServices.ToArray())); sb.AppendLine("These services are required for OpenShift functionality."); Output.WriteFail(sb.ToString()); exitCode = ExitCode.FAIL; } if (stoppedServices.Count != 0) { StringBuilder sb = new StringBuilder(); sb.AppendLine("The following service(s) are stopped:"); sb.AppendLine(String.Join(", ", stoppedServices.ToArray())); sb.AppendLine("These services are required for OpenShift functionality."); Output.WriteFail(sb.ToString()); exitCode = ExitCode.FAIL; } if (noBoot.Count != 0) { StringBuilder sb = new StringBuilder(); sb.AppendLine("The following service(s) are not started at boot time:"); sb.AppendLine(String.Join(", ", noBoot.ToArray())); sb.AppendLine("These services are required for OpenShift functionality."); sb.AppendLine("Please ensure that they start at boot."); Output.WriteFail(sb.ToString()); exitCode = ExitCode.FAIL; } }
public void Run() { List<string> usersNotInPrison = new List<string>(); List<string> usersWithNoGears = new List<string>(); Output.WriteDebug("Checking cygwing passwd file consistency"); NodeConfig nodeConfig = new NodeConfig(); Etc etc = new Etc(nodeConfig); EtcUser[] etcUsers = etc.GetAllUsers(); Output.WriteDebug(string.Format("Found {0} Etc Users", etcUsers)); Prison.Prison[] prisons = Prison.Prison.Load(); Output.WriteDebug(string.Format("Found {0} Prison Users", prisons.Count())); List<ApplicationContainer> gears = ApplicationContainer.All(null, false).ToList<ApplicationContainer>(); Output.WriteDebug(string.Format("Found {0} gears", gears.Count())); foreach (EtcUser etcUser in etcUsers) { Output.WriteDebug(string.Format("Checking user {0}", etcUser.Name)); if (etcUser.Name == "administrator") { //skipping administrator user continue; } if (prisons.Where(p => p.ID.ToString().TrimStart('0').Replace("-", "") == etcUser.Name).Count() == 0) { usersNotInPrison.Add(etcUser.Name); } if (gears.Where(g => g.Uuid == etcUser.Name).Count() == 0) { usersWithNoGears.Add(etcUser.Name); } } if (usersNotInPrison.Count > 0) { StringBuilder sb = new StringBuilder(); sb.AppendLine("The following users exist in /etc/passwd"); sb.AppendLine(String.Join(", ", usersNotInPrison.ToArray())); sb.AppendLine("but have no prison user associated to them"); Output.WriteWarn(sb.ToString()); exitCode = ExitCode.WARNING; } if (usersWithNoGears.Count > 0) { StringBuilder sb = new StringBuilder(); sb.AppendLine("The following users exist in /etc/passwd"); sb.AppendLine(String.Join(", ", usersWithNoGears.ToArray())); sb.AppendLine("but have no gears associated to them"); Output.WriteWarn(sb.ToString()); exitCode = ExitCode.WARNING; } }
//************************************************************************* // Constructor: SaveGraphToNodeXLWorkbookException() // /// <summary> /// Initializes a new instance of the <see /// cref="SaveGraphToNodeXLWorkbookException" /> class. /// </summary> /// /// <param name="exitCode"> /// The program exit code to use. /// </param> /// /// <param name="message"> /// Error message, suitable for displaying to the user. /// </param> //************************************************************************* public SaveGraphToNodeXLWorkbookException ( ExitCode exitCode, String message ) : base(message) { m_eExitCode = exitCode; AssertValid(); }
public static void Exit(ExitCode exitCode, string reason) { if (!_initialized) throw new InvalidOperationException("Application should be initialized before exiting"); //Ensure.NotNullOrEmpty(reason, "reason"); Log.Info("Exiting..."); Log.Info("Exit reason : {0}", reason); LogManager.Finish(); _exit((int)exitCode); }
internal ExitCode Run() { ProgramAction action; this.ExitCode = ExitCode.InvalidArguments; this.LoadArguments(); if (!_noLogo) { this.WriteHeader(); } action = this.DefineAction(); if (action == ProgramAction.None) { Console.WriteLine("At least one key to snapsnot or two files to compare must be specified."); } else { #if CATCHEXCEPTIONS try #endif { switch (action) { case ProgramAction.Snapshot: this.TakeSnapshot(); break; case ProgramAction.Compare: this.CompareSnapshots(); break; default: throw new ArgumentOutOfRangeException(); } } #if !CATCHEXCEPTIONS try { } #endif catch (Exception ex) { this.ExitCode = ExitCode.Exception; Console.Error.Write(ex.ToString()); } } return this.ExitCode; }
public static int ExitWithMessage(ExitCode exitCode, string stderr, string stdout = null) { if (stdout != null) Console.WriteLine(stdout); if(stderr != null) { if(exitCode == ExitCode.OK) log.InfoFormat(stderr); else log.ErrorFormat(stderr); } return (int)exitCode; }
static void CrashAndBurn(ExitCode code, string crashMessage, params object[] args) { // Preserve the foreground color var c = Console.ForegroundColor; // Write out our error message in bright red text Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("ERROR: " + crashMessage, args); // Restore the foreground color Console.ForegroundColor = c; // Die! Environment.Exit((int)code); }
public void Run() { Output.WriteDebug("Checking that the broker hostname resolves"); string brokerHostname = Helpers.GetNodeConfig().Get("BROKER_HOST"); try { IPHostEntry iphostEntry = Dns.GetHostEntry(brokerHostname); } catch (SocketException) { Output.WriteFail( string.Format("Broker hostname {0} is not resolved",brokerHostname)); exitCode = ExitCode.FAIL; } }
public void Run() { Output.WriteDebug("Checking Active MQ"); Config srvConfig = Helpers.GetMcollectiveSrvConfig(); string activemqHost = srvConfig.Get("plugin.activemq.pool.1.host"); string activemqPort = srvConfig.Get("plugin.activemq.pool.1.port"); TcpClient client = new TcpClient(); try { client.Connect(activemqHost, int.Parse(activemqPort)); } catch (SocketException) { Output.WriteFail(string.Format("Could not establish TCP connection to Active MQ server at {0}:{1}", activemqHost, activemqPort)); exitCode = ExitCode.FAIL; } }
public void Run() { Output.WriteDebug("Checking that required scheduled tasks exist"); List<string> notFoundTasks = new List<string>(); foreach (string task in TASKS) { try { ProcessResult result = ProcessExtensions.RunCommandAndGetOutput("PowerShell.exe", string.Format("Get-ScheduledTask -Taskname {0}", task), null); if (result.StdErr.Trim() != string.Empty) { notFoundTasks.Add(task); } } catch (Win32Exception) { notFoundTasks.Add(task); } } if (notFoundTasks.Count > 0) { StringBuilder sb = new StringBuilder(); sb.AppendLine("The following task(s) are missing:"); sb.AppendLine(String.Join(", ", notFoundTasks.ToArray())); sb.AppendLine("These tasks are required for OpenShift functionality."); Output.WriteFail(sb.ToString()); exitCode = ExitCode.FAIL; } }
private void Stop(ExitCode code) { Stop((int)code); }
void IProcessListener.OnExitCode(ExitCode exitCode) { }
static int exit(ExitCode code) { Console.Read(); // prevent closing the terminal return (int)code; }
static void Exit(ExitCode result) { L.Close(); Environment.Exit((int)result); }
private void Shutdown(ExitCode exitCode) { Shutdown((int)exitCode); }
public void When_I_run_the_create_site_command_with_path_that_already_exists() { exitCode = entryPoint.Run(new string[] { "create", "site", pathThatAlreadyExists }); }
private void PerformAction(Action action, string message) { Console.Write(message); Console.Write("... "); #if CATCHEXCEPTIONS try #endif { action(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Done"); } #if !CATCHEXCEPTIONS try { } #endif catch (Exception ex) { this.ExitCode = ExitCode.Exception; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Failed"); Console.WriteLine(ex.ToString()); } finally { Console.ResetColor(); } }
static void Main(string[] args) { // Bomb out here if the invoker failed to provide arguments if (args.Length == 0) { ShowHelp(); Environment.Exit((int)ExitCode.InvalidArguments); } // Initialise OLE if (OleInitialize(IntPtr.Zero) != 0) { Environment.Exit((int)ExitCode.OleError); } _unregister = false; _silent = false; // Process each argument available ExitCode exitResult = ExitCode.Load_Failed; foreach (var arg in args) { // Support - and / prefixes if (arg.Contains('-') || arg.Contains('/')) { switch (arg) { case "-s": _silent = true; break; case "-u": _unregister = true; break; } continue; } var modulePath = arg; if (File.Exists(modulePath) == false) { ShowResult(ExitCode.Load_Failed); OleUninitialize(); Environment.Exit((int)ExitCode.Load_Failed); } if (_unregister) { exitResult = UnRegister(modulePath); } else { exitResult = Register(modulePath); } ShowResult(exitResult); if (exitResult != ExitCode.Success) { OleUninitialize(); Environment.Exit((int)exitResult); } } // Clean up and report error code OleUninitialize(); Environment.Exit((int)exitResult); }
private static int Main() { if (CommandLine.ContainParameter("breakintodebugger")) { #if NETFRAMEWORK if (Environment.OSVersion.Platform == PlatformID.Win32NT) { System.Windows.Forms.MessageBox.Show("Debugger requested. Please attach a debugger and press OK"); } else #endif { Console.WriteLine("Debugger requested. Please attach a debugger and press ENTER to continue"); while (Console.ReadKey(true).Key != ConsoleKey.Enter) { Console.WriteLine("Press ENTER to continue"); } } Debugger.Break(); } // This GC gives a little bit better results than the other ones. "LowLatency" is giving really bad results(twice slower than the other ones). System.Runtime.GCSettings.LatencyMode = System.Runtime.GCLatencyMode.SustainedLowLatency; AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += AppDomain_UnhandledException; Mutex oneInstanceMutex = null; Argument parameters = new Argument(); ExitCode exitCode = ExitCode.Success; try { DebugEnable = CommandLine.ContainParameter("verbose") || CommandLine.ContainParameter("debug") || CommandLine.ContainParameter("diagnostics"); var sharpmakeAssembly = Assembly.GetExecutingAssembly(); Version version = sharpmakeAssembly.GetName().Version; string versionString = string.Join(".", version.Major, version.Minor, version.Build); string informationalVersion = sharpmakeAssembly.GetCustomAttribute <AssemblyInformationalVersionAttribute>()?.InformationalVersion; if (version.Revision != 0 || (informationalVersion != null && informationalVersion.IndexOf("+Branch.") == -1)) { versionString += " (non-official)"; if (DebugEnable && informationalVersion != null) { versionString += " " + informationalVersion; } } LogWriteLine($"sharpmake {versionString}"); LogWriteLine(" arguments: {0}", CommandLine.GetProgramCommandLine()); LogWriteLine(" directory: {0}", Directory.GetCurrentDirectory()); LogWriteLine(" platform: {0} - {1}", Util.GetExecutingPlatform().ToString(), RuntimeInformation.OSDescription); LogWriteLine(" compiled with framework: {0}", Util.FrameworkDisplayName()); LogWriteLine(" running on framework: {0}", RuntimeInformation.FrameworkDescription); LogWriteLine(string.Empty); // display help if wanted and quit if ((CommandLine.GetProgramCommandLine().Length == 0) || CommandLine.ContainParameter("help")) { LogWriteLine(CommandLine.GetCommandLineHelp(typeof(Argument), false)); return(CommandLine.ContainParameter("help") ? (int)ExitCode.Success : (int)ExitCode.Error); } AppDomain.CurrentDomain.AssemblyLoad += AppDomain_AssemblyLoad; // Log warnings and errors from builder Assembler.EventOutputError += ErrorWrite; Assembler.EventOutputWarning += WarningWrite; CommandLine.ExecuteOnObject(parameters); if (parameters.Exit) { return((int)ExitCode.Success); } const string sharpmakeSymbolPrefix = "_SHARPMAKE"; List <string> invalidSymbols = parameters.Defines.Where(define => define.StartsWith(sharpmakeSymbolPrefix)).ToList(); if (invalidSymbols.Any()) { string invalidSymbolsString = string.Join(", ", invalidSymbols); throw new Error($"Only Sharpmake process can define symbols starting with {sharpmakeSymbolPrefix}. Invalid symbols defined: {invalidSymbolsString}"); } parameters.Defines.Add(sharpmakeSymbolPrefix); // A generic sharpmake define to allow scripts to exclude part of code if not used with sharpmake parameters.Defines.Add($"{sharpmakeSymbolPrefix}_{version.Major}_{version.Minor}_X"); parameters.Defines.Add($"{sharpmakeSymbolPrefix}_{version.Major}_{version.Minor}_{version.Build}"); parameters.Validate(); // CommonPlatforms.dll is always loaded by default because those are shipped with // the Sharpmake package. PlatformRegistry.RegisterExtensionAssembly(typeof(Windows.Win32Platform).Assembly); // If any platform declares its own command line options, execute and validate // them as well. IEnumerable <Platform> platformsCmdLines = PlatformRegistry.GetAvailablePlatforms <ICommandLineInterface>(); foreach (var platform in platformsCmdLines) { var platformCmdLine = PlatformRegistry.Get <ICommandLineInterface>(platform); CommandLine.ExecuteOnObject(platformCmdLine); platformCmdLine.Validate(); } bool oneInstanceMutexCreated; string mutexName = string.Format("SharpmakeSingleInstanceMutex{0}", parameters.MutexSuffix); // Allow custom mutex name suffix. Useful to debug concurrently multiple sharpmake running from different branches oneInstanceMutex = new Mutex(true, mutexName, out oneInstanceMutexCreated); if (!oneInstanceMutexCreated) { try { if (!oneInstanceMutex.WaitOne(0)) { LogWriteLine("wait for another instance(s) of sharpmake to terminate..."); oneInstanceMutex.WaitOne(); } } catch (AbandonedMutexException) { // This occurs if another sharpmake is killed in the debugger } finally { LogWriteLine("waiting done."); } } if (parameters.RegexMatchCacheEnabled) { GlobalRegexMatchCache.Init(parameters.RegexMatchCacheInitialCapacity); } switch (parameters.TestOption) { case TestOptions.Regression: { var regressionTest = new BuildContext.RegressionTest(parameters.OutputDirectory, parameters.ReferenceDirectory, parameters.RemapRoot); GenerateAll(regressionTest, parameters); exitCode = ExitCode.Success; var regressions = regressionTest.GetRegressions().ToList(); if (regressions.Count > 0) { exitCode = ExitCode.Error; DebugWriteLine($"{regressions.Count} Regressions detected:"); List <BuildContext.RegressionTest.OutputInfo> fileChanges = regressions.Where(x => x.FileStatus == BuildContext.RegressionTest.FileStatus.Different).ToList(); LogFileChanges(fileChanges, parameters.RegressionDiff); var fileMissing = regressions.Where(x => x.FileStatus == BuildContext.RegressionTest.FileStatus.NotGenerated).Select(x => x.ReferencePath).ToList(); if (fileMissing.Count > 0) { fileMissing.Sort(); DebugWriteLine($" {fileMissing.Count} files are missing from the output:"); fileMissing.ForEach(x => DebugWriteLine($" {x}")); } } } break; case TestOptions.QuickConfigure: { exitCode = AnalyzeConfigureOrder(parameters, true); } break; case TestOptions.Configure: { exitCode = AnalyzeConfigureOrder(parameters, false); } break; case TestOptions.None: default: { if (parameters.OutputDirectory != null) { // output redirect mode var redirectOutput = new BuildContext.RedirectOutput(parameters.OutputDirectory, parameters.RemapRoot); GenerateAll(redirectOutput, parameters); exitCode = ExitCode.Success; } else { var generateAll = new BuildContext.GenerateAll(parameters.DebugLog, parameters.WriteFiles); GenerateAll(generateAll, parameters); exitCode = ExitCode.Success; Util.ExecuteFilesAutoCleanup(); } } break; } if (CSproj.AllCsProjSubTypesInfos.Any()) { Util.SerializeAllCsprojSubTypes(CSproj.AllCsProjSubTypesInfos); } if (parameters.RegexMatchCacheEnabled) { int regexMatchCacheInitialCapacity = parameters.RegexMatchCacheInitialCapacity; int regexMatchCacheSize = GlobalRegexMatchCache.Count; if (regexMatchCacheInitialCapacity < regexMatchCacheSize) { WarningWriteLine("Warning (perf): Consider increasing regex match cache initial capacity from {0} to at least {1} ( /regexMatchCacheInitialCapacity({1}) ).", regexMatchCacheInitialCapacity, regexMatchCacheSize); } GlobalRegexMatchCache.UnInit(); } } catch (Error e) { // Log error message Exception innerException = e; while (innerException.InnerException != null) { innerException = innerException.InnerException; } ErrorWriteLine(Environment.NewLine + "Error:" + Environment.NewLine + innerException.Message); // Then log details LogWriteLine(Util.GetCompleteExceptionMessage(e, "\t")); exitCode = ExitCode.Error; } catch (InternalError e) { ErrorWriteLine(Environment.NewLine + "Internal Error:"); LogWriteLine(Util.GetCompleteExceptionMessage(e, "\t")); exitCode = ExitCode.InternalError; } #if !DEBUG // Use this to catch right away if an exception throw catch (Exception e) { LogWriteLine(Environment.NewLine + "Exception Error:"); LogWriteLine(Util.GetCompleteExceptionMessage(e, "\t")); exitCode = ExitCode.UnknownError; } #endif finally { if (oneInstanceMutex != null) { oneInstanceMutex.ReleaseMutex(); GC.KeepAlive(oneInstanceMutex); } if (parameters.Debug) { Console.WriteLine("DEBUG Sharpmake.Application: Press any key to exit..."); Console.ReadKey(); } } LogWriteLine(@"{0} errors, {1} warnings", s_errorCount, s_warningCount); if (s_errorCount != 0) { if (Debugger.IsAttached) { LogWriteLine("Please look at the errors."); Debugger.Break(); } } // returning exit code and error count separately because they can result in an exit code of 0 if they are added together. if (s_errorCount != 0) { return(s_errorCount); } return((int)exitCode); }
// optimizes the screenshot and creates the result from slimer output private CaptureResult GetCaptureResult(string slimerOutput, string url, string screenshotPath, string screenshotUrl, ExitCode exit) { if (!File.Exists(screenshotPath)) { return(null); } // regular expression is used to parse the output of the slimer Match result = OutputRegex.Match(slimerOutput); if (!result.Success) { return(null); } // Screenshot over 20MB will timeout anyway so I'll not even try them. long screenshotLength = new FileInfo(screenshotPath).Length; if (screenshotLength < 20000000 && OptimizeScreenshot(screenshotPath)) { screenshotLength = new FileInfo(screenshotPath).Length; } else if (exit != ExitCode.SuccessTimeout) { exit = ExitCode.SuccessNotOptimized; } return(new CaptureResult() { Page = url, PageTitle = result.Groups[PageTitle].Value, PageCount = int.Parse(result.Groups[PageCount].Value, CultureInfo.InvariantCulture), PageSize = long.Parse(result.Groups[PageSize].Value, CultureInfo.InvariantCulture), Image = screenshotUrl, ImageSize = screenshotLength, Exit = exit, DetailsPath = Path.GetFileNameWithoutExtension(screenshotPath), ImagePath = Path.GetFileName(screenshotPath), }); }
/// <summary> /// Displays a detailed description of the error code. Does not show if -s has been used /// </summary> /// <param name="code">Code to detail</param> private static void ShowResult(ExitCode code) { var msg = ""; MessageBoxIcon icon = MessageBoxIcon.Error; switch (code) { case ExitCode.Load_Failed: msg = "Failed to load Dll please check the path and ensure the Dll is a valid COM object."; break; case ExitCode.DllRegisterServerNotFound: msg = "Failed to find DllRegisterServer entry point please ensure the Dll is a valid COM object."; break; case ExitCode.DllUnRegisterServerNotFound: msg = "Failed to find DllRegisterServer entry point please ensure the Dll is a valid COM object."; break; case ExitCode.FailedToCallRegisterMethod: msg = "DllRegisterServer was found but a call to it could not be made."; break; case ExitCode.FailedToCallUnRegisterMethod: msg = "DllUnRegisterServer was found but a call to it could not be made."; break; case ExitCode.InvalidArguments: msg = "One or more invalid argument supplied please check the arguments."; break; case ExitCode.OleError: msg = "Oleinitalise command failed. You PC may be low on memory close open programs and try again."; break; case ExitCode.ModulePlatform: msg = "Check if the module is compatible with x86 or x64 version of ManagedRegsvr32"; break; case ExitCode.AccessDenied: msg = "Access denied, please run from elevated prompt"; break; case ExitCode.Success: if (_unregister == false) { msg = "Dll was successfully registered!"; } else { msg = "Dll was succesfully unregistered!"; } icon = MessageBoxIcon.Information; break; default: msg = "How the hell did you break it?"; break; } if (_silent == false) { Console.WriteLine(msg); MessageBox.Show(msg, "ManagedRegsvr32", MessageBoxButtons.OK, icon); } }
/// <summary> /// Processes the certificate management. /// </summary> /// <param name="directoryPath">Directory to put the certificatex in.</param> /// <param name="certConfiguration">Certificate configuration. This is a combination of comma separated values in following format /// *certFileName*;*SourceOfCert*;*CertIdentifierInSource*.</param> /// <param name="keyVaultUri">KeyVault uri if key vault is to be used.</param> /// <param name="keyVaultClientId">Application client Id to access keyvault.</param> /// <param name="keyVaultClientSecret">Application client secret to access keyvault.</param> /// <param name="keyVaultClientCert">Application client certificate thumbprint if the keyvault app has certificate credentials.</param> /// <returns>Exit code for the operation.</returns> internal static async Task <ExitCode> ProcessAsync(string directoryPath, string certConfiguration, string keyVaultUri, string keyVaultClientId, string keyVaultClientSecret, string keyVaultClientCert) { if (string.IsNullOrEmpty(directoryPath)) { Logger.LogError(CallInfo.Site(), "Directory path missing for the Certificate directory."); return(ExitCode.DirectoryPathMissing); } if (string.IsNullOrEmpty(certConfiguration)) { Logger.LogError(CallInfo.Site(), "Cert configuration missing. Please specify CertsToConfigure option"); return(ExitCode.InvalidCertConfiguration); } // 1. Initialize KeyVault Client if params were passed. KeyVaultClient keyVaultClient = null; if (!string.IsNullOrEmpty(keyVaultUri)) { if (string.IsNullOrEmpty(keyVaultClientId)) { Logger.LogError(CallInfo.Site(), "If KeyVaultUri is specified, KeyVault ClientId must be specified"); return(ExitCode.KeyVaultConfigurationIncomplete); } if (string.IsNullOrEmpty(keyVaultClientSecret) && string.IsNullOrEmpty(keyVaultClientCert)) { Logger.LogError(CallInfo.Site(), "If KeyVaultUri is specified, KeyVault ClientSecret or KeyVault ClientCert must be specified"); return(ExitCode.KeyVaultConfigurationIncomplete); } if (!string.IsNullOrEmpty(keyVaultClientSecret)) { KeyVaultClient.AuthenticationCallback callback = (authority, resource, scope) => GetTokenFromClientSecretAsync(authority, resource, keyVaultClientId, keyVaultClientSecret); keyVaultClient = new KeyVaultClient(callback); } else { X509Certificate2Collection keyVaultCerts = CertHelpers.FindCertificates(keyVaultClientCert, X509FindType.FindByThumbprint); if (keyVaultCerts.Count == 0) { Logger.LogError(CallInfo.Site(), "Failed to find Client cert with thumbprint '{0}'", keyVaultClientCert); return(ExitCode.KeyVaultConfigurationIncomplete); } KeyVaultClient.AuthenticationCallback callback = (authority, resource, scope) => GetTokenFromClientCertificateAsync(authority, resource, keyVaultClientId, keyVaultCerts[0]); keyVaultClient = new KeyVaultClient(callback); } } // 2. Figure all the certs which need processing. string[] certsToConfigure = certConfiguration.Split(','); string currentExeDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string fullDirectoryPathForCerts = Path.Combine(currentExeDirectory, directoryPath); // 3. Process specified certs one by one. foreach (string certToConfigure in certsToConfigure) { // 3a. Split the cert configuration data to get actual details. This data is informat // <CertNameOnDisk>;CertSource(LocalMachine or KeyVault);<CertIdentifier(SecretName or Thumbprint)> string[] certConfigurationParams = certToConfigure.Split(';'); if (certConfigurationParams.Length != 3) { Logger.LogError(CallInfo.Site(), "Invalid certificate configuration '{0}'. Cert configuration must be in format <CertFileName>;<CertSource>;<CertIdentifier>", certToConfigure); return(ExitCode.InvalidCertConfiguration); } var certConfig = new { CertName = certConfigurationParams[0], CertSource = certConfigurationParams[1], CertIdentifier = certConfigurationParams[2] }; // 3b. Depending on the source of Cert get the PFX for the certs dropped into the directory. if (certConfig.CertSource.Equals("MyLocalMachine", StringComparison.OrdinalIgnoreCase)) { ExitCode localMachineCertHandler = await LocalMachineCertHandlerAsync( certConfig.CertName, certConfig.CertIdentifier, fullDirectoryPathForCerts).ConfigureAwait(false); if (localMachineCertHandler != ExitCode.Success) { return(localMachineCertHandler); } } else if (certConfig.CertSource.StartsWith("KeyVault", StringComparison.OrdinalIgnoreCase)) { ExitCode keyVaultCertHandlerExitCode = await KeyVaultCertHandlerAsync( certConfig.CertSource, certConfig.CertName, certConfig.CertIdentifier, fullDirectoryPathForCerts, keyVaultClient, keyVaultUri).ConfigureAwait(false); if (keyVaultCertHandlerExitCode != ExitCode.Success) { return(keyVaultCertHandlerExitCode); } } else { Logger.LogError(CallInfo.Site(), "Unsupported Certificate source '{0}' for cert '{1}'", certConfig.CertSource, certConfig.CertName); return(ExitCode.UnsupportedCertSource); } // 3c. Convert PFX into .Key and .Crt. We are placing openssl next to this exe hence using current directory. ExitCode conversionExitCode = ConvertPfxIntoPemFormat(certConfig.CertName, fullDirectoryPathForCerts, currentExeDirectory, password: string.Empty); if (conversionExitCode != ExitCode.Success) { return(conversionExitCode); } // 3d. Delete the PFX as it is no longer needed. File.Delete(Path.Combine(fullDirectoryPathForCerts, certConfig.CertName + ".pfx")); } return(ExitCode.Success); }
private int Run(string[] args) { // Add a default trace listener Trace.AddListener(new SimpleColorConsoleTraceListener() { TraceOutputOptions = System.Diagnostics.TraceOptions.None }); // Output version info AssemblyInformationalVersionAttribute versionAttribute = Attribute.GetCustomAttribute(typeof(Program).Assembly, typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute; Trace.Information("Wyam version {0}", versionAttribute == null ? "unknown" : versionAttribute.InformationalVersion); // Parse the command line bool hasParseArgsErrors; if (!ParseArgs(args, out hasParseArgsErrors)) { return(hasParseArgsErrors ? (int)ExitCode.CommandLineError : (int)ExitCode.Normal); } // It's not a serious console app unless there's some ASCII art OutputLogo(); // Fix the root folder and other files DirectoryPath currentDirectory = Environment.CurrentDirectory; _rootPath = _rootPath == null ? currentDirectory : currentDirectory.Combine(_rootPath); _logFilePath = _logFilePath == null ? null : _rootPath.CombineFile(_logFilePath); _configFilePath = _rootPath.CombineFile(_configFilePath ?? "config.wyam"); // Set up the log file if (_logFilePath != null) { Trace.AddListener(new SimpleFileTraceListener(_logFilePath.FullPath)); } // Prepare engine's metadata if (!_verifyConfig && _globalMetadataArgs != null && _globalMetadataArgs.Count > 0) { try { _globalMetadata = GlobalMetadataParser.Parse(_globalMetadataArgs); } catch (MetadataParseException ex) { Trace.Error("Error while parsing metadata: {0}", ex.Message); if (Trace.Level == System.Diagnostics.SourceLevels.Verbose) { Trace.Error("Stack trace:{0}{1}", Environment.NewLine, ex.StackTrace); } return((int)ExitCode.CommandLineError); } // Not used anymore, release resources. _globalMetadataArgs = null; } // Get the engine Engine engine = GetEngine(); if (engine == null) { return((int)ExitCode.CommandLineError); } // Pause if (_pause) { Trace.Information("Pause requested, hit any key to continue"); Console.ReadKey(); } // Configure and execute if (!Configure(engine)) { return((int)ExitCode.ConfigurationError); } if (_verifyConfig) { Trace.Information("No errors. Exiting."); return((int)ExitCode.Normal); } Console.WriteLine($"Root path:{Environment.NewLine} {engine.FileSystem.RootPath}"); Console.WriteLine($"Input path(s):{Environment.NewLine} {string.Join(Environment.NewLine + " ", engine.FileSystem.InputPaths)}"); Console.WriteLine($"Output path:{Environment.NewLine} {engine.FileSystem.OutputPath}"); if (!Execute(engine)) { return((int)ExitCode.ExecutionError); } bool messagePump = false; // Start the preview server IDisposable previewServer = null; if (_preview) { messagePump = true; try { var rootPath = _previewRoot == null?engine.FileSystem.GetOutputDirectory().Path.FullPath : _previewRoot.FullPath; Trace.Information("Preview server listening on port {0} and serving from path {1}", _previewPort, rootPath); previewServer = Preview(engine, rootPath); } catch (Exception ex) { Trace.Critical("Error while running preview server: {0}", ex.Message); } } // Start the watchers IDisposable inputFolderWatcher = null; IDisposable configFileWatcher = null; if (_watch) { messagePump = true; Trace.Information("Watching paths(s) {0}", string.Join(", ", engine.FileSystem.InputPaths)); inputFolderWatcher = new ActionFileSystemWatcher(engine.FileSystem.GetOutputDirectory().Path, engine.FileSystem.GetInputDirectories().Select(x => x.Path), true, "*.*", path => { _changedFiles.Enqueue(path); _messageEvent.Set(); }); if (_configFilePath != null) { Trace.Information("Watching configuration file {0}", _configFilePath); Engine closureEngine = engine; configFileWatcher = new ActionFileSystemWatcher(engine.FileSystem.GetOutputDirectory().Path, new[] { _configFilePath.Directory }, false, _configFilePath.FileName.FullPath, path => { FilePath filePath = new FilePath(path); if (_configFilePath.Equals(filePath)) { _newEngine.Set(); _messageEvent.Set(); } }); } } // Start the message pump if an async process is running ExitCode exitCode = ExitCode.Normal; if (messagePump) { // Start the key listening thread Trace.Information("Hit any key to exit"); var thread = new Thread(() => { Console.ReadKey(); _exit.Set(); _messageEvent.Set(); }) { IsBackground = true }; thread.Start(); // Wait for activity while (true) { _messageEvent.WaitOne(); // Blocks the current thread until a signal if (_exit) { break; } // See if we need a new engine if (_newEngine) { // Get a new engine Trace.Information("Configuration file {0} has changed, re-running", _configFilePath); engine.Dispose(); engine = GetEngine(); // Configure and execute if (!Configure(engine)) { exitCode = ExitCode.ConfigurationError; break; } Console.WriteLine($"Root path:{Environment.NewLine} {engine.FileSystem.RootPath}"); Console.WriteLine($"Input path(s):{Environment.NewLine} {string.Join(Environment.NewLine + " ", engine.FileSystem.InputPaths)}"); Console.WriteLine($"Root path:{Environment.NewLine} {engine.FileSystem.OutputPath}"); if (!Execute(engine)) { exitCode = ExitCode.ExecutionError; break; } // Clear the changed files since we just re-ran string changedFile; while (_changedFiles.TryDequeue(out changedFile)) { } _newEngine.Unset(); } else { // Execute if files have changed HashSet <string> changedFiles = new HashSet <string>(); string changedFile; while (_changedFiles.TryDequeue(out changedFile)) { if (changedFiles.Add(changedFile)) { Trace.Verbose("{0} has changed", changedFile); } } if (changedFiles.Count > 0) { Trace.Information("{0} files have changed, re-executing", changedFiles.Count); if (!Execute(engine)) { exitCode = ExitCode.ExecutionError; break; } } } // Check one more time for exit if (_exit) { break; } Trace.Information("Hit any key to exit"); _messageEvent.Reset(); } // Shutdown Trace.Information("Shutting down"); engine.Dispose(); inputFolderWatcher?.Dispose(); configFileWatcher?.Dispose(); previewServer?.Dispose(); } return((int)exitCode); }
public static void Exit(ExitCode e) { Environment.Exit((int)e); }
/// <summary> /// Runs the application with specified command line arguments and environment variables, and returns the exit code. /// </summary> /// <remarks> /// If a <see cref="CommandException"/> is thrown during command execution, it will be handled and routed to the console. /// Additionally, if the debugger is not attached (i.e. the app is running in production), all other exceptions thrown within /// this method will be handled and routed to the console as well. /// </remarks> public async ValueTask <int> RunAsync( IReadOnlyList <string> commandLineArguments, IReadOnlyDictionary <string, string> environmentVariables) { try { var root = RootSchema.Resolve(_configuration.CommandTypes); var input = CommandInput.Parse(commandLineArguments, root.GetCommandNames()); // Debug mode if (_configuration.IsDebugModeAllowed && input.IsDebugDirectiveSpecified) { await LaunchAndWaitForDebuggerAsync(); } // Preview mode if (_configuration.IsPreviewModeAllowed && input.IsPreviewDirectiveSpecified) { WriteCommandLineInput(input); return(ExitCode.Success); } // Try to get the command matching the input or fallback to default var command = root.TryFindCommand(input.CommandName) ?? root.TryFindDefaultCommand() ?? StubDefaultCommand.Schema; // Version option if (command.IsVersionOptionAvailable && input.IsVersionOptionSpecified) { _console.Output.WriteLine(_metadata.VersionText); return(ExitCode.Success); } // Get command instance (also used in help text) var instance = GetCommandInstance(command); // To avoid instantiating the command twice, we need to get default values // before the arguments are bound to the properties var defaultValues = command.GetArgumentValues(instance); // Help option if (command.IsHelpOptionAvailable && input.IsHelpOptionSpecified || command == StubDefaultCommand.Schema && !input.Parameters.Any() && !input.Options.Any()) { _helpTextWriter.Write(root, command, defaultValues); return(ExitCode.Success); } // Bind arguments try { command.Bind(instance, input, environmentVariables); } // This may throw exceptions which are useful only to the end-user catch (CliFxException ex) { WriteError(ex.ToString()); _helpTextWriter.Write(root, command, defaultValues); return(ExitCode.FromException(ex)); } // Execute the command try { await instance.ExecuteAsync(_console); return(ExitCode.Success); } // Swallow command exceptions and route them to the console catch (CommandException ex) { WriteError(ex.ToString()); if (ex.ShowHelp) { _helpTextWriter.Write(root, command, defaultValues); } return(ex.ExitCode); } } // To prevent the app from showing the annoying Windows troubleshooting dialog, // we handle all exceptions and route them to the console nicely. // However, we don't want to swallow unhandled exceptions when the debugger is attached, // because we still want the IDE to show them to the developer. catch (Exception ex) when(!Debugger.IsAttached) { _errorTextWriter.WriteError(ex); return(ExitCode.FromException(ex)); } }
/// <summary> /// Object iterface. /// </summary> /// <returns>String representation of this object.</returns> public override string ToString() { return(ExitCode.ToString()); }
public void When_I_run_the_create_site_command_with_valid_path() { exitCode = entryPoint.Run(new string[] { "create", "site", validPath }); }
public ApplicationExitException(ExitCode exitCode) { ExitCode = exitCode; }
private void CompareSnapshots() { RegistrySnapshot lhs; RegistrySnapshot rhs; ChangeResult[] results; lhs = null; rhs = null; results = new ChangeResult[0]; this.PerformAction(() => lhs = RegistrySnapshot.LoadFromFile(PathHelpers.GetFullPath(_files[0])), "Loading first snapshot"); this.PerformAction(() => rhs = RegistrySnapshot.LoadFromFile(PathHelpers.GetFullPath(_files[1])), "Loading second snapshot"); if (lhs != null && rhs != null) { this.PerformAction(() => { RegistrySnapshotComparer comparer; comparer = new RegistrySnapshotComparer(lhs, rhs); results = comparer.Compare(); }, "Comparing snapshots"); } this.PrintResults(results); if (this.ExitCode == ExitCode.InvalidArguments) { this.ExitCode = results.Length == 0 ? ExitCode.Success : ExitCode.CompareMismatch; } }
private static void HandleParseErrors <T>(ParserResult <T> result, IEnumerable <Error> errors) { if (errors.IsVersion()) { Log.Info(HelpText.AutoBuild(result)); return; } else if (errors.IsHelp()) { HelpText helpText = HelpText.AutoBuild(result, h => { h.AddEnumValuesToHelpText = true; h.AdditionalNewLineAfterOption = false; h.MaximumDisplayWidth = 100; h.Heading = ProgramTitle; if (!string.IsNullOrEmpty(ProgramCopyright)) { h.Copyright = ProgramCopyright; } h.Copyright += "\n"; h.AddPreOptionsLines(new[] { ProgramUsage, "", ProgramDescription, "" }); return(h); }, e => e); Log.Info(helpText); return; } foreach (Error e in errors) { string msg = ""; switch (e.Tag) { case ErrorType.BadFormatConversionError: msg = string.Format(ParseErrorBadOptionValue, ((BadFormatConversionError)e).NameInfo.LongName); break; case ErrorType.MissingRequiredOptionError: var eMissingRequired = (MissingRequiredOptionError)e; msg = (eMissingRequired.NameInfo.Equals(NameInfo.EmptyName)) ? string.Format("{0}\nUsage: {1}", ParseErrorMissingRequiredPositional, ProgramUsage) : string.Format(ParseErrorMissingRequiredOption, eMissingRequired.NameInfo.LongName); break; case ErrorType.MissingValueOptionError: var eMissingValue = (MissingValueOptionError)e; msg = string.Format(ParseErrorMissingOptionValue, eMissingValue.NameInfo.LongName); break; case ErrorType.RepeatedOptionError: var eRepeated = (RepeatedOptionError)e; msg = string.Format(ParseErrorRepeatedOption, eRepeated.NameInfo.NameText); break; case ErrorType.UnknownOptionError: var eUnknown = (UnknownOptionError)e; msg = string.Format(ParseErrorUnknownOption, eUnknown.Token); break; default: msg = string.Format(ParseErrorOops, e); break; } Log.Error(msg); } RunResult = ExitCode.BadCommandLine; }
private void TakeSnapshot() { RegistrySnapshot snapshot; RegistrySnapshotBuilder builder; builder = new RegistrySnapshotBuilder(); snapshot = new RegistrySnapshot(); foreach (string key in _keys) { this.PerformAction(() => { RegistryKeySnapshot keySnapshot; keySnapshot = builder.TakeSnapshot(key); keySnapshot.Name = key; snapshot.Keys.Add(keySnapshot); }, $"Snapshotting {key}"); } _currentSnapshot = snapshot; this.SaveSnapshot(); if (this.ExitCode == ExitCode.InvalidArguments) { this.ExitCode = ExitCode.Success; } }
/// <summary> /// Main method. /// </summary> /// <param name="Arguments">Command line</param> public static ExitCode Process(string[] Arguments) { // Initial check for local or build machine runs BEFORE we parse the command line (We need this value set // in case something throws the exception while parsing the command line) IsBuildMachine = !String.IsNullOrEmpty(Environment.GetEnvironmentVariable("uebp_LOCAL_ROOT")) || Arguments.Any(x => x.Equals("-BuildMachine", StringComparison.InvariantCultureIgnoreCase)); // Scan the command line for commands to execute. var CommandsToExecute = new List <CommandInfo>(); string OutScriptsForProjectFileName; var AdditionalScriptsFolders = new List <string>(); ParseCommandLine(Arguments, CommandsToExecute, out OutScriptsForProjectFileName, AdditionalScriptsFolders); // Get the path to the telemetry file, if present string TelemetryFile = CommandUtils.ParseParamValue(Arguments, "-Telemetry"); Log.TraceVerbose("IsBuildMachine={0}", IsBuildMachine); Environment.SetEnvironmentVariable("IsBuildMachine", IsBuildMachine ? "1" : "0"); // should we kill processes on exit ShouldKillProcesses = !GlobalCommandLine.NoKill; Log.TraceVerbose("ShouldKillProcesses={0}", ShouldKillProcesses); if (CommandsToExecute.Count == 0 && GlobalCommandLine.Help) { DisplayHelp(); return(ExitCode.Success); } // Disable AutoSDKs if specified on the command line if (GlobalCommandLine.NoAutoSDK) { PlatformExports.PreventAutoSDKSwitching(); } // Setup environment Log.TraceLog("Setting up command environment."); CommandUtils.InitCommandEnvironment(); // Determine if the engine is installed bIsEngineInstalled = GlobalCommandLine.Installed; string InstalledBuildFile = Path.Combine(CommandUtils.CmdEnv.LocalRoot, "Engine", "Build", "InstalledBuild.txt"); bIsEngineInstalled |= File.Exists(InstalledBuildFile); if (bIsEngineInstalled.Value) { bIsEngineInstalled = !GlobalCommandLine.NotInstalledEngine; } else { bIsEngineInstalled = GlobalCommandLine.InstalledEngine; } // Initialize UBT if (!UnrealBuildTool.PlatformExports.Initialize(bIsEngineInstalled.Value)) { Log.TraceInformation("Failed to initialize UBT"); return(ExitCode.Error_Unknown); } // Change CWD to UE4 root. Environment.CurrentDirectory = CommandUtils.CmdEnv.LocalRoot; // Fill in the project info UnrealBuildTool.UProjectInfo.FillProjectInfo(); // Clean rules folders up ProjectUtils.CleanupFolders(); // Compile scripts. ScriptCompiler Compiler = new ScriptCompiler(); using (TelemetryStopwatch ScriptCompileStopwatch = new TelemetryStopwatch("ScriptCompile")) { Compiler.FindAndCompileAllScripts(OutScriptsForProjectFileName, AdditionalScriptsFolders); } if (GlobalCommandLine.CompileOnly) { Log.TraceInformation("Compilation successful, exiting (CompileOnly)"); return(ExitCode.Success); } if (GlobalCommandLine.List) { ListAvailableCommands(Compiler.Commands); return(ExitCode.Success); } if (GlobalCommandLine.Help) { DisplayHelp(CommandsToExecute, Compiler.Commands); return(ExitCode.Success); } // Enable or disable P4 support CommandUtils.InitP4Support(CommandsToExecute, Compiler.Commands); if (CommandUtils.P4Enabled) { Log.TraceLog("Setting up Perforce environment."); CommandUtils.InitP4Environment(); CommandUtils.InitDefaultP4Connection(); } // Find and execute commands. ExitCode Result = Execute(CommandsToExecute, Compiler.Commands); if (TelemetryFile != null) { Directory.CreateDirectory(Path.GetDirectoryName(TelemetryFile)); CommandUtils.Telemetry.Write(TelemetryFile); } return(Result); }
/////////////////////////////////////////////////////////////////////// /// <summary> /// This method is an event handler that is called when the file /// download has completed, successfully or otherwise. It will /// display the overall result of the file download on the console, /// including any <see cref="Exception" /> information, if applicable. /// The <see cref="exitCode" /> field is changed by this method to /// indicate the overall result of the file download and the event /// within the <see cref="doneEvent" /> field will be signaled. /// </summary> /// <param name="sender"> /// The source of the event. /// </param> /// <param name="e"> /// Information for the event being processed. /// </param> private static void DownloadFileCompleted( object sender, AsyncCompletedEventArgs e ) { if (e != null) { lock (syncRoot) { if (previousPercent < 100) Console.Write(' '); } if (e.Cancelled) { Console.WriteLine("Canceled"); lock (syncRoot) { exitCode = ExitCode.DownloadCanceled; } } else { Exception error = e.Error; if (error != null) { Console.WriteLine("Error: {0}", error); lock (syncRoot) { exitCode = ExitCode.DownloadError; } } else { Console.WriteLine("Done"); } } } if (doneEvent != null) doneEvent.Set(); }
public ApplicationExitException(ExitCode exitCode, string?message, Exception?innerException) : base(message, innerException) { ExitCode = exitCode; }
public static int Main(string[] Arguments) { // Ensure UTF8Output flag is respected, since we are initializing logging early in the program. if (CommandUtils.ParseParam(Arguments, "-Utf8output")) { Console.OutputEncoding = new System.Text.UTF8Encoding(false, false); } // Parse the log level argument if (CommandUtils.ParseParam(Arguments, "-Verbose")) { Log.OutputLevel = LogEventType.Verbose; } if (CommandUtils.ParseParam(Arguments, "-VeryVerbose")) { Log.OutputLevel = LogEventType.VeryVerbose; } // Initialize the log system, buffering the output until we can create the log file StartupTraceListener StartupListener = new StartupTraceListener(); Trace.Listeners.Add(StartupListener); // Configure log timestamps Log.IncludeTimestamps = CommandUtils.ParseParam(Arguments, "-Timestamps"); // Enter the main program section ExitCode ReturnCode = ExitCode.Success; try { // Set the working directory to the UE4 root Environment.CurrentDirectory = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetOriginalLocation()), "..", "..", "..")); // Ensure we can resolve any external assemblies as necessary. string PathToBinariesDotNET = Path.GetDirectoryName(Assembly.GetEntryAssembly().GetOriginalLocation()); AssemblyUtils.InstallAssemblyResolver(PathToBinariesDotNET); AssemblyUtils.InstallRecursiveAssemblyResolver(PathToBinariesDotNET); // Initialize the host platform layer HostPlatform.Initialize(); // Log the operating environment. Since we usually compile to AnyCPU, we may be executed using different system paths under WOW64. Log.TraceVerbose("{2}: Running on {0} as a {1}-bit process.", HostPlatform.Current.GetType().Name, Environment.Is64BitProcess ? 64 : 32, DateTime.UtcNow.ToString("o")); // Log if we're running from the launcher string ExecutingAssemblyLocation = Assembly.GetExecutingAssembly().Location; if (string.Compare(ExecutingAssemblyLocation, Assembly.GetEntryAssembly().GetOriginalLocation(), StringComparison.OrdinalIgnoreCase) != 0) { Log.TraceVerbose("Executed from AutomationToolLauncher ({0})", ExecutingAssemblyLocation); } Log.TraceVerbose("CWD={0}", Environment.CurrentDirectory); // Hook up exit callbacks AppDomain Domain = AppDomain.CurrentDomain; Domain.ProcessExit += Domain_ProcessExit; Domain.DomainUnload += Domain_ProcessExit; HostPlatform.Current.SetConsoleCtrlHandler(CtrlHandlerDelegateInstance); // Log the application version FileVersionInfo Version = AssemblyUtils.ExecutableVersion; Log.TraceVerbose("{0} ver. {1}", Version.ProductName, Version.ProductVersion); // Don't allow simultaneous execution of AT (in the same branch) ReturnCode = InternalUtils.RunSingleInstance(() => MainProc(Arguments, StartupListener)); } catch (AutomationException Ex) { // Output the message in the desired format if (Ex.OutputFormat == AutomationExceptionOutputFormat.Silent) { Log.TraceLog("{0}", ExceptionUtils.FormatExceptionDetails(Ex)); } else if (Ex.OutputFormat == AutomationExceptionOutputFormat.Minimal) { Log.TraceInformation("{0}", Ex.ToString().Replace("\n", "\n ")); Log.TraceLog("{0}", ExceptionUtils.FormatExceptionDetails(Ex)); } else { Log.WriteException(Ex, LogUtils.FinalLogFileName); } // Take the exit code from the exception ReturnCode = Ex.ErrorCode; } catch (Exception Ex) { // Use a default exit code Log.WriteException(Ex, LogUtils.FinalLogFileName); ReturnCode = ExitCode.Error_Unknown; } finally { // In all cases, do necessary shut down stuff, but don't let any additional exceptions leak out while trying to shut down. // Make sure there's no directories on the stack. NoThrow(() => CommandUtils.ClearDirStack(), "Clear Dir Stack"); // Try to kill process before app domain exits to leave the other KillAll call to extreme edge cases NoThrow(() => { if (ShouldKillProcesses && !Utils.IsRunningOnMono) { ProcessManager.KillAll(); } }, "Kill All Processes"); // Write the exit code Log.TraceInformation("AutomationTool exiting with ExitCode={0} ({1})", (int)ReturnCode, ReturnCode); // Can't use NoThrow here because the code logs exceptions. We're shutting down logging! Trace.Close(); } return((int)ReturnCode); }
public static int AsInt(this ExitCode value) { return((int)value); }
private void Stop(ExitCode exitCode, Object data = null) { Stop((int)exitCode, data); }
public static int Main() { var CommandLine = SharedUtils.ParseCommandLine(); LogUtils.InitLogging(CommandLine); ExitCode ReturnCode = ExitCode.Success; try { // ensure we can resolve any external assemblies as necessary. AssemblyUtils.InstallAssemblyResolver(Path.GetDirectoryName(Assembly.GetEntryAssembly().GetOriginalLocation())); HostPlatform.Initialize(); Log.TraceVerbose("{2}: Running on {0} as a {1}-bit process.", HostPlatform.Current.GetType().Name, Environment.Is64BitProcess ? 64 : 32, DateTime.UtcNow.ToString("o")); XmlConfigLoader.Init(); // Log if we're running from the launcher var ExecutingAssemblyLocation = Assembly.GetExecutingAssembly().Location; if (string.Compare(ExecutingAssemblyLocation, Assembly.GetEntryAssembly().GetOriginalLocation(), StringComparison.OrdinalIgnoreCase) != 0) { Log.TraceVerbose("Executed from AutomationToolLauncher ({0})", ExecutingAssemblyLocation); } Log.TraceVerbose("CWD={0}", Environment.CurrentDirectory); // Hook up exit callbacks var Domain = AppDomain.CurrentDomain; Domain.ProcessExit += Domain_ProcessExit; Domain.DomainUnload += Domain_ProcessExit; HostPlatform.Current.SetConsoleCtrlHandler(CtrlHandlerDelegateInstance); var Version = AssemblyUtils.ExecutableVersion; Log.TraceVerbose("{0} ver. {1}", Version.ProductName, Version.ProductVersion); // Don't allow simultaneous execution of AT (in the same branch) ReturnCode = InternalUtils.RunSingleInstance(MainProc, CommandLine); } catch (AutomationException Ex) { Log.TraceError("AutomationTool terminated with exception: {0}", Ex); ReturnCode = Ex.ErrorCode; } catch (Exception Ex) { // Catch all exceptions and propagate the ErrorCode if we are given one. Log.TraceError("AutomationTool terminated with exception: {0}", Ex); ReturnCode = ExitCode.Error_Unknown; } finally { // In all cases, do necessary shut down stuff, but don't let any additional exceptions leak out while trying to shut down. // Make sure there's no directories on the stack. NoThrow(() => CommandUtils.ClearDirStack(), "Clear Dir Stack"); // Try to kill process before app domain exits to leave the other KillAll call to extreme edge cases NoThrow(() => { if (ShouldKillProcesses && !Utils.IsRunningOnMono) { ProcessManager.KillAll(); } }, "Kill All Processes"); Log.TraceInformation("AutomationTool exiting with ExitCode={0} ({1})", (int)ReturnCode, ReturnCode); // Can't use NoThrow here because the code logs exceptions. We're shutting down logging! LogUtils.ShutdownLogging(); } // STOP: No code beyond the return statement should go beyond this point! // Nothing should happen after the finally block above is finished. return((int)ReturnCode); }
private async Task <ExitCode> InternalDeployAsync( ImmutableArray <DeploymentExecutionDefinition> deploymentExecutionDefinitions, SemanticVersion explicitVersion, CancellationToken cancellationToken = default) { var tempDirectoriesToClean = new List <DirectoryInfo>(); var tempFilesToClean = new List <string>(); try { _logger.Verbose("Executing deployment execution definitions [{Length}]: {Executions}", deploymentExecutionDefinitions.Length, string.Join($"{Environment.NewLine}\t", deploymentExecutionDefinitions.Select(_ => $"'{_}'"))); foreach (DeploymentExecutionDefinition deploymentExecutionDefinition in deploymentExecutionDefinitions) { if (string.IsNullOrWhiteSpace(deploymentExecutionDefinition.TargetDirectoryPath) && string.IsNullOrWhiteSpace(deploymentExecutionDefinition.PublishSettingsFile)) { throw new InvalidOperationException($"{nameof(deploymentExecutionDefinition.TargetDirectoryPath)} and {nameof(deploymentExecutionDefinition.PublishSettingsFile)} are both not set"); } string asJson = JsonConvert.SerializeObject(deploymentExecutionDefinition, Formatting.Indented); _logger.Information("Executing deployment execution definition: '{DeploymentExecutionDefinition}'", asJson); const string TempPrefix = "MD-"; string uniqueSuffix = DateTime.Now.ToString("MMddHHmmssfff", CultureInfo.InvariantCulture); string tempPath = Path.Combine( Path.GetTempPath(), $"{TempPrefix}{uniqueSuffix}{Guid.NewGuid().ToString().Substring(0, 6)}"); var tempWorkingDirectory = new DirectoryInfo(tempPath); DirectoryInfo packageInstallTempDirectory = tempWorkingDirectory; tempDirectoriesToClean.Add(packageInstallTempDirectory); MayBe <InstalledPackage> installedMainPackage = await _packageInstaller.InstallPackageAsync( deploymentExecutionDefinition, packageInstallTempDirectory, false, explicitVersion, cancellationToken).ConfigureAwait(false); if (!installedMainPackage.HasValue) { _logger.Error( "Could not install package defined in deployment execution definition {DeploymentExecutionDefinition}", deploymentExecutionDefinition); return(ExitCode.Failure); } InstalledPackage installedPackage = installedMainPackage.Value; _logger.Information( "Successfully installed NuGet package '{PackageId}' version '{Version}' to path '{NugetPackageFullPath}'", installedPackage.PackageId, installedPackage.Version.ToNormalizedString(), installedPackage.NugetPackageFullPath); tempWorkingDirectory.Refresh(); DirectoryInfo[] packagesDirectory = tempWorkingDirectory.GetDirectories(); DirectoryInfo packageDirectory = packagesDirectory.Single(directory => directory.Name.Equals(installedPackage.PackageId, StringComparison.OrdinalIgnoreCase)); SemanticVersion version = explicitVersion ?? GetSemanticVersionFromDefinition( deploymentExecutionDefinition, packageDirectory, installedPackage.Version); _logger.Verbose("Package version is {Version}", version.ToNormalizedString()); var possibleXmlTransformations = new List <FileMatch>(); var replaceFiles = new List <FileMatch>(); var environmentPackageResult = new EnvironmentPackageResult(true); var contentDirectory = new DirectoryInfo(Path.Combine(packageDirectory.FullName, "Content")); if (!contentDirectory.Exists) { _logger.Error("Content directory '{FullName}' does not exist", contentDirectory.FullName); return(ExitCode.Failure); } FileInfo contentFilesJson = packageDirectory.GetFiles("contentFiles.json").SingleOrDefault(); if (contentFilesJson?.Exists == true) { ExitCode exitCode = VerifyFiles(contentFilesJson.FullName, contentDirectory); if (!exitCode.IsSuccess) { return(exitCode); } } else { _logger.Debug("No file contentFiles.json was found in package directory {PackageDirectory}", packageDirectory.FullName); } if (!string.IsNullOrWhiteSpace(deploymentExecutionDefinition.EnvironmentConfig)) { _logger.Information( "Fetching environment packages for package {Package} and environment {Environment}", deploymentExecutionDefinition.PackageId, deploymentExecutionDefinition.EnvironmentConfig); environmentPackageResult = await AddEnvironmentPackageAsync(deploymentExecutionDefinition, packageInstallTempDirectory, possibleXmlTransformations, replaceFiles, tempDirectoriesToClean, version, cancellationToken).ConfigureAwait(false); if (!environmentPackageResult.IsSuccess) { return(ExitCode.Failure); } if (environmentPackageResult.Version != null) { _logger.Information("Installed environment package version {Version}", environmentPackageResult.Version.ToNormalizedString()); } else { _logger.Information("No environment package was installed"); } } else { _logger.Debug("Definition has no environment configuration specified"); } if (possibleXmlTransformations.Any()) { _logger.Debug("Possible Xml transformation files {V}", string.Join(", ", possibleXmlTransformations.Select(fileMatch => $"'{fileMatch.TargetName}' replaced by --> '{fileMatch.ActionFile.FullName}'"))); } var xmlTransformedFiles = new List <string>(); foreach (FileMatch possibleXmlTransformation in possibleXmlTransformations) { TransformationResult result = _xmlTransformer.TransformMatch(possibleXmlTransformation, contentDirectory); if (!result.IsSuccess) { return(ExitCode.Failure); } xmlTransformedFiles.AddRange(result.TransformedFiles); } if (replaceFiles.Any()) { _logger.Debug("Possible replacing files {Files}", string.Join(", ", replaceFiles.Select(fileMatch => $"'{fileMatch.TargetName}' replaced by --> '{fileMatch.ActionFile.FullName}'"))); } var replacedFiles = new List <string>(); foreach (FileMatch replacement in replaceFiles) { ReplaceResult result = ReplaceFileIfMatchingFiles(replacement, contentDirectory); if (!result.IsSuccess) { return(ExitCode.Failure); } replacedFiles.AddRange(result.ReplacedFiles); } if (!string.IsNullOrWhiteSpace(deploymentExecutionDefinition.WebConfigTransformFile)) { DeploymentTransformation.Transform(deploymentExecutionDefinition, contentDirectory, _logger); } string uniqueTargetTempSuffix = DateTime.Now.ToString("MMddHHmmssfff", CultureInfo.InvariantCulture); string uniqueTargetTempPath = Path.Combine( Path.GetTempPath(), $"{TempPrefix}t{uniqueTargetTempSuffix}{Guid.NewGuid().ToString().Substring(0, 6)}"); var targetTempDirectoryInfo = new DirectoryInfo(uniqueTargetTempPath); if (!targetTempDirectoryInfo.Exists) { _logger.Debug("Creating temp target directory '{FullName}'", packageInstallTempDirectory.FullName); targetTempDirectoryInfo.Create(); } string wwwrootPath = Path.Combine(contentDirectory.FullName, "wwwroot"); var wwwRootDirectory = new DirectoryInfo(wwwrootPath); DirectoryInfo applicationMetadataTargetDirectory = wwwRootDirectory.Exists ? wwwRootDirectory : contentDirectory; string versionFile = ApplicationMetadataCreator.SetVersionFile( installedMainPackage.Value, applicationMetadataTargetDirectory, deploymentExecutionDefinition, xmlTransformedFiles, replacedFiles, environmentPackageResult, _logger); _logger.Information("Successfully wrote metadata file {Path}", versionFile); _logger.Verbose("Copying content files to '{FullName}'", targetTempDirectoryInfo.FullName); bool usePublishSettingsFile = !string.IsNullOrWhiteSpace(deploymentExecutionDefinition.PublishSettingsFile); var targetAppOffline = new FileInfo(Path.Combine(targetTempDirectoryInfo.FullName, DeploymentConstants.AppOfflineHtm)); var ruleConfiguration = RuleConfiguration.Get(deploymentExecutionDefinition, DeployerConfiguration, _logger); if (ruleConfiguration.AppOfflineEnabled && usePublishSettingsFile) { string sourceAppOffline = Path.Combine(contentDirectory.FullName, DeploymentConstants.AppOfflineHtm); if (!File.Exists(sourceAppOffline) && !targetAppOffline.Exists) { using var _ = File.Create(targetAppOffline.FullName); _logger.Debug("Created offline file '{File}'", targetAppOffline.FullName); if (DeployerConfiguration.DefaultWaitTimeAfterAppOffline > TimeSpan.Zero) { await Task.Delay(DeployerConfiguration.DefaultWaitTimeAfterAppOffline, cancellationToken) .ConfigureAwait(false); } tempFilesToClean.Add(targetAppOffline.FullName); } } RecursiveIO.RecursiveCopy(contentDirectory, targetTempDirectoryInfo, _logger, deploymentExecutionDefinition.ExcludedFilePatterns); tempDirectoriesToClean.Add(targetTempDirectoryInfo); _logger.Debug("Copied content files from '{ContentDirectory}' to '{FullName}'", contentDirectory, targetTempDirectoryInfo.FullName); tempDirectoriesToClean.Add(packageInstallTempDirectory); bool hasPublishSettingsFile = !string.IsNullOrWhiteSpace(deploymentExecutionDefinition.PublishSettingsFile) && File.Exists(deploymentExecutionDefinition.PublishSettingsFile); if (hasPublishSettingsFile) { _logger.Debug("The publish settings file '{PublishSettingsFile}' exists", deploymentExecutionDefinition.PublishSettingsFile); } else { _logger.Debug("The deployment definition has no publish setting file"); } if (deploymentExecutionDefinition.PublishType == PublishType.WebDeploy) { _webDeployHelper.DeploymentTraceEventHandler += (sender, args) => { if (string.IsNullOrWhiteSpace(args.Message)) { return; } if (args.EventLevel == TraceLevel.Verbose) { _logger.Verbose("{Message}", args.Message); return; } _logger.Information("{Message}", args.Message); }; } bool hasIisSiteName = deploymentExecutionDefinition.IisSiteName.HasValue(); IDeploymentChangeSummary summary; try { IIisManager?manager = default; if (!string.IsNullOrWhiteSpace(deploymentExecutionDefinition.IisSiteName)) { manager = _iisManager(deploymentExecutionDefinition); } if (hasIisSiteName && manager is {}) { bool stopped = manager.StopSiteIfApplicable(); if (!stopped) { _logger.Error( "Could not stop IIS site for deployment execution definition {DeploymentExecutionDefinition}", deploymentExecutionDefinition); return(ExitCode.Failure); } } try { if (deploymentExecutionDefinition.PublishType == PublishType.WebDeploy) { _logger.Information("Deploying {Target} with WebDeploy", deploymentExecutionDefinition.TargetDirectoryPath); summary = await _webDeployHelper.DeployContentToOneSiteAsync( targetTempDirectoryInfo.FullName, deploymentExecutionDefinition.PublishSettingsFile, DeployerConfiguration.DefaultWaitTimeAfterAppOffline, doNotDelete : ruleConfiguration.DoNotDeleteEnabled, appOfflineEnabled : ruleConfiguration.AppOfflineEnabled, useChecksum : ruleConfiguration.UseChecksumEnabled, whatIf : ruleConfiguration.WhatIfEnabled, traceLevel : TraceLevel.Verbose, appDataSkipDirectiveEnabled : ruleConfiguration.AppDataSkipDirectiveEnabled, applicationInsightsProfiler2SkipDirectiveEnabled : ruleConfiguration.ApplicationInsightsProfiler2SkipDirectiveEnabled, logAction : message => _logger.Debug("{Message}", message), targetPath : hasPublishSettingsFile ?string.Empty : deploymentExecutionDefinition.TargetDirectoryPath ).ConfigureAwait(false); } else if (deploymentExecutionDefinition.PublishType.IsAnyFtpType) { var basePath = deploymentExecutionDefinition.FtpPath; bool isSecure = deploymentExecutionDefinition.PublishType == PublishType.Ftps; var ftpSettings = new FtpSettings(basePath, isSecure); _logger.Information("Deploying {Target} with {PublishType}", deploymentExecutionDefinition.FtpPath?.Path, deploymentExecutionDefinition.PublishType); string publishSettingsFile = deploymentExecutionDefinition.PublishSettingsFile; if (string.IsNullOrWhiteSpace(publishSettingsFile)) { _logger.Error( "Deployment target type is set to {Type} but no publish file is set", deploymentExecutionDefinition.PublishTypeValue); return(ExitCode.Failure); } using IFtpHandler ftpHandler = await _ftpHandlerFactory.CreateWithPublishSettings( publishSettingsFile, ftpSettings, _logger, cancellationToken); _logger.Verbose("Created FTP handler, starting publish"); summary = await ftpHandler.PublishAsync( ruleConfiguration, targetTempDirectoryInfo, cancellationToken); } else { throw new InvalidOperationException( $"Publish type {deploymentExecutionDefinition.PublishType} is not supported"); } } catch (Exception ex) when(!ex.IsFatal()) { _logger.Error(ex, "Could not deploy site {DeploymentExecutionDefinition}", deploymentExecutionDefinition); return(ExitCode.Failure); } finally { manager?.Dispose(); } } catch (Exception ex) when(!ex.IsFatal()) { _logger.Error(ex, "Could not handle start/stop for iis site {Site}", deploymentExecutionDefinition.IisSiteName); return(ExitCode.Failure); } _logger.Information("Summary: {Summary}", summary.ToDisplayValue()); }
public CheckerException(ExitCode exitCode, string stdOut = null) { ExitCode = exitCode; StdOut = stdOut; }
private static async Task <ExitCode> RunProcessAsync( string executePath, string formattedArguments, Action <string, string> standardErrorAction, Action <string, string> standardOutputLog, CancellationToken cancellationToken, Action <string, string> toolAction, Action <string, string> verboseAction = null, IEnumerable <KeyValuePair <string, string> > environmentVariables = null, Action <string, string> debugAction = null, bool addProcessNameAsLogCategory = false, bool addProcessRunnerCategory = false, string parentPrefix = null, bool noWindow = false) { toolAction = toolAction ?? ((message, prefix) => { }); Action <string, string> standardAction = standardOutputLog ?? ((message, prefix) => { }); Action <string, string> errorAction = standardErrorAction ?? ((message, prefix) => { }); Action <string, string> verbose = verboseAction ?? ((message, prefix) => { }); Action <string, string> debug = debugAction ?? ((message, prefix) => { }); var taskCompletionSource = new TaskCompletionSource <ExitCode>(); string processWithArgs = $"\"{executePath}\" {formattedArguments}".Trim(); string toolCategory = parentPrefix + ToolName; toolAction($"Executing '{processWithArgs}'", toolCategory); bool useShellExecute = standardErrorAction == null && standardOutputLog == null; string category = $"[{Path.GetFileNameWithoutExtension(Path.GetFileName(executePath))}] "; string outputCategory = parentPrefix + (addProcessRunnerCategory ? ToolName : string.Empty) + (addProcessNameAsLogCategory ? category : string.Empty); bool redirectStandardError = standardErrorAction != null; bool redirectStandardOutput = standardOutputLog != null; var processStartInfo = new ProcessStartInfo(executePath) { Arguments = formattedArguments, RedirectStandardError = redirectStandardError, RedirectStandardOutput = redirectStandardOutput, UseShellExecute = useShellExecute }; if (!useShellExecute) { processStartInfo.CreateNoWindow = noWindow; } if (environmentVariables != null) { foreach (KeyValuePair <string, string> environmentVariable in environmentVariables) { processStartInfo.EnvironmentVariables.Add(environmentVariable.Key, environmentVariable.Value); } } var exitCode = new ExitCode(-1); var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; process.Disposed += (sender, args) => { if (!taskCompletionSource.Task.IsCompleted) { verbose($"Task was not completed, but process '{processWithArgs}' was disposed", toolCategory); taskCompletionSource.TrySetResult(ExitCode.Failure); } verbose($"Disposed process '{processWithArgs}'", toolCategory); }; if (redirectStandardError) { process.ErrorDataReceived += (sender, args) => { if (args.Data != null) { errorAction(args.Data, outputCategory); } }; } if (redirectStandardOutput) { process.OutputDataReceived += (sender, args) => { if (args.Data != null) { standardAction(args.Data, outputCategory); } }; } process.Exited += (sender, args) => { var proc = (Process)sender; try { exitCode = new ExitCode(proc.ExitCode); } catch (InvalidOperationException ex) { toolAction($"Could not get exit code for process, {ex}", toolCategory); if (!taskCompletionSource.Task.IsCompleted && !taskCompletionSource.Task.IsCanceled && !taskCompletionSource.Task.IsFaulted) { taskCompletionSource.SetResult(new ExitCode(1)); } return; } toolAction($"Process '{processWithArgs}' exited with code {exitCode}", toolCategory); taskCompletionSource.SetResult(new ExitCode(proc.ExitCode)); }; int processId = -1; try { bool started = process.Start(); if (!started) { errorAction($"Process '{processWithArgs}' could not be started", toolCategory); return(ExitCode.Failure); } if (redirectStandardError) { process.BeginErrorReadLine(); } if (redirectStandardOutput) { process.BeginOutputReadLine(); } int bits = process.IsWin64() ? 64 : 32; try { processId = process.Id; } catch (InvalidOperationException ex) { debug($"Could not get process id for process '{processWithArgs}'. {ex}", toolCategory); } string temp = process.HasExited ? "was" : "is"; verbose( $"The process '{processWithArgs}' {temp} running in {bits}-bit mode", toolCategory); } catch (Exception ex) { if (ex.IsFatal()) { throw; } errorAction($"An error occured while running process '{processWithArgs}': {ex}", toolCategory); taskCompletionSource.SetException(ex); } bool done = false; try { while (process.IsAlive(taskCompletionSource.Task, cancellationToken, done, processWithArgs, toolAction, standardAction, errorAction, verbose)) { if (cancellationToken.IsCancellationRequested) { break; } Task delay = Task.Delay(TimeSpan.FromMilliseconds(50), cancellationToken); await delay; if (taskCompletionSource.Task.IsCompleted) { done = true; exitCode = await taskCompletionSource.Task; } else if (taskCompletionSource.Task.IsCanceled) { exitCode = ExitCode.Failure; } else if (taskCompletionSource.Task.IsFaulted) { exitCode = ExitCode.Failure; } } } finally { if (!exitCode.IsSuccess) { if (cancellationToken.IsCancellationRequested) { if (process != null && !process.HasExited) { try { toolAction($"Cancellation is requested, trying to kill process '{processWithArgs}'", toolCategory); if (processId > 0) { string args = $"/PID {processId}"; string killProcessPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "taskkill.exe"); toolAction($"Running {killProcessPath} {args}", toolCategory); Process.Start(killProcessPath, args); errorAction( $"Killed process '{processWithArgs}' because cancellation was requested", toolCategory); } else { debugAction( $"Could not kill process '{processWithArgs}', missing process id", toolCategory); } } catch (Exception ex) { if (ex.IsFatal()) { throw; } errorAction( $"ProcessRunner could not kill process '{processWithArgs}' when cancellation was requested", toolCategory); errorAction( $"Could not kill process '{processWithArgs}' when cancellation was requested", toolCategory); errorAction(ex.ToString(), toolCategory); } } } } using (process) { verbose( $"Task status: {taskCompletionSource.Task.Status}, {taskCompletionSource.Task.IsCompleted}", toolCategory); verbose($"Disposing process '{processWithArgs}'", toolCategory); } } verbose($"Process runner exit code {exitCode} for process '{processWithArgs}'", toolCategory); try { if (processId > 0) { Process stillRunningProcess = Process.GetProcesses().SingleOrDefault(p => p.Id == processId); if (stillRunningProcess != null) { if (!stillRunningProcess.HasExited) { errorAction( $"The process with ID {processId.ToString(CultureInfo.InvariantCulture)} '{processWithArgs}' is still running", toolCategory); return(ExitCode.Failure); } } } } catch (Exception ex) { if (ex.IsFatal()) { throw; } debugAction($"Could not check processes. {ex}", toolCategory); } return(exitCode); }
public static ExitCode Exit(string msg, ExitCode code) { Log(msg); return(code); }
public CommandFailedException(ExitCode ExitCode, string Message) : base(ExitCode, Message) { }
public ApplicationExitException(ExitCode exitCode, string?message) : base(message) { ExitCode = exitCode; }
public ExitCodeException(ExitCode exitCode) { ExitCode = exitCode; }
private static extern bool ExitWindowsEx(ExitCode code, int ret);
protected async Task Executing() => ExitCode = (ExitCode)await Subject.Execute();
public static int SetExitCode(ExitCode exitCode) { Environment.ExitCode = (int)exitCode; return(Environment.ExitCode); }
/// <summary> /// 退出window /// </summary> /// <param name="code"></param> /// <returns></returns> private static bool ExitWindows(ExitCode code) { return AdjustSelfToken() && ExitWindowsEx(code, 0); }
protected void TheExitCodeIs(ExitCode exitCode) => ExitCode.Should().Be(exitCode);
/// <summary> /// Prints usage instructions to the Console, and returns the int value for the ExitCode passed in /// </summary> private static int PrintUsage(ExitCode exitCode) { ConsoleColor originalColor = Console.ForegroundColor; Console.WriteLine(""); Console.WriteLine(" WTV (When The Version) Automatic date-based version numbering for .Net projects"); Console.WriteLine(" Andrew Freemantle - www.fatlemon.co.uk/wtv"); Console.WriteLine(""); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(" Error: " + exitCode.ToString().Replace("_", " ")); Console.ForegroundColor = originalColor; Console.WriteLine(""); Console.WriteLine(" Usage: WTV \"file-in\" \"file-out\" [\"path to SubWCrev.exe\" \"SVN working-copy-path\"]"); Console.WriteLine(" \"file-in\" can contain the following placeholders:"); Console.WriteLine(" {DD} - Day"); Console.WriteLine(" {MM} - Month"); Console.WriteLine(" {YYYY} - Year"); Console.WriteLine(" {SVN} - SubVersion revision (must specify the path to SubWCrev.exe and working copy path)"); Console.WriteLine(""); Console.WriteLine(" Example Pre-Build command: (remove the line breaks)"); Console.WriteLine(" \"C:\\Path\\To\\WTV.exe\""); Console.WriteLine(" \"$(ProjectDir)Properties\\AssemblyInfo.Template.cs\""); Console.WriteLine(" \"$(ProjectDir)Properties\\AssemblyInfo.cs\""); Console.WriteLine(" \"C:\\Program Files\\TortoiseSVN\\bin\\SubWCRev.exe\""); Console.WriteLine(" \"$(SolutionDir).\""); return (int)exitCode; }
public AutomationException(ExitCode ErrorCode, string Msg) : base(Msg) { this.ErrorCode = ErrorCode; }
public static void Exit(ExitCode exitCode, string reason) { Exit((int)exitCode, reason); }
public AutomationException(ExitCode ErrorCode, string Format, params object[] Args) : base(string.Format(Format, Args)) { this.ErrorCode = ErrorCode; }