I have created WinForms app, when I run it from console (cmd) the console is does not show anything I have logged using Console.WriteLine. It just "hangs" until the program has finished execution. In VS the Output shows a lot of informations, both in Debug and Release mode.
I was hopeing to use console and tracing tool and later be able to determine why something did not work on some outside environment. How to enable that in Console?
You may want to see if redirecting the console error output like this suggests will work for you. Or you could use Log4Net like #Mitch Wheat suggested
I was shocked but doing "MyApp.exe > a.log" has created a log file with information I wanted.
Related
It just came to attention that every time we run the c# console application, at the end it shows text stating "Press any key to continue... ".
And the moment you hit any key, it terminates the console/program.
In actual program there is no mentioning about such text printing on standard output console, then from where and why it comes out on screen?
Can someone explain the logic behind?
Code:
static void Main(string[] args)
{
Console.WriteLine("Test Application");
}
Output:
Test Application
Press any key to continue . . .
It has nothing to do with your application itself. When you double-click on the output EXE file you'll not see it. It is only when we run the app from within Visual Studio without the debugger attached when this behavior is seen.
When you press Ctrl+F5, Visual Studio is running your app in a way that causes the console window to remain open.
I think it comes from cmd parameters that are used. Something like :
%COMSPEC% /k "C:\VS\MyApplication.exe"
Do you use CodeBlocks ?
If yes, it is a Feature of CodeBlocks. That you can read the Output without to write something like getChar() at the end that the console stay open. Otherwise it would close instantly and you can't read the output.
In normal application the console will close when done and that is the expected behaviour. This prompt simply helps you to check the results of your code when you are writing your application and you do not have to put (and remember about later removal) of the:
Console.ReadLine();
in your application just to test it and see what the output is.
I have just got the wierdest problem in my Windows Froms C# application
I got a few Console.WriteLine in my code for debug, but suddenly this stopped working. For example
try{
line(of.code);
Console.WriteLine("HERE");
other.line(of.code);
}
catch (Exception e)
{
logger.logg(e.ToString());
}
I will not get to the other.line(of.code); line, and I do not get the "HERE" in the console.
There is a few places in the code, the same happens on all of them. It just stops, it does NOT get to the catch...
And the worst part, it worked earlier. I have worked on applications for a long time, and have never seen anything like it.
If you need it just for debugging, try
System.Diagnostics.Debug.WriteLine("HERE");
instead.
This will write the output into the output window of your development environment and, more important, it will work regardless of the type of application you are developing (console app, win forms, web app etc).
As soon as you change to "release", the debug information will be ignored and not compiled into the code. If you would require it there, too, you should try Trace.Writeline instead.
I can think of a few scenarios that will cause Console.WriteLine to fail:
The output stream has been set to an invalid object or something that will misbehave (in your case stop the program).
You are running in an environment that doesn't give you permission to use the console*.
It is not System.Console.WriteLine but another method with the same name that gets invoked thanks to some using directives.
*: I can't think of such environment, but may be some plug-in system?
If you are making a Windows Froms Application and not setting the output stream for your Console then Console.WriteLine should do nothing. So, if you need debugging follow Matt's recomendation.
I have a test project in Visual Studio. I use Microsoft.VisualStudio.TestTools.UnitTesting.
I add this line in one of my unit tests:
Console.WriteLine("Some foo was very angry with boo");
Console.ReadLine();
When I run the test, the test passes, but the console window is not opened at all.
Is there a way to make the console window available to be interacted via a unit test?
Someone commented about this apparently new functionality in Visual Studio 2013. I wasn't sure what he meant at first, but now that I do, I think it deserves its own answer.
We can use Console.WriteLine normally and the output is displayed, just not in the Output window, but in a new window after we click "Output" in the test details.
NOTE: The original answer below should work for any version of Visual Studio up through Visual Studio 2012. Visual Studio 2013 does not appear to have a Test Results window any more. Instead, if you need test-specific output you can use #Stretch's suggestion of Trace.Write() to write output to the Output window.
The Console.Write method does not write to the "console" -- it writes to whatever is hooked up to the standard output handle for the running process. Similarly, Console.Read reads input from whatever is hooked up to the standard input.
When you run a unit test through Visual Studio 2010, standard output is redirected by the test harness and stored as part of the test output. You can see this by right-clicking the Test Results window and adding the column named "Output (StdOut)" to the display. This will show anything that was written to standard output.
You could manually open a console window, using P/Invoke as sinni800 says. From reading the AllocConsole documentation, it appears that the function will reset stdin and stdout handles to point to the new console window. (I'm not 100% sure about that; it seems kind of wrong to me if I've already redirected stdout for Windows to steal it from me, but I haven't tried.)
In general, though, I think it's a bad idea; if all you want to use the console for is to dump more information about your unit test, the output is there for you. Keep using Console.WriteLine the way you are, and check the output results in the Test Results window when it's done.
You could use this line to write to Output Window of the Visual Studio:
System.Diagnostics.Debug.WriteLine("Matrix has you...");
Must run in Debug mode.
As stated, unit tests are designed to run without interaction.
However, you can debug unit tests, just like any other code. The easiest way is to use the Debug button in the Test Results tab.
Being able to debug means being able to use breakpoints. Being able to use breakpoints, then, means being able to use Tracepoints, which I find extremely useful in every day debugging.
Essentially, Tracepoints allow you to write to the Output window (or, more accurately, to standard output). Optionally, you can continue to run, or you can stop like a regular breakpoint. This gives you the "functionality" you are asking for, without the need to rebuild your code, or fill it up with debug information.
Simply add a breakpoint, and then right-click on that breakpoint. Select the "When Hit..." option:
Which brings up the dialog:
A few things to note:
Notice that the breakpoint is now shown as a diamond, instead of a sphere, indicating a trace point
You can output the value of a variable by enclosing it like {this}.
Uncheck the "Continue Execution" checkbox to have the code break on this line, like any regular breakpoint
You have the option of running a macro. Please be careful - you may cause harmful side effects.
See the documentation for more details.
There are several ways to write output from a Visual Studio unit test in C#:
Console.Write - The Visual Studio test harness will capture this and show it when you select the test in the Test Explorer and click the Output link. Does not show up in the Visual Studio Output Window when either running or debugging a unit test (arguably this is a bug).
Debug.Write - The Visual Studio test harness will capture this and show it in the test output. Does appear in the Visual Studio Output Window when debugging a unit test, unless Visual Studio Debugging options are configured to redirect Output to the Immediate Window. Nothing will appear in the Output (or Immediate) Window if you simply run the test without debugging. By default only available in a Debug build (that is, when DEBUG constant is defined).
Trace.Write - The Visual Studio test harness will capture this and show it in the test output. Does appear in the Visual Studio Output (or Immediate) Window when debugging a unit test (but not when simply running the test without debugging). By default available in both Debug and Release builds (that is, when TRACE constant is defined).
Confirmed in Visual Studio 2013 Professional.
You can use
Trace.WriteLine()
to write to the Output window when debugging a unit test.
In Visual Studio 2017, "TestContext" doesn't show the Output link into Test Explorer.
However, Trace.Writeline() shows the Output link.
First of all unit tests are, by design, supposed to run completely without interaction.
With that aside, I don't think there's a possibility that was thought of.
You could try hacking with the AllocConsole P/Invoke which will open a console even when your current application is a GUI application. The Console class will then post to the now opened console.
Debug.WriteLine() can be used as well.
IMHO, output messages are relevant only for failed test cases in most cases. I made up the below format, and you can make your own too. This is displayed in the Visual Studio Test Explorer Window itself.
How can we throw this message in the Visual Studio Test Explorer Window?
Sample code like this should work:
if(test_condition_fails)
Assert.Fail(#"Test Type: Positive/Negative.
Mock Properties: someclass.propertyOne: True
someclass.propertyTwo: True
Test Properties: someclass.testPropertyOne: True
someclass.testPropertyOne: False
Reason for Failure: The Mail was not sent on Success Task completion.");
You can have a separate class dedicated to this for you.
I have an easier solution (that I used myself recently, for a host of lazy reasons). Add this method to the class you are working in:
public static void DumbDebug(string message)
{
File.WriteAllText(#"C:\AdHocConsole\" + message + ".txt", "this is really dumb. I wish Microsoft had more obvious solutions to its solutions problems.");
}
Then...open up the directory AdHocConsole, and order by created time. Make sure when you add your 'print statements'. They are distinct though, else there will be juggling.
Visual Studio For Mac
None of the other solutions worked on Visual Studio for Mac
If you are using NUnit, you can add a small .NET Console Project to your solution, and then reference the project you wish to test in the References of that new Console Project.
Whatever you were doing in your [Test()] methods can be done in the Main of the console application in this fashion:
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Console");
// Reproduce the unit test
var classToTest = new ClassToTest();
var expected = 42;
var actual = classToTest.MeaningOfLife();
Console.WriteLine($"Pass: {expected.Equals(actual)}, expected={expected}, actual={actual}");
}
}
You are free to use Console.Write and Console.WriteLine in your code under these circumstances.
I've already wrote an application that works user base. I was looking for the best way to use for current user logging-out. So I've used Application.Restart();
Soon I found that the code doesn't work properly and Program.Main() doesn't call back again.
I wondered that my Login form Load Method is not going to perform (The Login Form is calling from program class).
So I'll really thankful if you let me know about my bugs and correct solutions.
http://msdn.microsoft.com/en-us/library/system.windows.forms.application.restart.aspx
Comment listed "Bug in VS2010 SP1"
after calling this method, the application no longer run in debug mode, it's not spawned by the IDE and all breakpoints stop functioning.
EDIT:
This is where something like log4net can really be helpful. It's a very simple library to add to your project and would let you write out debug information to a file so, even though the next instance wasn't spawned by the IDE and wont get breakpoints, you could still do some verification that it's hitting what you expect through the use of Debug traces. Just a suggestion...
A new process gets created, and it's not spawned by the IDE.
A breakpoint is not a valid way to test if Main is entered again.
See somewhat related post:
Does Application.Restart() creates new process for application or no?
If you'd like, you could write to a file or some other simple test in Main just to prove to yourself that it is entered.
Microsoft recently released a solution that allows debugging to continue after Application.Restart(), in the form of a Power Tool:
Child Process Debugging Power Tool
Blog Post
Download in VS Gallery
I am currently creating a customer application for a local company. I have a datagridview linked to the customers table, and I am trying to link it up so that updates, inserts and deletions are handled correctly. I am very new to c# so I am starting with the basics (like about 2 days ago I knew nothing - I know vb.net, Java and several other languages though..).
Anywho from what I understand anything output through Debug.WriteLine should only appear when in debug mode (common sense really) but anything output through Concole.WriteLine should appear whether or not in debug mode. However I have checked the immediate and output windows and nothing is being output when in normal mode. Does anyone have any idea why this is??
Edit: I have event handlers for clicking a cell - it should output CellClicked and set the gridview to invisible when a cell is clicked. The latter works whichever mode I am in, but CellClicked is only output in debug mode. I am using Console.WriteLine("CellClicked").
Edit: Seems I may have solved it - I just set the output to Console Application in the project settings pages. It now opens a command line window as well as a windows form, but I can change the output back again when I compile for distribution. Thanks for the help.
Console.WriteLine() outputs to the console window in the case of a console app only.
You are probably looking for Trace.WriteLine().
Getting the output of Console.Write/Line() written to the Visual Studio Output window is a feature of the Visual Studio Hosting process. Project + Properties, Debug tab. This will not work if you run your app without a debugger, the hosting process isn't being used.
Using Console.WriteLine for debugging isn't the greatest solution. That code will still run in your Release build and take time formatting the output string. And prevent the JIT optimizer from doing a good job generating the most efficient machine code. Output will fall in the bit bucket, nothing to actually write it to.
And it is unnecessary, the debugger gives you much better tools to find out what is going on in your program. Take some time to familiarize yourself with its capabilities. If you want to find out if an event handler runs, just set a breakpoint. Such a breakpoint can even trace output without actually breaking. Right-click the red dot, click "When hit" and use the "Print message" option.
I think you'll like the tracing infrastructure a lot better than Console.WriteLine. Tracing gives you many different options for where the trace messages can go, as well as being able to turn them on or off. You can also set different levels of tracing output so that you can adjust how much logging actually gets done. The built in tracing in .NET is very flexible, and is well worth the investment to learn.
Here are a couple of references to help you get started:
http://msdn.microsoft.com/en-us/library/ms228993.aspx
http://msdn.microsoft.com/en-us/library/ms228984.aspx
http://www.code-magazine.com/Article.aspx?quickid=0409081
HTH!
Chris
You could go to Tools | Options | Look for Debugging, General, Choose the Redirect all Output Window text to the immediate window, or try to log the console-intended output to a file and view it there instead.