/// <summary> /// clears states and enables motors /// </summary> /// <returns>bool that indicates, if operation was successful</returns> public bool Enable() { try { //reset fault state of motor 1 if (_sm1.GetFaultState()) { _sm1.ClearFault(); } //enable motor 1 _sm1.SetEnableState(); //reset fault state of motor 2 if (_sm2.GetFaultState()) { _sm2.ClearFault(); } //enable motor 2 _sm2.SetEnableState(); //returns true if Enable() was successful return(true); } //an error may occur catch (Exception e) { ConsoleFormatter.Error("Failed to activate the engine.", "Message: " + e.Message); //returns false if Enable() fails return(false); } }
/// <summary> /// makes right motor move with given velocity /// </summary> /// <param name="v2">velocity for the right motor epos2</param> /// <exception cref="DeviceException">thrown, when USB connection is lost</exception> /// <exception cref="Exception">thrown, when <see cref="ActivateVelocityMode"/> or <see cref="_pvm1.MoveWithVelocity"/> fails</exception> /// <returns>bool that indicates, if operation was successful</returns> public bool MoveWithVelocity2(int v2) { try { //velocity should be between specified borders //motor will not move with to high or to low velocity if (v2 >= -MaxVelocity && v2 <= MaxVelocity) { //VelocityMode is needed to let robot drive with a given velocity ActivateVelocityMode(); //negative velocity will make wheel move forwards _pvm2.MoveWithVelocity(v2 * -1); //returns true if operation was successfull return(true); } } //an error may occur catch (Exception e) { ConsoleFormatter.Error("Failed to move with velocity " + v2 + " for engine 2", "Message: " + e.Message); } //returns false if an error was thrown return(false); }
/// <summary> /// makes motors move with given velocities /// </summary> /// <param name="v1">velocity for left motor epos1</param> /// <param name="v2">velocity for right motor epos2</param> /// <returns>bool that indicates, if operation was successful</returns> public bool MoveWithVelocity(int v1, int v2) { try { //velocities should be between specified borders //motors will not move with to high or to low velocities if (v1 >= -MaxVelocity && v1 <= MaxVelocity && v2 >= -MaxVelocity && v2 <= MaxVelocity) { //VelocityMode is needed to let robot drive with a given velocity ActivateVelocityMode(); //negative velocities will make robot move forwards //both wheels should turn _pvm1.MoveWithVelocity(v1 * -1); _pvm2.MoveWithVelocity(v2 * -1); //returns true, if MoveWithVelocity() was successful return(true); } } //an error may occur catch (Exception e) { ConsoleFormatter.Error("Failed to move with velocity " + v1 + " and " + v2, "Message: " + e.Message); } //returns false if MoveWithVelocity() fails return(false); }
public ConsoleRunner() { formatter = new ConsoleFormatter(); console = new CSpecConsole(formatter); InitializeActions(); }
public static void WriteLine(string value, ConsoleColor color) { using (ConsoleFormatter.ForegroundColorScope(color)) { System.Console.WriteLine(value); } }
public override void Render() { ConsoleFormatter.Write(new ConsoleTable( new ConsoleCell("Unable to run action with supplied parameters.").WithPadding(0)) .AddEmptyRow() .AddRow(new ConsoleCell(_message).WithPadding(0))); }
public override void Render() { if (ActionName == null) { ConsoleFormatter.Write(new ConsoleTable() .AddRow( new ConsoleCell("You must specify an action name for command '{0}'.", Command.Name).WithPadding(0))); } else { ConsoleFormatter.Write(new ConsoleTable() .AddRow( new ConsoleCell("'{0}' is not a valid action for command '{1}'.", ActionName, Command.Name).WithPadding(0))); } var formattedActionList = string.Join(" or ", (PossibleActions.Count > 0 ? PossibleActions : AvailableActions).Select( c => String.Format("'{0}'", c.Name)).ToArray()); ConsoleFormatter.Write(new ConsoleTable() .AddEmptyRow() .AddRow( new ConsoleCell("Did you mean:").WithPadding(0)) .AddRow( new ConsoleCell(formattedActionList))); }
static void Main(string[] args) { if (args.Length == 0) { ShowUsage(); return; } try { var classFilter = args.Length > 1 ? args[1] : ""; var specDLL = args[0]; var domain = new NSpecDomain(specDLL + ".config"); var console = new ConsoleFormatter(); domain.Run(specDLL, classFilter, console, (dll, filter, formatter) => { var finder = new SpecFinder(dll, new Reflector(), filter); var builder = new ContextBuilder(finder, new DefaultConventions()); var runner = new ContextRunner(builder, formatter); runner.Run(); }); } catch (Exception e) { //hopefully this is handled before here, but if not, this is better than crashing the runner Console.WriteLine(e); } }
/// <summary> /// Inserts user into database /// </summary> /// <param name="_user"></param> /// <returns></returns> public UserModel Insert(UserModel _user) { using (MySqlConnection connection = CreateConnection()) { try { connection.Open(); MySqlCommand command = connection.CreateCommand(); command.CommandText = "INSERT INTO users (user_id, password_hash) VALUES (@user_id, @password_hash)"; command.Parameters.AddWithValue("@user_id", _user.UserID); command.Parameters.AddWithValue("@password_hash", _user.PswdHash); try { int rowsAffected = command.ExecuteNonQuery(); ConsoleFormatter.WriteLineWithTimestamp("User " + _user.UserID + " inserted"); _user.Status = RequestStatus.Success; return(_user); } catch (Exception e) { ConsoleFormatter.WriteLineWithTimestamp("ERROR: " + e.Message); _user.Status = RequestStatus.AlreadyExists; return(_user); } } catch (Exception e) { ConsoleFormatter.WriteLineWithTimestamp("ERROR: " + e.Message); _user.Status = RequestStatus.ConnectionError; return(_user); } } }
public void output_verification(Type output, Type [] testClasses, string tags) { var finder = new SpecFinder(testClasses, ""); var tagsFilter = new Tags().Parse(tags); var builder = new ContextBuilder(finder, tagsFilter, new DefaultConventions()); var consoleFormatter = new ConsoleFormatter(); var actual = new System.Collections.Generic.List <string>(); consoleFormatter.WriteLineDelegate = actual.Add; var runner = new ContextRunner(tagsFilter, consoleFormatter, false); runner.Run(builder.Contexts().Build()); var expectedString = GetExpectedOutput(output) .ScrubNewLines() .ScrubStackTrace() .ScrubTimes(); var actualString = String.Join("\n", actual) .ScrubStackTrace() .Trim() .ScrubTimes(); actualString.Should().Be(expectedString); }
public int Execute(string[] args) { if (IsVersionCommand(args)) { Console.Write($"Calamari version: {typeof(Program).Assembly.GetInformationalVersion()}"); return(0); } Log.Verbose($"Octopus Deploy: Calamari version {typeof(Program).Assembly.GetInformationalVersion()}"); Log.Verbose($"Environment Information:{Environment.NewLine}" + $" {string.Join($"{Environment.NewLine} ", EnvironmentHelper.SafelyGetEnvironmentInformation())}"); EnvironmentHelper.SetEnvironmentVariable(SpecialVariables.CalamariWorkingDirectory, Environment.CurrentDirectory); ProxyInitializer.InitializeDefaultProxy(); try { if (command == null) { return(PrintHelp(PluginUtils.GetFirstArgument(args))); } return(command.Execute(args.Skip(1).ToArray())); } catch (Exception ex) { return(ConsoleFormatter.PrintError(ex)); } }
/// <summary> /// Find an implementation of IFormatter with the given class name /// </summary> /// <param name="formatterClassName"></param> /// <param name="formatterOptions"></param> /// <returns></returns> static IFormatter FindFormatter(string formatterClassName, IDictionary <string, string> formatterOptions) { // Default formatter is the standard console formatter if (string.IsNullOrEmpty(formatterClassName)) { var consoleFormatter = new ConsoleFormatter(); consoleFormatter.Options = formatterOptions; return(consoleFormatter); } Assembly nspecAssembly = typeof(IFormatter).GetTypeInfo().Assembly; // Look for a class that implements IFormatter with the provided name var formatterType = nspecAssembly.GetTypes().FirstOrDefault(type => (type.Name.ToLowerInvariant() == formatterClassName) && typeof(IFormatter).IsAssignableFrom(type)); if (formatterType != null) { var formatter = (IFormatter)Activator.CreateInstance(formatterType); formatter.Options = formatterOptions; return(formatter); } else { throw new TypeLoadException("Could not find formatter type " + formatterClassName); } }
protected CalamariResult InvokeInProcess(CommandLine command, IVariables variables = null) { var args = command.GetRawArgs(); var program = new TestProgram(Log); int exitCode; try { exitCode = program.Run(args); } catch (Exception ex) { exitCode = ConsoleFormatter.PrintError(Log, ex); } variables = variables ?? new CalamariVariables(); var capture = new CaptureCommandInvocationOutputSink(); var sco = new SplitCommandInvocationOutputSink(new ServiceMessageCommandInvocationOutputSink(variables), capture); foreach (var line in Log.StandardOut) { sco.WriteInfo(line); } foreach (var line in Log.StandardError) { sco.WriteError(line); } return(new CalamariResult(exitCode, capture)); }
public override void Render() { ConsoleFormatter.Write(new ConsoleTable() .AddRow( new ConsoleCell("There are currently no commands defined.").WithPadding(0)) .AddRow( new ConsoleCell("Please ensure commands are correctly defined and registered within Synoptic using the [Command] attribute."))); }
public void DefaultFormatDoesNotChangeString() { var writer = Substitute.For <IConsoleWriter>(); var formatter = new ConsoleFormatter(writer); formatter.WriteLine(new TerminalMessage("this is a normal message", TerminalStyle.Default)); writer.Received(1).WriteLine("this is a normal message"); }
public void Format_GivenAGridWithASingleDeadCell_WillPrintACenteredDot() { var game = new Game(1, 1); var output = ConsoleFormatter.Format(game); output.Should().Be($"·{Environment.NewLine}"); }
private static void PrintInfo() { var xmlFormatter = new XmlFormatter(null); var consoleFormatter = new ConsoleFormatter(); consoleFormatter.Format(tracer.GetTraceResult()); xmlFormatter.Format(tracer.GetTraceResult()); }
public void WritesFlairInFrontOfInputtedCommand() { var writer = Substitute.For <IConsoleWriter>(); var formatter = new ConsoleFormatter(writer); formatter.WriteLine(new TerminalMessage("print hello", TerminalStyle.Command)); writer.Received(1).WriteLine(" > print hello"); }
static void Main(string[] args) { var shouldShowHelp = false; var useXUnitFormatter = false; var options = new OptionSet { { "h|help", "show this message and exit", h => shouldShowHelp = h != null }, { "f|formatter", "console (default) | xunit", f => useXUnitFormatter = string.Compare(f, "xunit", StringComparison.InvariantCultureIgnoreCase) == 0 } }; if (shouldShowHelp) { Console.WriteLine("Usage: [OPTIONS] path/to/test.assembly.dll path/to/test.2.assembly.dll"); Console.WriteLine(); Console.WriteLine("Options:"); options.WriteOptionDescriptions(Console.Out); } IFormatter formatter = null; if (useXUnitFormatter) { formatter = new XUnitFormatter(); } else { formatter = new ConsoleFormatter(); } IEnumerable <FileInfo> extra; try { extra = options.Parse(args).Select(n => new FileInfo(n)).Where(n => n.Exists); foreach (var asm in extra) { var invocation = new RunnerInvocation(asm.FullName, null, formatter, false); var result = invocation.Run(); var failes = result.Failures().ToArray(); if (failes.Any()) { throw new Exception($"NSpec run of {asm} reported Failures"); } } } catch (OptionException e) { Console.WriteLine(e.Message); Console.WriteLine("Try `--help' for more information."); return; } }
/// <summary> /// Initializes a default constructor. /// </summary> /// <remarks> /// In this context is hard to use the parmetrized contructor ( : base(....) ) /// thus we use the second option, /// we initialize the constructor ourselfs and then we call /// the method from base class InitializeFacade and pass our Spec(ed) class. /// </remarks> public CSpecConsoleSpec() { formatter = new ConsoleFormatter(); CSpecConsole console = new CSpecConsole(formatter); InitializeFacade(console); CreateOperations(); }
public void setup() { exceptionMessage = "Exception Message"; output = new ConsoleFormatter().Write(new Example("An Failed Example") { Exception = new Exception(exceptionMessage) }); }
public void Format_GivenAGridWithASingleAliveCell_WillPrintACapitalX() { var game = new Game(1, 1); game.ToggleState(0, 0); var output = ConsoleFormatter.Format(game); output.Should().Be($"X{Environment.NewLine}"); }
public void ChangesColorOnError() { var writer = Substitute.For <IConsoleWriter>(); var formatter = new ConsoleFormatter(writer); formatter.WriteLine(new TerminalMessage("[ERROR] Broke the everything", TerminalStyle.Error)); writer.Received(1).WriteLine("[ERROR] Broke the everything"); writer.Received(1).ChangeColor(ConsoleColor.Red); writer.Received(1).ChangeColor(ConsoleColor.White); }
/// <summary> /// Default constructor that initializes the console and it's formatters, as /// well as a list of commands used. /// </summary> public TestRunnerAction() { runner = new CSpecTestRunner(); formatter = new ConsoleFormatter(); console = new CSpecConsole(formatter); Commands = new List <ICommand>() { new Commands.RunnerAllCommand() }; }
private void PrintGeneration() { var stringBuilder = new StringBuilder(); stringBuilder.AppendJoin( Environment.NewLine, MakeHeader(), ConsoleFormatter.Format(_game) ); Console.Clear(); Console.WriteLine(stringBuilder.ToString()); }
public PlayerDataModel Select(PlayerDataModel data) { using (MySqlConnection connection = CreateConnection()) { try { connection.Open(); MySqlCommand command = connection.CreateCommand(); command.CommandText = "SELECT user_id, position_x, position_y, online FROM players WHERE user_id = @user_id"; command.Parameters.AddWithValue("@user_id", data.UserID); MySqlDataReader reader = command.ExecuteReader(); string user_id = ""; float position_x = 0; float position_y = 0; bool online = false; DateTimeOffset createdAt = DateTime.Now; while (reader.Read()) { user_id = reader["user_id"].ToString(); position_x = float.Parse((reader["position_x"].ToString())); position_y = float.Parse((reader["position_y"].ToString())); online = Convert.ToBoolean((reader["online"])); } if (!string.IsNullOrEmpty(user_id)) { data.PositionX = position_x; data.PositionY = position_y; data.Online = online; data.PlayerDataStatus = PlayerDataStatus.Success; return(data); } else { ConsoleFormatter.WriteLineWithTimestamp("User with ID " + data.UserID + " does not exist, or couldn't be found"); data.PlayerDataStatus = PlayerDataStatus.DoesNotExist; return(data); } } catch (Exception e) { ConsoleFormatter.WriteLineWithTimestamp("ERROR: " + e.Message); data.PlayerDataStatus = PlayerDataStatus.ConnectionFailed; return(data); } } }
public static int Main(string[] args) { try { SecurityProtocols.EnableAllSecurityProtocols(); var options = CommonOptions.Parse(args); return(new Program(ConsoleLog.Instance).Run(options)); } catch (Exception ex) { return(ConsoleFormatter.PrintError(ConsoleLog.Instance, ex)); } }
public void TestConsole_Read() { /* GIVEN */ const string stringInput = "InputString"; Console.SetIn(new StringReader(stringInput)); var consoleFormatter = new ConsoleFormatter(); /* WHEN */ var readString = consoleFormatter.Read(); /* THEN */ Assert.AreEqual(stringInput, readString); }
protected virtual int Run(string[] args) { try { SecurityProtocols.EnableAllSecurityProtocols(); var options = CommonOptions.Parse(args); Log.Verbose($"Calamari Version: {GetType().Assembly.GetInformationalVersion()}"); if (options.Command.Equals("version", StringComparison.OrdinalIgnoreCase)) { return(0); } var envInfo = string.Join($"{Environment.NewLine} ", EnvironmentHelper.SafelyGetEnvironmentInformation()); Log.Verbose($"Environment Information: {Environment.NewLine} {envInfo}"); EnvironmentHelper.SetEnvironmentVariable("OctopusCalamariWorkingDirectory", Environment.CurrentDirectory); ProxyInitializer.InitializeDefaultProxy(); var builder = new ContainerBuilder(); ConfigureContainer(builder, options); using var container = builder.Build(); container.Resolve <VariableLogger>().LogVariables(); #if DEBUG var waitForDebugger = container.Resolve <IVariables>().Get(KnownVariables.Calamari.WaitForDebugger); if (string.Equals(waitForDebugger, "true", StringComparison.CurrentCultureIgnoreCase)) { using var proc = Process.GetCurrentProcess(); Log.Info($"Waiting for debugger to attach... (PID: {proc.Id})"); while (!Debugger.IsAttached) { Thread.Sleep(1000); } } #endif return(ResolveAndExecuteCommand(container, options)); } catch (Exception ex) { return(ConsoleFormatter.PrintError(ConsoleLog.Instance, ex)); } }
public override int Execute(string[] commandLineArguments) { Options.Parse(commandLineArguments); try { CheckArguments( packageId, packageVersion, feedId, feedUri, feedUsername, feedPassword, maxDownloadAttempts, attemptBackoffSeconds, out var version, out var uri, out var parsedMaxDownloadAttempts, out var parsedAttemptBackoff); var packageDownloaderStrategy = new PackageDownloaderStrategy(log, scriptEngine, fileSystem, commandLineRunner, variables); var pkg = packageDownloaderStrategy.DownloadPackage( packageId, version, feedId, uri, feedType, feedUsername, feedPassword, forcePackageDownload, parsedMaxDownloadAttempts, parsedAttemptBackoff); log.VerboseFormat("Package {0} v{1} successfully downloaded from feed: '{2}'", packageId, version, feedUri); log.SetOutputVariableButDoNotAddToVariables("StagedPackage.Hash", pkg.Hash); log.SetOutputVariableButDoNotAddToVariables("StagedPackage.Size", pkg.Size.ToString(CultureInfo.InvariantCulture)); log.SetOutputVariableButDoNotAddToVariables("StagedPackage.FullPathOnRemoteMachine", pkg.FullFilePath); } catch (Exception ex) { log.ErrorFormat("Failed to download package {0} v{1} from feed: '{2}'", packageId, packageVersion, feedUri); return(ConsoleFormatter.PrintError(log, ex)); } return(0); }
public void output_verification(Type output, Type []testClasses, string tags) { var finder = new SpecFinder(testClasses, ""); var builder = new ContextBuilder(finder, new Tags().Parse(tags), new DefaultConventions()); var consoleFormatter = new ConsoleFormatter(); var actual = new System.Collections.Generic.List<string>(); consoleFormatter.WriteLineDelegate = actual.Add; var runner = new ContextRunner(builder, consoleFormatter, false); runner.Run(builder.Contexts().Build()); var expectedString = ScrubStackTrace(ScrubNewLines(output.GetField("Output").GetValue(null) as string)); var actualString = ScrubStackTrace(String.Join("\n", actual)).Trim(); actualString.should_be(expectedString); }
public void setup() { try { throw new Exception("BOOM!"); } catch (Exception exception) { example = new Example("example name") { Exception = exception }; } var context = new Context("context name"); context.AddExample(example); output = new ConsoleFormatter().WriteFailure(example); }
public void setup() { formatter = new ConsoleFormatter(); }