Issue regarding exception details c# - c#

I was trying to capture exception details with the below code, but it is not giving error in details.
I was trying to download a file from our ftp server with code like ftp classes. When file was not found, I fire the above method and pass in the exception. Unfortunately the method printed the following:
Error occured and Error details as follows
Exception occured in file
Exception occured in method SyncRequestCallback
Exception occured in line & column number 0 0
Here is my code. How can I capture the exception details (e.g. line number, method where the exception was thrown, etc.)?
public static string GetException(Exception ex)
{
//Get a StackTrace object for the exception
StackTrace st = new StackTrace(ex, true);
//Get the first stack frame
StackFrame frame = st.GetFrame(0);
//Get the file name
string fileName = frame.GetFileName();
//Get the method name
string methodName = frame.GetMethod().Name;
//Get the line number from the stack frame
int line = frame.GetFileLineNumber();
//Get the column number
int col = frame.GetFileColumnNumber();
string strBody = "Hi,<br/><br/>";
strBody = strBody + "Error occured and Error details as follows<br/>";
strBody = strBody + "Error message " + ex.Message + "<br/>";
strBody = strBody + "Exception occured in file " + fileName + "<br/>";
strBody = strBody + "Exception occured in method " + methodName + "<br/>";
strBody = strBody + "Exception occured in line & column number " + line + " " + col + "<br/><br/>Thanks";
return strBody;
}
Thanks

In order to capture more information you'll need to deploy .pdb files generated on build. This will allow you to know specific line where error happened.
As a side note, it seems to me that you're reinventing the wheel creating such a complex logic to log. There plenty of frameworks that will do the dirty job for you as log4net.

Calling ToString on an exception generally generates a readable version of the public details. And only the details available to the exception will be shown, so if the app is not running in debug mode and doesn't have corresponding *.pdb files (or you don't have them to attach, after the fact) - and symbols loads - then you can't get detailed source information.

Related

Can't Write to Windows Application Log (C#)

I'm having a really strange problem with an application I wrote a while back. It has worked without issues, but after leaving it alone for a while, it simply stopped functioning. I'll attach the code here:
try
{
using (Process proc = Process.Start(starter))
{
windowHider();
proc.WaitForExit();
DateTime endStamp = DateTime.Now;
endStamp = truncate(endStamp);
TimeSpan diff = endStamp.Subtract(startStamp);
string programSource = "applicationName";
string logLocation = "Application";
string occurance = "Var='" + varName + "' Var2='"+ var2Name + "' Var3='" + var3Name + "' Var4='" + var4Name + "' Var5='" + var5Name + "' Var6='" + var6Name + "'";
try
{
if (!EventLog.SourceExists(programSource))
{
EventLog.CreateEventSource(programSource, logLocation);
}
else
{
EventLog.WriteEntry(programSource, occurance);
}
}
catch (Exception err)
{
string message = "There was an error with usage logging. Please contact IT.";
MessageBox.Show(message);
errorLogger(message, err.ToString(), ((Control)sender).Name);
this.Close();
}
this.Close();
}
}
When the process that was started exits, the program writes to the application log. For some reason, however, I am getting the following error:
Exception: System.ComponentModel.Win32Exception (0x80004005): The
specified path is invalid
It cites this line as the cause:
EventLog.WriteEntry(programSource, occurance);
Any ideas as to what this sudden problem could be?
I figured it out! There was something corrupted in the registry, and there must have been another corrupted component lurking around somewhere. I changed the sourcename, and it worked without any issues.
The original sourcename works on other machines, which makes me think it was definitely just something wonky with the registry.

Log.txt of an unhandled exception of type 'System.InvalidOperationException'

I am currently working on a way to log into a text file an exception error of type System.InvalidOPerationException via a try{}... catch{} block. My concern is that Log.txt outputs:
Message :Exception of type 'System.Exception' was thrown.
StackTrace :
Date :4/21/2016 9:50:42 AM
Ideally I'd like it to be a bit more informative on the nature of the exception such those revealed by Microsoft Visual Studio dialog box. As an illustration:
An unhandled exception of type System.InvalidOPerationException occured
inSystem.dll
Additional information: the given ColumnName .... does not match up with
any column in datasource
see below the try....catch block applied on my method:
EDIT
try
{
// call method
}
catch (InvalidOperationException exc)
{
using (StreamWriter writer = new StreamWriter(logPath, true))
{
writer.WriteLine("Message :" + exc.Message + "<br/>" +
Environment.NewLine + "StackTrace :" + exc.StackTrace +
"" + Environment.NewLine + "Date :" +
DateTime.Now.ToString());
writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------"
+ Environment.NewLine);
}
}
Any relevant idea would be appreciated. Thanks in advance.

No line breaks when using File.WriteAllText(string,string)

I noticed that there are no line breaks in the file I'm creating using the code below. In the database, where I also store the text, those are present.
string story = "Critical error occurred after "
+ elapsed.ToString("hh:mm:ss")
+ "\n\n" + exception.Message;
File.WriteAllText(path, story);
So after some short googling I learned that I'm supposed to refer to the new lines using Environment-NewLine rather than the literal \n. So I added that as shown below.
string story = "Critical error occurred after "
+ elapsed.ToString("hh:mm:ss")
+ "\n\n" + exception.Message;
.Replace("\n", Environment.NewLine);
File.WriteAllText(path, story);
Still, no line breaks in the output file. What Am I missing?
Try StringBuilder methods - it's more readable and you don't need to remember about Environment.NewLine or \n\r or \n:
var sb = new StringBuilder();
string story = sb.Append("Critical error occurred after ")
.Append(elapsed.ToString("hh:mm:ss"))
.AppendLine()
.AppendLine()
.Append(exception.Message)
.ToString();
File.WriteAllText(path, story);
Simple solution:
string story = "Critical error occurred after "
+ elapsed.ToString("hh:mm:ss")
+ Environment.NewLine + exception.Message;
File.WriteAllLines(path, story.Split('\n'));
Instead of using
File.WriteAllText(path, content);
use
File.WriteAllLines(path, content.Split('\n'));
You can use WriteLine() method like below code
using (StreamWriter sw = StreamWriter(path))
{
string story = "Critical error occurred after " +elapsed.ToString("hh:mm:ss");
sw.WriteLine(story);
sw.WriteLine(exception.Message);
}
WriteAllText strips newlines, because it is not text.

"Cannot find Table[0]" - Only in production?

Some code on our production server is suddenly giving us some trouble. Production has not been changed in about a year, and I've confirmed that the database has not changed either.
If I run the same code on my machine (Yay Source Control!), I do not get the error that appears in production and everything works fine. I'll post the code below, but there has to be something else going on.
Correct me if I'm wrong, but if there is no Table[0], that means my query isn't returning any data. Yet, running the same query directly through SQL Management Studio gives me the data I want.
var ds = GetData(queryString);
if (ds.Tables.Count > 0)
{
var ddlDataSet = GetAdds();
}
private List<tAdd> GetAdds()
{
var ds = GetData(queryString);
var aList = new tAdd[ds.Tables[0].Rows.Count];//THIS IS WHERE ERROR HITS
//Do other stuff
...
}
private DataSet GetData(string queryString)
{
var connectionString =
ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
var ds = new DataSet();
try
{
var connection = new SqlConnection(connectionString);
var adapter = new SqlDataAdapter(queryString, connection);
adapter.Fill(ds);
}
catch (Exception ex)
{
ErrorPanel.Visible = true;
ErrorPanel.Enabled = true;
SearchPanel.Enabled = false;
const string NotificationsEmail = "mailto:emailguy#email.com";
ErrorAlertLabel.Text =
"An err happened. " +
"Please contact the people who do stuff ";
ErrorAlertLabel.Visible = true;
ErrorMessageLiteral.Text = "<br />" + "<br />" +
"Message: " + ex.Message + "<br />" +
"StackTrace: " + ex.StackTrace + "<br />" +
"Inner Exception: " + ex.InnerException + "<br />" +
"Full Detals: " + ex + "<br />";
ErrorMessageLiteral.Visible = true;
}
return ds;
}
I may just try republishing the same version again, but who knows if that will fix it. If anyone needs more info please let me know and thank you in advance.
Actual Error Text: "System.IndexOutOfRangeException: Cannot find table 0."
I think you still have a flaw in your error handling that got exposed.
In GetData, you catch any Exception that occurs and set a bunch of UI elements to Visible and populate them with information, but you don't stop the process from continuing. GetData just continues on after the catch block, and returns an empty DataSet. GetAdds is oblivious to the fact that an error occured, tries to access a table in the DataSet that doesn't exist, and throws another exception that is not handled by your code, but is instead handled by ASP.NET, which throws away all of your error information and just shows a generic error page.
I would not use such detailed error handling within a low-level method, but add more global error handling. Since you don't add any meaningful information to the exception, I would just let it bubble up and handle it at the application level.
If you want to add more information to a low-level exception, throw a new exception with more detail, and assign the original exception to the new exception's InnerException property.
Please check whether you have any pdb files in production , if you dont have them than go to your project right click on properties under Build -> Advanced -> debug info -> pdb build this and please run it production,
If you have these than you can get the exact line where it is breaking.
This might occure,if there is a dead lock on the tables on production. or the permissions are missing.
Got it working today. I finally got a-hold of our Web Admin and asked him to restart the web server - this after I'd confirmed that my code and the DB were not the problem.
As soon as the web server booted back up everything was working fine. There are quite a few applications running on the server, so it may have been something getting tangled up.

Try catch when opening a text file for read

I have some code that is attempts to open a file on our network and what I am trying to do is put this into a try|catch block and I am running into a problem. When I try run my code I get an error: The name 'readProfile' does not exist in the current context (CS0103).
I know that since I am defining my streadreader object (readProfile) in the TRY of the try|catch block that I am not able to access the object but I don't know how to fix that. What I am trying to do is catch an error if I am unable to open the file (if someone else has it open, for example). Here is my code:
try {
StreamReader readProfile = new System.IO.StreamReader(ProDirectory.ToString() + #"\" + myProFile.ToString());
} catch (Exception ex) {
datalogger.Fatal(DateTime.Now.ToString() + ": Error while attempting to read file - " + ProDirectory.ToString() + #"\" + myProFile.ToString() + " The error is - " + ex.ToString());
}
If I remove the try|catch block, the code runs fine and does what I expect.
You can define variables outside the try, and then instantiate them inside:
StreamReader readProfile;
try
{
readProfile = new System.IO.StreamReader(ProDirectory.ToString() + #"\" + myProFile.ToString());
}
catch (Exception ex)
{
datalogger.Fatal(DateTime.Now.ToString() + ": Error while attempting to read file - " + ProDirectory.ToString() + #"\" + myProFile.ToString() + " The error is - " + ex.ToString());
// whatever you want to do with readProfile here. Of course, if the issue was that it couldn't create it, it still won't have been created...
}
Declare the StreamReader outside the try block but leave the assignment inside it.

Categories

Resources