As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I'm looking for a command line argument parser, such as "Command line parser" from http://www.sellsbrothers.com/tools/Genghis/ .
Features I'm looking for:
Auto-generation of usage
Should able to check required and optional parameters
Parameters should support IEnumerable with separator support
Should support flag parameters
Would be nice to support combining parameters such as "/fx" == "/f /x"
Would be nice to not force for a space after a parameter such as "/ftest.txt" == "/f test.txt"
P.S :
"Command line parser" is quite good, I really like the design of it but there is no documentation, no new updates and I couldn't figure out to do certain stuff such as how to check for required parameters.
My personal favourite 3rd party commandline parsing library is Command Line Parser and I assume this is the one you are referring to. The most recent release was less than 2 months ago and there are regular commits. If you want a more mature offering you could check out the console library in the mono project (sorry I can't seem to find a direct link to the namespace at the moment, but its a part of the mono framework)
Have a look at ndesk.options.
It is called Mono.Options now.
A popular and pretty comprehensive C command-line parser is GNU getopt. This has been ported (or cloned) for C#/.Net several times. Some of these include:
getopt# on freshmeat.net
C# getopt at PHPGuru
XGetoptCS on CodeProject
GetOpt for .NET on CodeProject
Getopt C#.NET on Codeplex
Take your pick! There are several others, and google can tell you about those,
Sadly there's no built in support for handling that in a standard manner. Have you looked into PowerShell? I bet there's a class in that shell which does exactly what you want or something similar.
Edit: as fatcat1111 points out, this feature did not ship with the final version of .net 4.0.
C# 4.0 has a pretty good one. Probably not very helpful yet, but you might want to consider looking at something that will make the jump to the built in one easy when it comes out. Bart De Smet talked about it on his
B# blog
I suggest NDesk.Options
look here:
Best way to parse command line arguments in C#?
Consider that once you start using this parser, you'll either have to maintain it yourself, or else depend on someone else to maintain it for you. You may be better off writing your own, starting from your most critical, immediate, requirements. I've found that it doesn't take too much work to produce some fairly complicated command-line parsing for most console-based applications I've worked on.
I've also found that when the parsing gets too complicated, it may be time to stop using the command line.
I'm betting this is not quite what you're looking for, but:
Somebody here had that problem, and his first thought was "hey, ocaml has a pretty good one!", and quickly ported it to F#.
I'm using the parser out of the C# 3.0 cookbook.
All the examples from this book can be downloaded here:
http://examples.oreilly.com/9780596516109/
Search for 'Arguments' and you'll find it. You have to do some little code changes to get it out of the whole thing into your own class, but this is no big problem.
It supports all your points except the last two ones (parameter combining & missing space).
The BizArk library contains a command-line parser.
Basically you just create a class that inherits from CmdLineObject, add properties that you want populated from the command-line, add a CmdLineArgAttribute to the properties, then call Initialize in your program. It supports ClickOnce URL arguments too!
Features (from the site)...
Automatic initialization: Class properties are automatically set based on the command-line arguments.
Default properties: Send in a value without specifying the property name.
Value conversion: Uses the powerful ConvertEx class also included in BizArk to convert values to the proper type.
Boolean flags. Flags can be specified by simply using the argument (ex, /b for true and /b- for false) or by adding the value true/false, yes/no, etc.
Argument arrays. Simply add multiple values after the command-line name to set a property that is defined as an array. Ex, /x 1 2 3 will populate x with the array { 1, 2, 3 } (assuming x is defined as an array of integers).
Command-line aliases: A property can support multiple command-line aliases for it. For example, Help uses the alias ?.
Partial name recognition. You don’t need to spell out the full name or alias, just spell enough for the parser to disambiguate the property/alias from the others.
Supports ClickOnce: Can initialize properties even when they are specified as the query string in a URL for ClickOnce deployed applications. The command-line initialization method will detect if it is running as ClickOnce or not so your code doesn’t need to change when using it.
Automatically creates /? help: This includes nice formatting that takes into account the width of the console.
Load/Save command-line arguments to a file: This is especially useful if you have multiple large, complex sets of command-line arguments that you want to run multiple times.
I'm a fan of the C# port to OptParse, a built in library in Python. It's rather simple to use compared to most of the other suggestions here and contains a number of useful features in addition to just auto parsing.
You may like my one Rug.Cmd
Easy to use and expandable command line argument parser. Handles: Bool, Plus / Minus, String, String List, CSV, Enumeration.
Built in '/?' help mode.
Built in '/??' and '/?D' document generator modes.
static void Main(string[] args)
{
// create the argument parser
ArgumentParser parser = new ArgumentParser("ArgumentExample", "Example of argument parsing");
// create the argument for a string
StringArgument StringArg = new StringArgument("String", "Example string argument", "This argument demonstrates string arguments");
// add the argument to the parser
parser.Add("/", "String", StringArg);
// parse arguemnts
parser.Parse(args);
// did the parser detect a /? argument
if (parser.HelpMode == false)
{
// was the string argument defined
if (StringArg.Defined == true)
{
// write its value
RC.WriteLine("String argument was defined");
RC.WriteLine(StringArg.Value);
}
}
}
Edit: This is my project and as such this answer should not be seen as an endorsement from a third party. That said I do use it for every command line based program I write, it is open source and it is my hope that others may benefit from it.
Related
I am asking this question, because I didn't find yet any posts that are C# related and there might be some build in methods for that I couldn't find. If there are, please tell me so and I can close this question.
Basically I have the common situation:
User types a function w.r.t. one or two variables into some TextBlock
I take this string analyse it
As a return I would like to have a delegate to a method that will take one or two inputs (the variables) and return the function value according to what the user typed in.
Now, I could probably think (and I would like to do this on my own, because I want to use my brain) of an algorithm of analysing the string step by step to actually find out, what has to be calculated first and in what way. E.g. First scan for parentheses, look for the expression within a group of parantheses and calculate that according to more general functions etc.
But in the end I would like to "create" a method of this analysis to be easily used as a normal delegate with a couple of arguments that will return the correct function value.
Are there any methods included in C# for that already, or would I have to go and program everything by myself?
As a remark: I don't want to use anybody else' library, only .NET libraries are acceptable for me.
Edit: After Matt pointed out expression trees, I found this thread which is a good example to my problem.
Edit2: The example pointed out does only include simple functions and will not be useful if I want to include more complex functions such as trigonometric ones or exponentials.
What you are describing is a parser. There are a number of different ways of implementing them, although generally speaking, for complex grammars, a "parser generator" is often used.
A parser generator will take a description of the grammar and convert it into code that will parse text that conforms to the grammar into some form of internal representation that can be manipulated by the program, e.g. a parse tree.
Since you indicate you want to avoid third-party libraries, I'll assume that the use of a parser generator is similarly excluded, which leaves you with implementing your own parser (which fortunately is quite an interesting exercise).
The Wikipedia page on Recursive descent parsers will be particularly useful. I suggest reading through it and perhaps adapting the example code therein to your particular use case. I have done this myself a number of times for different grammars with this as a starting point, so can attest to its usefulness.
The output from such a parser will be a "parse tree". And you then have a number of possibilities for how you convert this into an executable delegate. One option is to implement an Evaluate() method on your parse tree nodes, which will take a set of variables and return the result of evaluating the user's expression. As others have mentioned, your parse tree could leverage .NET's Expression trees, or you can go down the route of emitting IL directly (permitting you to produce a compiled .NET assembly from the user's expression for later use as required).
You might want to look at expression trees.
Check out NCalc for some examples of how to do this. You don't need to use the library, but reading the source is pretty educational.
I found a very helpful pdf explaining the parsing in C# 2.0. This link leads to a very good tutorial on parsers used in C# and also applies that later on to an arithmetic expression.
As this directly helps and answers to my question, I posted this as an answer, rather than as a comment or edit.
I am researching ways, tools and techniques to parse code files in order to support syntax highlighting and intellisence in an editor written in c#.
Does anyone have any ideas/patterns & practices/tools/techiques for that.
EDIT: A nice source of info for anyone interested:
Parsing beyond Context-free grammars
ISBN 978-3-642-14845-3
My favourite parser for C# is Irony: http://irony.codeplex.com/ - i have used it a couple of times with great success
Here is a wikipedia page listing many more: http://en.wikipedia.org/wiki/Compiler-compiler
There are two basic aproaches:
1) Parse the entire solution and everything it references so you understand all the types involved in the code
2) Parse locally and do your best to guess what types etc are.
The trouble with (2) is that you have to guess, and in some circumstances you just can't tell from a code snippet exactly what everything is. But if you're happy with the sort oif syntax highlighting shown on (e.g.) Stack Overflow, then this approach is easy and quite effective.
To do (1) then you need to do one of (in decreasing order of difficulty):
Parse all the source code. Not possible if you reference 3rd party assemblies.
Use reflection on the compiled code to garner type information you can use when parsing the source.
Use the host IDE's (if avaiable - so not applicable in your case!) code element interfaces to provide the information you need
You could take a look at how http://www.icsharpcode.net/ did it. They wrote a book doing just that, Dissecting a C# Application: Inside SharpDevelop, it even has a chapter called
Implement a parser to provide syntax
highlighting and auto-completion as
users type
I often type string in c# when actually I want to type String.
I know that string is an alias of String and I am really just being pedantic but i wish to outlaw string to force me to write String.
Can this be done in ether visual studio intellesence or in resharper and how?
I've not seen it done before, but you may be able to achieve this with an Intellisense extension. A good place to start would be to look at the source for this extension on CodePlex.
Would be good to hear if you have any success with this.
I have always read in "Best Coding Practices" for C# to prefer string, int, float ,double to String, Int32, Single, Double. I think it is mostly to make C# look less like VB.NET, and more like C, but it works for me.
Also, you can go the other way, and add the following on top of every file
using S = System.String;
..
S msg = #"I don't like string.";
you may laugh at this, but I have found it invaluable when I have two similar source codes with different underlying data types. I usually have using num=System.Single; or using num=System.Double; and the rest of the code is identical, so I can copy and paste from one file to the other and maintain both single precision and double precision library in sync.
I think ReSharper can do this!
Here is an extract from the documentation:
ReSharper 5 provides Structural Search and Replace to find custom code constructs and replace them with other code constructs. What's even more exciting is that it's able to continuously monitor your solution for your search patterns, highlight code that matches them, and provide quick-fixes to replace the code according to your replace patterns. That essentially means that you can extend ReSharper's own 900+ code inspections with your custom inspections. For example, if you're migrating to a newer version of a framework, you can create search patterns to find usages of its older API and replace patterns to introduce an updated API.
cheers,
Chris
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
Is there a ready-to-use C# interpreter out there, that is does not rely on runtime compilation?
My requirements are :
A scripting engine
Must Handle C# syntax
Must work on medium-trust environments
Must not use runtime compilation (CodeDomProvider ...)
Open source (or at least free of charge both for personal and professional use)
If this is not clear, I need something like Jint (http://jint.codeplex.com/), but which allows me to write C# scripts instead of JavaScript ones.
Thanks for your help.
Have you looked at paxScript.NET?
Check out the Mono project. They recently demoed CsharpRepl which sounds like what you're after. The PDC 2008 video here.
Update:
On a close look it seems like using Mono.CSharp service to evaluate scripts won't be possible. Currently it is linked to the Mono runtime and they don't expect it to run in a medium trust environment. See this discussion for more info.
On alternative possibility is to include the Mono C# compiler (sources here) in your project and use it to generate assemblies that you load from the file system. It you are worried about the resources required to load all those assemblies you might have to load them in a separate AppDomain.
I need to evaluate 10000+ small
scripts that are all differents,
compiling all of them would be just
dramatically slow
Interpretting these would be even more painfully slow. We have a similar issue that we address as follows:
We use the Gold Parser project to parse source code and convert it to an XML based 'generic language'. We run this through a transform that generates VB.Net source code (simply because it's case insensitive). We then compile these using the .Net runtime into a standalone DLL, and call this using heavily restricted access.
It sounds as though you are creating something like a dynamic website where people can create custom modules or snippets of functionality, but using C# to do this introduces a couple of main problems; C# has to be compiled, and the only way around this is to interpet it at runtime, and this is unfeasible, and even if you do compile each snippet then you end up with 10,000 DLLs, which is impractical and unusable.
If your snippets are rarely changing, then I would consider programatically wrapping them into a single set of source, with each having a unique name, then compile them in a single shot (or as a timed process every 10mins?). This is what we do, as it also allows 'versioning' of peoples sessions so they continue using the version of DLL they had at the start of their session, but when every session stops using an old version then it's removed.
If your snippets change regularly throughout the day then I would suggest you look at an interpretted scripting language instead, even PHP, and mix your languages depending on the functionality you require. Products such as CScript and LinqPad all use the CodeDomProvider, because you have to have IMSL somewhere if you want to program compiled logic.
The only other option is to write your own interpretter and use reflection to access all the other libraries you need to access, but this is extremely complex and horrible.
As your requirements are effectively unachievable, I would suggest you take a step back and figure out a way of removing one or more restrictions. Whether you find a FullTrust environment to compile your snippets in, remove the need for full code support (i.e. move to interpretted code snippet support), or even change the whole framework to something non .Net.
LINQPad can work as a code snippet IDE. The application is very small and lightweight. It is free (as in beer) but not open-source. Autocompletion costs extra but not much ($19).
Edit: after reading over the comments in this post a little more carefully, I don't think LINQPad is what you want. You need something that can programmatically evaluate thousands of little scripts dynamically, right? I did this at work using Iron Ruby very easily. If you're willing to use a DLR language, this would probably be more feasible. I also did some similar work with some code that could evaluate a C# lambda expression passed in as a string but that was extremely limited.
I have written an open source project, Dynamic Expresso, that can convert text expression written using a C# syntax into delegates (or expression tree). Expressions are parsed and transformed into Expression Trees without using compilation or reflection.
You can write something like:
var interpreter = new Interpreter();
var result = interpreter.Eval("8 / 2 + 2");
or
var interpreter = new Interpreter()
.SetVariable("service", new ServiceExample());
string expression = "x > 4 ? service.SomeMethod() : service.AnotherMethod()";
Lambda parsedExpression = interpreter.Parse(expression,
new Parameter("x", typeof(int)));
parsedExpression.Invoke(5);
My work is based on Scott Gu article http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx .
or http://www.csscript.net/
Oleg was writing a good intro at code project
It doesn't handle exact C# syntax, but PowerShell is so well enmeshed with the .NET framework and is such a mature product, I think you would be unwise to ignore it as at least a possible solution. Most server products being put out by Microsoft are now supporting PowerShell for their scripting interface including Microsoft Exchange and Microsoft SQL Server.
I believe Mono has mint, an interpreter they use before implementing the JIT for a given platform. While the docs in the official site (e.g. Runtime) say it's just an intermediate state before consolidating the jitting VM, I'm pretty sure it was there the last time I compiled it on Linux. I can't quite check it right now, unfortunately, but maybe it's in the direction you want.
bungee# is the thing that you want, in a short time, bungee sharp will be an open source project in
http://www.crssoft.com/Services/Bungee
. you can create scripts with the same c# syntaxt. there is no assembly creation when you run the script, interpretation is done on the fly, so the performance is high. all the keywords are available like c#. I hope u will like it very much..
I faced the same problem. In one project I was looking to provide a generic way to specify conditions controlling when a certain letter has to be generated. In another project the conditions were controlling how cases were assigned to queues. In both of them The following solution worked perfectly:
The Language for the snippets - I chose JScript so that I do not have to worry about variable types.
The Compilation - yes it requires full trust, but you can place your code in a separate assembly and give it full trust. Do not forget to mark it with AllowPartiallyTrustedCaller attribute.
Number of code snippets - I treated every snippet as a method, not a class. This way multiple methods can be combined into a single assembly
Disk usage - I did all compilation in memory without saving the assembly to disk. It also helps if you need to reload it.
All of this works in production without any problems
Edit
Just to clarify 'snippet' - The conditions I am talking about are just boolean expressions. I programatically add additional text to turn it to methods and methods to compilable classes.
Also I can do the same with C# although I still think JScript is better for code snippets
And BTW my code is open source feel free to browse. Just keep in mind there is a lot of code there unrelated to this discussion. Let me know if you need help to locate the pieces concerning the topic
This one works really well
c# repl and interactive interpreter
Is Snippet Compiler something you looking for?
I wrote an application which makes use of a meta-parser generated using CSharpCC (a port of JavaCC). Everything works fine and very good I can say.
For the nature of the project, I would like to have more flexibility on the possibility to extend the syntax of the meta-language used by the application.
Do you know any existing libraries (or articles describing the process of implementation) for Java or C# which I could use to programatically implement my own parser, without being forced to rely to a static syntax?
Thank you very much for the support.
Would Scala's combinator parsers do the trick for you? Since Scala compiles to Java bytecode, anything you write could be called from your Java code however you please.
Take a look at the way that the JNode command-line interface handles parsing of command line arguments. Each command 'registers' descriptors for the arguments it is expecting. The command line syntax is specified separately in XML descriptors, allowing users to tailor a command's syntax to meet their needs.
This is underpinned by a framework of Argument classes that are basically context sensitive token recognizers, and a two level grammar / parser. The parser 'prepares' a user-friendly form of a command syntax into something like BNF, then does a naive backtracking parse, accepting the first complete parse that it finds.
The downside of the current implementation is that the parser is inefficient, and probably impractical for parsing input that is more than 20 or so tokens, depending on the syntax. (We have ideas for improving performance, but a real fix is probably not possible without a major redesign ... and banning potentially ambiguous command syntaxes.)
(Aside: one motivation for this is to support intelligent command argument completion. To do this, the parser runs in a "completion" mode in which it explores all possible (partial) parses, noting its state when it encounters the token / position that the user is trying to complete. Where appropriate, the corresponding Argument classes are then asked to provide context sensitive completions for the current "word".)
The parser (written in C#) used in the Heron language (a simple object-oriented language) is relatively simple and stable, and should be easy to modify for your needs. You can download the source here.