C# Command Line Script Ending Prematurely in Visual Studio - c#

(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

Related

C# not outputting to console

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.

why visual studio 2013 isn't returning a string from a method whilst using debug

My problem is that my return value seems to disappear after it has exited it's method.
public async Task<string> mMethod(){
// My methods code (creates a string to be used as html is quite large)
return htmlString;
}
when following through on the debugger this method will execute fine and the returned string is exactly what I expect it to be. My problem arises with it's invoking method
public async void setHtml(){
String html = await mMethod(); // Break point here is triggered
// code below this is never used, the application is almost in a state of limbo
}
I'm using Visual Studio 2013 for windows, I'm developing for windows 8.1. This is only happening when I am using debugger, if I start without debugging this problem doesn't happen. Does anyone know whats going wrong or how to fix it?
I seem to have found a soloution although I am not sure why this works if anyone does I would appreciate if they could explain it for me.
When calling mMethod() inserting Task.WaitAny(); above stopped this bug from happening.
public async void setHtml(){
Task.WaitAny();
String html = await mMethod();
//Break point on this line will now activate
}

Implement auto code structure with visual studio

I am using VS2013 for development. I want to implement such functionality that automatically write a method structure while I just write a method name with parameter and press TAB.
For example: when I write public void testMethod(string param) and press TAB, visual studio automatically writes the TRY, CATCH and FINALLY block and my method look like below:
public void testMethod(string param)
{
try
{
}
catch
{
}
finally
{
}
}
I have googled for this but get no success, I have no idea how to achieve this task, Please guide me for the same.
Visual Studio Code Snippets available when you type anything in the IDE an when you use Ctrl+K, X could also be a solution (They are harder to create than simple text snippets but the experience is better in the IDE with direct auto completion)
Or you could get a ReSharper license and obtain the best of both world (And thousand of must-have features)
You could use the Code Snippet
Here is a similar question:
How to store reusable code

How to make C# application crash

I want to test if my application crash dump can be debugged. But firstly, I need to generate a crash dump of my application. I'm using C# to code my app, and have tried with many exceptions and unsafe code etc. but don't get it.
Thanks!
Edit: Sorry, Just forgot something, I'm making the application with Unity3D, which handles exceptions for me automatically.
Edit 2: Thanks all for your answers. I've tested your suggestions in a standard C# application and it all works fine, but not in my Unity3D application (written with C#). It seems like Unity3D requires more effort to cause a crash, I might email Unity3D to get a answer. I will post here if I get it. Cheers!
The following will provide an unhandled exception and will ask for you to choose a debugger:
System.Diagnostics.Debugger.Launch()
StackOverflowException is a badass:
void PerformOverflow()
{
PerformOverflow();
}
Usage:
PerformOverflow();
Throw an exception :)
throw new Exception("Your exception here!");
For C# in Unity3D
There is UnityEngine.Diagnostics.Utils.ForceCrash (in Unity 2018.3)
This can be used with one of the following ForcedCrashCategory enum parameter:
AccessViolation
Cause a crash by performing an invalid memory
access.The invalid memory access is performed on each platform as
follows:
FatalError
Cause a crash using Unity's native fatal error
implementation.
Abort
Cause a crash by calling the abort() function.
PureVirtualFunction
Cause a crash by calling a pure virtual function
to raise an exception.
For older versions of Unity:
UnityEngine.Application.ForceCrash(int mode)
For even older versions (Unity 5):
UnityEngine.Application.CommitSuicide(int mode)
From my experience, mode 0 causes a "unity handled" crash (where the Unity crash dialog appears), and mode 2 causes a "hard" crash where the Windows error dialog appears.
This seems consistent with this post by Smilediver on mode:
0 - will simulate crash, 1 - will simulate a fatal error that Unity
has caught, 2 - will call abort().
(These methods are not documented as they were intended for Unity's internal use. They may also be marked [Obsolete] depending on your Unity version.)
Well. The only good 100% way actualy crash CLR is to inject a native exception into the managed world.
Calling the Kernel32.dll's RaiseException() directly will immediately crash ANY C# application, and Unity Editor as well.
[DllImport("kernel32.dll")]
static extern void RaiseException(uint dwExceptionCode, uint dwExceptionFlags, uint nNumberOfArguments, IntPtr lpArguments);
void start()
{
RaiseException(13, 0, 0, new IntPtr(1));
}
Happy crashing. Please note that in order to debug native and managed, you will need two instances of Visual Studio running. If you are developing native P/INVOKE plugin, set up it that Visual Studio Instance 1 is native debugger and uses Unity or your C# program as a Host program, and you attach to the Host program from another Visual Studio Instance.
Another option is to call
System.Environment.FailFast("Error happened")
A surefire way to do it is as follows:
ThreadPool.QueueUserWorkItem(new WaitCallback(ignored =>
{
throw new Exception();
}));
All the others can be handled by the top level ApplicationDomain.OnUnhandledException and the like.
This one will kill it dead (assuming .NET 2.0+, and not using 'legacyUnhandledExceptionPolicy': http://msdn.microsoft.com/en-us/library/ms228965.aspx).
None of the answers crashed my app the way I was looking for. So here is the approach that worked for me.
private void Form1_Load(object sender, EventArgs e)
{
object p = 0;
IntPtr pnt = (IntPtr)0x123456789;
Marshal.StructureToPtr(p, pnt, false);
}
public void Loop()
{
Loop();
}
//call this
Loop();
I think there was a code in earlier unity versions like
Application.commitSuicide(number Input);
Now it is replaced by
Application.ForceCrash(number input);
Till this point, I dont know what different numbers do in number input, but for me,
Application.ForceCrash(1);
does the job.
you could also divide by zero,
z = 0;
int divide = 1 / x;
int[] x = {0};
int blah = x[2];
will cause an exception just as well
It's easy enough to reproduce if you try to transform a null game object. For example, like this:
public static GameObject gameObjectCrash;
public void GenerateCrash()
{
gameObjectCrash.transform.rotation = Quaternion.Euler(90, 0, 0);
}
Use below code to close the application.
Environment.Exit(1);
Exit needs a parameter called exitcode. If exitcode=0 means there was no error. Supply a non-zero exit code to to reflect an error.

Application hangs only when breakpoint is triggered, .NET, C#, Visual Studio

I refactored my application a while ago and since then I've been having problems with debugging using Visual Studio 2010.
My application works as expected while not debugging (not stepping through the application. An attached debugger does not cause any issues). However, when a breakpoint is triggered and I start to step through the app, Visual Studio and the app both hang after at most 3-4 steps.
To emphasize this point even more: It works well with my customers and regardless of whether I start it from Visual Studio or stand-alone - as long as no break point is triggered.
It does not matter where in the code I place the break point.
IDE: Visual Studio 2010 x64
Platform: .NET 4.0
The refactoring included a lot of cross-thread calls to BeginInvoke - all channeled through the following method:
public static void BeginInvokeIfRequired(this Control control, Action action)
{
if (control.InvokeRequired)
{
control.BeginInvoke(action);
}
else
{
action.Invoke();
}
}
There is not a single call to Control.Invoke() in the project.
Is there something wrong with the above method?
Additionally, I'd appreciate any hints on how you would track down this bug. My current approach is to add output to the console and selectively deactivating parts of the code.
I would suspect that in some cases the code you show poses a problem since InvokeRequired lies in case IsHandleCreated is false - it returns false even if you are not on the GUI thread.
For reference see http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx .
The following code throws an exception instead of hanging... the fact that it "works as expected" when no breakpoint is hit might be a result of the debugger freezing all threads on hitting a breakpoint which in turn might lead to a different order of execution etc.
Altogether this means: you might have some "race condition" in your code where BeginInvokeIfRequired is called on a freshly created control before that control has a Handle. This can even be some 3rd-party code you use...
public static void BeginInvokeIfRequired(this Control control, Action action)
{
if (control.IsHandleCreated)
{
if (control.InvokeRequired)
{
control.BeginInvoke(action);
}
else
{
action.Invoke();
}
}
else {
// in this case InvokeRequired might lie !
throw new Exception ( "InvokeRequired is possibly wrong in this case" );
}
}

Categories

Resources