When I build a Windows Forms project in VS2010 in debug mode (F5) a window appears titled Output Window. There are buttons along the top of the Output Window: "Find Message in Code", "Next Message", and "Previous Message". However, they are always grayed-out (disabled). How do these become enabled?
I'm expecting the intent of these buttons is to help me find lines of code that caused a message to appear in the Output Window. For example, if I write Trace.WriteLine("MyMessage"); in client code, when executed it will make 'MyMessage' appear in the Output Window; I thought by selecting a message in the Output Window and clicking "Find message in Code" it would navigate to the line of the client code that contains "MyMessage". This would be a slick feature if it were enabled and my presumptions were correct. Unfortunately I can't get the buttons to enable.
To answer this question please explain how to enable and use these buttons and if any best practices should be applied (optional).
Here is some source code to use as reference. Create a Windows Forms project and make the changes you see below and you can reproduce what I am attempting.
// program.cs
using System;
using System.Diagnostics;
using System.Windows.Forms;
namespace MyNamespace
{
internal static class Program
{
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
throw new ApplicationException("MyMessage");
Application.Run(new FormMain());
}
catch (ApplicationException e)
{
Trace.WriteLine(e.ToString());
}
}
}
}
JasonD's recommendation
I replaced
Trace.WriteLine(e.ToString());
with
Trace.WriteLine("Program.cs" + "(" + 23 + ")" + " Some info");
End JasonD solution - result: buttons enabled
That solved it. And what an unexpected answer. In this era of strongly typed everything the answer depends on formatting strings with magic messages. I'm surprised by this.
You need to output something it can parse, which is essentially the same format as error/warning messages you see when compiling, consisting of "FILENAME(LINE) stuff".
In C#, something like this:
string file_= new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileName();
int line_= new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber();
System.Diagnostics.Trace.WriteLine(file_+ "(" + line_.ToString() + ") Some info");
(this is a little messy, but there's no good equivalent of C/C++'s __FILE__ and __LINE__ macros that I've found)
You can tidy that up a bit and wrap it in a function, but you need to get the file/line of the caller, not the actual function itself:
static void traceFunc(string msg)
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(true);
string file = trace.GetFrame(1).GetFileName();
int line = trace.GetFrame(1).GetFileLineNumber();
System.Diagnostics.Trace.WriteLine(file + "(" + line.ToString() + ") " + msg);
}
Related
Alright so I'm pretty new to programming in C#, and programming in general, and I decided to learn the programming language so I'm watching a youtube tutorial and writing everything in the same way as the guy in the video.
The only issue is that when I debug, I'm missing a few lines in the debug window.
I wrote 4 Console.WriteLine commands yet it only shows 2 of them in the debug window.
Example (current and expected):
https://gyazo.com/d363af46a05b804b65a927e9b075b6e4 (What I get when I debug)
https://gyazo.com/3fd4eed9d68983304b5098c9f07f809a (What I should be getting)
This might be a very popular issue that has been solved many times, but I haven't been able to find it since I don't know what to type specifically to find the solution to my problem.
I hope someone can help me. And again, the reason why the title of the question isn't specific is because I don't really know what I'm talking about so I'm relying on the images being enough.
The Code (has been moved from a comment of the author)
using System;
namespace Basics {
class Program {
static void Main(string[] args) {
string characterName = ("John");
int characterAge;
characterAge = 35;
Console.WriteLine("There one was a man named " + characterName);
Console.WriteLine("He was " + characterAge + " years old.");
Console.WriteLine("He really liked the name " + characterName);
Console.WriteLine("But didn't like being " + characterAge);
Console.ReadLine();
}
}
}
I have ran your code and it compiles fine. All four lines print.
You can try going to the solution explorer panel on the right -> right click your solution, -> Clean -> Rebuild. Then re-compile
Long time i work whit console..
But it pretty much working c# 8.0
namespace Basics
{
static class Program
{
static void Main() => ("John", 35).Story();
static void Story(this (string CharacterName, int CharacterAge) Infomation) {
Console.WriteLine("There one was a man named {0}", Infomation.CharacterName);
Console.WriteLine("He was {0} years old.",Infomation.CharacterAge);
Console.WriteLine("He really liked the name {0}", Infomation.CharacterName);
Console.WriteLine("But didn't like being {0}", Infomation.CharacterAge);
}
}
}
I have a C# ASP.net website. Locally I can run it in debug and step through the code to see why things arent working but when its hosted on my live site I cannot do this.
What is the best way to debug what is going on with my website?
Should I add debut/output/trace statements?
If so, which and how do I view the output of these? Can I view them in Chrome-->Developer Tools somehow?
For example, right now I can register a user on my site so I know the database connection is good, but I cannot login a registered user and want to figure out why.
Thanks
You may add trace and debug logs on your app. For ease, you may use logging frameworks like
http://nlog-project.org/
https://serilog.net/
You can actually write your own logging mechanism in which you can create a log class and some functions in it eg
public class Log
{
internal static bool RecordLog(string strSource, string strMethodName, string strStatement)//additional params you think appropriate for your logs
{
List<string> lstInfo = new List<string>();
string strProductName = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location.ToString()).ProductName.ToString();
string strProductVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location.ToString()).ProductVersion.ToString();
try
{
strProductName = FileVersionInfo.GetVersionInfo(Assembly.GetCallingAssembly().Location.ToString()).ProductName.ToString();
strProductVersion = FileVersionInfo.GetVersionInfo(Assembly.GetCallingAssembly().Location.ToString()).ProductVersion.ToString();
}
catch
{
}
try
{
lstInfo.Add("** Date=" + DateTime.Now.ToString("d MMM yy, H:mm:ss") + ", " + strProductName + " v" + strProductVersion);
lstInfo.Add("Source=" + strSource + ", Server=" + strServerIP + ""); //add more info in list as per rquirement
bool flag = blnWriteLog("LogFilename", lstInfo);
}
catch (Exception objEx)
{
//exception handling
}
return true;
}
private static bool blnWriteLog(string strProductName, List<string> lstInfo)
{
string strPath = strGetLogFileName(strProductName);
using StreamReader write in the log file received
return true;
}
private static string strGetLogFileName(string strFilePrefix)
{
//logic to check your file name, if it exists return name else create one
return strFile;
}
}
and then you can use the same from your file
Log.RecordLog()// Values as per your code and requirement
Note : Above is just a suggested way to do it, there can be many other and efficient ways also
You can use the built-in Microsoft Intellitrace feature to step through code from the generated intellitrace logs. This link https://msdn.microsoft.com/en-us/library/dn449058.aspx gives instructions on how to achieve the following;
"If you are using Microsoft Monitoring Agent to control IntelliTrace,
you also need to set up set up application performance monitoring on
your web server. This records diagnostic events while your app runs
and saves the events to an IntelliTrace log file. You can then look at
the events in Visual Studio Enterprise (but not Professional or
Community editions), go to the code where an event happened, look at
the recorded values at that point in time, and move forwards or
backwards through the code that ran. After you find and fix the
problem, repeat the cycle to build, release, and monitor your release
so you can resolve future potential problems earlier and faster."
I am trying to make a basic tool which will automatically move the mouse to a menu, and select from a drop-down menu the thing that's been selected.
So, this is the bit, that I'm trying to get my mouse to navigate to, specifically the "saimon" part. I will refer to this screenshot as A
The screenshot of the user's window, is a bigger picture than A. I just want to navigate to A's section within that screen.
Hopefully you understand the objective here.
Anyways, I was trying to do something simple like using an If statement, to see if I would find that icon within the screenshot, and if I did. It would navigate to those coordinates (I could input it manually, by having the user put the menu in a specific location OR grab the coordinates automatically). If it did not match, I would just say an error.
This answer uses OCR to find the location X,Y coordinates of the text 'Saimon'
You download TessNet(2)
Tessnet2 is a .NET 2.0 Open Source OCR assembly using Tesseract engine.
You can implement code similar to this:
using System;
namespace OCRTest
{
using System.Drawing;
using tessnet2;
class Program
{
static void Main(string[] args)
{
try
{
var image = new Bitmap(#"C:\OCRTest\saimon.jpg");
var ocr = new Tesseract();
ocr.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,$-/#&=()\"':?"); // If digit only
//#"C:\OCRTest\tessdata" contains the language package, without this the method crash and app breaks
ocr.Init(#"C:\OCRTest\tessdata", "eng", true);
var result = ocr.DoOCR(image, Rectangle.Empty);
foreach (Word word in result){
if(word.contains("aimon")){
Console.WriteLine("" + word.Confidence + " " + word.Text + " " +word.Top+" "+word.Bottom+ " " +word.Left + " " +word.Right);
}
}
Console.ReadLine();
}
catch (Exception exception)
{
}
}
}
}
You should be able to use these coordinates to automate your mouse to click.
To test online with another OCR how OCR works, please provide your screenprint and check their results. OCR is so good these days!
I am writing a simple C# program with some outputs (Console.WriteLine("...");). The problem is, each time I run it, I cannot see the program's output in the output window.
The "program output" tag is already checked, and I already redirected all outputs to the intermediate window but to no avail.
How do I enable seeing the program's output?
I don't think the problem lies with my code. I tried running a simple program that just outputs a string and readline "ala hello world" and I am still unable to see any output. The problem is either with me looking for the output in the wrong location or Visual Studio acting out.
The debug.write method also doesn't work.
Using debug.Write, it all works, though it didn't before. Either something bugged out with me before I restarted or I just need to take a break, either way it's all good now. Thanks all for the helpful comments =)
You can use the System.Diagnostics.Debug.Write or System.Runtime.InteropServices method to write messages to the Output Window.
Here are a couple of things to check:
For console.Write/WriteLine, your app must be a console application. (right-click the project in Solution Explorer, choose Properties, and look at the "Output Type" combo in the Application Tab -- should be "Console Application" (note, if you really need a windows application or a class library, don't change this to Console App just to get the Console.WriteLine).
You could use System.Diagnostics.Debug.WriteLine to write to the output window (to show the output window in VS, got to View | Output) Note that these writes will only occur in a build where the DEBUG conditional is defined (by default, debug builds define this, and release builds do not)
You could use System.Diagnostics.Trace.Writeline if you want to be able to write to configurable "listeners" in non-debug builds. (by default, this writes to the Output Window in Visual Studio, just like Debug.Writeline)
Add a Console.Read(); at the end of your program. It'll keep the application from closing, and you can see its output that way.
This is a console application I just dug up that stops after processing but before exiting:
class Program
{
static void Main(string[] args)
{
DummyObjectList dol = new DummyObjectList(2);
dol.Add(new DummyObject("test1", (Decimal)25.36));
dol.Add(new DummyObject("test2", (Decimal)0.698));
XmlSerializer dolxs = new XmlSerializer(typeof(DummyObjectList));
dolxs.Serialize(Console.Out, dol);
Console.WriteLine(string.Empty);
Console.WriteLine(string.Empty);
List<DummyObject> dolist = new List<DummyObject>(2);
dolist.Add(new DummyObject("test1", (Decimal)25.36));
dolist.Add(new DummyObject("test2", (Decimal)0.698));
XmlSerializer dolistxs = new XmlSerializer(typeof(List<DummyObject>));
dolistxs.Serialize(Console.Out, dolist);
Console.Read(); // <--- Right here
}
}
Alternatively, you can simply add a breakpoint on the last line.
Press Ctrl + F5 to run the program instead of F5.
System.Diagnostics.Debug.WriteLine() will work, but you have to be looking in the right place for the output. In Visual Studio 2010, on the menu bar, click Debug -> Windows -> Output. Now, at the bottom of the screen docked next to your error list, there should be an output tab. Click it and double check it's showing output from the debug stream on the dropdown list.
P.S.: I think the output window shows on a fresh install, but I can't remember. If it doesn't, or if you closed it by accident, follow these instructions.
To keep open your windows console and to not use other output methods rather than the standard output stream cout go to Name-of-your-project -> Properties -> Linker -> System.
Once there, select the SubSytem Tab and mark Console (/SUBSYSTEM:CONSOLE). Once you have done this, whenever you want to compile use Ctrl + F5 (Start without debugging) and your console will keep opened. :)
I run into this frequently for some reason, and I can't fathom why this solution hasn't been mentioned:
Click View → Output (or just hold Ctrl and hit W > O)
Console output then appears where your Error List, Locals, and Watch windows are.
Note: I'm using Visual Studio 2015.
Visual Studio is by itself covering the console window, try minimizing Visual Studio window they are drawn over each other.
In Program.cs, between:
static int Main(string[] agrs)
{
and the rest of your code, add:
#if DEBUG
int rtn = Main2(args);
Console.WriteLine("return " + rtn);
Console.WriteLine("ENTER to continue.");
Console.Read();
return rtn;
}
static int Main2(string[] args)
{
#endif
You could create 2 small methods, one that can be called at the beginning of the program, the other at the end. You could also use Console.Read(), so that the program doesn't close after the last write line.
This way you can determine when your functionality gets executed and also when the program exists.
startProgram()
{
Console.WriteLine("-------Program starts--------");
Console.Read();
}
endProgram()
{
Console.WriteLine("-------Program Ends--------");
Console.Read();
}
I have put some Console.WriteLine calls in to test, but they aren't appearing in the output box?
public static ArrayList myDeliveries = new ArrayList();
public mainForm(){
InitializeComponent();
}
private void mainForm_Load(object sender, EventArgs e){
if (!File.Exists("../../MealDeliveries.txt")){
MessageBox.Show("File not found!");
return;
}
using (StreamReader sr = new StreamReader("../../MealDeliveries.txt")){
//first line is delivery name
string strDeliveryName = sr.ReadLine();
Console.WriteLine("Test content");
while (strDeliveryName != null){
//other lines
Delivery d = new Delivery(
strDeliveryName,
sr.ReadLine(),
sr.ReadLine(),
sr.ReadLine(),
sr.ReadLine(),
sr.ReadLine(),
sr.ReadLine()
);
mainForm.myDeliveries.Add(d);
//check for further values
strDeliveryName = sr.ReadLine();
}
}
displayDeliveries();
}
private void displayDeliveries(){
lstDeliveryDetails.Items.Clear();
Console.WriteLine("Test content");
Console.WriteLine(mainForm.myDeliveries.Count);
foreach (Delivery d in mainForm.myDeliveries){
lstDeliveryDetails.Items.Add(d.DeliveryName);
}
}
Can anyone help??
Console outputs to the console window and Winforms applications do not show the console window. You should be able to use System.Diagnostics.Debug.WriteLine to send output to the output window in your IDE.
Edit: In regards to the problem, have you verified your mainForm_Load is actually being called? You could place a breakpoint at the beginning of mainForm_Load to see. If it is not being called, I suspect that mainForm_Load is not hooked up to the Load event.
Also, it is more efficient and generally better to override On{EventName} instead of subscribing to {EventName} from within derived classes (in your case overriding OnLoad instead of Load).
If you intend to use this output in production, then use the Trace class members. This makes the code portable, you can wire up different types of listeners and output to the console window, debug window, log file, or whatever else you like.
If this is just some temporary debugging code that you're using to verify that certain code is being executed or has the correct values, then use the Debug class as Zach suggests.
If you absolutely must use the console, then you can attach a console in the program's Main method.
If you want Console.WriteLine("example text") output to show up in the Debug Output window, temporarily change the Output type of your Application from Console Application to Windows Application.
From menus choose Project + Properties, and navigate to Output type: drop down, change to Windows Application then run your application
Of course you should change it back for building a console application intended to run outside of the IDE.
(tested with Visual Studio 2008 and 2010, expect it should work in latter versions too)
Using Console.WriteLine( "Test" ); is able to write log messages to the Output Window (View Menu --> Output) in Visual Studio for a Windows Forms/WPF project.
However, I encountered a case where it was not working and only System.Diagnostics.Debug.WriteLine( "Test" ); was working. I restarted Visual Studio and Console.WriteLine() started working again. Seems to be a Visual Studio bug.
If you are developing a command line application, you can also use Console.ReadLine() at the end of your code to wait for the 'Enter' keypress before closing the console window so that you can read your output. However, both the Trace and Debug answers posted above are better options.
Try to uncheck the CheckBox “Use Managed Compatibility Mode” in
Tools => Options => Debugging => General
It worked for me.
Try to uncheck the CheckBox “Redirect all Output Window text to the Immediate Window” in
Tools => Options => Debugging => General
I had it checked and everything was written in the Immediate Window and not in the Output Window
When issue happening on Mac VS 2017 (Which I faced).
Go to Project >> "Your Project name" options.
An option window will pop up
Go to RUN >> Default menu option
Tick the "Run on external console" option TRUE and say OK
Run your application code now.
Old Thread, But in VS 2015 Console.WriteLine does not Write to Output Window If "Enable the Visual Studio Hosting Process" does not Checked or its Disabled in Project Properties -> Debug tab