So I am writing an academic software where I need to get data from a network of 8 devices via online links. Note that this devices are configured in such a fashion that they sometime return no or null data. And I need to collect this data for a long time. Here, is the code:
public static void ParseJsonStatic(string link, ...9)
{
/access the URLs in a suitable interval and process data
var client = new WebClient();
var stream = client.OpenRead(link);
Debug.Assert(stream != null, "stream != null");
var reader = new StreamReader(stream);
var rootObject = JsonConvert.DeserializeObject<RootObject>(reader.ReadToEnd());
....
}
So whenever there is a null stream, Visual Studio will pause and show me the exception bubble and I will have to click this continue button.
Is there a way to handle this and make sure my code continues to run from start if such a situation occurs. So what I want is this:
while (stream == null) { ... retry to read stream and don't trigger nullPointerException... }
Because pausing in middle fails my purpose of data collection based on specific interval and also I cannot leave it unattended as such for long intervals.
Thanks.
Try this:
var stream = null;
while (stream == null) {
stream = client.OpenRead(link)
}
Maybe between reads you also want to wait for some time.
In Visual Studio: Ctrl + Alt + E or Debug > Exceptions.
This will open up a window where you can select which expections will cause the debugger to break.
The ones you are intrested in will probably be under "Common Language Runtime Exceptions"
Note that any unhandled exception which would cause your app to crash will still break debugging. You need to make sure to handle the exception with a Try/Catch.
Go to the Debug menu and then the Exceptions
To access this window go to the Debug menu and select Windows -> Exception Settings.
Select add and type in your exception. This will add a checkbox item
for your exception.
Anytime that exception is thrown your debugger will pause if that checkbox is on. In your situation this checkbox must be unchecked.
See this link on msdn for more info!
Related
Is there any way to pause the debugging without breakpoints in VS? (c# Console Application)
I noticed that after a few time my program simply stops working but no exception is thrown, it simply stop doing what it should do.
That's why I wanted to know if there is any way i could pause the code as if there was a breakpoint there, so that i would be able to understand what happend.
The program scrapes data from a website and inserts it into a MS SQL SERVER database if it matters.
EDIT :
That's the function that does the magic in my code and scrapes the data from the website. All other things are just data monipulatins.
public static string PostRequest(string url, string request)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = request;
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
And again no exception is being thrown.
I asked for no breakpoints because the program runs just fine for the first 500 times. Past that number give or take it freezes.
This line will break as if it were a break point:
System.Diagnostics.Debugger.Break();
Have you considered
Console.ReadLine();
or
Console.ReadKey();
?
You can put a System.Diagnostics.Debugger.Break(); somewhere, with some "activation" condition that can trigger it.
As example, you can have a thread just checking for some condition
As a start, something like this (yes, it can be improved, this is just an idea)
void CheckAndDebugBreak()
{
while (true)
{
string fileGuard = ...; // whatever file you can easily create/delete
if (File.Exists(fileGuard))
{
File.Delete(fileGuard); // to avoid hitting the breakpoint next time, recreate the file if needed
System.Diagnostics.Debugger.Break();
}
// some way to stop the infinite loop e.g.
if (somevariableSetOutside)
break;
// wait a while before next check
System.Threading.Thread.Sleep(1000);
}
}
If you are only avoiding breakpoints because you don't want to have to manually cycle through, you can try this:
Set a break point at the beginning of your function.
Mouse over the breakpoint and select the 'gear' symbol
Check the "Conditions" box
Select "Hit Count" from the first drop down, and set a value
This will stop execution on the breakpoint after that many cycles. So you could run for 500 cycles, then pause at a breakpoint.
Additionally, you can create a Count variable to count the cycles and output the number to the console each cycle to determine exactly how many cycles it makes it through, and if the number is consistent or not.
Select menu Debug - Break All to break into the next available line of code in an executing app. See Navigate Code with the Visual Studio Debugger for more information.
I'm building a Windows Form application and I want to open "Microsoft Edge" through my app with a specific URL and wait until the user closes the Edge Window.
I tried it with this code:
using (Process p = Process.Start("microsoft-edge:www.mysite.com"))
{
p.WaitForExit();
}
When I execute this code, Edge is launching with the correct URL ... but got a null object reference. The "p" object that I'm getting from Process.Start is null.
I think it's related to the reuse of Windows application.
Does anyone have a workaround/have an idea how I can wait for the user to close Edge?
Finally I did managed to do so:
When you launch Edge (at least) two process get created:
MicrosoftEdge and MicrosoftEdgeCP.
MicrosoftEdgeCP - foreach tab. So we can "wait" on this new tab process that was just created.
//Edge process is "recycled", therefore no new process is returned.
Process.Start("microsoft-edge:www.mysite.com");
//We need to find the most recent MicrosoftEdgeCP process that is active
Process[] edgeProcessList = Process.GetProcessesByName("MicrosoftEdgeCP");
Process newestEdgeProcess = null;
foreach (Process theprocess in edgeProcessList)
{
if (newestEdgeProcess == null || theprocess.StartTime > newestEdgeProcess.StartTime)
{
newestEdgeProcess = theprocess;
}
}
newestEdgeProcess.WaitForExit();
From an older solution - use a WebBrowser control to load the HTML. Once you get the data back, use an ObjectForScripting to call a c# method to notify when done.
See http://www.codeproject.com/Tips/130267/Call-a-C-Method-From-JavaScript-Hosted-in-a-WebBrowser
If I have these sprinkled throughout my code:
MessageBox.Show("See a format exception yet? #1");//todo: remove
(there are 7 of these, numbered from 1..7, most of which display (1,2,5,6,7))
I end up with one err msg ("Exception: Cannot find table 0 Location: frmFunction.SetPlatypus")
If I comment out all of those, I end up with a different err msg ("Exception: FormatException Location frmFunction.getDuckbillRecord")
How could this be? Shouldn't the existence/display of such an information msg have no effect on the way the code executes/the path it takes, etc.?
Note: getDuckbillRecord() is where all of the MessageBoxes are.
UPDATE
Using RT's suggestions as motivation, I came up with this:
public static StringBuilder LogMsgs = new StringBuilder();
public static void ExceptionHandler(Exception ex, string location)
{
try
{
LogMsgs.Append(string.Format("{0}\r\n", ex.Message)); //TODO: Comment out before deploying?
DateTime dt = DateTime.Now;
string timeAsStr = string.Format("{0}_{1}_{2}_{3}.txt", dt.Hour, dt.Minute, dt.Second, dt.Millisecond);
using (StreamWriter file = new StreamWriter(timeAsStr))
{
file.WriteLine(LogMsgs.ToString());
}
. . .
//in the problematic code, replacing the MessageBox.Show() calls:
TTBT.LogMsgs.Append("Made it to location 1 in frmOverFunction.GetDuckbillRecord()\r\n");
...and it did help - the exception is reached right after the first of 7 "code waypoints," so there's something rotten in that particular Denmark, apparently.
UPDATE 2
After the rare experience of being able to run the app without crashing somewhere, I realized I also need that file-writing code in the main form's OnClosing() event - being in the global exception handler had worked for awhile - I wasn't expecting a clean termination of the app to ever occur again, I guess.
I'd strongly encourage you NOT to use MessageBox.Show(...) to log/trace/debug errors, because popping-up a dialog can introduce many subtle bugs and changes in behavior, focus, etc., especially if your UI flow/state is important.
Instead, use System.Diagnostics.Trace for writing tracing code (which you can optionally compile into your production/release code) or System.Diagnostics.Debug to write debug messages which get removed when you build your release version.
For example:
public void DoSomething(int a, int b)
{
Trace.TraceInformation("Starting to do something: a = {0}, b = {1}",
a, b);
try
{
int c = a / b;
}
catch (DivideByZeroException e)
{
Debug.WriteLine("OH NO ... 'b' WAS ZERO!!!! RUN AWAY!!!!");
throw e;
}
Trace.TraceInformation("Done doing something");
}
In the example above, the debug output will be available in debug builds, but will be removed in release builds. Trace output will be available in debug and retail bugs (unless you turn off the TRACE build parameter) but introduces no measurable perf impact unless you hook-up a listener and start writing trace output to a slow medium like spinning disks, ticker-tape printers, etc. ;)
When you run code with Trace and/or Debug builds with Debug messages in Visual Studio, the messages are written to the Output pane so you can watch what's going on inside your app as it runs.
If you want to, you can also write a stand-alone trace listener that listens for Trace and/or Debug messages and log them to a file/database or display them in a console window (or GUI if you want to get fancy).
You can also use tools like log4net which enables you to write log/trace messages to a variety of file formats, databases, etc.
I am working on an app that uses location services. If I am debugging, the app works fine. If I start without debugging, on the first run (after rebuild), it crashes when asking for authorization to use location services. What happens is that if you let it sit, with the messagebox showing long enough (5-10 seconds), it crashes. If I start without debugging again, it works fine (though it doesn't show the messagebox again, because somehow it gets past that line to the next line AFTER the conditional statement, where it sets first run false (I assume, because it doesn't show again).
Again, if I am debugging, no problems. If I start without debugging, it dies. This is the case when building in either the Debug or Release modes.
If I comment this block of code out, it executes without a problem. If I click OK quickly, it executes without a problem.
if (settings.FirstRunLocationPermission)
{
string message = "Do you wish to use location services to see your location on the map? Your location is not being tracked. You can change this authorization in the settings.";
//if (MessageBox.Show(message,"authorization",MessageBoxButton.OKCancel) == MessageBoxResult.OK)
//{
// settings.AllowLocation = true;
//}
settings.FirstRunLocationPermission = false;
}
I would greatly appreciate it if anyone can explain to me why a simple messagebox checking for ok would cause a problem like this. Thanks!
Most likely you are showing the MessageBox in OnNavigatedTo. If that is the case, this SO answer should help. The problem is that if the user does not press a button your app will crash since the framework thinks that navigation has failed.
And yes, this behaviour occurs to me only when debugger is not attached.
If you look at the MSDN Documentation for the method, the reasons for the possible Exceptions is fairly clear:
MDSN - MessageBox.Show Method
The other possibility is that there is some code running in the setter for the settings.AllowLocation property that is throwing the Exception. It would help if you included the actual Exception being thrown.
I use it this way, and it works :
var msg = MessageBox.Show("Do you .... ?", "Title", MessageBoxButton.OKCancel);
if(msg == MessageBoxResult.OK)
{
//Do something;
}
Good luck
I'm trying to run dot net console application via Java:
process = Runtime.getRuntime().exec(commandLine);
I get the following output:
Detecting
The handle is invalid.
when running it directly via the console (windows) there is no problem:
Detecting
100%
Done.
100%
I'm running more applications in this form but have no problem .
Got this stack trace:
Detecting at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.Console.GetBufferInfo(Boolean throwOnNoConsole, Boolean& succeeded)
at System.Console.get_CursorTop()
at AutomaticImageOrientation.HelperClasses.General.WriteProgressToConsole(Int32 lastIndex, Int32 totalImages)
at AutomaticImageOrientation.MainManager.DetectImage(String[] files, String outputPath, String& globalErrorMessage, Dictionary`2& foundRotations)
The problem is when the .net app trying to write to the console What is the solution?
found the line that cause the problem:
Console.CursorLeft = 0;
Do you know why?
The console application is trying to set the cursor position for a console. This isn't possible, since there is in fact no console. All operations which don't result in a simple read or write are likely to cause errors when there is no console (since most of them require a console output buffer to work).
It is a bad idea to do stuff like setting the cursor position or clearing the screen in console applications you wish to automate. A basic workaround is to just put the offending statement in a try-catch, and discard the exception. From the MSDN page on System.Console:
You should not use the Console class
to display output in unattended
applications, such as server
applications. Similarly, calls to
methods such as Write and WriteLine
have no effect in Windows
applications.
Console class members that work
normally when the underlying stream is
directed to a console might throw an
exception if the stream is redirected,
for example, to a file. Consequently,
program your application to catch
System.IO.IOException if you redirect
a standard stream.
I ran into the same problem, only it was from running a c# console application via the SQL task scheduler.
I believe the problem is that some console methods and properties (Console.WindowWidth, Console.CursorLeft) are attempting to manipulate the console output, which isn't possible when the console is redirected.
I wrapped the section of the code in a simple try catch block, and it works fine now.
//This causes the output to update on the same line, rather than "spamming" the output down the screen.
//This is not compatible with redirected output, so try/catch is needed.
try
{
int lineLength = Console.WindowWidth - 1;
if (message.Length > lineLength)
{
message = message.Substring(0, lineLength);
}
Console.CursorLeft = 0;
Console.Write(message);
}
catch
{
Console.WriteLine(message);
}
Hard to diagnose without more detail - perhaps permissions... a little bit of exception handling (perhaps writing stack-trace to stderr) would help enormously. but not much help if you don't own the app.
If you don't get anywhere, you could try using reflector to see what the .NET app is doing during "Detecting" - it might help identify the cause.
I don't think there is a problem with your friend's program. You probably need to get the output stream of the process object you receive from Runtime.getRuntime().exec(commandLine), and call a read() method or something. It might work.
Try this to get the output stream of the call command
Runtime r = Runtime.getRuntime();
mStartProcess = r.exec(applicationName, null, fileToExecute);
StreamLogger outputGobbler = new StreamLogger(mStartProcess.getInputStream());
outputGobbler.start();
int returnCode = mStartProcess.waitFor();
class StreamLogger extends Thread{
private InputStream mInputStream;
public StreamLogger(InputStream is) {
this.mInputStream = is;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(mInputStream);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
That can depend on how your Java application is being run. If your java application doesn't have console, when there can be problems when console presence is necessary for your inner process. Read this.