Check command line arguments for input value - c#

i am using command line arguments and if conditions are used to check the input values but it is not looking good can i change it to switch but i have no idea how to change it my code is
if (args.Length > 0 && args.Length == 4)
{
string programName = args[0];
string file1= args[2];
string file2= args[3];
bool flag = false;
int num= 0;
bool isNum = Int32.TryParse(args[1].ToString(), out num);
if (!(programName.Equals("Army")))
{
Console.WriteLine("Error");
}
if (!Int32.TryParse(args[1].ToString(), out isNum ))
{
Console.WriteLine("value should be a number");
}
if (!File.Exists(file1))
{
Console.WriteLine("file 1 does not exist");
}
if (!File.Exists(file2))
{
Console.WriteLine("file 2 does not exist");
}

A switch statement isn't really called for here. That's useful when you have a single value and need to select from a series of possible mutually-exclusive steps based on that value. But that's not what you're doing here. These aren't a chain of if/else if statements keying off a value, these are more like guard clauses. All of them need to run in order to determine all of the output to show to the user.
You can shorten the code by removing the curly braces:
if (!(programName.Equals("Army")))
Console.WriteLine("Error");
if (!Int32.TryParse(args[1].ToString(), out isNum ))
Console.WriteLine("value should be a number");
if (!File.Exists(file1))
Console.WriteLine("file 1 does not exist");
if (!File.Exists(file2))
Console.WriteLine("file 2 does not exist");
You could also extract these lines of code into their own method, which would make the Main method a little cleaner. You could even extract the conditional checks themselves into very small methods to make it more prose-like for readability. But the conditional structure itself doesn't really need to change.

You can create class which will be responsible for retrieving and checking your application arguments. E.g. if your application has name Zorg, you can create following class:
public class ZorgConfiguration
{
private string num;
private string programName;
private string file1;
private string file2;
public static ZorgConfiguration InitializeFrom(string[] args)
{
if (args.Length < 4)
throw new ZorgConfigurationException("At least 4 arguments required");
return new ZorgConfiguration {
ProgramName = args[0],
Num = args[1],
File1 = args[2],
File2 = args[3]
};
}
// to be continued
}
As you can see, it's responsibility is to hold application settings. It has static method for creating instance of configuration from args array. This method checks if arguments count correct and then initializes each property of configuration class with appropriate argument. Checking argument value moved to properties:
public string ProgramName
{
get { return programName; }
private set {
if (value == "Army")
throw new ZorgConfigurationException("Error");
programName = value;
}
}
public string Num
{
get { return num; }
private set {
int i;
if (!Int32.TryParse(value, out i))
throw new ZorgConfigurationException("value should be a number");
num = value;
}
}
public string File1
{
get { return file1; }
private set {
if (!File.Exists(value))
throw new ZorgConfigurationException("file 1 does not exist");
file1 = value;
}
}
Each property is responsible for verifying corresponding argument value. If value is incorrect, then custom ZorgConfigurationException (that is simply class inherited from Exception) is thrown.
Now main application code looks very clean:
try
{
var config = ZorgConfiguration.InitializeFrom(args);
// you can use config.File1 etc
}
catch (ZorgConfigurationException e)
{
Console.WriteLine(e.Message);
// exit application
}

I use this class to parse command line arguments, I've found it somewhere, but I can't remember where:
public class Arguments
{
// Variables
private StringDictionary Parameters;
// Constructor
public Arguments(string[] Args)
{
Parameters = new StringDictionary();
Regex Spliter = new Regex(#"^-{1,2}|^/|=|:",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
Regex Remover = new Regex(#"^['""]?(.*?)['""]?$",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
string Parameter = null;
string[] Parts;
// Valid parameters forms:
// {-,/,--}param{ ,=,:}((",')value(",'))
// Examples:
// -param1 value1 --param2 /param3:"Test-:-work"
// /param4=happy -param5 '--=nice=--'
foreach (string Txt in Args)
{
// Look for new parameters (-,/ or --) and a
// possible enclosed value (=,:)
Parts = Spliter.Split(Txt, 3);
switch (Parts.Length)
{
// Found a value (for the last parameter
// found (space separator))
case 1:
if (Parameter != null)
{
if (!Parameters.ContainsKey(Parameter))
{
Parts[0] =
Remover.Replace(Parts[0], "$1");
Parameters.Add(Parameter, Parts[0]);
}
Parameter = null;
}
// else Error: no parameter waiting for a value (skipped)
break;
// Found just a parameter
case 2:
// The last parameter is still waiting.
// With no value, set it to true.
if (Parameter != null)
{
if (!Parameters.ContainsKey(Parameter))
Parameters.Add(Parameter, "true");
}
Parameter = Parts[1];
break;
// Parameter with enclosed value
case 3:
// The last parameter is still waiting.
// With no value, set it to true.
if (Parameter != null)
{
if (!Parameters.ContainsKey(Parameter))
Parameters.Add(Parameter, "true");
}
Parameter = Parts[1];
// Remove possible enclosing characters (",')
if (!Parameters.ContainsKey(Parameter))
{
Parts[2] = Remover.Replace(Parts[2], "$1");
Parameters.Add(Parameter, Parts[2]);
}
Parameter = null;
break;
}
}
// In case a parameter is still waiting
if (Parameter != null)
{
if (!Parameters.ContainsKey(Parameter))
Parameters.Add(Parameter, "true");
}
}
// Retrieve a parameter value if it exists
// (overriding C# indexer property)
public string this[string Param]
{
get
{
return (Parameters[Param]);
}
}
}
I use it this way:
var cmdParams = new Arguments(args);
if (cmdParams["File"] != null && parametros["cmdParams"] == "Filename.txt) { }
Hope it helps!

Command line arguments can get complicated if there are different functions and arguments..
Best way is to tokenize your arguments, function switch examples are /p /a, or -h, -g etc...Your cmd arg parser looks for these tokens (pattern) - once found you know which cmd it is.. Have switch - case or any other mechanism for this. Also tokenise the other data arguments. Hence you have two sets of arguments - easy to manage.

Related

Get a variable value from a method to another?

In this situation, I am trying to get the value of "FileSizeType", an integer variable, into the method that's under it "NomCategorie"and convert it to a string(that's what the comment says).
static int ChoisirCategory()
{
int FileSizeType;
Console.Write("What type do you want: ");
FileSizeType = Convert.ToInt32(Console.ReadLine());
return FileSizeType;
}
static string NomCategorie(int c)
{
//get FileSizeType into c
string FileType;
if (c == 1)
{
return FileType = "Small";
}
else if (c == 2)
{
return FileType = "Medium";
}
else if (c == 3)
{
return FileType = "Large";
}
else if (c == 4)
{
return FileType = "Huge";
}
else
{
return FileType="Non-valid choice";
}
I would suggest using enum class
public enum Test
{
Small = 1,
Medium = 2,
Large = 3,
Huge = 4
}
then you can simply convert the number by using
int integer = 1;
if (Enum.IsDefined(typeof(Test), integer)
{
Console.WriteLine((Test)integer).
}
else
{
Console.WriteLine("Bad Integer");
}
output:
Small
Looking at your existing code, you are already returning the value of FileSizeType from the ChoisirCategory, so you can capture it in a variable and then pass that to the NomCategorie method to get the category name, for example:
int categoryId = ChoisirCategory();
string categoryName = NomCategorie(categoryId);
Note that there are many other improvements that can be made (for example, what happens if the user types in "two" instead of "2"?), but I think those suggestions may be out of scope based on the question.
Here's how your code could be simplified if you combine both suggestions above. I've also added an if clause to verify that the value is not higher than those available.
static enum AvailableSizes
{
Small = 1,
Medium = 2,
Large = 3,
Huge = 4
}
static int ChoisirCategory()
{
int FileSizeType;
GetInput:
Console.Write("What type do you want: ");
FileSizeType = Convert.ToInt32(Console.ReadLine());
// Ensure the value is not higher than expected
// (you could also check that it is not below the minimum value)
if (FileSizeType > Enum.GetValues(typeof(AvailableSizes)).Cast<int>().Max());
{
Console.WriteLine("Value too high.");
goto GetInput;
}
return FileSizeType;
}
static string NomCategorie(int c)
{
if (Enum.IsDefined(typeof(AvailableSizes), c)
{
return (AvailableSizes)c;
}
else
{
return "Invalid category";
}
}
Then somewhere in your code you would call these using this statement
string categoryStr = NomCategorie(ChoisirCategory());
Console.WriteLinte(categoryStr); // or do whatever you want with the returned value
With this code, if the input is higher than 4, it will output "Value too high." and ask the question again until the value is no higher than 4.
If the user types 0 or a negative value, then it will output "Invalid category".
This might help you decide where you want to handle input errors: right after user input or during the parsing of the number to a string.

Getting expression text

I want to pass the name of a property of a model to a method. Instead of using the name as string, I am using lambda expression as it is easy to make a typo, and also property names may be changed. Now if the property is a simple property (e.g: model.Name) I can get the name from the expression. But if it is a nested property (e.g: model.AnotherModel.Name) then how can I get full text ("AnotherModel.Name") from the expression. For example, I have the following classes:
public class BaseModel
{
public ChildModel Child { get; set; }
public List<ChildModel> ChildList { get; set; }
public BaseModel()
{
Child = new ChildModel();
ChildList = new List<ChildModel>();
}
}
public class ChildModel
{
public string Name { get;set; }
}
public void GetExpressionText<T>(Expression<Func<T, object>> expression)
{
string expText;
//what to do??
return expText;
}
GetExpressionText<BaseModel>(b => b.Child); //should return "Child"
GetExpressionText<BaseModel>(b => b.Child.Name); //should return "Child.Name"
GetExpressionText<BaseModel>(b => b.ChildList[0].Name); //should return "ChildList[0].Name"
My first thought was to use expression.Body.ToString() and tweak that a bit, but you would still need to deal with Unary (convert) etc. Assuming this is for logging and you want more control, the below can be used for formatting as wanted (e.g. if you want Child->Name for display purposes, string.Join("->",..) can be used). It may not be complete, but should you find any unsupported types, they should be easy to add.
PS: this post was generated before the question was closed. Just noticed it was reopend and submitting it now, but I haven't checked if particulars have been changed.
public string GetName(Expression e, out Expression parent)
{
if(e is MemberExpression m){ //property or field
parent = m.Expression;
return m.Member.Name;
}
else if(e is MethodCallExpression mc){
string args = string.Join(",", mc.Arguments.SelectMany(GetExpressionParts));
if(mc.Method.IsSpecialName){ //for indexers, not sure this is a safe check...
return $"{GetName(mc.Object, out parent)}[{args}]";
}
else{ //other method calls
parent = mc.Object;
return $"{mc.Method.Name}({args})";
}
}
else if(e is ConstantExpression c){ //constant value
parent = null;
return c.Value?.ToString() ?? "null";
}
else if(e is UnaryExpression u){ //convert
parent= u.Operand;
return null;
}
else{
parent =null;
return e.ToString();
}
}
public IEnumerable<string> GetExpressionParts(Expression e){
var list = new List<string>();
while(e!=null && !(e is ParameterExpression)){
var name = GetName(e,out e);
if(name!=null)list.Add(name);
}
list.Reverse();
return list;
}
public string GetExpressionText<T>(Expression<Func<T, object>> expression) => string.Join(".", GetExpressionParts(expression.Body));
You could use the C# 6.0 feature: nameof(b.Child) "Used to obtain the simple (unqualified) string name of a variable, type, or member."
which will also change on renaming. But this will only return the propertyname and not the complete path. Returning a complete path will be difficult, because only one instance is passed.
Closest i know right now is by simply using expression.Body.ToString() which would result in b.ChildList.get_Item(0).Name as a result.
You would still have to remove the first b. from the string if not wanted, and you could go even further to your intended output with Regex by replacing the get_Item(0) with the typical Index-Accessor.
(Also i had to make the ChildList and the Name-Property of ChildModel public to get it to work)
This Should get you most of the way there:
public static string GetFullPath<T>(Expression<Func<T>> action)
{
var removeBodyPath = new Regex(#"value\((.*)\).");
var result = action.Body.ToString();
var replaced = removeBodyPath.Replace(result, String.Empty);
var seperatedFiltered = replaced.Split('.').Skip(1).ToArray();
return string.Join(".", seperatedFiltered);
}
It gets ugly quite quickly...
public static string GetExpressionText<T>(Expression<Func<T, object>> expression)
{
bool needDot = false;
Expression exp = expression.Body;
string descr = string.Empty;
while (exp != null)
{
if (exp.NodeType == ExpressionType.MemberAccess)
{
// Property or field
var ma = (MemberExpression)exp;
descr = ma.Member.Name + (needDot ? "." : string.Empty) + descr;
exp = ma.Expression;
needDot = true;
}
else if (exp.NodeType == ExpressionType.ArrayIndex)
{
// Array indexer
var be = (BinaryExpression)exp;
descr = GetParameters(new ReadOnlyCollection<Expression>(new[] { be.Right })) + (needDot ? "." : string.Empty) + descr;
exp = be.Left;
needDot = false;
}
else if (exp.NodeType == ExpressionType.Index)
{
// Object indexer (not used by C#. See ExpressionType.Call)
var ie = (IndexExpression)exp;
descr = GetParameters(ie.Arguments) + (needDot ? "." : string.Empty) + descr;
exp = ie.Object;
needDot = false;
}
else if (exp.NodeType == ExpressionType.Parameter)
{
break;
}
else if (exp.NodeType == ExpressionType.Call)
{
var ca = (MethodCallExpression)exp;
if (ca.Method.IsSpecialName)
{
// Object indexer
bool isIndexer = ca.Method.DeclaringType.GetDefaultMembers().OfType<PropertyInfo>().Where(x => x.GetGetMethod() == ca.Method).Any();
if (!isIndexer)
{
throw new Exception();
}
}
else if (ca.Object.Type.IsArray && ca.Method.Name == "Get")
{
// Multidimensiona array indexer
}
else
{
throw new Exception();
}
descr = GetParameters(ca.Arguments) + (needDot ? "." : string.Empty) + descr;
exp = ca.Object;
needDot = false;
}
}
return descr;
}
private static string GetParameters(ReadOnlyCollection<Expression> exps)
{
var values = new string[exps.Count];
for (int i = 0; i < exps.Count; i++)
{
if (exps[i].NodeType != ExpressionType.Constant)
{
throw new Exception();
}
var ce = (ConstantExpression)exps[i];
// Quite wrong here... We should escape string values (\n written as \n and so on)
values[i] = ce.Value == null ? "null" :
ce.Type == typeof(string) ? "\"" + ce.Value + "\"" :
ce.Type == typeof(char) ? "'" + ce.Value + "\'" :
ce.Value.ToString();
}
return "[" + string.Join(", ", values) + "]";
}
The code is quite easy to read, but it is quite long... There are 4 main cases: MemberAccess, that is accessing a property/field, ArrayIndex that is using the indexer of a single-dimensional array, Index that is unused by the C# compiler, but that should be using the indexer of an object (like the [...] of the List<> you are using), and Call that is used by C# for using an indexer or for accessing multi-dimensional arrays (new int[5, 4]) (and for other method calls, but we disregard them).
I support multidimensional arrays, jagged array s(arrays of arrays, new int[5][]) or arrays of indexable objects (new List<int>[5]) or indexable objects of indexable objects (new List<List<int>>). There is even support for multi-property indexers (indexers that use more than one key value, like obj[1, 2]). Small problem: printing the "value" of the indexers: I support only null, integers of various types, chars and strings (but I don't escape them... ugly... if there is a \n then it won't be printed as \n). Other types are not really supported... They will print what they will print (see GetParameters() if you want)

NEsper issue with regexp

I have been stuck here for a good while and seem to nail the problem to incorrect NEsper behaviour with regex. I wrote a simple project to reproduce the issue and it is available from github.
In a nutshell, NEsper allows me to pump messages (events) through a set of rules (SQL-like). If an event matches a rule, NEsper fires an alert. In my application I need to use a regular expression and this doesn't seem to work.
Problem
I tried both approaches of creating statements createPattern and createEPL and they are not firing a match event, however a regular expression and an input are matching by the .NET Regex class. If instead of regex ("\b\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}\b") I pass a matching value ("127.0.0.5") to the statement, the event successfully fires.
INPUT
127.0.0.5
==RULE FAIL==
every (Id123=TestDummy(Value regexp '\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b'))
// and I want this to pass
==RULE PASS==
every (Id123=TestDummy(Value regexp '127.0.0.5'))
Question
Could anyone help me out with a sample of NEsper regular expression matching? Or perhaps point to my dumb mistake in the code.
Code
This is my NEsper demo wrapper class
public class NesperAdapter
{
public MatchEventSubscrtiber Subscriber { get; set; }
internal EPServiceProvider Engine { get; private set; }
public NesperAdapter()
{
//This call internally depend on log4net,
//will throw an error if log4net cannot be loaded
EPServiceProviderManager.PurgeDefaultProvider();
//config
var configuration = new Configuration();
configuration.AddEventType("TestDummy", typeof(TestDummy).FullName);
configuration.EngineDefaults.Threading.IsInternalTimerEnabled = false;
configuration.EngineDefaults.Logging.IsEnableExecutionDebug = false;
configuration.EngineDefaults.Logging.IsEnableTimerDebug = false;
//engine
Engine = EPServiceProviderManager.GetDefaultProvider(configuration);
Engine.EPRuntime.SendEvent(new TimerControlEvent(TimerControlEvent.ClockTypeEnum.CLOCK_EXTERNAL));
Engine.Initialize();
Engine.EPRuntime.UnmatchedEvent += OnUnmatchedEvent;
}
public void AddStatementFromRegExp(string regExp)
{
const string pattern = "any (Id123=TestDummy(Value regexp '{0}'))";
string formattedPattern = String.Format(pattern, regExp);
EPStatement statement = Engine.EPAdministrator.CreatePattern(formattedPattern);
//this is subscription
Subscriber = new MatchEventSubscrtiber();
statement.Subscriber = Subscriber;
}
internal void OnUnmatchedEvent(object sender, UnmatchedEventArgs e)
{
Console.WriteLine(#"Unmatched event");
Console.WriteLine(e.Event);
}
public void SendEvent(object someEvent)
{
Engine.EPRuntime.SendEvent(someEvent);
}
}
Then subscriber and a DummyType
public class MatchEventSubscrtiber
{
public bool HasEventFired { get; set; }
public MatchEventSubscrtiber()
{
HasEventFired = false;
}
public void Update(IDictionary<string, object> rows)
{
Console.WriteLine("Match event fired");
Console.WriteLine(rows);
HasEventFired = true;
}
}
public class TestDummy
{
public string Value { get; set; }
}
And NUnit test. If one comments nesper.AddStatementFromRegExp(regexp); line and uncomments //nesper.AddStatementFromRegExp(input); line then test pass. However I need a regular expression there.
//Match any IP address
[TestFixture(#"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", "127.0.0.5")]
public class WhenValidRegexpPassedAndRuleCreatedAndPropagated
{
private NesperAdapter nesper;
//Setup
public WhenValidRegexpPassedAndRuleCreatedAndPropagated(string regexp, string input)
{
//check it is valid regexp in .NET
var r = new Regex(regexp);
var match = r.Match(input);
Assert.IsTrue(match.Success, "Regexp validation failed in .NET");
//create and start engine
nesper = new NesperAdapter();
//Add a rule, this fails with a correct regexp and a matching input
//PROBLEM IS HERE
nesper.AddStatementFromRegExp(regexp);
//PROBLEM IS HERE
//This works, but it is just input self-matching
//nesper.AddStatementFromRegExp(input);
var oneEvent = new TestDummy
{
Value = input
};
nesper.SendEvent(oneEvent);
}
[Test]
public void ThenNesperFiresMatchEvent()
{
//wait till nesper process the event
Thread.Sleep(100);
//Check if subscriber has received the event
Assert.IsTrue(nesper.Subscriber.HasEventFired,
"Event didn't fire");
}
}
I was debugging this issue for some time now and found that NEsper incorrectly handles
WHERE regexp 'foobar' statement
So if I have
SELECT * FROM MyType WHERE PropertyA regexp 'some valid regexp'
NEsper performs string formatting and validation with 'some valid regexp' and removes important (and valid) symbols from regexp. This is how I fixed it for myself. Not sure if it is a recommended approach.
File: com.espertech.esper.epl.expression.ExprRegexpNode
Reason: I think it is up to the user how regexp is constructed, this shall not be part of a framework.
// Inside this method
public object Evaluate(EventBean[] eventsPerStream, bool isNewData, ExprEvaluatorContext exprEvaluatorContext){...}
// Find two occurrences of
_pattern = new Regex(String.Format("^{0}$", patternText));
// And change to
_pattern = new Regex(patternText);
File: com.espertech.esper.epl.parse.ASTConstantHelper
Reason: requireUnescape for all strings, but skip regexp as this brakes valid regexp and removes some valid symbols from it.
// Inside this method
public static Object Parse(ITree node){...}
// Find one occurrence of
case EsperEPL2GrammarParser.STRING_TYPE:
{
return StringValue.ParseString(node.Text, requireUnescape);
}
// And change to
case EsperEPL2GrammarParser.STRING_TYPE:
{
bool requireUnescape = true;
if (node.Parent != null)
{
if (!String.IsNullOrEmpty(node.Parent.Text))
{
if (node.Parent.Text == "regexp")
{
requireUnescape = false;
}
}
}
return StringValue.ParseString(node.Text, requireUnescape);
}
File: com.espertech.esper.type.StringValue
Reason: unescape all strings, but the regexp value.
// Inside this method
public static String ParseString(String value){...}
// Change from
public static String ParseString(String value)
{
if ((value.StartsWith("\"")) & (value.EndsWith("\"")) || (value.StartsWith("'")) & (value.EndsWith("'")))
{
if (value.Length > 1)
{
if (value.IndexOf('\\') != -1)
{
return Unescape(value.Substring(1, value.Length - 2));
}
return value.Substring(1, value.Length - 2);
}
}
throw new ArgumentException("String value of '" + value + "' cannot be parsed");
}
// Change to
public static String ParseString(String value, bool requireUnescape = true)
{
if ((value.StartsWith("\"")) & (value.EndsWith("\"")) || (value.StartsWith("'")) & (value.EndsWith("'")))
{
if (value.Length > 1)
{
if (requireUnescape)
{
if (value.IndexOf('\\') != -1)
{
return Unescape(value.Substring(1, value.Length - 2));
}
}
return value.Substring(1, value.Length - 2);
}
}
throw new ArgumentException("String value of '" + value + "' cannot be parsed");
}

'Advanced' Console Application

I'm not sure if this question has been answered elsewhere and I can't seem to find anything through google that isn't a "Hello World" example... I'm coding in C# .NET 4.0.
I'm trying to develop a console application that will open, display text, and then wait for the user to input commands, where the commands will run particular business logic.
For example: If the user opens the application and types "help", I want to display a number of statements etc etc. I'm not sure how to code the 'event handler' for user input though.
Hopefully this makes sense. Any help would be much appreciated!
Cheers.
You need several steps to achieve this but it shouldn't be that hard. First you need some kind of parser that parses what you write. To read each command just use var command = Console.ReadLine(), and then parse that line. And execute the command... Main logic should have a base looking this (sort of):
public static void Main(string[] args)
{
var exit = false;
while(exit == false)
{
Console.WriteLine();
Console.WriteLine("Enter command (help to display help): ");
var command = Parser.Parse(Console.ReadLine());
exit = command.Execute();
}
}
Sort of, you could probably change that to be more complicated.
The code for the Parser and command is sort of straight forward:
public interface ICommand
{
bool Execute();
}
public class ExitCommand : ICommand
{
public bool Execute()
{
return true;
}
}
public static Class Parser
{
public static ICommand Parse(string commandString) {
// Parse your string and create Command object
var commandParts = commandString.Split(' ').ToList();
var commandName = commandParts[0];
var args = commandParts.Skip(1).ToList(); // the arguments is after the command
switch(commandName)
{
// Create command based on CommandName (and maybe arguments)
case "exit": return new ExitCommand();
.
.
.
.
}
}
}
I know this is an old question, but I was searching for an answer too. I was unable to find a simple one though, so I built InteractivePrompt. It's available as a NuGet Package and you can easily extend the code which is on GitHub. It features a history for the current session also.
The functionality in the question could be implemented this way with InteractivePrompt:
static string Help(string strCmd)
{
// ... logic
return "Help text";
}
static string OtherMethod(string strCmd)
{
// ... more logic
return "Other method";
}
static void Main(string[] args)
{
var prompt = "> ";
var startupMsg = "BizLogic Interpreter";
InteractivePrompt.Run(
((strCmd, listCmd) =>
{
string result;
switch (strCmd.ToLower())
{
case "help":
result = Help(strCmd);
break;
case "othermethod":
result = OtherMethod(strCmd);
break;
default:
result = "I'm sorry, I don't recognize that command.";
break;
}
return result + Environment.NewLine;
}), prompt, startupMsg);
}
This is easy enough, just use the Console.WriteLine and Console.ReadLine() methods. From the ReadLine you get a string. You could have a horrible if statement that validate this against known/expected inputs. Better would be to have a lookup table. Most sophisticated would be to write a parser. It really depends on how complex the inputs can be.
Console.WriteLine Console.ReadLine and Console.ReadKey are your friends. ReadLine and ReadKey waits for user input. The string[] args will have all of your parameters such as 'help' in them. The array is created by separating the command line arguments by spaces.
switch (Console.ReadLine())
{
case "Help":
// print help
break;
case "Other Command":
// do other command
break;
// etc.
default:
Console.WriteLine("Bad Command");
break;
}
If you're looking to parse commands that have other things in them like parameters, for example "manipulate file.txt" then this alone won't work. But you could for example use String.Split to separate the input into a command and arguments.
A sample:
static void Main(string[] args)
{
Console.WriteLine("Welcome to test console app, type help to get some help!");
while (true)
{
string input = Console.ReadLine();
int commandEndIndex = input.IndexOf(' ');
string command = string.Empty;
string commandParameters = string.Empty;
if (commandEndIndex > -1)
{
command = input.Substring(0, commandEndIndex);
commandParameters = input.Substring(commandEndIndex + 1, input.Length - commandEndIndex - 1);
}
else
{
command = input;
}
command = command.ToUpper();
switch (command)
{
case "EXIT":
{
return;
}
case "HELP":
{
Console.WriteLine("- enter EXIT to exit this application");
Console.WriteLine("- enter CLS to clear the screen");
Console.WriteLine("- enter FORECOLOR value to change text fore color (sample: FORECOLOR Red) ");
Console.WriteLine("- enter BACKCOLOR value to change text back color (sample: FORECOLOR Green) ");
break;
}
case "CLS":
{
Console.Clear();
break;
}
case "FORECOLOR":
{
try
{
Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), commandParameters);
}
catch
{
Console.WriteLine("!!! Parameter not valid");
}
break;
}
case "BACKCOLOR":
{
try
{
Console.BackgroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), commandParameters);
}
catch
{
Console.WriteLine("!!! Parameter not valid");
}
break;
}
default:
{
Console.WriteLine("!!! Bad command");
break;
}
}
}
}
This is very simplistic, but might meet your needs.
// somewhere to store the input
string userInput="";
// loop until the exit command comes in.
while (userInput != "exit")
{
// display a prompt
Console.Write("> ");
// get the input
userInput = Console.ReadLine().ToLower();
// Branch based on the input
switch (userInput)
{
case "exit":
break;
case "help":
{
DisplayHelp();
break;
}
case "option1":
{
DoOption1();
break;
}
// Give the user every opportunity to invoke your help system :)
default:
{
Console.WriteLine ("\"{0}\" is not a recognized command. Type \"help\" for options.", userInput);
break;
}
}
}
There is a C# nuget package called 'ReadLine' by 'tornerdo'. The statement ReadLine.Read(" prompt > "); prompts the user within options provided in CustomAutoCompletionHandler.PossibleAutoCompleteValues.
Additionally, you can change the CustomAutoCompletionHandler.PossibleAutoCompleteValues for each prompt. This ensures that the user get to choose an option from available\ supported list of options. Less error prone.
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(" Note! When it prompts, press <tab> to get the choices. Additionally, you can use type ahead search.");
Console.ForegroundColor = ConsoleColor.White;
// Register auto completion handler..
ReadLine.AutoCompletionHandler = new CustomAutoCompletionHandler();
CustomAutoCompletionHandler.PossibleAutoCompleteValues = new List<string> { "dev", "qa", "stg", "prd" };
var env = CoverReadLine(ReadLine.Read(" Environment > "));
Console.WriteLine($"Environment: {env}");
}
private static string CoverReadLine(string lineRead) => CustomAutoCompletionHandler.PossibleAutoCompleteValues.Any(x => x == lineRead) ? lineRead : throw new Exception($"InvalidChoice. Reason: No such option, '{lineRead}'");
public class CustomAutoCompletionHandler : IAutoCompleteHandler
{
public static List<string> PossibleAutoCompleteValues = new List<string> { };
// characters to start completion from
public char[] Separators { get; set; } = new char[] { ' ', '.', '/' };
// text - The current text entered in the console
// index - The index of the terminal cursor within {text}
public string[] GetSuggestions(string userText, int index)
{
var possibleValues = PossibleAutoCompleteValues.Where(x => x.StartsWith(userText, StringComparison.InvariantCultureIgnoreCase)).ToList();
if (!possibleValues.Any()) possibleValues.Add("InvalidChoice");
return possibleValues.ToArray();
}
}

c# main method ignores string variables

I've been given a small c# project to write, which basically is to wrap a few dlls in a console application.
I've hit what I see as a weird problem. I've declared a couple of local variables within the main method to use. The idea is that when the arguments are parsed they values are store in these variables ( the arguments are in key pairs e.g. -u:username ).
Below is the code that I am using to start the process..
namespace ziptogo
{
public class ZipToGo
{
public static void Main(string[] args)
{
string user = null;
int divisionid = 0;
string mysqlServer = null;
string mysqlName = null;
string mysqlUser = null;
string mysqlPwd = null;
string barcode = null;
bool zipped = false;
ZipToGo ziptogo = new ZipToGo();
if (args.Length == 0)
{
ziptogo.usage();
}
//we look throught the arguments and extract the values.
for (int i = 0; i < args.Length; i++)
{
string[] values = ziptogo.getArgValue(args[i]);
if (values[0].Equals("-U") || values[0].Equals("-u"))
{
user = values[1];
}
if (values[0].Equals("-D") || values[0].Equals("-d"))
{
divisionid = Int32.Parse(values[1]);
}
....
As I am new to writing in c# am I missing something obvious as to why the strings such as mysqlServer are being ignored by the main method??
The integer divisionid and string barcode is the only variables that are not being ignored by the method.
Thanks.
To test it quickly, you can add this line just after Main():
args = new String[] { "-u:username" };
Then go through the code step by step, using the debugger.
[Edit] If getArgValue looks something like this:
public String[] getArgValue(String s)
{
return s.Split(':');
}
then it should work IMHO (quick and dirty, just to get it running).
[Edit:] There are some nice solutions for command line parsing available, which remove the need to add all those conditionals, e.g. http://www.codeproject.com/KB/recipes/commandlineparser.aspx.
Do you know about debugger?
If you use Visual Studion do this.
Set you caret to string user = null;
Click F9 (Toggle breakpoint);
Click F5 (Strat debugging);
Click F10 to go through your application;
I think you quickly find what is wrong. Often this is stupid misspels...
What does getArgValue( string[] ) do?
I bet if you do...
public static void Main(string[] args)
{
if ( args.Length > 0 )
System.Diagnostics.Debug.WriteLine( args[0] );
/* etc */
}
You'll see your missing "-d".
Have a look at this code and see if it helps. It should be doing exactly what you want and is a bit cleaner.
string[] args = new string[] {"-u:username", "-dbs:servername", "-dbu:dbuser", "-dbp:dbpassword"};
string user = null;
int divisionid = 0;
string mysqlPwd = null;
foreach (string arg in args)
{
string[] parts = arg.Split(':');
switch (parts[0].ToUpper())
{
case "-U":
user = parts[1];
break;
case "-D":
divisionid = Int32.Parse(parts[1]);
break;
case "-DBP":
mysqlPwd = parts[1];
break;
// ....
default:
// Display usage
break;
}
}
Debug.WriteLine(string.Format("User {0} | Password {1}", user, mysqlPwd));
Obviously the args part should come from you command line and not be hard coded.

Categories