I am currently working on a project that is creating a rapid translating program to mess up text using google's API. But I keep running into warning CS0168 and don't know how to fix it. The code is here:
using System;
using Google.Cloud.Translation.V2;
namespace Program
{
public partial class Translate
{
[STAThread]
private static void Main()
{
Console.WriteLine("Write text to become cursed");
string Phrase = Console.ReadLine();
string TranslateText() //this variable is the problem
{
TranslationClient client = TranslationClient.Create();
//this block repeats with the language changing each time
var response = client.TranslateText(
text: Phrase,
targetLanguage: "language",
sourceLanguage: "language");
Console.WriteLine(response.TranslatedText);
Phrase = response.TranslatedText;
//end of reapeat
return response.TranslatedText;
}
}
}
}
Even if I ignore the warning the program wont run.
There are two main problems with your code:
As others have indicated, you declared a local function but you never used it.
The application exits right away because it's done all its work. You need to add Console.ReadLine(); or Console.ReadKey(); at the end to prevent it from closing.
Try something like this:
static void Main(string[] args)
{
Console.WriteLine("Write text to become cursed");
string Phrase = Console.ReadLine();
string TranslateText()
{
TranslationClient client = TranslationClient.Create();
//this block repeats with the language changing each time
var response = client.TranslateText(
text: Phrase,
targetLanguage: "language",
sourceLanguage: "language");
Console.WriteLine(response.TranslatedText);
Phrase = response.TranslatedText;
//end of reapeat
return response.TranslatedText;
}
string translatedText = TranslateText();
Console.WriteLine("The translated text is: " + translatedText);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
With that being said, a local function might not be the best way to handle this. Instead, you could move it outside the Main and add a string parameter to it so that you can pass the phrase as an argument to it. In this case, your code would look something like this:
static void Main(string[] args)
{
Console.WriteLine("Write text to become cursed");
string phrase = Console.ReadLine();
string translatedText = TranslateText(phrase);
Console.WriteLine("The translated text is: " + translatedText);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
static string TranslateText(string phrase)
{
TranslationClient client = TranslationClient.Create();
//this block repeats with the language changing each time
var response = client.TranslateText(
text: phrase,
targetLanguage: "language",
sourceLanguage: "language");
Console.WriteLine(response.TranslatedText);
//end of reapeat
return response.TranslatedText;
}
Related
I have a text-to-speech C#/WPF application. In it I need to display the duration of each speech. I've tried using the SpeakProgress and SpeakCompleted events, but I was unsuccessful. Can someone give me a direction to go, please? Thanks.
If using SpeechSynthesizer you can use the SpeakSsml option and add a <mark> element at the end of your text. Then, listen for the Bookmark reached event, which includes the AudioPosition in milliseconds. Note that you may also need to include a very short <break> at the end to ensure that event gets triggered. See this gist (powershell, sorry!) for an example.
using System;
using System.Speech.Synthesis;
namespace SampleSynthesis
{
class Program
{
static void Main(string[] args)
{
// Initialize a new instance of the SpeechSynthesizer.
SpeechSynthesizer synth = new SpeechSynthesizer();
// Configure the audio output.
synth.SetOutputToDefaultAudioDevice();
string END_MARKER = "__final__event";
// replace with your own text
string myText = "Hello World! This is my properly XML escaped text.";
// Build an SSML prompt in a string.
string str = "<speak version=\"1.0\"";
str += " xmlns=\"http://www.w3.org/2001/10/synthesis\"";
// change language as necessary
str += " xml:lang=\"en-US\">";
str += myText;
// add a 50ms break because otherwise the <mark> event may not be detected, for some reason
str += "<break time=\"50ms\">";
// add the marker element to generate a bookmark event
str += "<mark name=\"" + END_MARKER + "\" />";
str += "</speak>";
synth.BookmarkReached += new EventHandler<BookmarkReachedEventArgs>(synth_BookmarkReached);
// Speak the contents of the prompt synchronously.
synth.SpeakSsml(str);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
static void synth_BookmarkReached(object sender, BookmarkReachedEventArgs e)
{
if (e.Bookmark == END_MARKER) {
Console.WriteLine("Duration in MS is {0}", e.AudioPosition.TotalMilliseconds);
}
}
}
I am writing a simple shell program and I have written a few commands for the program. Unfortunately, I also want to allow the shell to pipe an echo command out to a text file and also be able to cat said file and output the contents. The issue I am having is the way that I have written how the echo command works.
public static void Main(string[] args)
{
string command;
do
{
Console.ForegroundColor =
ConsoleColor.DarkGreen;
Console.Write("console > ");
Console.ForegroundColor = ConsoleColor.Gray;
command = Console.ReadLine();
Handle(command);
} while (command != "exit");
}
public static string Handle(string command)
{
if (command.StartsWith("echo "))
{
command = command.Replace("\"", "");
Console.WriteLine(command.Substring(5));
}
if (command.Contains("->"))
{
// logic for echo "text" -> output.txt
}
}
}
You can try something like this that takes the content from before and after the ->. You will have to validate the string of course before you run this
string cmd = #"echo ""text"" -> output.txt";
string text = cmd.Split(" -> ").First().Replace("echo ", "").Replace(#"""", "");
string file = cmd.Split(" -> ").Skip(1).First();
Or, a more general solution (to allow extra commands). First I create a dictionary of commands. The Action<string,string> type represents a delegate to a function that takes two strings as as parameters. The StringComparer.CurrentCultureIgnoreCase means that the case (upper or lower) is ignored when matching:
private static readonly Dictionary<string, Action<string, string>> CommandList =
new Dictionary<string, Action<string, string>>(StringComparer.CurrentCultureIgnoreCase)
{
{"echo", EchoCommand},
{"exit", ExitCommand}
};
Now I have to implement the commands. The echo command is close to what you want to do (I don't bother trying to write to the file, but I get it to the point where you could). The exit command is empty (I just let it fall through). You may want to refactor that behavior.
private static void EchoCommand(string commandText, string file)
{
var fileNote = string.IsNullOrEmpty(file) ? string.Empty : $" ({file})";
Console.WriteLine($"{commandText} {fileNote}");
}
private static void ExitCommand(string commandText, string file)
{
}
Now I need something to parse my command line. This is a brute force hack, but it works. The weird return type is a tuple, an entity that contain many values, in this case three named strings.
static (string command, string text, string file) ParseCommandLine(string commandLine)
{
//find the first space:
var endOfCommandIndex = commandLine.IndexOf(" ");
if (endOfCommandIndex < 0)
{
return (commandLine, string.Empty, null);
}
//otherwise
var command = commandLine.Substring(0, endOfCommandIndex);
var rest = commandLine.Substring(endOfCommandIndex);
var redirectIndex = rest.IndexOf("->");
if (redirectIndex < 0)
{
//use the substring to get rid of the "->"
return (command, rest.Substring(2).Trim(), null);
}
//otherwise (the "+ 2" is to get rid of the "->"
return (command, rest.Substring(0, redirectIndex).Trim(), rest.Substring(redirectIndex + 2).Trim());
}
It bangs away at the command line string and parses it into a Command, some Text and possibly a File to redirect to. I only changed a bit of the core of your Main function. It ends up looking like:
string command, text, file;
do
{
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.Write("console > ");
Console.ForegroundColor = ConsoleColor.Gray;
var commandLine = Console.ReadLine();
(command, text, file) = ParseCommandLine(commandLine);
if (CommandList.TryGetValue(command, out var commandAction))
{
commandAction(text, file);
}
else
{
Console.WriteLine("ERROR: Unknown Command");
}
} while (command != "exit");
The TryGetValue call on the dictionary will return true if the command text is in the dictionary. If it returns true, then the commandAction will represent the function to call (so it calls it). If it returns false, then the command is not in the dictionary, so an error is signaled to the user.
And finally, you don't need to put the string to echo in quotes. It just echoes whatever it finds.
I am trying to merge two programs, using output of one as an input to other.
Program # 1 ends up writing the output and program 2 wants user input both using console. I don't want result of program 1 to be shown as output but rather used as input so that program 2 doesn't ask for user input.
foreach (var item in result)
{
Console.Write(item);
}
Console.ReadLine();
**end of program 1**
**program 2**
Console.WriteLine("Please, enter numbers");
var numbersStr = Console.ReadLine();
if (!string.IsNullOrEmpty(numbersStr))
{
numbersStr = numbersStr.Trim();
and program continues
It seems like you just need methods. You don't need two programs.
// name this method appropriately!
private static string Program1() {
string retVal = "";
// here goes your program 1
// replace every Console.Write with retVal += ...
// e.g.
foreach (var item in result)
{
retVal += item.ToString();
}
return retVal;
}
// name this properly as well
private static void Program2(string input) {
// program 2 goes here
}
In your Main,
Program2(Program1());
If this is a trivial program you could write the output of the first program to a file or database. And your second program could read from that.
using (var fileWriter = new StreamWriter(pathOfFile))
{
foreach (var item in result)
{
fileWriter.Write(item);
}
}
end of program 1
program 2
Console.WriteLine("Please, enter numbers");
var numbersStr = Console.ReadLine();
var input = File.ReadAllText(pathOfFile)
if (!string.IsNullOrEmpty(input))
{
numbersStr = numbersStr.Trim();
}
I am trying to create an ai. I have got it to write a topic with information to a text file but cant get it to read. this is what i have so far. Any ideas on why it isnt working?
string information = "blank";
Console.WriteLine("Hello my name is Lou-C.");
Console.WriteLine("What is yours?");
string name = Console.ReadLine();
Console.WriteLine("Hello {0}, What do you want to talk about?", name);
string topic = Console.ReadLine();
string[] lines = System.IO.File.ReadAllLines(#"C:\Users\simon.light\Documents\Visual Studio 2013\Projects\Lou-c\Lou-c\information.txt");
if (lines.Contains("beat"))
{
Console.WriteLine("Aaahh, {0}, I have heard of this before");
Console.WriteLine("Tell me what you know about this");
information = Console.ReadLine();
}
else
{
Console.WriteLine("{0}? I don't think i have come across this before.", topic);
Console.WriteLine("Tell me about it");
information = Console.ReadLine();
}
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(#"C:\Users\simon.light\Documents\Visual Studio 2013\Projects\Lou-c\Lou-c\information.txt", true))
{
file.WriteLine("${0} - %{1} - by {2}", topic, information, name);
}
To check for any line that contains "beat"
if (lines.Any(s => s.Contains("beat")))
However, if you used ReadAllText then your contains would work!
string text = System.IO.File.ReadAllText(...);
if (text.Contains("beat"))
I'm a bit confused. I've been looking through previous answers to the above question and NONE of them actually work for me, so I'm not sure what i'm doing wrong.
I have a simple c# console app: (outputsomething.exe)
static void Main(string[] args) {
Console.Out.Write("This is a test");
}
And another one that takes some args and piped input from the above code, like this:
dostuffwithinput.exe some args |outputsomething.exe
First problem is that I can't work out how to "read" the piped input, as I said above none of the existing answers work for me, reading from stdin (Console.In) just doesn't capture anything.
Secondly, after piping something in I can no longer write anything out to stdout (Console.Out).
The code I have is very simple it just writes out the args to a file, together with a few console attributes and tries to read from Console.In - which it does but it only reads input that I type in.
But with piped input it just never manages to capture what is piped in and the last output is never sent to the console.
static void Main(string[] args) {
bool ior = Console.IsInputRedirected;
bool keyavail = Console.KeyAvailable;
char[] chrs = new char[4];
int chr = Console.In.ReadBlock(chrs, 0, 4);
using (StreamWriter stream = new StreamWriter("fred.txt")) {
foreach (var arg in args) {
stream.WriteLine(arg);
Console.WriteLine(arg);
}
stream.WriteLine("input = " + new string(chrs));
stream.WriteLine("io redirectirected = " + ior);
stream.WriteLine("is key available = " + keyavail);
}
Console.WriteLine("fin");
Console.Out.Flush();
}
(I'm also having serious problems with this pile-of-crap editor that keeps showing a red warning about indentation show i've have to remove a lot of examples to get it in a sendable form!)
What am I doing wrong? (this is on windows 10/9879)
TIA
Tried the same with the below example codes. It is working for me.
WriteText
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Test Line1");
Console.WriteLine("test Line2");
}
}
ProcessInput
class Program
{
static void Main(string[] args)
{
string s=Console.In.ReadToEnd();
Console.WriteLine("Redirected Text: " + s);
}
}
I invoked the app using WriteText.exe | ProcessInput.exe
It showed the output string exactly passed by the WriteText.exe
Please let me know, if this helps.
If you want to pipe from outputsomething.exe to dostuffwithinput.exe it should be
outputsomething.exe|dostuffwithinput.exe some args