public void Should_get_simple_variables() { var p = new OptionSet(); var name = p.AddVariable<string>("n", ""); var age = p.AddVariable<int>("a", ""); var myArgs = "-n FindThisString -a:23".Split(' '); p.Parse(myArgs); Assert.AreEqual(23, age); Assert.AreEqual("FindThisString", name); }
public void Should_Get_Simple_Variables() { var optionSet = new OptionSet(); var name = optionSet.AddVariable<string>("n", ""); var age = optionSet.AddVariable<int>("a", ""); /* TODO: The splitskies are clever, but are also error prone. We're assuming * by this that the string is as it appears at the command line, when this is * not the case. This is as the text appears after the command line parser is * through presenting the args to the application. */ var args = "-n FindThisString -a:23".Split(' '); optionSet.Parse(args); Assert.AreEqual(23, age); Assert.AreEqual("FindThisString", name); }
public void Should_Get_Simple_Variables() { var optionSet = new OptionSet(); var name = optionSet.AddVariable <string>("n", ""); var age = optionSet.AddVariable <int>("a", ""); /* TODO: The splitskies are clever, but are also error prone. We're assuming * by this that the string is as it appears at the command line, when this is * not the case. This is as the text appears after the command line parser is * through presenting the args to the application. */ var args = "-n FindThisString -a:23".Split(' '); optionSet.Parse(args); Assert.AreEqual(23, age); Assert.AreEqual("FindThisString", name); }
public void Should_Not_Throw_Exception_Multiset_Variable() { var optionSet = new OptionSet(); var n = optionSet.AddVariable <string>("n", ""); //TODO: Screaming for an NUnit-test-case-coverage. var args = "-n:Noah -n:Moses -n:David".Split(' '); try { optionSet.Parse(args); } catch (OptionException oex) { Assert.Fail("Unexpected exception: {0}", oex); } }
public void Should_throw_exception_of_setting_variable_twice() { var exceptionHappened = false; var p = new OptionSet(); var n = p.AddVariable<string>("n", ""); var myArgs = "-n:Ryan -n:Jer".Split(' '); try { p.Parse(myArgs); } catch (OptionException ex) { if (ex.OptionName == "n=") exceptionHappened = true; } Assert.IsTrue(exceptionHappened); }
static void Main(string[] args) { var os = new OptionSet(); var dir = os.AddVariable <string>("d|dir", "Directory to sniff, defaults to current"); var csv = os.AddVariable <string>("c|csv", "FileSpec of csv output"); var deepInfo = os.AddSwitch("i|inf", "Deep scan of pages and images. If csv specified outputs additional page and image files."); var showHelp = os.AddSwitch("h|help", "Show Help"); os.Parse(args); if (showHelp.Enabled) { Console.WriteLine("Options:"); os.WriteOptionDescriptions(Console.Out); return; } var directoryToScan = dir.Value ?? Directory.GetCurrentDirectory(); if (!Directory.Exists(directoryToScan)) { Console.WriteLine($"Error - Can't find directory {directoryToScan}"); return; } string[] pdfFiles = Directory.GetFiles(directoryToScan, "*.pdf", SearchOption.AllDirectories); Console.WriteLine($"Found {pdfFiles.Length} PDF files"); string csvFileDir = null; string csvFileName = null; string csvFileExt = null; string fileCsvFilePath = null; FileStream fileCsvFs = null; StreamWriter filesr = null; string piCsvFilePath = null; FileStream piCsvFs = null; StreamWriter pisr = null; string imCsvFilePath = null; FileStream imCsvFs = null; StreamWriter imsr = null; if (csv.Value != null) { csvFileDir = Path.GetDirectoryName(csv.Value); csvFileName = Path.GetFileNameWithoutExtension(csv.Value); csvFileExt = Path.GetExtension(csv.Value); fileCsvFilePath = csvFileDir + "\\" + csvFileName + csvFileExt; piCsvFilePath = csvFileDir + "\\" + csvFileName + "_pageinf" + csvFileExt; imCsvFilePath = csvFileDir + "\\" + csvFileName + "_imginf" + csvFileExt; fileCsvFs = new FileStream(fileCsvFilePath, FileMode.Create); filesr = new StreamWriter(fileCsvFs); filesr.WriteLine("FilePath, FileName, PDFVersion, CreationDate, Creator, ModDate, Producer, PageCount, FileSize, ImageCount, TextCharacters, ImageBytes, ErrorMessageCount, Errors"); if (deepInfo.Enabled) { piCsvFs = new FileStream(piCsvFilePath, FileMode.Create); pisr = new StreamWriter(piCsvFs); pisr.WriteLine("FilePath, PageNum, TextCharacters, ImageCount, ImageBytes "); imCsvFs = new FileStream(imCsvFilePath, FileMode.Create); imsr = new StreamWriter(imCsvFs); imsr.WriteLine("FilePath, PageNum, ImageNum, ImageBytes, ImageFormat, ImageType, ImageInfo, ImageWidth, ImageHeight, ImageResolution"); } } for (int i = 0; i < pdfFiles.Length; i++) { if (i > 0 && i % 100 == 0) { Console.WriteLine($"Processed {i} Files"); } var fileSpec = pdfFiles[i]; using (var fs = File.OpenRead(fileSpec)) { var fileInfo = iTextPDFHelper.GetPDFMetaData(fs, fileSpec, deepInfo); if (filesr != null) { var Errors = String.Join("|", fileInfo.ErrorMessages); filesr.WriteLine($"\"{fileInfo.FilePath}\", {fileInfo.FileName.Replace(',',' ')}, {fileInfo.PDFVersion}, " + $"{fileInfo.CreationDate}, {fileInfo.Creator}, {fileInfo.ModDate}, {fileInfo.Producer}, " + $"{fileInfo.PageCount}, {fileInfo.FileSize}, {fileInfo.ImageCount}, " + $"{fileInfo.TextCharacters}, {fileInfo.ImageBytes}, {fileInfo.ErrorMessages.Count}, {Errors}"); if (pisr != null) { foreach (var page in fileInfo.Pages) { pisr.WriteLine($"\"{fileInfo.FilePath}\", {page.PageNum}, {page.TextCharacters}, " + $"{page.ImageCount}, {page.ImageBytes}"); } } if (imsr != null) { foreach (var page in fileInfo.Pages) { foreach (var img in page.Images) { imsr.WriteLine($"\"{fileInfo.FilePath}\", {page.PageNum}, {img.ImageNum}, " + $"{img.ImageBytes}, {img.ImageFormat}, {img.ImageType}, {img.ImageInfo}, " + $"{img.ImageWidth}, {img.ImageHeight}, {img.ImageResolution}"); } } } } else { Console.WriteLine("---------------------------------------"); Console.WriteLine($"FilePath: {fileInfo.FilePath}"); Console.WriteLine($"FileName: {fileInfo.FileName}"); Console.WriteLine($"PDFVersion: {fileInfo.PDFVersion}"); Console.WriteLine($"CreationDate: {fileInfo.CreationDate}"); Console.WriteLine($"Creator: {fileInfo.Creator}"); Console.WriteLine($"ModDate: {fileInfo.ModDate}"); Console.WriteLine($"Producer: {fileInfo.Producer}"); Console.WriteLine($"PageCount: {fileInfo.PageCount}"); Console.WriteLine($"FileSize: {fileInfo.FileSize}"); Console.WriteLine($"ImageCount: {fileInfo.ImageCount}"); Console.WriteLine($"ImageBytes: {fileInfo.ImageBytes}"); Console.WriteLine($"TextCharacters: {fileInfo.TextCharacters}"); Console.WriteLine($"ErrorMessageCount: {fileInfo.ErrorMessages.Count}"); foreach (var msg in fileInfo.ErrorMessages) { Console.WriteLine("Error:" + msg); } Console.WriteLine(); } } } if (filesr != null) { filesr.Close(); } if (fileCsvFs != null) { fileCsvFs.Close(); } if (pisr != null) { pisr.Close(); } if (piCsvFs != null) { piCsvFs.Close(); } if (imsr != null) { imsr.Close(); } if (imCsvFs != null) { imCsvFs.Close(); } Console.WriteLine("Scan Completed"); }
static void Main(string[] args) { var opts = new OptionSet(); var friendlyName = opts.AddVariable <string>("friendlyname", "(required) friendly name of cert to generate"); var operatorName = opts.AddVariable <string>("operator", "operator name"); var siteId = opts.AddVariable <string>("siteid", "Site Id"); var seq = opts.AddVariable <int>("seq", "Sequence no"); var server = opts.AddSwitch("server", "create server certificate"); var delete = opts.AddSwitch("delete", "delete cert/rules with given friendly name/acl"); var filename = opts.AddVariable <string>("filename", "file to save"); var pwd = opts.AddVariable <string>("password", "password to apply to saved cert"); var help = opts.AddSwitch("help", "Show help"); var acl = opts.AddVariable <string>("urlacl", "urlAcl rule to add in form of hostname:port. e.g. \"quantumApi:4433\""); opts.Parse(args); if (help || string.IsNullOrEmpty(friendlyName.Value)) { opts.WriteOptionDescriptions(Console.Out); Console.ReadKey(); return; } CertificateHelper.FriendlyName = friendlyName.Value; var cert = CertificateHelper.GetClientCertificateByFriendlyName(friendlyName.Value); if (!delete) { if (cert != null) { if (string.IsNullOrEmpty(filename.Value)) { Console.WriteLine($"Certificate with friendly name {friendlyName.Value} already exists"); } } else { var urlOnly = acl.Value; if (!string.IsNullOrEmpty(urlOnly) && (urlOnly.IndexOf(":") > 0)) { urlOnly = urlOnly.Substring(0, urlOnly.IndexOf(":")); } ; if ( (server && !CertificateHelper.CreateAndStoreServerSelfSignedCertificate(friendlyName.Value, urlOnly)) || (!server && !CertificateHelper.CreateAndStoreSelfSignedCertificate(operatorName.Value, siteId.Value, seq.Value, server)) ) { throw new System.Exception("could not create certficate!"); } cert = CertificateHelper.GetClientCertificateByFriendlyName(friendlyName.Value); } } if (!string.IsNullOrEmpty(acl.Value)) { //add sslcert //Generate App guid. var appGuid = Guid.NewGuid(); System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = "cmd.exe"; if (!delete) { Console.WriteLine($"Attempting to add sslcert rule with app id {appGuid.ToString()}"); var cmdargs = $"/C netsh http add sslcert hostnameport={acl.Value} appid={{\"{appGuid.ToString()}\"}} certhash={cert.Thumbprint} certstorename=MY"; Console.WriteLine(cmdargs); startInfo.Arguments = cmdargs; } else { Console.WriteLine($"Attempting to delete sslcert rule {acl.Value}"); startInfo.Arguments = $"/C netsh http delete sslcert hostnameport={acl.Value}"; } startInfo.RedirectStandardError = true; startInfo.RedirectStandardOutput = true; startInfo.UseShellExecute = false; process.StartInfo = startInfo; process.Start(); Console.WriteLine("Waiting for process...."); string output = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); process.WaitForExit(); Console.WriteLine($"Process finished (exit code = {process.ExitCode})"); Console.WriteLine(output); Console.WriteLine(error); // now we add a urlACL rule... process = new System.Diagnostics.Process(); startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = "cmd.exe"; if (!delete) { Console.WriteLine($"Attempting to add urlACL rule for https://{acl.Value}/"); var cmdargs = $"/C netsh http add urlacl url=https://{acl.Value}/ user=EVERYONE"; Console.WriteLine(cmdargs); startInfo.Arguments = cmdargs; } else { Console.WriteLine($"Attempting to delete urlacl rule {acl.Value}"); startInfo.Arguments = $"/C netsh http delete urlacl url=https://{acl.Value}/"; } startInfo.RedirectStandardError = true; startInfo.RedirectStandardOutput = true; startInfo.UseShellExecute = false; process.StartInfo = startInfo; process.Start(); Console.WriteLine("Waiting for process...."); output = process.StandardOutput.ReadToEnd(); error = process.StandardError.ReadToEnd(); process.WaitForExit(); Console.WriteLine($"Process finished (exit code = {process.ExitCode})"); Console.WriteLine(output); Console.WriteLine(error); //try to save cert for adding to clients as a 'trusted doohickey' if (!delete) { string fname; if (string.IsNullOrEmpty(filename.Value)) { fname = friendlyName.Value; } else { fname = filename.Value; } if (File.Exists($"{fname}.pfx")) { File.Delete($"{fname}.pfx"); } var pwdGuid = Guid.NewGuid().ToString().Replace("{", "").Replace("}", "").Replace("-", "").Substring(0, 8); byte[] certData = cert.Export(X509ContentType.Pfx, pwdGuid); File.WriteAllBytes($"{fname}.pfx", certData); File.WriteAllText("pass.txt", pwdGuid); Console.WriteLine($"saved file to {fname}.pfx - add this to Trusted providers on clients (password is {pwdGuid}), saved to pass.txt"); } } else if (!string.IsNullOrEmpty(filename.Value) && !delete) { //try to save cert... byte[] certData = cert.Export(X509ContentType.Pfx, pwd.Value); File.WriteAllBytes(filename.Value, certData); Console.WriteLine($"saved file to {filename.Value}"); } Console.WriteLine($"finished. Cert thumbprint = {cert?.Thumbprint ?? "n/a"} saved to thumbprint.txt"); if (cert != null) { File.WriteAllText("thumbprint.txt", cert.Thumbprint); } //Console.ReadKey(); if (delete) { CertificateHelper.DeleteCertificatesWithFriendlyName(friendlyName.Value); } }
private static CmdOptions ParseOptions(string[] args) { var options = new OptionSet(); var lex = options.AddSwitch("l|lex", "Run the lexer and output the tokens"); var printTree = options.AddSwitch("t|tree", "Print the parse tree"); var validate = options.AddSwitch("v|validate", "Run compilation and produce errors, but don't emit anything"); var outputPath = options.AddVariable <string>("o|output", "Path to write output to"); var filePatterns = options.Parse(args); var workingDirectory = Directory.GetCurrentDirectory(); var sourcePaths = filePatterns.SelectMany(pattern => Directory.GetFiles(workingDirectory, pattern)).ToArray(); #region Single Action if (lex && printTree) { Console.WriteLine("Can't lex and print tree at same time"); return(null); } if (lex && validate) { Console.WriteLine("Can't lex and validate at same time"); return(null); } if (printTree && validate) { Console.WriteLine("Can't print tree and validate at same time"); return(null); } #endregion if (sourcePaths.Length == 0) { Console.WriteLine("Must specify at least one source file"); } if (sourcePaths.Any(sourcePath => !HasAdamantExtension(sourcePath))) { Console.WriteLine("All source files must have Adamant Extension (*.adam)"); } if (lex) { return(new CmdOptions() { Action = CmdAction.Lex, SourcePaths = sourcePaths, OutputPath = outputPath.Value, }); } if (printTree) { return(new CmdOptions() { Action = CmdAction.PrintTree, SourcePaths = sourcePaths, OutputPath = outputPath.Value, }); } if (validate) { return(new CmdOptions() { Action = CmdAction.Validate, SourcePaths = sourcePaths, OutputPath = outputPath.Value, }); } Console.WriteLine("Must specify an action. One of -l -t -v"); return(null); }
private static CmdOptions ParseOptions(string[] args) { var options = new OptionSet(); var lex = options.AddSwitch("l|lex", "Run the lexer and output the tokens"); var printTree = options.AddSwitch("t|tree", "Print the parse tree"); var validate = options.AddSwitch("v|validate", "Run compilation and produce errors, but don't emit anything"); var outputPath = options.AddVariable<string>("o|output", "Path to write output to"); var filePatterns = options.Parse(args); var workingDirectory = Directory.GetCurrentDirectory(); var sourcePaths = filePatterns.SelectMany(pattern => Directory.GetFiles(workingDirectory, pattern)).ToArray(); #region Single Action if(lex && printTree) { Console.WriteLine("Can't lex and print tree at same time"); return null; } if(lex && validate) { Console.WriteLine("Can't lex and validate at same time"); return null; } if(printTree && validate) { Console.WriteLine("Can't print tree and validate at same time"); return null; } #endregion if(sourcePaths.Length == 0) Console.WriteLine("Must specify at least one source file"); if(sourcePaths.Any(sourcePath => !HasAdamantExtension(sourcePath))) Console.WriteLine("All source files must have Adamant Extension (*.adam)"); if(lex) { return new CmdOptions() { Action = CmdAction.Lex, SourcePaths = sourcePaths, OutputPath = outputPath.Value, }; } if(printTree) { return new CmdOptions() { Action = CmdAction.PrintTree, SourcePaths = sourcePaths, OutputPath = outputPath.Value, }; } if(validate) { return new CmdOptions() { Action = CmdAction.Validate, SourcePaths = sourcePaths, OutputPath = outputPath.Value, }; } Console.WriteLine("Must specify an action. One of -l -t -v"); return null; }
private static CmdOptions ParseOptions(string[] args) { var options = new OptionSet(); var tokenize = options.AddSwitch("tokenize", "Rather than compiling, run the lexer and output the tokens"); var printTree = options.AddSwitch("tree", "Print the parse tree"); var outputPath = options.AddVariable<string>("o|output", "Path to write output to"); var files = options.Parse(args); if(files.Count > 1) { Console.WriteLine("Can only specify one file"); return null; } var filePath = files.FirstOrDefault(); if(tokenize && printTree) { Console.WriteLine("Can't tokenize and print tree at same time"); return null; } if((tokenize || printTree) && IsAdamantCode(filePath)) { Console.WriteLine("When tokenizing or printing parse tree, must specify an adamant source file (*.adam)"); return null; } if(tokenize) { return new CmdOptions() { FilePath = filePath, Action = CmdAction.PrintTree, OutputPath = outputPath.Value, }; } if(printTree) { return new CmdOptions() { FilePath = filePath, Action = CmdAction.Tokenize, OutputPath = outputPath.Value, }; } // Some form of compile if(Directory.Exists(filePath)) // directory path filePath = Path.Combine(filePath, ProjectFileName); if(Path.GetExtension(filePath) == ".vson") { if(Path.GetFileName(filePath) != ProjectFileName) { Console.WriteLine($"project file must be named {ProjectFileName}"); return null; } if(outputPath.Value != null) { Console.WriteLine($"When compiling {ProjectFileName} file don't specify output path"); return null; } return new CmdOptions() { FilePath = filePath, Action = CmdAction.Forge, }; } else { if(!IsAdamantCode(filePath)) { Console.WriteLine("When compiling, must specify an adamant source file (*.adam)"); return null; } return new CmdOptions() { FilePath = filePath, Action = CmdAction.Compile, OutputPath = outputPath.Value, }; } }
public void Should_Not_Throw_Exception_Multiset_Variable() { var optionSet = new OptionSet(); var n = optionSet.AddVariable<string>("n", ""); //TODO: Screaming for an NUnit-test-case-coverage. var args = "-n:Noah -n:Moses -n:David".Split(' '); try { optionSet.Parse(args); } catch (OptionException oex) { Assert.Fail("Unexpected exception: {0}", oex); } }
public bool Parse(string[] cmdArgs) { bool argumentsOk = true; var os = new OptionSet(); var showHelp = os.AddSwitch("h|?|help", "Shows the help"); var mode = os.AddVariable <String>("m|mode", "Select the mode of the tool. \n 'index' to index directory \n 'search' to search within already indexed directory \n 'auto' to use CLI"); var idxPath = os.AddVariable <String>("ip|indexPath", "Location where the index is or should be stored (mandatory)"); var srcPath = os.AddVariable <String>("sp|sourcePath", "Location of files, which should be indexed (mandatory in case of 'mode=index')"); var fileExtensions = os.AddVariable <String>("fe|fileExtensions", "Extensions of files to index (optional in case of 'mode=index', default is '.cs,.xml,.csproj')"); var searchedWord = os.AddVariable <String>("sw|searchedWord", "word to look for into index (mandatory in case of 'mode=search')"); var numberOfHitsToShow = os.AddVariable <Int32>("hits|numerOfHits", "Amount of files with findings (optional, default is 1000)"); var hitsPerPage = os.AddVariable <Int32>("hpp|hitsPerPage", "Amount of findings to show at once (optional, default = -1; -1 means all)"); var export = os.AddSwitch("e|export", "Indicates wheater results should be exported to temp file (optional, default = false)"); var wildcardSearch = os.AddSwitch("wc|wildcard", "Use wildcard search query, which is possible slower (optional, default = false)"); try { for (int i = 0; i < cmdArgs.Length; i++) { cmdArgs[i] = cmdArgs[i].Trim(); } os.Parse(cmdArgs); } catch (OptionException) { PrintUsage(os); argumentsOk = false; } if (showHelp) { PrintUsage(os); } else if (argumentsOk) { if (String.IsNullOrWhiteSpace(mode)) { PrintUsage(os); argumentsOk = false; } else { if (mode == "index" || mode == "i") { argumentsOk = SetArgumentsForIndexing(os, idxPath, srcPath, fileExtensions); } else if (mode == "search" || mode == "s") { argumentsOk = SetArgumentsForSearching(os, idxPath, searchedWord, numberOfHitsToShow, hitsPerPage, export, wildcardSearch); } else if (mode == "auto" || mode == "a") { m_Arguments[ProgramMode] = mode; argumentsOk = true; } else { PrintUsage(os); argumentsOk = false; } } } return(argumentsOk); }