UpdatePanel Postback Error: Sys.WebForms.PageRequestManagerParserErrorException - c#

Already looked at this:
Sys.WebForms.PageRequestManagerParserErrorException - what it is and how to avoid it
Problem is that it's only happening on my dev box. Two other developers are fine.
It's consistent and reproducible - I've tried deleting temporary internet files, deleted my obj and bin files and rebooting.
The response is clearly truncated when I look at it in the debugger when it hits the error.
Where else do I need to check to clear/clean out?
The error I'm seeing in the code is:
Microsoft JScript runtime error:
Sys.WebForms.PageRequestManagerParserErrorException: The message
received from the server could not be parsed. Common causes for this
error are when the response is modified by calls to Response.Write(),
response filters, HttpModules, or server trace is enabled. Details:
Error parsing near ' </tr>
'.
_endPostBack: function PageRequestManager$_endPostBack(error, executor, data) {
if (this._request === executor.get_webRequest()) {
this._processingRequest = false;
this._additionalInput = null;
this._request = null;
}
var eventArgs = new Sys.WebForms.EndRequestEventArgs(error, data ? data.dataItems : {}, executor);
Sys.Observer.raiseEvent(this, "endRequest", eventArgs);
if (error && !eventArgs.get_errorHandled()) {
throw error; // THIS IS WHERE THE ERROR IS THROWN
}
},
This is during an Ajax postback.
There are no Response.Write calls.
I'm using Cassini/VS 2010 Development Server, how do I tell if there are filters?
ditto
Server trace is not enabled
No calls to Server.Transfer
In firebug, I can see that the response to the POST is truncated. Problem happens in Firefox or IE, and whether I'm debugging in VS or not.
The problem does go away if I switch to IIS Express in Visual Studio, and then it returns when I am back on the ASP.NET Development Server.

I have seen this problem before with Cassini. I solved it by adding the following to the Web.config:
<system.web>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>
The entry above is for version 1.0. Make sure that the Version and PublickKeyToken attributes match the ASP.net Ajax version that you are using. Also you may want to disable event validation in your page:
enableEventValidation="false"
Hope it helps!

After our talk, my idea was that maybe for some reason the cassini can not hold a big post back field, and a big one is the viewstate.
So if the viewstate is a very big one maybe this is the problem.
A second case maybe if the viewstate contain characters that some time not pass by the router or some firewall and cut them as possible attach or virus.
Possible solutions: To compress the viewstate, and/or to cut it in smaller parts.
You can also download the latest developer edition version of Cassini with lot of improvements at http://cassinidev.codeplex.com/ that maybe have fix this issue.

Are you using some kind of http module compression? It seems to cause problems very much like yours when using updatepanels. Please review this post.
If you are not ussing compression, maybe another httpmodule related error is making you suffer. Try adding this to your webpage:
enableEventValidation="false"
Maybe you could catch the exception with this kind of code:
protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
{
ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Message+e.Exception.StackTrace ;
}
<asp:ScriptManager ID="ScriptManager1" runat="server"
OnAsyncPostBackError="ScriptManager1_AsyncPostBackError">
</asp:ScriptManager>
Source for that last thing.

Error:
Sys.WebForms.PageRequestManagerServerErrorException: Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 500
solution:
<add key="aspnet:MaxHttpCollectionKeys" value="100000"/ >
Add above key in app setting section.

Related

Timeout error in ASP.NET mvc

I am facing a weird issue, I am running Quartz jobs to fetch data from 2 different URL, but getting timeout error on one, another is working just fine. The inner exception of error that I get says 'The operation has timed out'.
One more interesting thing is that I am not getting this error on my local system, on my local, both the jobs are fetching data correctly, but on server one fails.
I also spoke to the team of the website from which I am fetching data, they told me that their configuration for both urls are same, so there is no issue at their end.
I have made some changes in my webconfig file while trying to fix this issue by reading online, but no luck yet.
I have added this line in the appSettings tag in web.config
<add key="SqlCommandTimeOut" value="10000000" />
My connection string looks like:
<add name="xyzDBEntities" connectionString="metadata=res://*/xyzDB.csdl|res://*/xyzDBEntities.ssdl|res://*/xyzDBEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=SQL1234.xyzsite.com;initial catalog=xyzDB;User Id=xyzDB_admin;Password=xyzpassword;App=EntityFramework"" providerName="System.Data.EntityClient" />
It would be great if someone can help me in sorting this out. Please let me know if more details are needed. Thanks!
Extending WebClient class and overriding GetWebRequest() by setting timeout to 1 minute resolved my issue.
public class CustomWebClient : WebClient{
protected override WebRequest GetWebRequest(Uri address){
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
request.Timeout = 60000; //1 minute timeout
return request;
}
}

Setting StatusCode in error.aspx triggers another Page_Load()

In web.config, the error page is set to /errorpages/error.aspx
<httpErrors errorMode="Custom" existingResponse="Replace" >
<remove statusCode="500" subStatusCode="-1" />
<error statusCode="500" path="/errorpages/error.aspx" responseMode="ExecuteURL" />
</httpErrors>
But when the page /errorpages/error.aspx is loaded in the browser, the status code is 200. This results in various problems, like the fact that when I have a JS file that's in the wrong URL, instead of getting a specific error, I get a JS error like unexpected < (same logic is used for 404.aspx page).
So, to fix this, inside error.aspx, in Page_Load(), I set
Response.StatusCode = 500;
and the page is returned with 500 status code, which can be observed in the browser.
The problem is that if I place a breakpoint inside Page_Load() in /errorpages/error.aspx, it is being hit twice. First time it enters the StatusCode is 200, it sets it to 500, so my suspicion is that IIS tries to handle that from web.config, it loads the page again. And again the StatusCode is 200, and changes to 500, but this time it doesn't trigger another execution.
This is probably caused by the fact that the exceptions are being handled in Global.asax.cs, where after handling, this is executed:
Server.TransferRequest("/errorpages/error.aspx?someExceptionInfo=" + exceptionInfo);
So this diagram shows what I think is happening:
I could just set a status code instead of calling TransferRequest, and let IIS handle it, and pass the exception info via the Session. But I'm worried that at some point it might cause some kind of redirect loop or something on Production servers.
Question (one of them):
How do I ensure I won't get a redirect loop?
How do I configure IIS to make error pages return a status code without actually writing Response.StatusCode = ***?
How do I impede my application from repeating execution of the page when I set the StatusCode?

IIS & Chrome: failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING

I recently came across a Chrome issue which I think is worth sharing it with you.
I worked on a self written API using an HttpHandler which primary should return json data. But when an error occures I wanted to display an html file. That worked pretty well in IE and FF, but not in Chrome.
Looking to the developer tools revealed this error: net::ERR_INCOMPLETE_CHUNKED_ENCODING
Google said not very much about this issue while it was seen very much. All I got to know was, that it was magically disappearing after some time.
I found out it lays on this lines of code:
result.StoreResult(context);
context.Response.Flush();
context.Response.Close(); //<-- this causes the error
After removing the last line it worked well. I donĀ“t know why only Chrome had/has an issue with that, but it seemed as if I closed the response stream before chrome finished reading it.
I hope it helps those of you coming across the same or a similar issue.
Now my question:
How is the best pratice in closing/flushing the response stream? Are there any rules?
According to ASP.NET sets the transfer encoding as chunked on premature flushing the Response:
ASP.NET transfers the data to the client in chunked encoding (Transfer-Encoding: chunked), if you prematurely flush the Response stream for the Http request and the Content-Length header for the Response is not explicitly set by you.
Solution: You need to explicitly set the Content-Length header for the Response to prevent ASP.NET from chunking the response on flushing.
Here's the C# code that I used for preventing ASP.NET from chunking the response by setting the required header:
protected void writeJsonData (string s) {
HttpContext context=this.Context;
HttpResponse response=context.Response;
context.Response.ContentType = "text/json";
byte[] b = response.ContentEncoding.GetBytes(s);
response.AddHeader("Content-Length", b.Length.ToString());
response.BinaryWrite(b);
try
{
this.Context.Response.Flush();
this.Context.Response.Close();
}
catch (Exception) { }
}
I was running into this error when generating a file and pushing it to the user for download, but only occasionally. When it didn't fail, the file was consistently 2 bytes short. Close() forcibly closes the connection, whether it's finished or not, and in my case it was not. Leaving it out, as suggested in the question, meant the resulting file contained both the generated content as well as the HTML for the entire page.
The solution here was replacing
context.Response.Flush();
context.Response.Close();
with
context.Response.End();
which does the same, but without cutting the transaction short.
In my case, the problem was cache-related and was happening when doing a CORS request.
Forcing the response header Cache-Control to no-cache resolved my issue:
[ using Symfony HttpFoundation component ]
<?php
$response->headers->add(array(
'Cache-Control' => 'no-cache'
));
I was also getting same error. This issue was with web server user permission on cache folder.
On the offchance that someone is landing here as a result of issues with their ASP.net Core project, I was able to resolve by adding the IIS middleware.
This is done by adding UseIISIntegration when instantiating your webhost instance.
Once I had the same problem and the main reason was lying in my controller return type.
If you try to return a C# object just as-is, you will only get net::ERR_INCOMPLETE_CHUNKED_ENCODING so don't forget to serialize your complex objects before sending them out for java script client (or View).
i.e. my controller return type was :
public async Task<List<ComplexModel>> GetComplexModelList(){
return new List<ComplexModel>()
}
Which caused INCOMPLETE_CHUNKED_ENCODING error, so I tried to fix my mistake with something like:
using Newtonsoft.Json;
...
public async Task<string> GetComplexModelList(){
return JsonConvert.SerializeObject(new List<ComplexModel>())
}

ASP.NET MVC URL Parameters Double Escaped?

I've got a text area that contains HTML. I expect the content to be escaped when posted to the controller method but I'm finding it is escaped twice. What could possibly cause this? See the example below:
Pulled from request:
&lt;b&gt;test&lt;/b&gt;
WebUtility.HtmlDecode 1st time:
<b>test</b>
WebUtility.HtmlDecode 2nd time:
<b>test</b>
I'm no expert when it comes to web development but I've got about 2 years of experience. This is the first time I've seen anything like this. I've attempted adding the following sections to my Web.config with no luck:
<pages validateRequest="false" />
<httpRuntime requestValidationMode="2.0" /
<security>
<requestFiltering allowDoubleEscaping="false" />
</security>
Please let me know if I can provide more information.
It turns out the problem lay in the textarea itself. In the view it was just a standard textarea, but in Javascript document.Ready was then made to be a kendoEditor. The kendoEditor was encoding the HTML first, then ASP.net was applying its standard encoding as well. Setting the attribute encoded equal to false fixed the issue:
$("#editor").kendoEditor({
encoded: false
});
Update:
I found later that setting the encoded attribute to false would introduce another problem. On submit I received a "A potentially dangerous Request.Form value was detected from the client" error when using formatting tools from the built-in KendoEditor toolbar. My solution was to double-decode the posted request:
WebUtility.HtmlDecode(WebUtility.HtmlDecode(Request["value"]));

Silverlight 3 WCF Service `CommunicationException` Server returned error: NotFound

I have a Silverlight 3 application, which 95% of the time is successfully requesting data from a WCF Service (in the same webapp) and displaying it.
This happens infrequently, usually if I hit the service a bunch of times quickly, but sometimes it'll happen on a single lone request.
Every once in a while, if I request a lot of transactions in a short period, I get one of two exceptions, they both occure in the Reference.cs file in the EndMyMethod(System.IAsyncResult result).
There are a few methods, and the exceptions occure on any number of them. The first one, is a TimeoutException() which I understand and it makes sense, the second one, which I totally don't get is the "CommunicationException() was unhandled by user code: The remote server returned an error: NotFound."
I've put try..catch blocks both arround the .MyMethodAsync() and in the handler for MyMethodCompleted both to no avail, as the exception occurs in the generated Reference.cs file.
Any help is greatly appreciated.
update
Reference.cs -- generated by "Add Service Reference"
public System.IAsyncResult BeginTogglePicked(string ID, string toggle, System.AsyncCallback callback, object asyncState)
{
object[] _args = new object[2];
_args[0] = ID;
_args[1] = toggle;
System.IAsyncResult _result = base.BeginInvoke("TogglePicked", _args, callback, asyncState);
return _result;
}
public void EndTogglePicked(System.IAsyncResult result)
{
object[] _args = new object[0];
// This is the line where the Exception is Thrown
base.EndInvoke("TogglePicked", _args, result);
}
Calling Code -- pickedIDs is a list of Strings, and userIDSelecting is a string defined at the top of the procedure. The Event Handler mdc_TogglePIckedCompleted is empty at the moment.
MapDataClient mdc = new MyDataClient();
mdc.TogglePickedCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(mdc_TogglePickedCompleted);
foreach (string id in pickedIDs)
{
mdc.TogglePickedAsync(id, userIDSelecting, mdc);
}
Update 2
This is the "InnerException" from the CommunicationException: System.Net.WebException: The remote server returned an error: NotFound.
Not sure if this is any more helpful, since it doesn't give any extra details. As I said, this happens intermitently not every time I call a service method. I'd also like to point out that the same call will work sometimes and not others, I'm starting to think this issue is because IIS is failing to respond to my service calls, thoughts?
Update 3
When I mean intermiently, I mean truel intrmitent. This may only occur a single time in a user's session, and it may only occur on one of fifty sessions. Its not an all-or-nothing sitation. The calling application is hosted within the same "webite" as the WCF Service, so I don't think a clintaccesspolicy.xml is the issue, but I could be wrong.
The message that you are getting are probably a red herring :-(
When internal WCF service exceptions are thrown, these will ALWAYS manifest themselves as Server Not Found exceptions in the Silverlight UI. This is because the HTTP response is of type 500. The best article I read on this was from David Betz - http://www.netfxharmonics.com/2008/11/Understanding-WCF-Services-in-Silverlight-2 (this was written for SL2, but the concepts still holds for SL3. Also, some of his approaches are for purists - e.g. "NEVER" using the Add Service Reference features from VS - you don't have to follow all his advice ;-) )
Anyway, back to your question, you need to convert the response type to 200 and parse the exception in the message. This can be done using a MessageInspector (in the service and SL app).
There are quite a few articles on how
to do this on the net:
http://www.liquidjelly.co.uk/supersearch/?q=silverlight%20messageinspector&lang=en-GB.
A working example can be downloaded
from CodePlex:
http://code.msdn.microsoft.com/silverlightws/Release/ProjectReleases.aspx?ReleaseId=1660
(download link at the bottom of the
page "Message Inspectors")
Some of these approaches can seem quite daunting - take some time to understand this - the concept is crucial for WCF <--> SL applications, and it makes sense once you get it :-)
We've used this with a lot of success since the start of the year, so if you need anymore help with this just let me know.
Can I recommend always, always having Fiddler running when you are working with Silverlight and WCF?
Is your service returning exception details to the client? By default it does not. You could add the following attribute to your service class.
[ServiceBehavior(IncludeExceptionDetailInFaults=true)]
public class MyService ...
You may find you're getting some kind of server-side exception that is not visible to the client.
Make sure you have a clientaccesspolicy.xml file. Otherwise you may get that error cause the policy file cannot be found.
I had exactly the same problem as you - absolute nightmare, it would work sometimes and then just stop.
After reading your post earlier I kept looking for clientaccesspolicy info and found this (can't remember where), but I use it and it now works fine!
Hope the same is good for you :) My file was missing the extra detail on the allow-from section.
<?xml version="1.0" encoding="utf-8" ?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="http://*" />
<domain uri="https://*" />
</allow-from>
<grant-to>
<resource include-subpaths="true" path="/"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>

Categories