How to debug a C# command-line program - c#

I'm trying to build a command-line tool in C# with VS2010.
My question is: how do I debug this, like I would a winforms.
With winforms, I can step through the code, see the values at each individual step, etc...
Here however, the program only responds when I talk to it from the command line. I can't start a debug session, since that will first fully start the program. And due to the nature of the program, it will shut itself because there were no command-line arguments.
So no debugging can occur.
What do I need to do here?
EDIT: an example, since someone made a comment that makes me feel this explanation is needed.
C:\Path\To\File\file.exe -help
That is an example of how this program is adressed. The command, -help, is given in the same line that the program is started. In other words, I cannot first start the program, and then give it a command while it's running... because it won't be running anymore. It'll start, see that it had no arguments on startup, and because of that, shut down. That's how a command-line tool works.
Activate
Process possible arguments
Output results
Shut down automatically
It is not something that keeps running till you click the little x in the top right corner.

In the Project properties, under Debug, you can enter any Command Line Arguments you would like, and then run the app with F5, the debugger will be attached automatically.

You could add a call to Debugger.Launch to your startup code. Then you can compile, and start your app from the command line. You'll get a prompt asking you which debugger you want to attach (typically this will be a list of the different versions of Visual Studio you have installed), and away you go.
(But really, setting command-line parameters in Project properties > Debug tab is the better way to go most of the time. If that's not working for you, you should figure out why.)

You can use Visual Studio to attach a debugger to the command line application, once it is under way with the correct arguments. I'm not sure if your application will terminate quickly or give you any opportunity to attach the debugger, but if it will, this should work.
I'm using VS2008 but I'll bet the process is similar in 2010:
In VS, go to Tools and click Attach to Process
Choose your application from the list and press Attach
Now VS should be able to finagle its way into your application and break on an error.

You just need to add a breakpoint to the first line of the main function (you can do this by clicking on the line in the Visual Studio editor and hitting F9) and hit F5 to start a debug session.

Either add a breakpoint to the opening { of Main, or step into the program (Debug menu). At that point set a watch on the parameter for main (the command line arguments) by selecting it and either right-click/Add Watch or drag the parameter to to watch window if it is already open. Double-click the Value column in the Watch window and set it to whatever you want it to be.
Note: the value added must be valid code -- that is, to add a -help to the string[] you would have to type new string[] {"-help"} or new [] {"-help"} depending on the version you are using.
This has the advantage over setting the parameter in the Debug tab of the Properties window by allowing different parameters for each run without having to return to the Properties window.

When you have command line arguments then you need to follow different route to debug. Go to project and then select properties. There you will see debug section and then give required parameters. So that it will take care of passing parameters to the program. If you have multiple parameters then separate them with space. After that if you debug it will hit the break point directly. For more info check here how to debug c# through command line arguments in visual studio

Related

Visual Studio debugger - run until next user prompt

I'm in a Visual Studio debugging session, debugging a WinForms app, but I think this question applies to an ASP.Net code-behind debug session also. Let's say that I have lots of breakpoints set and I want to test a condition that requires running a setup test case first, then I want to run another test case that exercises the code again. The first time, I have to hit the Continue (F9) button 5 times to progress through the code breakpoints and finally arrive at the point where I'm prompted for input again. Now I want to input some data and I now want to carefully step through all the breakpoints.
Is there some way I can quickly push a button and tell the debugger to skip all those breakpoints during the setup test case entry and just progress to the next data input field? I know about the run to cursor capablilty, but that doesn't seem any easier than clicking thru all of the breakpoints.
I know this may sound trivial, but I find myself in this situation all the time.
I just want a super-continue button.
You can open the Breakpoints window (Debug -> Windows -> Breakpoints) and then you can select multiple breakpoints and disable or enable them as you go:
The best thing i can think of would be to create a condition on the breakpoint to only break when the data is set up.
E.g.
Or if all else fails, set a BreakPoint Hit Count, if you know it'll always be the 6th break that is relevant. E.g.

Can I write into the console in a unit test? If yes, why doesn't the console window open?

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.

Visual Studio attach to process and view the code on break?

I must not have some configuration property set correctly...
Basically when I run the app as a service via srvany.exe, it starts, but a class doesn't get instantiated correctly. I've put in a 60 second delay to allow me to attach to the process, but I can't get that exe to break when it hits the break I set in the debugger (I guess that doesn't get compiled in?), and all I can view is the disassembler. Is it possible to do more?
Sounds like VS may be assuming that SrvAny is stricly native code. When you attach to it, make sure that the "Attach to" box contains "Managed code" as a selection. Also, watch the debugger attaching to the process in the output window and make sure that it says "Symbols loaded" when your assemblies are loaded (indicating that the PDB file was found successfully)
Instead of inserting delays and rushing to attach to the process in time, you can call
System.Diagnostics.Debugger.Break();
to break execution and attach the debugger programmatically.

Debugging C# WinForm apps

I am working in Microsoft Visual C# 2008 on a Windows Form application.
I would like to write some variables out to a window in the IDE to determine what values they contain. I thought perhaps I could write to the console using console.writeline however I did not see where I could open a console window.
Is there a command I should be using to write to the immediate window or some other place where the information can easily be seen in the IDE?
Use Debug.WriteLine(). It's output goes to the Output window. Console.WriteLine() works the same way in a Winforms app but using Debug is better since that code automatically gets removed in the Release build.
And of course, you'll want to leverage the debugger first.
You can use Trace also, which has more features:
http://msdn.microsoft.com/en-us/library/4y5y10s7.aspx
Trace.WriteLine("Error ")
If you just want to see what the current value of a variable is, put a breakpoint in your code somewhere where this variable is referenced (a breakpoint is a red dot that will appear if you click on the left side of your code window).
Then just run the program, and when your breakpoint is hit the execution will suspend right on the breakpoint. Just hold your mouse over the variable and the popup will show you what the value is.
You can use the Spywindows in debug mode.
Console.WriteLine() writes to the standard output stream. while Debug.WriteLine() writes to all trace listeners in the Listeners collection, it is possible that this could be output in more than one place (VS output window, Console, Log file)
1) Use Debug.WriteLine to output to the debug window in DEBUG builds.
2) Use Console.WriteLine when you need to output to a console (unless it's a console application it also outputs to the debug window)
3) Use Trace.WriteLine to output to the output window in all builds. It's output can also be seen when running Mark Russinovich's (formerly SysInternals) Dgbview, which allows you to look at trace statements in a running process (without any debugger attached).
4) Use a trace-point: put a break-point on the line of interest, right-click the red bullet indicating the break-point, choose "When hit..", check "Print A message" and in the window type something like "The value of x is {x}" where x is your variable. The expression in the curly braces will be evaluated for output. This can be useful when you don't want to edit your code.

Displaying console output?

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.

Categories