What can cause Application_Error not to be invoked? - c#

For the last 2 weeks I have a case that I can't figure it out, maybe you guys already passed through the same problem or ear/read about it and can help me.
I have an ASP.NET Project that I run on my machine and other machines fine, every time I try to temper the QueryString I get an error that is been thrown by the System.Exception
problem is, in this particular machine (witch is in Holland) the Application_Error never catches the Exception, it saves the Exception message to the log (as in my application should be done) but it does not "break" the web application... it just continues!
How and what can make this possible?
for an example sake, this is my webpage (HttpCache canot be invoked like this, but is only to point that I'm using the Web.HttpCache object)
if( Request.QueryString["user"] != HttpCache["MYAPP-user"] ) {
myApp.DebugWrite("User was tempered.");
throw System.Exception("User was tempered.");
}
and in global.asax I have
...
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
if (Server.GetLastError() != null)
{
Exception objErr = Server.GetLastError().GetBaseException();
String url = Request.Url.ToString();
String msg = objErr.Message;
String trc = objErr.StackTrace.ToString();
Response.Clear();
StringBuilder html = new StringBuilder();
// fill up html with html code in order to present a nice message
Response.Write(html.ToString());
Server.ClearError();
Response.Flush();
Response.End();
}
}
...
in my test machines, I always get the html with the error message, as well the message in the log... in this particular machine, I only see the error in the log, but the application continue!!!
web.config is exactly the same as in all machines and this web application runs on .NET 2.0
What can it be?

Comment out the Response and Server.ClearError() part in your code:
//Response.Clear();
StringBuilder html = new StringBuilder();
// fill up html with html code in order to present a nice message
Response.Write(html.ToString());
//Server.ClearError();
//Response.Flush();
//Response.End();

Related

"Maximum request length exceeded" error handling only working for large files

I'm trying to handle the "Maximum request length exceeded" error after an ajax request, it works fine for really large files, but for smaller files the error response is lost so I can't handle it the way I want to. This is the relevant code:
$(document).on({
ajaxError: function (event, request, settings) {
console.log("error Ajax error");
console.log(event);
console.log(request);
console.log(settings);
if(request.responseText.contains("Maximum request length exceeded")){
alert("Error! max file size: " + "#HttpContext.Current.Session["MaxFileSize"]");
}
}
});
For files above 150Mb or so in size it works, the responseText is the html error page, everything runs as I want to. But for smaller files the responseText is empty. I've tried to configure the maxRequestLength in the web.config with 20Mb and 100Mb, the behavior is the same.
When I breakpoint in my application_error I can see that indeed the error happened and it was a "Max Request Exceeded" error, but if I try to modify the Response it does not work, again, for smaller files, for really large files it works fine, here is my example code:
void Application_Error(object sender, EventArgs e)
{
var lastException = Server.GetLastError();
var logger = NLog.LogManager.GetCurrentClassLogger();
logger.Fatal(lastException);
if (lastException.Message.Contains("Maximum request length exceeded"))
{
this.Server.ClearError();
HttpContext.Current.ClearError();
Response.Write(
new JavaScriptSerializer().Serialize(
new { error = "MaxLength Error Occured, handle in page" }
)
);
}
}
One thing I noticed is that when the responseText is lost application_error is called twice, which I'm not sure if its relevant.
I've been searching all over and I haven't found any solution, most people's problem is that the error happens even after configuring it correctly, my problem is not that it happens when it shouldn't, it happens when it should but I can't handle it because the error's responseText is lost. I would greatly appreciate any directions to solve this issue.
Update: I had not tried a different browser, I was doing it all in Firefox, I have tried it now in Chrome and IE and it doesn't work no matter the file size, the responseText of the request object is always empty. Application_Error is called only once though, in Firefox is called twice, and with the same error.
I wanted to close the question. I finally figured it out. The problem is when debugging in Visual Studio, I guess the server behaves differently, once I published in our test environment the error behaved as I expected it, and worked with any file above the limit I configured.

Xamarin Android - Webclient

I'm trying to build an app for android (school project (technology)), however,
I'm keep getting an error and searching on the internet, gave no answer. So I'm hereby asking in here.
I got an MySQL 5.6 Server up and running, it works. PHP standalone and Xampp for file directory, and everything works fine in browser. The error occurs on the the arrow sign and exception error is about access (I think). I can upload the PHP files if needed.
The first one is a button, the second is an event fired when download is complete.
private void LoginButton_Click(object sender, EventArgs e)
{
TextView userName = FindViewById<TextView>(Resource.Id.editTextUsername);
TextView userPass = FindViewById<TextView>(Resource.Id.editTextPassword);
client = new WebClient();
url = new Uri(#"http://127.0.0.1/memento/accountcheck.php");
//url = new Uri(#"http://127.0.0.1/memento/phpinfo.php");
/*
NameValueCollection parameters = new NameValueCollection();
parameters.Add("Username", userName.Text);
parameters.Add("Password", userPass.Text);
*/
client.DownloadDataCompleted += Client_DownloadDataCompleted;
client.DownloadDataAsync(url);
}
private void Client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
Console.WriteLine(e.Result); // <------
}
EDIT:
Unhandled Exception: System.Reflection.TargetInvocationException: An exception occurred during the operation, making the result invalid. Check InnerException for exception details.
Exception Settings: C++ Exceptions, Common Language Runtime Exceptions, JavaScript Runtime Exceptions, Managed Debugging Assistants & Win32 Exceptions.
Each contain tons of check checkboxes except JavaScript. It contains one "0x80070005 Access is denied".

.net web forms application gives "Object reference not set to an instance of an object" for some users on chrome

I made a web application, and tested it locally. Everything worked fine so it was deployed to the hosting server.
After a few weeks some of the users started to experience the "Object reference not set to an instance of an object" error.
This is currently happening only in the chrome browser(on other browsers the application starts normally for them), and also if they use the incognito mode in chrome the application is opening normally.
Here is the whole error message, unfortunately i didn't get the line in code where the error is, even though i used
Server Error in '/' Application.
Object reference not set to an instance of an object.
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.NullReferenceException: Object reference not set to an instance of an object.
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:
[NullReferenceException: Object reference not set to an instance of an object.]
INAWebAppTest.SiteMaster.Page_Load(Object sender, EventArgs e) +884
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
System.Web.UI.Control.OnLoad(EventArgs e) +92
System.Web.UI.Control.LoadRecursive() +54
System.Web.UI.Control.LoadRecursive() +145
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
I don't know if this can be because of a newer version of application being deployed on the server, in combination with the users cookies?
If so, can You please advise what i could try to correct this issue. I can't ask all of the users to clean up their browser history and cookies, there are too many of them, and it wouldn't solve this issue if it happened again in the future.
Here is the code from the site master:
public partial class SiteLogin : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.Cookies["userInfo"] != null)
{
Response.Cookies.Set(Request.Cookies["userInfo"]);
Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString();
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(7);
if (Server.HtmlEncode(Request.Cookies["userInfo"]["userName"]) == null)
{
Response.Redirect("~/Account/login.aspx");
}
if (Server.HtmlEncode(Request.Cookies["userInfo"]["role"]).Equals("3"))
Response.Redirect("~/Form/Progress.aspx");
if (Server.HtmlEncode(Request.Cookies["userInfo"]["role"]).Equals("2"))
Response.Redirect("~/CForm/CHome.aspx");
if (Server.HtmlEncode(Request.Cookies["userInfo"]["role"]).Equals("1"))
Response.Redirect("~/AForm/AHome.aspx");
}
}
}
}
Here is the code from global.asax page:
protected void Session_Start(object sender, EventArgs e)
{
string sessionId;
if (Session.SessionID!=null)
sessionId = Session.SessionID;
else
{
SmtpClient client = new SmtpClient();
client.Port = xxx;
client.Host = "xxx.xxx.xxx.xxx";
client.EnableSsl = false;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("");
MailMessage mm = new MailMessage();
mm.From = new MailAddress("xxx", "xxx");
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
mm.Subject = "Null object";
mm.IsBodyHtml = true;
mm.To.Add("xxx");
string body = "null";
mm.Body = body;
try
{
client.Send(mm);
}
catch
{
}
}
In the first version of the application the global.asax was empty, but there were some problems with session being flushed, so I googled and found that the solution is this line of code:
string sessionId = Session.SessionID;
This fixed that issue, but since some users were having the problem mentioned in this subject, i added some code around so that i get a message if the session variable isn't found. I never received this mail, so i don't think the problem is there.
Thank You for the help!
We don't really have enough information to tell you exactly what went wrong, all I can tell from the trace you've included is that the exception is being thrown in your master page's Page_Load method.
Take a look through this method and check for any point where you access properties of an object without checking that the object exists. Common culprits in my experience are pulling things out of the session or cookies collection and trying to use them without checking that you didn't just pull a null value out. The best way to fix it would be if you could replicate this problem yourself by using chrome and stepping through the Page_Load method.
EDIT: After seeing your posted source, I don't see anything that immediately stands out as breaking chrome compatibility, you have some weird cookie logic imo but nothing breaking. My only suggestion would be for you to try to replicate this further, and add more logging into your solution so that when your users hit this exception you can get more information.
One technique I've used in the past was to deploy the site in debug mode with all the .pdb files in place, and use something like this:
var stack = new StackTrace(exception, true);
// Get the top stack frame
var frame = st.GetFrame(0);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
then log that value. It should give you the line number that the exception was thrown on, although as I said nothing in your code stands out as being wrong to me, so I'm not totally sure.

ASP.NET getting the URL of a redirect after interacting with a login prompt

I'm trying to scrape the URL from an IE browser control after completing Facebook login. The problem arises when I try to detect the redirect after the login. I'm using the Response.Redirect(Url,false) function, but that simply allows me to interact with the page before it loads but not afterward.
How do I detect the redirect after the page has loaded (triggered at end of log in process) when no response object is available in the Page_Unload function? I'm stuck.
The lifecycle doc doesn't mention any state after unload which is exactly when I have to scrape the URL. I've tried using IsPostBack however the code never reaches this point until after I've closed the window. Any help is greatly appreciated.
System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\Users\user_name\LogUnLoad.txt");
System.IO.StreamWriter errorfile = new System.IO.StreamWriter(#"C:\Users\user_name\LogUnLoadError.txt");
try
{
base.OnUnload(e);
if (Page.IsPostBack)
{
file.Write("\r\n This branch does not get executed. Neither does this");
}
}
catch( Exception ex)
{
errorfile.Write("Page_Unload \r\n\t Error Message \r\n\t\t:"+ex.Message +"\r\n\t Stack Trace: \r\n\t"+ex.StackTrace);
errorfile.Close();
file.Close();
}
source for page lifcycle: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.85).aspx
Update: I'm the Global.asax file suggested here .
I thought asking for the previous URL before close would be the solution but no dice.
Just in case someone likes to skip over the comments I'll put this here.
If you check the HttpRequest.UrlReferrer you can get the URL of the previous page. This can be used to check for redirects.

Weird Error screen in ASP.net Application

I am working on some ASP.NET Application. In case of some breakdown or error, I am getting some weird error screen. The error page shows something like:
��`I�%&/m�{J�J��t��`$ؐ#�������iG#)�*��eVe]f#�흼��{����{����;�N'���?
\fdl��J�ɞ!���?~|?"��Ey�')=��y6�����h��贮
�:�V�˼n��E:��,m�Wy�����<�ӶJ�e;~|W^�`4�u�A:�f��/>
and so on....
The application is currently in test phase so, I have left the error screen visible from web.config. Anyone who have faced the same issue, and got the problem and solution for it?
Check out whether the ASP.NET application you are working on utilizes some form of automatic GZip compression, your error page is very reminiscent of what Rick Strahl describes here: http://www.west-wind.com/weblog/posts/2011/May/02/ASPNET-GZip-Encoding-Caveats. There is also a solution in that blog post.
Thanks to Rick Strahl for the solution, and #Andrew Sklyarevsky for referring :D
Reference and Complete Description: http://www.west-wind.com/weblog/posts/2011/May/02/ASPNET-GZip-Encoding-Caveats
I solved the issue, and thus the solution, is adding following codes to Global.asax:
protected void Application_Error(object sender, EventArgs e)
{
// Remove any special filtering especially GZip filtering
Response.Filter = null;
…
}
Or even better
protected void Application_PreSendRequestHeaders()
{
// ensure that if GZip/Deflate Encoding is applied that headers are set
// also works when error occurs if filters are still active
HttpResponse response = HttpContext.Current.Response;
if (response.Filter is GZipStream && response.Headers["Content-encoding"] != "gzip")
response.AppendHeader("Content-encoding", "gzip");
else if (response.Filter is DeflateStream && response.Headers["Content-encoding"] != "deflate")
response.AppendHeader("Content-encoding", "deflate");
}

Categories