I'm trying to run a simple Hello World code in VSC 1.13.1.
using System;
public class Hello1
{
public static void Main()
{
Console.WriteLine("Hello, World!");
}
}
It successfully completes execution but doesnt produce any output ie - Hello, World!
Any help please!
Using Code Runner.
Add Console.ReadKey() , so the output will be there until the key is pressed
public static void Main()
{
Console.WriteLine("Hello, World!");
Console.ReadKey();
}
There currently seems to be a problem with VSCode (or the C# extension). Other StackOverflow answers show that this didn't work a few years ago, then it started working, and now (2018) it doesn't work once again.
I'm having the same problem. The workaround I found is this: If I run my code in the debugger (Debug > Start Debugging), it shows the output. But if I just run it normally, it doesn't. That's the only workaround I've found or read about that works for me.
Another option is to start the project with ctrl + F5 instead of just F5, it will keep the terminal open until you press a key as well
How to keep the console window open in Visual C++?
It have come to my attention that Using Code Runner, at this time, indeed produces some inconsistent behavior for JS as well.
However, on a first look you have not installed the proper supporting addons (which may be the cause for your particular problem):
Code Runner requires : "To run C# script, you need to install scriptcs"
Which is said to use Chocolatey - package manager for Windows.
For the moment, disabling the extension, restarting VSCode and then enabling it - fixed the current common problem for JS (not always producing an output). Which may be preceding with C#, as well.
NB! Make sure you save your files manually before you run them using Code Run
I will test this today and add the results.
Test Results: After installing scriptcs and Chocolatey your HelloWorld.cs file can run, BUT will not produce result.The reason: the code is treated as a script. Meaning that there is nothing invoking the Main() method. Meaning, you have to do it. Example:
using System;
public class Hello
{
public static void Main()
{
var message = "hiiii inside => Works" ;
Console.WriteLine(message);
HW();
}
public static void HW(){
Console.WriteLine("Hello, World!");
// the ReadLine will not work because it is only one way solution : ouptut only
// var a = Console.ReadLine();
// Console.WriteLine("key pressed: " + a + "Doesn't work");
}
}
Hello.Main();
//can be used like this as well
var message= "Hey helloooo outside WORKS";
Console.WriteLine(message);
Use Ctrl+Alt+N to start and Ctrl+Alt+M to stop(if hung). And it will hung, if you use Console.ReadLine(); - check(uncomment) the example code in the HW() method.
P.S. Namespaces can't be used in scripts - will be the error message you get, if you try to use them with Code Runner
Well, Code Runner is a tool to run C# script. It will treat the main method as a normal method and will not call it.
You should just write the Main method:
System.Console.WriteLine("hello, world");
or
static class Test
{
public static void Main()
{
System.Console.WriteLine("hello, world");
}
}
Test.Main();
Related
Context:
We have some users reporting issues with a file upload feature in our web application. It only happens occasionally and without any special pattern. We have been trying to figure it out for a long time, adding debug information anywhere we can think it might help, crawling the logs etc, but we have not been able to reproduce or figure it out.
Problem:
I'm now trying to reproduce this by using MSTest and WatiN to repeat the operation that is supposed to fail a large number of times (several hundreds). Just to have a clue about how far in the loop the test has gotten, I want to print something like:
Console.WriteLine(String.Format("Uploaded file, attempt {0} of {1}", i, maxUploads));
This does however not appear in the Output window. Now I know that you'll get the console output in the test results (as well as what you output from Debug.Writeline etc), but this is not available until after the test has finished. And since my test with hundreds of repetitions could take quite some time, I'd like to know how far it has gotten.
Question:
Is there a way I can get the console output in the Output window during test execution?
The Console output is not appearing is because the backend code is not running in the context of the test.
You're probably better off using Trace.WriteLine (In System.Diagnostics) and then adding a trace listener which writes to a file.
This topic from MSDN shows a way of doing this.
According to Marty Neal's and Dave Anderson's comments:
using System;
using System.Diagnostics;
...
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
// or Trace.Listeners.Add(new ConsoleTraceListener());
Trace.WriteLine("Hello World");
Use the Debug.WriteLine. This will display your message in the Output window immediately. The only restriction is that you must run your test in Debug mode.
[TestMethod]
public void TestMethod1()
{
Debug.WriteLine("Time {0}", DateTime.Now);
System.Threading.Thread.Sleep(30000);
Debug.WriteLine("Time {0}", DateTime.Now);
}
Output
I found a solution of my own. I know that Andras answer is probably the most consistent with MSTEST, but I didn't feel like refactoring my code.
[TestMethod]
public void OneIsOne()
{
using (ConsoleRedirector cr = new ConsoleRedirector())
{
Assert.IsFalse(cr.ToString().Contains("New text"));
/* call some method that writes "New text" to stdout */
Assert.IsTrue(cr.ToString().Contains("New text"));
}
}
The disposable ConsoleRedirector is defined as:
internal class ConsoleRedirector : IDisposable
{
private StringWriter _consoleOutput = new StringWriter();
private TextWriter _originalConsoleOutput;
public ConsoleRedirector()
{
this._originalConsoleOutput = Console.Out;
Console.SetOut(_consoleOutput);
}
public void Dispose()
{
Console.SetOut(_originalConsoleOutput);
Console.Write(this.ToString());
this._consoleOutput.Dispose();
}
public override string ToString()
{
return this._consoleOutput.ToString();
}
}
I had the same issue and I was "Running" the tests. If I instead "Debug" the tests the Debug output shows just fine like all others Trace and Console.
I don't know though how to see the output if you "Run" the tests.
It's not the console, but it is in the output panel.
public class Test
{
public TestContext TestContext { get; set; }
[TestMethod]
public void Foo()
{
TestContext.WriteLine("Hello World");
}
}
You better setup a single test and create a performance test from this test. This way you can monitor the progress using the default tool set.
I am writing a C# application which is running on Linux with Mono, and I want to hide the console cursor. But since this Console.CursorVisible = false seems to do nothing at all, is there another way of doing this, e.g. a console command or a native function?
This is highly dependent upon the terminal/shell type you are using, but on OS-X iTerm or Terminal bash here is how I do it:
public static void Main(string[] args)
{
Process.Start("tput", "civis -- invisible");
Console.WriteLine("Hello World!");
Console.Read(); // no cursor
Process.Start("tput", "cnorm -- normal");
Console.Read(); // with cursor
}
This should work fine on Linux/bash and possibly others as it is using the terminfo database, if it does not, I would check your terminfo database for the missing elements.
I am trying to update a C# application published by VS2010 on IIS7.5.
I need to uninstall it and then install a new one.
If I ran the code in debug mode, it worked well.
But, if I ran it in release without debug mode. I got error of
Another version of the product is already installed. Installation of this version cannot continue. To configure or remove the existing version of this product, use Add/remove programs on the control panel.
I found the reason is that "install" started when "uninstall" is still not finished. How to make sure that the "uninstall" is finished before "install" started ? I used WaitForExit() (https://msdn.microsoft.com/en-us/library/ty0d8k56.aspx) but, after uninstall, the "install" was not executed.
The code is here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace msiexec_uninstall_install
{
class Program
{
static void Main(string[] args)
{
var p = System.Diagnostics.Process.Start("msiexec", "/uninstall http://MyServer/MyApp.msi");
p.WaitForExit();
Console.WriteLine("after uninstall");
System.Diagnostics.Process.Start("msiexec", "/i http://myServer/MyApp_new.msi");
Console.WriteLine("after install");
Console.ReadLine();
}
}
}
If your installation takes longer than it takes to finish your Main program, you won't see it.
Try adding WaitForExit(); for your installation as well.
static void Main(string[] args)
{
var uninstallProcess = System.Diagnostics.Process.Start("msiexec", "/uninstall http://MyServer/MyApp.msi");
uninstallProcess.WaitForExit();
Console.WriteLine("after uninstall");
var installProcess = System.Diagnostics.Process.Start("msiexec", "/i http://myServer/MyApp_new.msi");
installProcess.WaitForExit();
Console.WriteLine("after install");
Console.ReadLine();
}
That way your Main method will only end after installation is complete. To be on the safe side, you can even add some timeout for WaitForExit():
installProcess.WaitForExit(10000); //10 sec
Context:
We have some users reporting issues with a file upload feature in our web application. It only happens occasionally and without any special pattern. We have been trying to figure it out for a long time, adding debug information anywhere we can think it might help, crawling the logs etc, but we have not been able to reproduce or figure it out.
Problem:
I'm now trying to reproduce this by using MSTest and WatiN to repeat the operation that is supposed to fail a large number of times (several hundreds). Just to have a clue about how far in the loop the test has gotten, I want to print something like:
Console.WriteLine(String.Format("Uploaded file, attempt {0} of {1}", i, maxUploads));
This does however not appear in the Output window. Now I know that you'll get the console output in the test results (as well as what you output from Debug.Writeline etc), but this is not available until after the test has finished. And since my test with hundreds of repetitions could take quite some time, I'd like to know how far it has gotten.
Question:
Is there a way I can get the console output in the Output window during test execution?
The Console output is not appearing is because the backend code is not running in the context of the test.
You're probably better off using Trace.WriteLine (In System.Diagnostics) and then adding a trace listener which writes to a file.
This topic from MSDN shows a way of doing this.
According to Marty Neal's and Dave Anderson's comments:
using System;
using System.Diagnostics;
...
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
// or Trace.Listeners.Add(new ConsoleTraceListener());
Trace.WriteLine("Hello World");
Use the Debug.WriteLine. This will display your message in the Output window immediately. The only restriction is that you must run your test in Debug mode.
[TestMethod]
public void TestMethod1()
{
Debug.WriteLine("Time {0}", DateTime.Now);
System.Threading.Thread.Sleep(30000);
Debug.WriteLine("Time {0}", DateTime.Now);
}
Output
I found a solution of my own. I know that Andras answer is probably the most consistent with MSTEST, but I didn't feel like refactoring my code.
[TestMethod]
public void OneIsOne()
{
using (ConsoleRedirector cr = new ConsoleRedirector())
{
Assert.IsFalse(cr.ToString().Contains("New text"));
/* call some method that writes "New text" to stdout */
Assert.IsTrue(cr.ToString().Contains("New text"));
}
}
The disposable ConsoleRedirector is defined as:
internal class ConsoleRedirector : IDisposable
{
private StringWriter _consoleOutput = new StringWriter();
private TextWriter _originalConsoleOutput;
public ConsoleRedirector()
{
this._originalConsoleOutput = Console.Out;
Console.SetOut(_consoleOutput);
}
public void Dispose()
{
Console.SetOut(_originalConsoleOutput);
Console.Write(this.ToString());
this._consoleOutput.Dispose();
}
public override string ToString()
{
return this._consoleOutput.ToString();
}
}
I had the same issue and I was "Running" the tests. If I instead "Debug" the tests the Debug output shows just fine like all others Trace and Console.
I don't know though how to see the output if you "Run" the tests.
It's not the console, but it is in the output panel.
public class Test
{
public TestContext TestContext { get; set; }
[TestMethod]
public void Foo()
{
TestContext.WriteLine("Hello World");
}
}
You better setup a single test and create a performance test from this test. This way you can monitor the progress using the default tool set.
Isn't there a better looking statement (or way) to keep the console from disappearing than the hackish Console.ReadLine() call. Something that's more expressive of the purpose of, more orthogonal to, keeping the Console visible ?
If you are still developing application you can run via Ctrl + F5 (Without debugging)
otherwise you can use Console.ReadKey() (same but there is no more option)
You can do:
Console.ReadKey();
Console.ReadLine() is not really hackish, your pausing the screen to wait for input. The input can either be a single key, or a string.
Update
One nice thing about the ReadKey() method is that it "waits, that is, blocks on the thread issuing the ReadKey method, until a character or function key is pressed." MSDN
This is different than ReadLine which takes in a string. Arguably, cleaner.
It depends on the context. If you're talking about running a command line, debugging through your code, and then being able to view the results on the console you have two options:
If you run with the debugger attached (f5), you must use Console.ReadLine
If you run without the debugger attached (ctrl + f5), it will stay open ... but then you obviously can't debug through.
I'm not sure why that's the default behavior, but there it is :-)
I usually use one of these:
Console.ReadKey(true); //You might want to put this in an infinite loop
new AutoResetEvent(false).WaitOne();
In VS You can also run (Ctrl + F5) the program (in distinction to running in debug) and it will add a system pause after it finishes executing.
I'd say that WaitOne, and just running (& not debugging) the program are your non-hackish options.
If you do want to debug, perhaps set a breakpoint at the last }.
Depends on what I am doing. If I am doing multi-threaded work and want my Console application to remain alive until all other work is done, I usually do something like this. (Similar to MasterMastic)
using System;
using System.Threading;
namespace Test_Console
{
class Program
{
static EventWaitHandle EWHandle;
static void Main(string[] args)
{
EWHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
Thread WorkThread = new Thread(new ThreadStart(DoStuff));
EWHandle.WaitOne();
}
static void DoStuff()
{
Console.WriteLine("Do what you want here");
EWHandle.Set();
}
}
}
Of course, there's always just using the regular breakpoints and the other debugging tools if that's what you're going for.