I'm writing a flesch index calculator and I want to be able to start my program with a console command and the .exe itself. I want to read in .txt files in the console with the command fleschIndexCalc.exe -f "path of the file" and then be able to select the calculation formula either for an english text with the parameter -e or a german text with -g.
When I start it with the console command: I type in the parameters by myself.
When I start it with the .exe: The program asks for the language and I just have to write g ore and press enter.
Now my question: how can I tell my program while starting it with the console that I already chose the language so it doesn't ask me for it again like I started it with the .exe?
Here's what I got:
(If you need more code from my FleschScore.cs ask for it :) )
namespace Flesch_Reading_Ease
{
public class Program
{
public static void Main(string[] args)
{
string fileName = string.Empty;
string[] parameters = new string[] { "-f", "-g", "-e" };
Console.WriteLine("Flesch Reading Ease");
Console.WriteLine("");
if (args.Length == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("error!");
Console.ResetColor();
Console.WriteLine("no file found!");
Console.WriteLine("");
Console.Write("press any key...");
Console.ReadKey();
return;
}
foreach (string arg in args)
{
//------- WHAT TO WRITE HERE? -------
}
fileName = args[0];
FleschScore fs = new FleschScore(fileName);
fs.Run();
}
}
}
My method to choose the language looks like this:
private void SelectLanguage()
{
do
{
Console.WriteLine("choose language:");
Console.WriteLine("- german(g)");
Console.WriteLine("- english(e)");
string lang = Console.ReadLine();
switch (lang.ToUpper())
{
case "D":
_selectedLanguage = Language.German;
break;
case "E":
_selectedLanguage = Language.English;
break;
default:
_selectedLanguage = Language.Undefined;
Console.WriteLine("wrong input. Enter viable letter.");
Console.WriteLine("");
break;
}
} while (_selectedLanguage == Language.Undefined);
}
You basically loop through all the arguments and keep track of what's already entered. Then after that you check if you have all the info you need and pass everything as parameters to whatever method/class needs it.
bool isGerman = false;
bool isEnglish = false;
bool nextEntryIsFileName = false;
string filename = null;
foreach (string arg in args)
{
switch (arg)
{
case "-e":
isEnglish = true;
nextEntryIsFileName = false;
break;
case "-g":
isGerman = true;
nextEntryIsFileName = false;
break;
case "-f":
nextEntryIsFileName = true;
break;
default:
if (nextEntryIsFileName)
{
filename = arg;
nextEntryIsFileName = false;
}
break;
}
}
if (!(isEnglish ^ isGerman))
{
// Select language
}
if (String.IsNullOrEmpty(filename))
{
// Ask for filename
}
var language = ...
FleschScore fs = new FleschScore(language, fileName);
fs.Run();
Related
I have an encoder connected from Siemens PLC with data block "DB1.DBD56".
My problem is, the two textbox has the same result or value.
Scenario:
Read Before 1seconds and
Read After 1seconds
I want the result like this:
[For reference]
(https://i.stack.imgur.com/HK9zU.png)
[PLC Ladder]
(https://i.stack.imgur.com/kGN62.png)
#region EVENT TO START READING THE ENCODER
private void timer_anvilState_Tick(object sender, EventArgs e)
{
try
{
Edata_convertion();
read_lastweld_result();
bool anvilState = (bool)plc_s7_1200.Read("DB1.DBX68.4");
if (plc_s7_1200.IsConnected)
{
if (anvilState == true)
{
timer_OneCycleProcess.Start(); //STATE MACHINE TIMER
}
else
{
timer_OneCycleProcess.Stop();
command = "IDLE";
}
}
}
catch (Exception ex)
{
MessageBox.Show("Please check between PC and PLC connection " + "\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#region READ BEFORE
public void Read_Before()
{
if (plc_s7_1200.IsConnected)
{
bool anvilState = (bool)plc_s7_1200.Read("DB1.DBX68.4");
if (anvilState == true)
{
string Edata = string.Format("{0:0.0}", convertTomm);
txtbefore.Text = Edata;
}
}
}
#endregion
#region READ AFTER
public void Read_After()
{
bool gen_US_on = (bool)plc_s7_1200.Read("DB1.DBX78.2");
if (gen_US_on == true)
{
string Edata = string.Format("{0:0.0}", convertTomm);
txtafterWeld.Text = Edata;
}
}
#endregion
Here's my solution.
Only revised the PLC ladder as stated my replied at comment section.
https://i.stack.imgur.com/GUBtg.png
My C# program nothing changes.
Sharing my basic state machine code
#region ONE CYCLE PROCESS
private void timer_OneCycleProcess_Tick(object sender, EventArgs e)
{
switch (command)
{
case "IDLE":
command = "BEFORE";
break;
case "BEFORE":
before();
command = "AFTER";
break;
case "AFTER":
after();
prev_result();
read_maintenanceCounter();
read_outputCounter();
command = "SAVE";
break;
case "SAVE":
command = "STOP";
save();
save_history();
break;
case "STOP":
timer_OneCycleProcess.Stop();
plc_s7_1200.Write("DB1.DBX38.0", 0);
break;
default:
break;
}
}
#endregion
This question already has answers here:
Append lines to a file using a StreamWriter
(11 answers)
Closed 3 years ago.
I'm trying to create a code that asks for a user name and saves it in a text file. The problem is when I close the console app and try to run it again, it deletes all the information that was in the text file. Can anyone help me solve this problem?
public static void UserWriter(StreamWriter WriteNewLine)
{
bool EndOfWrite = true;
char Answer;
while (EndOfWrite)
{
Console.WriteLine("eneter a user name");
WriteNewLine.WriteLine(Console.ReadLine());
Console.WriteLine("did you finish ? Y/N");
Wrong: Answer = Convert.ToChar(Console.ReadLine());
switch (Answer)
{
case 'Y':
EndOfWrite = false;
break;
case 'N':
break;
default:
goto Wrong;
}
}
WriteNewLine.Close();
}
static void Main(string[] args)
{
string fileLoction = #"C:\project\user.txt";
StreamWriter WriteNewLine = new StreamWriter(fileLoction);
if (File.Exists(fileLoction))
{
WriteNewLine.Close();
WriteNewLine = File.AppendText(fileLoction);
UserWriter(WriteNewLine);
WriteNewLine.Close();
}
else
{
UserWriter(WriteNewLine);
WriteNewLine.Close();
}
}
Along with #metal answer, this shall do the job.
static void Main(string[] args)
{
string fileLoction = #"C:\project\user.txt";
StreamWriter WriteNewLine = new StreamWriter(fileLoction, true);
WriteNewLine = File.AppendText(fileLoction);
WriteNewLine.Close();
}
If I write the following code (inside the Main method):
Console.Write("First name: ");
student.FirstName = Console.ReadLine();
where FirsName is a property of Student class, how can I prevent the user from entering integer characters? Can this be done using try-catch block?
If you want to prevent user from "entering" Numeric Characters, you could do the following.
var value = new StringBuilder();
var run = true;
while (run)
{
var inputKey = Console.ReadKey(true);
switch (inputKey.Key)
{
case ConsoleKey.Enter:
run = false;
Console.WriteLine();
break;
case ConsoleKey.Backspace:
value.Append(inputKey.KeyChar);
break;
default:
if (!char.IsDigit(inputKey.KeyChar))
value.Append(inputKey.KeyChar);
Console.Write(inputKey.KeyChar);
break;
}
}
var name = value.ToString();
You were not very specific, but based on the data you gave you can do something like this using try catch:
class Program
{
static void Main(string[] args)
{
Student student = new Student();
try
{
Console.Write("First name: ");
student.FirstName = Console.ReadLine();
ValidateMyString(student.FirstName);
Console.ReadLine();
}
catch(Exception e)
{
throw e;
}
}
static void ValidateMyString(string s)
{
if (s.Any(char.IsDigit))
{
throw new FormatException();
}
}
}
Here a example in dotnetfiddle.
Hey guys can you tell me how should can I call "print: if . It never goes inside print if . It loops out.
static void Main(string[] args)
{
if (commands == "Read" || commands == "read")
{
fileread obj = new fileread();
lcsString = obj.getlcs();
commands = Console.ReadLine(); // If command = print I want it go to print but it never goes . it loops out
}
else if (commands =="print")
{
}
}
You can use while, here you go..
while (!commands.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
if (commands.Equals("read", StringComparison.OrdinalIgnoreCase))
{
fileread obj = new fileread();
lcsString = obj.getlcs();
}
else if (commands == "print")
{
// print ...
}
commands = Console.ReadLine();
}
It is not clear what you asking but looks like there is an option;
Moving your commands = Console.ReadLine() outside in your if statement. Like;
commands = Console.ReadLine();
if (commands == "Read" || commands == "read")
{
fileread obj = new fileread();
lcsString = obj.getlcs();
}
else if (commands =="print")
{
}
Because if your first if statement works, that's mean your command is Read or read. After that, your program doesn't go your else if part. It goes outside of your if statement.
Im working with the custom compiler from MSDN website. When I try to compile/run some test code (drag and drop to .exe), the console window opens then closes instead of staying open until I choose to close it. How do I keep it open?
Source: http://msdn.microsoft.com/en-us/magazine/cc136756.aspx#S8
Program.cs
if (args.Length != 1)
{
// Display title, reset cursor to normal, add space
Console.WriteLine("Alt ver 1.0 (Alpha)");
Console.WriteLine();
Console.ReadLine();
try
{
Scanner scanner = null;
using (TextReader input = File.OpenText(args[0]))
{
scanner = new Scanner(input);
}
Parser parser = new Parser(scanner.Tokens);
CodeGen codeGen = new CodeGen(parser.Result, Path.GetFileNameWithoutExtension(args[0]) + ".exe");
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Console.ReadLine();
}
} //if
add a Console.ReadLine();
at the last inside the try block
try this
if (args.Length != 1)
{
// Display title, reset cursor to normal, add space
Console.WriteLine("Alt ver 1.0 (Alpha)");
Console.WriteLine();
Console.ReadLine();
try
{
Scanner scanner = null;
using (TextReader input = File.OpenText(args[0]))
{
scanner = new Scanner(input);
}
Parser parser = new Parser(scanner.Tokens);
CodeGen codeGen = new CodeGen(parser.Result, Path.GetFileNameWithoutExtension(args[0]) + ".exe");
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Console.ReadLine();
}
finally
{
Console.Readkey();
}
} //if
else
{
Console.WriteLine("no args");
Console.ReadKey();
}
EDIT:--- passing argument problem
i have made this program and it works perfectly as far as getting filename as arguments
please have a look
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
foreach (var arg in args)
{
Console.WriteLine(arg);
}
Console.ReadKey();
}
else
{
Console.WriteLine("NO ARGS");
var fileName = Console.ReadLine();
Main(new string[] { fileName });
}
}
}