Check and get user input from terminal C# - c#

I am trying to get user input from the terminal in C#, but I only want to ReadLine when the user starts typing. Basically the way I have it set up now is that I am in a while loop and I want to either check to see if I got messages or send them, but I don't want to get stuck trying to send one by calling ReadLine and waiting for the user to send a message if they have nothing to send at the moment. My code looks something like this:
While (true)
{
// If messages to be received
// Receive them
// Check to see if the user is typing input
if (Console.KeyAvailable)
{
string userInput = Console.ReadLine();
// Do stuff...
}
}
Basically what is happening is that it works completely fine, but the first letter that the user types does not show up in the terminal window, but it does get picked up by the ReadLine no problem. Is there anyway I can get this to work so that the user can see everything they are typing right away?
Thanks!

You can use Console.ReadKey(true); to read missing item, then read other parts with readline method append it to your input.

Related

Discord command stops after attempting to read text file

I am trying to make a discord bot that saves some data to a text file. However, when I execute the command the line that creates a stream reader stops the command.
I have tried putting the stream reader in a separate function
I have tried executing the function before the command executes and getting the data through a string
public class Commands : ModuleBase<SocketCommandContext>
{
[Command("create")]
[Summary("Creates a new group")]
public async Task Create(IRole role)
{
//check for duplicates
StreamReader reader = new StreamReader(Path.Combine(Directory.GetCurrentDirectory(), "Data.txt"));
//Code will not go pass this line
Console.WriteLine(reader.ReadToEnd());
await ReplyAsync("Making " + role + " into a group");
}
}
I want to be able to read the file (that I will use to check for duplicates of the role) and continue with the command and have the bot say "Making role into a group" but when I execute the command, the bot doesn't say anything and the code stopped after trying to create a stream reader. However, the bot continues to run with no errors as it just stops the command from further executing.
First off, in the System.IO namespace, you can use helper methods to easily read the entire file and create a string with its contents, all in a single programming statement. This saves you the hassle of having to write out the entire streaming process, which I think would be beneficial for your purpose.
string rawTextFromFile = File.ReadAllText(pathToFileAsString);
If you want each line as a separate index in an array of strings, there is a function for that too:
string[] rawLinesFromFile = File.ReadAllLines(pathToFileAsString);
If my solutions are not helpful to you, or you have further issues with your bot, you can use a try-catch block and you might see the problem show up in your console log. Also, this will stop the bot from crashing, because it will handle the error and continue with whatever is next in its call stack.
try
{
(your code here)
}
catch(e)
{
Console.WriteLine(e.message);
}
I somehow managed to fix this problem by putting the saving feature in a different class file in an asynchronous function. I found that out after creating a new bot. Still have no idea what happened.

How to call a script with SignalR when item created to DB

I'm newbie with SignalR and want to learn so much. i already read beginner documents. But in this case i've stucked. what i want to do is when a user got new message i want to fire a script, like alert or showing div like "you have new mail" for notify the recieved user. And my question is how can i do that ? is there anyone know how to achieve this ? or good "step-by-step" document? i really want to work with SignalR.
ps: i'm using Visual Studio 2012 and MsSQL server
edit: i forgot to write, notification must be fired when message created to DB
Thank you
In your Scripts use the following, naturally this is not all the code, but enough based off tutorials to get you going. Your userId will be generated server side, and somehow your script can get it off an element of the page, or whatever method you want. It runs when the connection is started and then every 10 seconds. Pinging our server side method of CheckMessage() .
This js would need refactoring but should give you the general idea.
...
var messageHub = $.connection.messageHub;
var userId = 4;
$.connection.hub.start().done(function () {
StartCheck();
}
//Runs every 10 seconds..
function StartCheck()
{
setInterval(messageHub.server.checkMessage(userId,$.connection.hub.id), 10000);
}
This method takes in a userId, assuming your db is set up that way, and grabs them all from your database; naturally the method used is probably not appropriate for your system, however change it as you need to. It also checks if the user has any messages, and if so sends down another message to our SignalR scripts.
public void CheckMessage(int userId,int connectionId)
{
var user = userRepo.RetrieveAllUsers.FirstOrDefault(u=>u.id == userId);
if(user.HasMessages)
{
Clients.Group(connectionId).DisplayMailPopUp();
}
}
Finally this message, upon being called would run your code to do the 'You have Mail alert' - be it a popup, a div being faded in or whatever.
...
messageHub.client.displayMailPopUp = function () {
alert("You have Mail!");
};
...
Hopefully this helps - I recommend the following links for reading up and building your first SignalR app:
http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-getting-started-with-signalr-20-and-mvc-5
And a smaller sample: http://code.msdn.microsoft.com/SignalR-Getting-Started-b9d18aa9

Console window keeps closing, even after I type in other statements

I am new to programming and as seems to be traditional I tried to create a "hello world" program in C#; however, as soon as I run the program it closes.
This is my code inside:
main()
console.writeline("hello world");
console.writeline("enter name");
console.writeline("where is the frikin console");
It's really annoying and I know it might be something simple for the additional users but how do I keep the window open.
Use Console.ReadLine(); or Console.ReadKey(); at the end of your program to wait for the return key or for any key.
You can build your program and run the exe from the command line, that will allow you to see the output.
If you want the program to remain running then adding the Read() statement is the traditional approach, as others have already said.
If you just want to see it in debugging and do not want or need the read statement then place a breakpoint at the end of the program during a debug session.
It's really quite simple.
After this line of code:
Console.WriteLine("where is the frikin console");
You need to add this:
Console.ReadLine();
That should work.
The reason the console closes is because you told it to write some stuff to the screen, after it has finished writing what you told it to write it simply closes itself all in the fraction of a second. if you add Console.ReadLine, the console will wait for you to input something before closing, like pressing a key on the keyboard.
Try adding Console.Read(). You need to pause execution somehow.
Console.WriteLine("hello world");
Console.WriteLine("enter name");
Console.WriteLine("where is the frikin console");
Console.ReadLine();
Console.ReadLine(); will close the console after you've hit (for example) enter.
Console.ReadKey(); will close the console after the next key-hit
You can read the console-contents with these methods,too
Console.WriteLine("hello world");
Console.WriteLine("enter name");
string name = Console.ReadLine();
Console.WriteLine("Your name is: " + name);
Console.ReadLine();
add below line at the end
Console.ReadLine();
You could use CTRL + F5 which will opens the command line and after execution of your code, it shows Press any key to continue.... This will be handy for you than adding few lines of code additionally.
Use
Console.ReadLine();
in the end of your code. You are having this problem because the program just write the message then it ends, that's why you can't see anything. By adding that line, you keep the program waiting something to be typed and you can read the message. After this, type something to end the program.
The window automatically closes after your program, you need to let it take some input, for example:
Add
Console.ReadLine();
Which takes a line of input (till "\n"). And your program will wait until somebody hit the return key (they can type anything and the program won't close: until you hit the return key. You can type in "hello world back what's up are you ok?" and nothing will happen.)
or
Console.ReadKey();
Which will take a character of input. This will make your program wait for the user to press any key and then closes.

C# Sending Data over serial port between 2 PC using own Protocol

I have an assignment where I need to load some data like user (pouzivatel) and some int(stav odberu) through link modem with the serial port and store it in my local database. I know how to load data, send data over the serial port, but I need to make it happen in a structure on the image.
First I dial the telephone number of the device with AT command, btw this is working, but I do not know now how to stop and wait for SOH+adresa objektu (SOH+some string about address). Then send data about confirmation (ACK) and wait for new data to come.
The wait sequence is my biggest problem. How do I stop and wait for data being received.
Using the component and utilizing its DataReceived event as suggested in the comments would probably solve your problem easy and effectively. But you may have been looking for something more low-level to do it yourself.
If you want/need to do it in-line without any fancy event based system that would assume you are already in some message queue based environment like WinForms, you could do something like this.
while (true)
{
// check for new data
...
// if you got some, respond to it
...
if (someConditionThatTellsYouYouAreDoneOrSupposedToTerminate) break;
System.Threading.Thread.Sleep(50);
}

Clear Console Buffer

I'm writing a sample console application in VS2008. Now I have a Console.WriteLine() method which displays output on the screen and then there is Console.ReadKey() which waits for the user to end the application.
If I press Enter while the Console.WriteLine() method is displaying then the application exits.
How can I clear the input buffer before the Console.ReadKey() method so that no matter how many times the user presses the Enter button while the data is being displayed, the Console.ReadKey() method should stop the application from exiting?
Unfortunately, there is no built-in method in Console class. But you can do this:
while(Console.KeyAvailable)
Console.ReadKey(false); // skips previous input chars
Console.ReadKey(); // reads a char
Use Console.ReadKey(true) if you don't want to print skipped chars.
Microsoft References
Console.KeyAvailable
Console.ReadKey(bool)

Categories

Resources