public void TestArray() { // Test that we can parse array parameters, and we strip empty entries var obj = new ArrayTest(); var onlyNum = new Dictionary <string, Variant>(); onlyNum["num1"] = new Variant("10,11,12"); onlyNum["str"] = new Variant("string 1,string2,,,,,,,,,,,string three"); ParameterParser.Parse(obj, onlyNum); Assert.NotNull(obj.num1); Assert.NotNull(obj.num2); Assert.NotNull(obj.str); Assert.AreEqual(3, obj.num1.Length); Assert.AreEqual(0, obj.num2.Length); Assert.AreEqual(3, obj.str.Length); Assert.AreEqual(10, obj.num1[0]); Assert.AreEqual(11, obj.num1[1]); Assert.AreEqual(12, obj.num1[2]); Assert.AreEqual("string 1", obj.str[0]); Assert.AreEqual("string2", obj.str[1]); Assert.AreEqual("string three", obj.str[2]); }
/// <summary> /// The main program /// </summary> static int Main(string[] args) { Console.WriteLine("OpenIZ HTML Applet Compiler v{0} ({1})", Assembly.GetEntryAssembly().GetName().Version, Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion); Console.WriteLine("Copyright (C) 2015-2018 Mohawk College of Applied Arts and Technology"); int retVal = 0; ParameterParser <ConsoleParameters> parser = new ParameterParser <ConsoleParameters>(); var parameters = parser.Parse(args); if (parameters.Help) { parser.WriteHelp(Console.Out); return(0); } else if (parameters.Compile) { return(Compile(parameters)); } else if (parameters.Sign) { return(Sign(parameters)); } else { Console.WriteLine("Nothing to do!"); return(0); } }
private static void Main(string[] args) { try { var parser = new ParameterParser(new MainExecutionGroup(), new EveMarketExecutionGroup()); parser.Parse(args); if (!parser.Execute()) { parser.ShowHelp(); } } catch (RequiredParametersMissingException requiredE) { Console.WriteLine("Required parameters were not set: " + requiredE.MissingRequiredParameters.Join(", ")); Environment.Exit(3); } catch (UnknownParameterException unknownE) { Console.WriteLine("Unknown parameter: " + unknownE.Parameter); Environment.Exit(2); } catch (Exception e) { Console.WriteLine(e.GetStackTrace()); Environment.Exit(-10); } }
/// <summary> /// /// </summary> /// <param name="stream">Stream containing the content</param> /// <param name="contentType">Content type header</param> /// <param name="encoding">Stream encoding</param> /// <returns>Collection with all parameters.</returns> /// <exception cref="FormatException">Body format is invalid for the specified content type.</exception> /// <exception cref="InternalServerException">Failed to read all bytes from body stream.</exception> public DecodedData Decode(Stream stream, ContentTypeHeader contentType, Encoding encoding) { if (stream == null || stream.Length == 0) { return(null); } if (encoding == null) { encoding = Encoding.UTF8; } try { var content = new byte[stream.Length]; int bytesRead = stream.Read(content, 0, content.Length); if (bytesRead != content.Length) { throw new InternalServerException("Failed to read all bytes from body stream."); } return(new DecodedData { Parameters = ParameterParser.Parse(new BufferReader(content, encoding)) }); } catch (ArgumentException err) { throw new FormatException(err.Message, err); } }
public void ShouldAcceptionOptionalArguments() { var environmentProvider = Substitute.For <IEnvironmentProvider>(); var buildService = Substitute.For <IBuildService>(); var cloneRoot = Faker.Random.String(10); var commitHash = Faker.Random.String(10); var gitHubOwner = Faker.Random.String(10); var gitHubRepo = Faker.Random.String(10); var token = Faker.Random.String(10); var configuration = Faker.Random.String(10); var annotationCount = Faker.Random.Int(0); var pullrequest = Faker.Random.Int(0); buildService.CloneRoot.Returns(cloneRoot); buildService.CommitHash.Returns(commitHash); buildService.GitHubOwner.Returns(gitHubOwner); buildService.GitHubRepo.Returns(gitHubRepo); environmentProvider.GetEnvironmentVariable("BCC_TOKEN").Returns(token); var parameterParser = new ParameterParser(environmentProvider, buildService); var parameters = parameterParser.Parse($"configuration={configuration};annotationcount={annotationCount};pullrequest={pullrequest}"); parameters.Should().NotBeNull(); parameters.CloneRoot.Should().Be(cloneRoot); parameters.Hash.Should().Be(commitHash); parameters.Owner.Should().Be(gitHubOwner); parameters.Repo.Should().Be(gitHubRepo); parameters.Token.Should().Be(token); parameters.ConfigurationFile.Should().Be(configuration); parameters.AnnotationCount.Should().Be(annotationCount); parameters.PullRequestNumber.Should().Be(pullrequest); }
static void Main(string[] args) { Console.WriteLine("OpenIZ Debugger v{0} ({1})", Assembly.GetEntryAssembly().GetName().Version, Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion); Console.WriteLine("Copyright (C) 2015-2018 Mohawk College of Applied Arts and Technology"); ParameterParser <DebuggerParameters> parser = new ParameterParser <DebuggerParameters>(); var parameters = parser.Parse(args); if (parameters.Help) { parser.WriteHelp(Console.Out); } else if (parameters.Protocol) { new ProtoDebugger(parameters).Debug(); } else if (parameters.BusinessRule) { new BreDebugger(parameters).Debug(); } else { Console.WriteLine("Nothing to do!"); } }
public void ShouldGetFromBuildService() { var environmentProvider = Substitute.For <IEnvironmentProvider>(); var buildService = Substitute.For <IBuildService>(); var cloneRoot = Faker.Random.String(10); var commitHash = Faker.Random.String(10); var gitHubOwner = Faker.Random.String(10); var gitHubRepo = Faker.Random.String(10); var token = Faker.Random.String(10); buildService.CloneRoot.Returns(cloneRoot); buildService.CommitHash.Returns(commitHash); buildService.GitHubOwner.Returns(gitHubOwner); buildService.GitHubRepo.Returns(gitHubRepo); environmentProvider.GetEnvironmentVariable("BCC_TOKEN").Returns(token); var parameterParser = new ParameterParser(environmentProvider, buildService); var parameters = parameterParser.Parse(string.Empty); parameters.Should().NotBeNull(); parameters.CloneRoot.Should().Be(cloneRoot); parameters.Hash.Should().Be(commitHash); parameters.Owner.Should().Be(gitHubOwner); parameters.Repo.Should().Be(gitHubRepo); parameters.Token.Should().Be(token); }
public VmwareMonitor(IAgent agent, string name, Dictionary <string, Variant> args) : base(agent, name, args) { ParameterParser.Parse(this, args); if (!SnapshotIndex.HasValue && string.IsNullOrEmpty(SnapshotName)) { throw new PeachException("Either SnapshotIndex or SnapshotName is required."); } if (SnapshotIndex.HasValue && !string.IsNullOrEmpty(SnapshotName)) { throw new PeachException("Only specify SnapshotIndex or SnapshotName, not both."); } try { GetErrorText(VixError.VIX_OK); } catch (DllNotFoundException ex) { string msg = "VMWare VIX library could not be found. Ensure VIX API 1.12 has been installed. The SDK download can be found at 'http://www.vmware.com/support/developer/vix-api/'"; throw new PeachException(msg, ex); } }
public void ShouldBeOverrideable() { var environmentProvider = Substitute.For <IEnvironmentProvider>(); var buildService = Substitute.For <IBuildService>(); buildService.CloneRoot.Returns(Faker.Random.String(10)); buildService.CommitHash.Returns(Faker.Random.String(10)); buildService.GitHubOwner.Returns(Faker.Random.String(10)); buildService.GitHubRepo.Returns(Faker.Random.String(10)); environmentProvider.GetEnvironmentVariable("BCC_TOKEN").Returns(Faker.Random.String(10)); var cloneRoot = Faker.Random.String(10); var commitHash = Faker.Random.String(10); var gitHubOwner = Faker.Random.String(10); var gitHubRepo = Faker.Random.String(10); var token = Faker.Random.String(10); var parameterParser = new ParameterParser(environmentProvider, buildService); var parameters = parameterParser.Parse($"cloneroot={cloneRoot};hash={commitHash};owner={gitHubOwner};repo={gitHubRepo};token={token}"); parameters.Should().NotBeNull(); parameters.CloneRoot.Should().Be(cloneRoot); parameters.Hash.Should().Be(commitHash); parameters.Owner.Should().Be(gitHubOwner); parameters.Repo.Should().Be(gitHubRepo); parameters.Token.Should().Be(token); }
private static void Main(string[] args) { Console.WriteLine("SanteDB Business Rule & CDSS Debugger v{0} ({1})", Assembly.GetEntryAssembly().GetName().Version, Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion); Console.WriteLine(Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyCopyrightAttribute>().Copyright); ParameterParser <DebuggerParameters> parser = new ParameterParser <DebuggerParameters>(); var parameters = parser.Parse(args); if (parameters.Help || args.Length == 0) { parser.WriteHelp(Console.Out); } else if (parameters.Protocol) { new ProtoDebugger(parameters).Debug(); } else if (parameters.BusinessRule) { new BreDebugger(parameters).Debug(); } else { Console.WriteLine("Nothing to do!"); } }
public LinuxDebugger(IAgent agent, string name, Dictionary <string, Variant> args) : base(agent, name, args) { ParameterParser.Parse(this, args); _exploitable = FindExploitable(); }
static void Main(string[] args) { // Parse paramters try { // Setup parameters ParameterParser <ConsoleParameters> parser = new ParameterParser <ConsoleParameters>(); ConsoleParameters parms = parser.Parse(args); MessageWriter mw = new MessageWriter(Console.Out, String.IsNullOrEmpty(parms.Verbosity) ? MessageWriter.VerbosityType.Information : (MessageWriter.VerbosityType)Int32.Parse(parms.Verbosity)); System.Diagnostics.Trace.Listeners.Add(mw); if (String.IsNullOrEmpty(parms.Output) || String.IsNullOrEmpty(parms.Assembly)) { Console.WriteLine("Must specify the output and assembly parameters"); return; } FileName = parms.Output; FileContents = GenerateScaffold(parms); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { #if DEBUG System.Console.ReadKey(); #endif } }
static void Main(string[] args) { // Parse paramters try { // Setup parameters ParameterParser<ConsoleParameters> parser = new ParameterParser<ConsoleParameters>(); ConsoleParameters parms = parser.Parse(args); MessageWriter mw = new MessageWriter(Console.Out, String.IsNullOrEmpty(parms.Verbosity) ? MessageWriter.VerbosityType.Information : (MessageWriter.VerbosityType)Int32.Parse(parms.Verbosity)); System.Diagnostics.Trace.Listeners.Add(mw); if (String.IsNullOrEmpty(parms.Output) || String.IsNullOrEmpty(parms.Assembly)) { Console.WriteLine("Must specify the output and assembly parameters"); return; } FileName = parms.Output; FileContents = GenerateScaffold(parms); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { #if DEBUG System.Console.ReadKey(); #endif } }
public void ShouldThrowOnUnknown() { var environmentProvider = Substitute.For <IEnvironmentProvider>(); var buildService = Substitute.For <IBuildService>(); var cloneRoot = Faker.Random.String(10); var commitHash = Faker.Random.String(10); var gitHubOwner = Faker.Random.String(10); var gitHubRepo = Faker.Random.String(10); var token = Faker.Random.String(10); var configuration = Faker.Random.String(10); var annotationCount = Faker.Random.Int(0); buildService.CloneRoot.Returns(cloneRoot); buildService.CommitHash.Returns(commitHash); buildService.GitHubOwner.Returns(gitHubOwner); buildService.GitHubRepo.Returns(gitHubRepo); environmentProvider.GetEnvironmentVariable("BCC_TOKEN").Returns(token); var parameterParser = new ParameterParser(environmentProvider, buildService); new Action(() => parameterParser.Parse($"unknown=value")) .Should().Throw <ArgumentException>() .WithMessage("Unknown key `unknown`"); }
public void Parse_WithParameter_AddsStringToDictionary() { var context = BuildContext("http://localhost/test?param=value", "/test"); var parameters = ParameterParser.Parse(context); ApiAssert.ContainsParameter(parameters, "param", "value"); }
public void Parse_WithID_ReturnsDictionaryWithParameter() { var context = BuildContext("http://localhost/test/1", "/test/{id}"); var parameters = ParameterParser.Parse(context); ApiAssert.ContainsParameter(parameters, "id", 1); }
public void Parse_WithParameter_DecodesParameter() { var value = HttpUtility.UrlEncode("encoded value"); var context = BuildContext("http://localhost/test?param=" + value, "/test"); var parameters = ParameterParser.Parse(context); ApiAssert.ContainsParameter(parameters, "param", "encoded value"); }
public void Parse_NoParameters_ReturnsEmptyDictionary() { var context = BuildContext("http://localhost/", "/"); var parameters = ParameterParser.Parse(context); Assert.NotNull(parameters); Assert.AreEqual(0, parameters.Count); }
public void ReturnsIEnumerableOfParameter() { object result = ParameterParser.Parse(null); IEnumerable <Parameter> implements = result as IEnumerable <Parameter>; Assert.NotNull(implements); }
public static IEnumerable <object> ApplyODataUriFilter <T>(this NancyContext context, IEnumerable <T> modelItems) { var nv = ParseUriOptions(context); var parser = new ParameterParser <T>(); var filter = parser.Parse(nv); return(filter.Filter(modelItems)); }
public FillValueFixup(DataElement parent, Dictionary <string, Variant> args) : base(parent, args, "ref") { ParameterParser.Parse(this, args); if (stop < start) { throw new PeachException("Value of 'start' must be less than or equal to the value of 'stop'."); } }
public void TestHexStringBad() { var obj = new HexPlugin(); var args = new Dictionary <string, Variant>(); args["arg"] = new Variant("Hello"); ParameterParser.Parse(obj, args); }
public InternetFixup(DataElement parent, Dictionary <string, Variant> args, params string[] refs) : base(parent, args, refs) { ParameterParser.Parse(this, args); srcAddress = src != null?src.GetAddressBytes() : new byte[0]; dstAddress = dst != null?dst.GetAddressBytes() : new byte[0]; }
/// <summary> /// Filters the source collection using the passed query parameters. /// </summary> /// <param name="source">The source items to filter.</param> /// <param name="query">The query parameters defining the filter.</param> /// <typeparam name="T">The <see cref="Type"/> of items in the source collection.</typeparam> /// <returns>A filtered and projected enumeration of the source collection.</returns> public static IQueryable <object> Filter <T>(this IEnumerable <T> source, NameValueCollection query) { Contract.Requires <ArgumentNullException>(source != null); Contract.Requires <ArgumentNullException>(query != null); var parser = new ParameterParser <T>(); return(Filter(source, parser.Parse(query))); }
public void ParameterParserTest() { ParameterParser p = new ParameterParser(); p.AddParser(typeof(FooParser)); Foo f = (Foo)p.Parse(typeof(Foo), "woot"); Assert.AreEqual(f.s, "woot"); }
/// <summary> /// Substitutes ADO parameter placeholders (?) for all encountered /// parameter specifications. It also tracks the positions of these /// parameter specifications within the query string. This accounts for /// ordinal-params, named-params, and ejb3-positional-params. /// </summary> /// <param name="sqlString">The query string. </param> /// <returns> The SQL query with parameter substitution complete. </returns> private SqlString SubstituteParams(string sqlString) { var recognizer = new ParameterSubstitutionRecognizer(factory); ParameterParser.Parse(sqlString, recognizer); parametersSpecifications = recognizer.ParametersSpecifications.ToList(); return(recognizer.result.ToSqlString()); }
public void TestReturnSubclass() { ParameterParser p = new ParameterParser(); p.AddParser(typeof(BarParser)); Bar f = (Bar)p.Parse(typeof(Foo), "woot"); Assert.AreEqual(f.s, "woot"); }
public IEnumerable <Command> Build(string config) { var settings = _parser.Parse(config); foreach (var setting in settings) { yield return(_builders[setting.Name].Build(setting)); } }
/// <summary> /// The main entry point for the application. /// </summary> internal static void Main(string[] args) { // Parser var parser = new ParameterParser <ConsoleParameters>(); // Trace copyright information var entryAsm = Assembly.GetEntryAssembly(); var hasConsole = true; traceSource.TraceEvent(TraceEventType.Information, 0, "Patient Generator Startup : v{0}", entryAsm.GetName().Version); traceSource.TraceEvent(TraceEventType.Information, 0, "Patient Generator Working Directory : {0}", entryAsm.Location); traceSource.TraceEvent(TraceEventType.Information, 0, "Operating System: {0} {1}", Environment.OSVersion.Platform, Environment.OSVersion.VersionString); traceSource.TraceEvent(TraceEventType.Information, 0, "CLI Version: {0}", Environment.Version); try { var parameters = parser.Parse(args); // What to do? if (parameters.ShowHelp) { parser.WriteHelp(Console.Out); } else if (parameters.ConsoleMode) { Console.WriteLine("Patient Generator {0}", entryAsm.GetName().Version); Console.WriteLine("{0}", entryAsm.GetCustomAttribute <AssemblyCopyrightAttribute>().Copyright); ServiceUtil.Start(typeof(Program).GUID); Console.WriteLine("Press [ENTER] to stop..."); Console.ReadLine(); ServiceUtil.Stop(); } else { hasConsole = false; ServiceBase[] servicesToRun = new ServiceBase[] { new PatientGenerator() }; ServiceBase.Run(servicesToRun); } } catch (Exception e) { #if DEBUG Trace.TraceError(e.ToString()); if (hasConsole) { Console.WriteLine(e.ToString()); } #else Trace.TraceError("Error encountered: {0}. Will terminate", e.Message); #endif } }
public void ParseSingleInt() { var name = "num"; var expected = 12; var input = $"{name}={expected}"; var parser = new ParameterParser(); var provider = parser.Parse(input); Assert.AreEqual(expected, provider.Get <int>(name)); }
public void ParseMultipleParameters() { var input = "w=640 h=480 optimize no-default"; var parser = new ParameterParser(); var provider = parser.Parse(input); Assert.AreEqual(640, provider.Get <int>("w")); Assert.AreEqual(480, provider.Get <int>("h")); Assert.AreEqual(true, provider.Get <bool>("optimize")); Assert.AreEqual(true, provider.Get <bool>("no-default")); }
static void Main(string[] args) { Console.WriteLine("XML ITS1 Formatter Pregenerator Utility"); Console.WriteLine("Copyright (C) 2012, Mohawk College of Applied Arts and Technology"); ParameterParser<Parameters> parser = new ParameterParser<Parameters>(); try { var arguments = parser.Parse(args); if (arguments.ShowHelp) { ShowHelp(); return; } // Generate formatter utility MARC.Everest.Formatters.XML.ITS1.CodeGen.TypeFormatterCreator creator = new MARC.Everest.Formatters.XML.ITS1.CodeGen.TypeFormatterCreator(); // Create code namespace CodeNamespace ns = new CodeNamespace(arguments.TargetNs); // Load assembly Assembly rmimAssembly = Assembly.LoadFile(arguments.AssemblyFile); List<Type> rmimTypes = new List<Type>(); if (arguments.Interactions != null) foreach (var s in arguments.Interactions) rmimTypes.Add(rmimAssembly.GetTypes().First(o => o.Name == s)); else rmimTypes.AddRange(rmimAssembly.GetTypes()); // Validate parameters if (rmimTypes.Count == 0) throw new ArgumentException("Type array must have at least one element", "t"); // Create a list of types (a todo list) that represent the types we want to format List<Type> types = new List<Type>(200); // Iterate through types and create formatter // Iterate throgh the types foreach (Type type in rmimTypes) { if (type.Assembly != rmimAssembly) throw new InvalidOperationException("All types must belong to the same revision assembly"); GetUniqueTypes(type, types, true); } // Waith thread pool WaitThreadPool wtp = new WaitThreadPool(); try { // Create type definitions foreach (Type t in types) { // Check if we need to gen this type if (t.GetCustomAttributes(typeof(StructureAttribute), false).Length == 0 || s_formatterGenerated.Contains(t)) continue; s_formatterGenerated.Add(t); // Structure Attribute StructureAttribute sta = t.GetCustomAttributes(typeof(StructureAttribute), false)[0] as StructureAttribute; // Type formatter creator TypeFormatterCreator crtr = new TypeFormatterCreator(); // Reset event crtr.CodeTypeDeclarationCompleted += new CreateTypeFormatterCompletedDelegate(delegate(CodeTypeDeclaration result) { // Add to the code currently created if (result != null) lock (ns) ns.Types.Add(result); }); // Helper result wtp.QueueUserWorkItem(crtr.CreateTypeFormatter, t); } // Wait for final pool to clear wtp.WaitOne(); } finally { wtp.Dispose(); } if (ns.Types.Count == 0) { Console.WriteLine("Didn't create any formatter helpers..."); return; } // Setup compiler and referenced assemblies CSharpCodeProvider csharpCodeProvider = new CSharpCodeProvider(); using (TextWriter tw = File.CreateText(arguments.Output ?? "output.cs")) csharpCodeProvider.GenerateCodeFromNamespace(ns, tw, new System.CodeDom.Compiler.CodeGeneratorOptions() { IndentString = "\t" }); } catch (ArgumentNullException) { ShowHelp(); } catch (Exception e) { Console.WriteLine(e.ToString()); return; } finally { } #if DEBUG Console.ReadKey(); #endif }
public static void Main(string[] args) { ConsoleTraceWriter consoleWriter = null; try { // Create a parser ParameterParser<MifConverterParameters> parser = new ParameterParser<MifConverterParameters>(); parameters = parser.Parse(args); // Create the console writer consoleWriter = new ConsoleTraceWriter(MessageWriter.VerbosityType.Information | MessageWriter.VerbosityType.Fatal | MessageWriter.VerbosityType.Error); // Are there any shortcuts if (parameters.Quiet) consoleWriter.Verbosity = MessageWriter.VerbosityType.None; else if (parameters.ErrorsOnly) consoleWriter.Verbosity = MessageWriter.VerbosityType.Error | MessageWriter.VerbosityType.Fatal; else if (parameters.Debug) consoleWriter.Verbosity = (MessageWriter.VerbosityType)15; else if (parameters.Chatty) consoleWriter.Verbosity = (MessageWriter.VerbosityType)31; else if(parameters.Verbosity != null) consoleWriter.Verbosity = (MessageWriter.VerbosityType)Convert.ToInt32(parameters.Verbosity); // Are we doing anything? bool noAction = !parameters.Help && !parameters.ShowVersion && (args.Length == 0 || parameters.Sources == null || parameters.Sources.Count == 0 || parameters.Renderers == null || parameters.Renderers.Count == 0); // IF no parameters, then help will be displayed // Now default System.Diagnostics.Trace.Listeners.Add(consoleWriter); // Display information Console.WriteLine("General Purpose MIF Converter & Render Tool v{0}", Assembly.GetEntryAssembly().GetName().Version); Console.WriteLine("Copyright (C) 2008-2013 Mohawk College of Applied Arts and Technology"); Console.WriteLine("All rights reserved"); // Load extensions loadAssemblies(consoleWriter); // Help being displayed? if (noAction) { Console.WriteLine("\r\nNothing to do! \r\nUsage:"); Console.WriteLine("gpmr --renderer=xxxx --source=source.mif\r\ngpmr --renderer=xxxx source.mif\r\ngpmr --renderer=xxxx --output-dir=out_dir\r\n"); Console.WriteLine("For parameter listing use : gpmr --help"); } else if (parameters.Help) dumpHelp(); else if (parameters.ShowVersion) dumpVersions(); else processTranformation(); // Write out stats Console.WriteLine("\r\nOperation completed, following messages were generated:"); foreach (KeyValuePair<string, Int32> kv in consoleWriter.MessageCount) Console.WriteLine("{0} -> {1}", kv.Key, kv.Value); Environment.Exit(0); } catch(Exception e) { Console.WriteLine(e.Message); System.Diagnostics.Debug.Print(e.ToString()); Environment.Exit(1); } #if DEBUG System.Console.ReadKey(); #endif }