C# not outputting to console - c#

I'm sure there's some simple answer, but none of the other Stack Overflow posts has helped me. My code will not log to the Console, and it's hard to do anything useful with that state of affairs.
using System;
using System.Diagnostics;
namespace Learning
{
class MainClass
{
public static void Main (string[] args)
{
Debug.Log ("this?");
Debug.Print ("How about this?");
Console.WriteLine ("WORK");
Console.ReadLine ();
}
}
}
I've been able to write to the console before, I don't know why it's being persnickety now.

Probably because your code doesn't actually compile. Log() is a static method of Debugger, not Debug, and it takes three arguments: level, category, and message.
public static void Main (string[] args)
{
System.Diagnostics.Debugger.Log(1, "category", "this?");
System.Diagnostics.Debug.Print ("How about this?");
Console.WriteLine ("WORK");
Console.ReadLine ();
}
It's worth noting that Debug/Debugger methods will not do you any good unless you are Debugging. To start a debugging session in mono, go to the Run -> Debug

You may want to check what kind of application you are using. For example, if you are making a Forms Application, you won't have access to the Console functions.
You can change this by going into the Solution Properties, and changing it from a Windows Forms Application to a Console Application. This won't have any effect on your program, other than it will run a Console alongside.

Related

Console application message does not show up

using System;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
Code is perfect and simple.. you know :D
but the editor is empty? Whats the matter?
I first suggest you go to "Tools->Options->Debugging" and then make sure the checkbox at "Close the console when debug ends" (4th element from the bottom) is not checked. That will leave the console window open when the application exits.
Try running with Ctrl-F5.
This starts without the debugger and keeps the window open after the program ends.
I always set up a button for it each VS install, to make my life easier.
and the results:

while loop prevents other code from executing c#

I'm trying to write a drawing library. In this drawing library there is an update function that should update every frame. I do this by using a do while loop See code below:
private void UpdateCanvas()
{
do
{
Canvas.PumpEvents();
if(UserUpdateVoid != null) UserUpdateVoid();
} while (Canvas.Exists);
}
I also have a function in which the user can set their own update function. This function is part of the SharpDraw class, see code below:
public void SetCustomUpdateFunction(Action function)
{
Console.WriteLine("updated the user function");
UserUpdateVoid = function;
Console.WriteLine(UserUpdateVoid);
}
all this is called in the following way:
public class SharpCanvas
{
private Sdl2Window Canvas;
private GraphicsDevice GraphicsManager;
private Action UserUpdateVoid = null;
public SharpCanvas()
{
WindowCreateInfo WindowInfo = new WindowCreateInfo(
200,
200,
100,
100,
WindowState.Normal,
"SharpWindow"
);
CreateCanvas(WindowInfo);
UpdateCanvas();
}
}
And the SharpDraw instance is made in the following way:
namespace test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
SharpCanvas Canvas = new SharpCanvas(200,200);
Canvas.SetCustomUpdateFunction(Update);
}
private static void Update(){
Console.WriteLine("update");
}
}
}
But the problem is that the Console.Writelines in the SetCustomUpdateFunction() are never executed. I guess this has to do with the fact that the while loop keeps the program from further execution. So my question is how do i keep the while loop running while still being able to execute different pieces of code? In unity they are able to do it :P
If there is something unclear let me know so i can clarify!
That is entirely normal. It does not mater if you are running a console application, a Windows Form or WPF/UWP application*: Only one piece of code can be executing. While one piece of code does not return, not other code can run.
You need to add some form of Multitasking into the mix. Now that looks extremely like a Console Application and those are the last place I would advise learning Multithreading in. My personal advise is to start under Windows Forms using the BackgroundWorker. It is dated and rarely used in practice, but it can help you get up to speed with the rules and conventions. But this is one area where you can ask 10 people and get 11 Opinions.
*Web Applciations are semi special. As they are pleasingly parallel and it helps with isolation usually each request is given their own Thread. But at least for each singular request, it still holds true.
When you call UpdateCanvas, you enter a loop and code never goes further. To prevent this, you should use threads, async-await or something similar else (see this answer for async-await).
You have to use Multithreading programming. Look for it on google, there are plenty of examples.

C# Command Line Script Ending Prematurely in Visual Studio

(Sorry if a few parts aren't correct...
I'm a bit of a novice to C# syntax)
I am currently working on a command line project. The project involves creating an algorithm that solves Problem 4 on Project Euler:
https://projecteuler.net/problem=4
From the beginning, ever since I have started the challenges, I've mainly been using Visual Studio to solve them. I've been using a "C# Command Line' type project for the interpretation of information.
Ever since I started using this type of windows form, I've found that as soon as:
static void Main(string[] args)
{
//Insert Code Here...
}
Function finished its events and arguments, it suddenly crashed (well, closed)
I believe that this is because it has and end, it ends itself...
I may be wrong...
In the meantime, I simply used a Thread.Sleep() function as a temporary fix.
How can I solve this problem, and why do you think this is happening?
Thank you!
Try this:
public static void Main(string[] args)
{
try
{
// Your code here
}
catch (Exception ex)
{
// This code will only run if your code fails
Console.WriteLine(ex.ToString()); // Show the exception on the console.
}
Console.ReadKey(); // Make a pause so that the screen does not dissapears when I hit Debug -> Run
}
Try running the project using ctrl + F5 instead of just F5. This is a lot cleaner than adding an unnecessary line to detect keypress at the end of the program IMO

.Net Program with both WinForm and Console Interfaces

I have a simple question and I'm sure it's been answered, but I can't seem to find the solution I'm looking for.
My basic question is that I've created a console app in .Net that runs automatically on a task scheduler every day, but now my clients also want a windows form-based interface that they can use to run special runs (they use the GUI to specify a few parameters - such as specific dates, etc - to make the program run a bit differently).
The way I thought to do this would be to convert my console app to a WinForm solution and to include Command Line Arguments for when I wanted it to run as the original console app with defaults, but I'm thinking that's not the right way since it would still involve a form load.
My other thought was to convert the "engine" part to a DLL and to make 2 executables - One a console app and one a winforms app, but I'm not sure if that's right either / could lead to more maintenance.
What is the correct way to do this?
I'm writing this in VB, but am equally comfortable with C# solutions if that is easier for you.
Thanks!!
Typically, I'd split the logic into a library, then make a simple console app and a simple Forms app to call into the logic in the library.
You can then distribute these separately and use them as they are intended, without duplication of code.
You can modify your Program.cs to accept arguments, then if some args had been passed to your app prcess them and exit from main, else start your main form, something like this:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
if (ProcessCommandLine(args))
return;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
static bool ProcessCommandLine(string[] args)
{
//Process it, if some has been processed return true, else return false
}
}
Or you can make the form invisible and go with your first option, reading the commandline.
here is a way of making the invitial form invisible. Form Invisible
Three projects as Reed suggested is a correct approach, however if you really need 1 executable (which we for some reason really wanted in one case) you can do following:
static class Program
{
[STAThread]
static void Main(string[] args)
{
if (args[0]== "-ui")
{
System.Windows.Forms.Application.EnableVisualStyles();
System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
System.Windows.Forms.Application.Run(new MyFormWork());
}
else if (args[0] == "-console")
{
Helper.AllocConsole();
DoYourConsoleWork();
Helper.FreeConsole();
}
}
public static class Helper
{
[DllImport("kernel32.dll")]
public static extern Boolean AllocConsole();
[DllImport("kernel32.dll")]
public static extern Boolean FreeConsole();
}
1: you can use XML for arguments. your console just need to read XML for its argument.
then create a form app just for editing XML and save.
Benefit:
your app is running by task scheduler so your form do not need to .
for user it's easy to open form app and change something that will save to xml
Console --run every day without any notice
Argument.xml -- argument for Console .
Form -- user interface
2: you can mix both within a form but it will run every day in form base not good idea

Capture console output for debugging in VS?

Under VS's external tools settings there is a "Use Output Window" check box that captures the tools command line output and dumps it to a VS tab.
The question is: can I get the same processing for my program when I hit F5?
Edit: FWIW I'm in C# but if that makes a difference to your answer then it's unlikely that your answer is what I'm looking for.
What I want would take the output stream of the program and transfer it to the output tab in VS using the same devices that output redirection ('|' and '>') uses in the cmd prompt.
You should be able to capture the output in a text file and use that.
I don't have a VS handy, so this is from memory:
Create a C++ project
Open the project settings, debugging tab
Enable managed debugging
Edit command line to add "> output.txt"
Run your program under the debugger
If things work the way I remember, this will redirect STDOUT to a file, even though you're not actually running under CMD.EXE.
(The debugger has its own implementation of redirection syntax, which is not 100% the same as cmd, but it's pretty good.)
Now, if you open this file in VS, you can still see the output from within VS, although not in exactly the same window you were hoping for.
The console can redirect it's output to any textwriter. If you implement a textwriter that writes to Diagnostics.Debug, you are all set.
Here's a textwriter that writes to the debugger.
using System.Diagnostics;
using System.IO;
using System.Text;
namespace TestConsole
{
public class DebugTextWriter : TextWriter
{
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
//Required
public override void Write(char value)
{
Debug.Write(value);
}
//Added for efficiency
public override void Write(string value)
{
Debug.Write(value);
}
//Added for efficiency
public override void WriteLine(string value)
{
Debug.WriteLine(value);
}
}
}
Since it uses Diagnostics.Debug it will adhere to your compiler settings to wether it should write any output or not. This output can also be seen in Sysinternals DebugView.
Here's how you use it:
using System;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
Console.SetOut(new DebugTextWriter());
Console.WriteLine("This text goes to the Visual Studio output window.");
}
}
}
If you want to see the output in Sysinternals DebugView when you are compiling in Release mode, you can use a TextWriter that writes to the OutputDebugString API. It could look like this:
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace TestConsole
{
public class OutputDebugStringTextWriter : TextWriter
{
[DllImport("kernel32.dll")]
static extern void OutputDebugString(string lpOutputString);
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
//Required
public override void Write(char value)
{
OutputDebugString(value.ToString());
}
//Added for efficiency
public override void Write(string value)
{
OutputDebugString(value);
}
//Added for efficiency
public override void WriteLine(string value)
{
OutputDebugString(value);
}
}
}
I'm going to make a few assumptions here. First, I presume that you are talking about printf output from an application (whether it be from a console app or from a windows GUI app). My second assumption is the C language.
To my knowledge, you cannot direct printf output to the output window in dev studio, not directly anyway. [emphasis added by OP]
There might be a way but I'm not aware of it. One thing that you could do though would be to direct printf function calls to your own routine which will
call printf and print the string
call OuputDebugString() to print the string to the output window
You could do several things to accomplish this goal. First would be to write your own printf function and then call printf and the OuputDebugString()
void my_printf(const char *format, ...)
{
char buf[2048];
// get the arg list and format it into a string
va_start(arglist, format);
vsprintf_s(buf, 2048, format, arglist);
va_end(arglist);
vprintf_s(buf); // prints to the standard output stream
OutputDebugString(buf); // prints to the output window
}
The code above is mostly untested, but it should get the concepts across.
If you are not doing this in C/C++, then this method won't work for you. :-)
Maybe this will work for you: set a breakpoint on the close } in Main, and then look at the console window before it closes. You can even copy the text out of it if you need to.
On every machine that I use for development, I configure my console window in a certain way, which happens to make this approach work better:
Run cmd.exe
ALT-SPACE, D
In Options, enable QuickEdit mode.
In Layout, set Buffer Height to 9999
Click OK
Exit the CMD window.
System.Diagnostics.Debug.Writeline() or Trace.Writeline()
You can use Systems.Diagnostics.Trace class to write your output to the Output window instead of (or in addition to) the console. It take a little configuration, but it works. Is that along the line of what you want?
You can also add your own tab per this article, but I've never tried it.

Categories

Resources