Weird Error screen in ASP.net Application - c#

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");
}

Related

Object Reference Error when Debugging Webpage

I'm having issues with a piece of code for a website in C# and when I debug it, it opens the site (localhost in Chrome. Every page works except the one I'm debugging, regardless of whether or not that's the page I'm debugging. Whenever I try to open it, it gives me an Object Reference error at the line I've marked below. This happens no matter which browser I use.
Protected void page_load (object sender, EventArgs e)
{
DateTime dteNow = SI.Getsource.DAL.Time.Now.Eastern();
If(!IsPostBack)
{
txtStartDate.SelectDate = dteNow.AddDays(-2)
txtEndDate.SelectedDate = dtenow.AddDays(1)
txtStartDate.Visible = False
txtEndDate.Visible = False
Shipping.DataTable.dt = SI.Getsource.DAL.EquipmentDB.getPrinter();
ddlPrinter.DataSource = dt.Result
ddlPrinter.DataTextField = dt.Result.Columns["Name"] //Error is here
ddlPrinter.DataValueField = dt.Result.Columns["PrinterID"]
ddlPrinter.DataBind();
Try
{
ddlPrinter.SelectedValue = System.Web.Configuration.WebConfigurationManager.AppSettings["DefaultPrinterID"]
}
Catch
}
}
I've tried running it in IE and Firefox. I also tried adding a try-catch for "Name" similar to the one for "Printer" but that didn't do anything. Any suggestions would be greatly appreciated, since this error prevents me from debugging the actual issue.
Edit: I'm using Visual Studio 2015. Also, this only happens when I run the page locally, ie. When debugging.
Set a breakpoint on the line giving you the error, then add dt.Result to the Watch window to examine its value when the execution breaks on this line. It could be that dt.Result is null.
edit: Also, I think you only need to specify the field name for .DataTextField and .DataValueField.
As it turns out, it was an issue with memory. Once I took care of that, it worked.

"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.

ASP.NET 4.5 ViewState not available

I already searched on many Websites but I found no solution :-(
I want to use the ViewState after the Postback (after clicking on a Image link).
my PageLoad:
protected void Page_Load(object sender, EventArgs e)
{
...
if (!IsPostBack && !IsCallback)
{
pivotPlan.DataSource = Keys.ToList();
ViewState["pivotPlan"] = pivotPlan.DataSource;
}
else
{
pivotPlan.DataSource = ViewState["pivotPlan"];
}
}
The strange Thing is that the ViewState is null when I step through the code and the Debugger reaches the masterpage. I enabled the ViewState in the masterpage, but when I click on the imagebutton I will get this error:
Server Error in '/' Application.
The state information is invalid for this page and might be corrupted.
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.Web.HttpException: The state information is
invalid for this page and might be corrupted.
Source Error:
[No relevant source lines]
Source File: c:\Users\neunin\AppData\Local\Temp\Temporary ASP.NET
Files\root\7b4d9801\69af7fa1\App_Web_2nxwrvxv.1.cs Line: 0
I really don't have a clue what the Problem is :(
Maybe anybody can help me?
Thank you very much in advance! :-)
Regards,
Nina
That source file looks suspicious to me. If you created a new ASP.NET website, tried adding some basic info to ViewState, and then retrieving it, does it work? I'm wondering if you should delete all ASP.NET temp files and try compiling\running the app again, check out this answer: ASP.NET Temporary files cleanup
Hope this helps, and welcome to SO :)

Can I detect if content has been compressed in my HttpModule?

I have an HttpModule which is used to dynamically compress content from an ASP.NET (MVC3) web application. The approach is very similar to the CompressionModule in this article (where the module applies a GZip filter to the HttpResponse and sets the correct Content-encoding header).
For one reason and another, this needs to run in classic mode, not integrated pipeline mode.
The problem I've got, is that on some servers that have IIS compression enabled, IIS compresses the content and then my module compresses that.
The upshot is that I get content compressed twice, with an encoding:
Content-encoding: gzip,gzip
one from IIS, and one from this line in my code:
httpResponse.AppendHeader("Content-encoding", "gzip");
Does anyone know a way, in classic mode, that I can check to see if the content is already compressed, or if compression is enabled on the server, in order to bypass my own compression?
In pipeline mode, this check is as simple as
if (httpResponse.Headers["Content-encoding"]!= null)
{
return;
}
i.e. check if anything has already set a content-encoding and if so, do nothing.
However, I'm stumped in classic mode. Unfortunately, accessing HttpResponse.Headers is not allowed in classic mode, so I can't do my barrier check.
All ideas gratefully received.
Theoretically, you can use reflection to peek into HttpRequest._cacheHeaders field, where ASP.NET apparently stores all yet-to-be sent headers in classic mode:
if (this._wr is IIS7WorkerRequest)
{
this.Headers.Add(HttpResponseHeader.MaybeEncodeHeader(name), HttpResponseHeader.MaybeEncodeHeader(value));
}
else if (flag)
{
if (this._cacheHeaders == null)
{
this._cacheHeaders = new ArrayList();
}
this._cacheHeaders.Add(new HttpResponseHeader(knownResponseHeaderIndex, value));
}
I found a relatively easy way to check if the output is already compressed or not; my approach works even with IIS running in classic mode and although it may be considered a "hack" I found it to be working quite consistently; the idea is more or less the following
// checks if the response is already compressed
private bool IsResponseCompressed(HttpApplication app)
{
string filter = app.Response.Filter.ToString().ToLower();
if (filter.Contains("gzip") | filter.Contains("deflate"))
{
return true;
}
return false;
}
basically the code works by checking the response filter name; if the output stream is compressed the name contains "gzip" or "deflate" so it's easy to check for compression

What can cause Application_Error not to be invoked?

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();

Categories