Include full trace with stack trace / error output c# - c#

I'm using the following code in my global.asax file:
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error Caught in Application_Error event<hr />" + "Current User: " + HttpContext.Current.User.Identity.Name + "<hr />" +
"Error in: " + Request.Url.ToString() +
"<hr />Error Message:" + objErr.Message.ToString() +
"<hr />Stack Trace:" + objErr.StackTrace.ToString();
//EventLog.WriteEntry("Sample_WebApp", err, EventLogEntryType.Error);
doEmail.sendEmail("Application Error - Curato (" + System.Configuration.ConfigurationManager.AppSettings["OrganisationName"].ToString() + ")", err);
// We do not want the error handled by the web.config as well, so clear the error.
Server.ClearError();
// Now redirect ourselves...
Response.Redirect("~/error.aspx?aspxerrorpath=" + Server.UrlEncode(Request.Url.PathAndQuery));
}
This sends the stackTrace and current user to an admin email address, and redirects the user to a friendly error page.
How would I be able to include the full Trace information in err? That is, the same information as if I had set Trace="True" in the <%# Page directive.
I'm exploring the Trace object - and found how to read it from a 3rd party reader how to read trace but I'd like to read it just in native code.

You're already getting the full StackTrace of the exception, I believe you're looking at the wrong Exception object:
I think your error is in this line:
Exception objErr = Server.GetLastError().GetBaseException();
I think the correct one should be:
Exception objErr = Server.GetLastError();
You can also inspect the exception to see if there are InnerException:
if (objErr.InnerException != null)
err = err + "<hr/>Message:" + objErr.InnerException.Message;
See this question also:
Application_Error - GetLastError() or GetLastError().GetBaseException()

Related

Response.Redirect not sending string

i've got a bit of a problem trying to set up a general error page in MVC.
I am handling all app errors in Global.asax.cs with the following code ->
protected void Application_Error(object sender, EventArgs e)
{
//if (Request.Url.ToString().StartsWith("http://localhost:"))
// return;
string msg;
Exception ex = Server.GetLastError().GetBaseException();
StringBuilder sb = new StringBuilder();
sb.AppendLine("Exception Found");
sb.AppendLine("Timestamp: " + System.DateTime.Now.ToString());
sb.AppendLine("Error in: " + Request.Url.ToString());
sb.AppendLine("Browser Version: " + Request.UserAgent.ToString());
sb.AppendLine("User IP: " + Request.UserHostAddress.ToString());
sb.AppendLine("Error Message: " + ex.Message);
sb.AppendLine("Stack Trace: " + ex.StackTrace);
msg = sb.ToString();
Server.ClearError();
Response.Redirect(string.Format("~/Error/Error?w={0}", msg ));
}
My problem is that i'm not getting a redirect. I see the same page URL and a blank page when i'm creating an error.
If i remove "errorMsg" and add a SIMPLE STRING, it works, redirects with the required param. Ex:
string test = "testme";
Response.Redirect(string.Format("~/Error/Error?w={0}", test));
That does redirect me to the error page with param "testme". What am i doing wrong here?
You to need escape all the parameters (UrlEncode). At the moment it is unescaped and has a whole bunch of new lines too.
Before you do that, I suggest you just append "hello world" parameter and re-display that to ensure your redirect page is working

Attempting to use OOPFactory to parse 271 benefits using EligibilityBenefitDocument

I'm attempting to use OOPFactory to parse 271 files. (source code here: https://x12parser.codeplex.com/SourceControl/latest) The part I'm struggling with at the moment is getting benefits information. (I can get subscriber and source information just fine).
I've followed the instructions in this post:
(Anyone translate a X12 271 Healthcare response) I can get an EligibilityBenefitDocument with the Subscriber and Source information, but the benefit information on the document winds up being either null, empty, or some other unhelpful value.
I've gone through the raw 271 data and verified that the information I'm looking for is indeed in there. (for reference, I've run multiple files from multiple payers)
I've traced through the both X12SteamReader and the X12Parser while they ran, and verified that the data made it all the way through the parser. It looks like things are working well with the parser. I'm not totally sure on how the EligiblityBenefitDocument is supposed to be generated. It looks like it uses some sort of xslt translation that doesn't seem to be working well for my 271 files. I've applied this tweak to my xslt file (https://x12parser.codeplex.com/workitem/2765) - it cleans up some null values, but still doesn't parse correctly.
What should I be looking at next?
It's possible that I'm using an unsupported EDI format. I'm not sure how to tell if that's the case
I've been programming for a long time, but I've never used the XSLT features of .NET Does anyone have any good links on where to get started there?
A quick solution would be AWESOME if anyone has one.
Thx!
=========
Edit 1:
Here is my code that kicks things off:
Dim ediFileString = path_to_my_file
Dim fstream = New FileStream(ediFileString, FileMode.Open, FileAccess.Read)
Dim service = New EligibilityTransformationService()
Dim benefitDoc = service.Transform271ToBenefitResponse(fstream)
Dim responses = benefitDoc.EligibilityBenefitResponses
I'm calling it from VB.NET instead of C#, but given that it all compiles down to MSIL, and that Source, Receiver, and Subscriber properties are all working, I don't think that's a reason why BenefitInfos would fail.
=========
Edit 2: including more code in response to a request for more detail of what I'm trying to do
Dim ediFileString = path_to_my_file
Dim fstream = New FileStream(ediFileString, FileMode.Open, FileAccess.Read)
Dim service = New EligibilityTransformationService()
Dim benefitDoc = service.Transform271ToBenefitResponse(fstream)
Dim responses = benefitDoc.EligibilityBenefitResponses
Dim strClient = ""
For Each client In benefitDoc.EligibilityBenefitResponses
Try
strClient = "MemberID: " + tidyNull(client.Subscriber.MemberId) + " Transaction Control Number: " + tidyNull(client.TransactionControlNumber) + Constants.vbCrLf
Catch ex As Exception
End Try
Try
strClient += "Member Name: " + tidyNull(client.Subscriber.Name.FirstName) + " " + tidyNull(client.Subscriber.Name.MiddleName) + " " + tidyNull(client.Subscriber.Name.LastName) + Constants.vbCrLf
Catch ex As Exception
End Try
Try
strClient += "Payer Name: " + tidyNull(client.Source.Name.LastName) + Constants.vbCrLf
Catch ex As Exception
End Try
Try
strClient += "Date of Birth: " + tidyNull(client.Subscriber.SerializableDateOfBirth) + Constants.vbCrLf
Catch ex As Exception
End Try
Try
strClient += "Address: " + tidyNull(client.Subscriber.Address.Line1)
strClient += " " + tidyNull(client.Subscriber.Address.Line2) + " " + Constants.vbCrLf
strClient += "Address: " + tidyNull(client.Subscriber.Address.City) + ", " + tidyNull(client.Subscriber.Address.StateCode) + ", " + tidyNull(client.Subscriber.Address.PostalCode) + Constants.vbCrLf
Catch ex As Exception
End Try
Dim results As List(Of EligibilityBenefitInformation)
Try
results = client.BenefitInfos.FindAll(AddressOf searchPlanActive)
If results.Count > 0 Then
strClient += "Active Coverage!" + Constants.vbCrLf
End If
Catch ex As Exception
strClient += "Coverage Type: Couldn't be found"
End Try
For Each benefit In client.BenefitInfos
If benefit.Amount IsNot Nothing Then
strClient &= " Code: " & benefit.Amount
End If
strClient &= " Percentage: " & benefit.Percentage
Try
strClient &= " CoverageLevel: " & benefit.CoverageLevel.Description
Catch ex As Exception
End Try
Try
strClient &= " InPlanNetwork: " & benefit.InPlanNetwork.Description
Catch
End Try
Try
strClient &= " PlanCoverageDescription: " & benefit.PlanCoverageDescription
Catch ex As Exception
End Try
'strClient &= " Messages: " & benefit.Messages.FindLast()
Try
strClient &= " Amount: " & benefit.Amount.Value
Catch ex As Exception
End Try
'strClient &= " Amount: " & benefit.AdditionalInfos
strClient &= Constants.vbCrLf
Next
MsgBox(strClient)
Next
=======
EDIT 3:
I'm attempting to process a 5010 file; OOPFactory says "The built-in specs contain all 4010 standards and some 5010 specifications" https:// x12parser.codeplex.com/ (can't post another working link yet due to lack of reputation points)
=======
Edit 4:
The failure seems to be happening in EligibilityTransformationService.cs on line 35. The correct information is making it into the XML, but is not deserializing properly.
var response = EligibilityBenefitDocument.Deserialize(responseXml);
I'm investigating why that might be.
=====
Edit 5:
In EligiblityTransformationService.cs, starting on line 32, the XML is transformed and then deserialized. The data in question is last seen on line 35 in the responseXml variable, but it never makes it into the response object.
It looks like an issue with the XSLT file.
transform.Transform(XmlReader.Create(new StringReader(xml)), new XsltArgumentList(), outputStream);
outputStream.Position = 0;
string responseXml = new StreamReader(outputStream).ReadToEnd();
var response = EligibilityBenefitDocument.Deserialize(responseXml);
I actually use this same method for my own work at the office. The issues we always run into is the response we receive is either null or random values. What we had to do was continue searching patient information until we found as many possible results that would come back to us. So for example, if we wanted to look up policy date information, we use:
var service = new EligibilityTransformationService();
EligibilityBenefitDocument eligibilityBenefitDocument = service.Transform271ToBenefitResponse(response271Stream);
eligibilityBenefitDocument.EligibilityBenefitResponses = eligibilityBenefitDocument.EligibilityBenefitResponses;
foreach (EligibilityBenefitInformation benefitInfo in eligibilityBenefitDocument.EligibilityBenefitResponses[0].BenefitInfos)
{
if (benefitInfo.InfoType.Code == "V")
return Tuple.Create(false, "Medicare cannot process");
if (benefitInfo.InfoType.Code == "6")
return Tuple.Create(false, "Inactive Policy");
if (benefitInfo.InsuranceType.Code == "HN" || benefitInfo.InsuranceType.Code == "12")
{
try
{
return Tuple.Create(false, "MADV " + benefitInfo.Identifications[0].Id + " " + benefitInfo.RelatedEntities[0].Name.LastName);
}
catch
{
return Tuple.Create(false, "MADV");
}
}
}
We still work off and on with these responses to try and get them as accurate as possible, but unfortunately, it seems like the codes can change for different payers, and its a bit time consuming figuring out how each one works until you get their possible response variations.
EDIT:
If there are no benefitInfos in the response, it means that you are submitting the incorrect patient Information. I have the following check in my program:
if(eligiblityBenefitDocument.EligiblityBenefitResponses[0].BenefitInfos.Count() < 1)
return "Subscriber Info Invalid"

Passing long querystrings over urls shows page not found error(404)

I have a "error.aspx" page which is there to mail me if any exception is caught. When I open the page manually, mysite.com/error.aspx, the page opens fine but when it is redirected by a catch block with the exception.message and exception.stackTrace as querystrings, I get an error "page not found". Are the querystrings directing the browser to open a different url? It works fine when run on localhost, though.
public void send_error(Exception ex)
{
Response.Redirect("error.aspx?time=" + DateTime.Now.ToString() + "&ex=" + ex.Message + "&st=" + ex.StackTrace.Replace("\n", " "), false);
}
If you check this Article, you will see that the max query length of url string is 2048 symbols for Internet explorer. Probably the url is bigger and because of that you have this problem. One solution is to save the desire message in the session as string and after that retrieve it on other pages.
string errorMessage = DateTime.Now.ToString() + " " + ex.Message + " " + ex.StackTrace.Replace("\n", " ");
Session["__ErrMessage"] = errorMessage;
When you are in other pages you can access this string like this:
string errMessage = "";
if(Session["__ErrMessage"] != null)
errMessage = Session["ErrMessage"].ToString();

File.CopyTo error

I have a C# program that queries a remote database for an image file based on a key number. When it finds a match, it locates the file locally (on the server where the program is run) and copies it to a temporary local directory, from where the image is served up in the user's browser. However, I am getting a COM error directed at the file.CopyTo line of the program. The program DOES successfully locate the file and copy it to the temp directory, so it actually works, but for some reason, it apparently doesn't get a success message back or something, and so it stops before returning the filename back to the module that would serve it up in the browser. My apologies if this is too vague. Below is the Error, and then I have put the line of code it points to. There is really not much more to add, as it apparently has what it needs to be successful, but doesn't seem to acknowledge it. Let me know if I need to post more Anyway...
Server Error in '/Indus' Application.
DB-0039 An error occurred while copying a file.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Runtime.InteropServices.COMException:
DB-0039 An error occurred while copying a file.
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[COMException (0x80004005): DB-0039 An error occurred while copying a
file.] XtenderSolutions.interop.AEXDBLib.IObjectFile.CopyTo(Object
FileName) +0 ip_axdb.AXNetConnect.GetAXDocuments(String FieldValue)
in C:\IndusAXProject2013\IP_AXDb\AXDB\AXNetConnect.cs:67
IP_EDMSforVentyx._Default.Page_Load(Object sender, EventArgs e) in
C:\IndusAXProject2013\IP_EDMSforVentyx\EDMSforVentyx_Default.cs:21
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object
o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender,
EventArgs e) +35 System.Web.UI.Control.OnLoad(EventArgs e) +91
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+2207
And the line of code is simply:
file.CopyTo(filepath + filename);
which is part of this:
for (int j = 1; j <= ((int) pages.Count); j++)
{
PAGE page = (PAGE) pages[j];
PageVersions versions = (PageVersions) page.Versions;
int num4 = 0;
num4 = (int) versions.Count;
if (num4 < 1)
{
break;
}
PAGEVERSION pageversion = (PAGEVERSION) versions[num4];
ObjectFile file = (ObjectFile) app.FileObject;
filename = i.ToString() + "_" + j.ToString() + ".tif";
file.ObjectId = pageversion.ObjectId;
file.PathId = (pageversion.PathId);
file.GenerateNewFileName();
file.CopyTo(filepath + filename);
if (IsJpegHeader(filepath, filename))
{
this.DeleteImgFile(filepath, filename);
file.CopyTo(filepath + (i.ToString() + "_" + j.ToString() + ".jpg"));
}
}
Anyway, thanks if anyone has any ideas.

ASP.net Custom Errors Loggin

I'm using the customErrors attribute of the web.config file to present custom errors pages:
<customErrors mode="On" defaultRedirect="/errorpage.aspx">
<error statusCode="404" redirect="/404Page.aspx"/>
<error statusCode="403" redirect="/403page.aspx"/>
</customErrors>
Nothing too fancy. Now what I want to do is log the error that occurs when any of these pages are loaded. I'm specifically interested in any exceptions, I don't really care what page the user was on when they got a 404.
I'd like to capture the exception and record it into a db Table. Will something like this work:
//errorpage.aspx
public void Page_Load(object sender,EventArgs e)
{
Exception objErr = Server.GetLastError().GetBaseException();
var err = new {Url = Request.Url.ToString(),
Message = objErr.Message,
Trace = objErr.StackTrace.ToString()};
db.Errors.InsertOnSubmit(err);
db.SubmitChanges();
Server.ClearError();
}
Is there any other information that is worth capturing, or is generally captured on an error?
I think there are better ways to do this:
Use ELMAH!
Run your code in the Global.asax Application_Error event.
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError().GetBaseException();
EventLog.WriteEntry("Test Web",
"MESSAGE: " + ex.Message +
"\nSOURCE: " + ex.Source +
"\nFORM: " + Request.Form.ToString() +
"\nQUERYSTRING: " + Request.QueryString.ToString() +
"\nTARGETSITE: " + ex.TargetSite +
"\nSTACKTRACE: " + ex.StackTrace,
EventLogEntryType.Error);
}
Rather than rolling your own, have you considered using something like Elmah, which can handle this all for you:
http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx
Why don't you simply use the application server log, what happed if the error/exception is due to the impossibility of accessing the data base. Here is how I log the errors in some web site:
public static void WriteException(Exception exception)
{
EventLog eventLog = null;
try
{
StringBuilder message = new StringBuilder();
message.Append("[").Append(exception.Source).Append(" - ").Append(exception.GetType().FullName);
message.Append("]").Append(#"\r\n").Append(exception.ToString());
eventLog = new EventLog();
eventLog.Log = "LOG_FILE_NAME";
eventLog.Source = "APP_IDENTIFIER";
eventLog.WriteEntry(message.ToString(), EventLogEntryType.Warning);
}
catch (Exception ex) {/*DO-NOTHING*/ string msg = ex.Message; }
finally { if (eventLog != null) { eventLog.Dispose(); } eventLog = null; }
}

Categories