Timeout error in ASP.NET mvc - c#

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

Related

An unexpected error occurred on a receive. WebRequest already overriden

I never thought I have to ask a question here, but I am at my wit's end.
We try contact a server and receive XML Data via SOAP from there. Regulary it's running fine, but sometimes and without any hint why, we've got the the following error:
Translated from german:
The underlying connection was closed: An unexpected error occurred on a
receive.
So I looked for possible reasons. And I overrode the WebRequest Method.
public class MyHttpClientProtocol : SoapHttpClientProtocol
{
protected override WebRequest GetWebRequest(Uri uri)
{
HttpWebRequest webRequest = (HttpWebRequest) base.GetWebRequest(uri);
//Setting KeepAlive to false
webRequest.KeepAlive = false;
return webRequest;
}
}
First of all? - Is this correct or did I chose the wrong base class?
I am not sure at all, but I use SoapHttpClientProtocoll in my service, but in the Request Header (used Fiddler) the "Connection" stills "keep-alive".
The error is rare but it occours and if it does, it does it for a longer time.
So I tried to debug the problem. And if I do and I've got the error he repeats to try the delegate:
ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };
I can't jump in. VS 2010 does not support it.
I am working with X509Certificate2.
Please give me an idea.. I can't see the solution.

How do I specify a global HttpWebRequest timeout?

I'm using a twitter library that uses HttpWebRequest internally to make requests to the twitter API. For some odd reason, the requests sometimes take a lot of time to complete (~10 minutes).
The HttpWebRequest object is not exposed by the library.
Is there any way to specify a global timeout and readwritetimeout for the requests, perhaps via app.config?
Unfortunately not currently possible. The constructor of HttpWebRequest has this value hardcoded - reference source.
That timeout is in milliseconds - so 2000ms = only 2 seconds.
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("URL");
req.Timeout = Convert.ToInt32(ConfigurationManager.AppSettings["timeOut"]);
Req.ReadWriteTimeout = Convert.ToInt32(ConfigurationManager.AppSettings["readWriteTimeout "]);
App.config
<appSettings>
<add key="timeOut" value="200" />
<add key="readWriteTimeout " value="10000" />
</appSettings>
Timeout = time spent trying to establish a connection (not including lookup time)
ReadWriteTimeout = time spent trying to read or write data after connection established

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

UpdatePanel Postback Error: Sys.WebForms.PageRequestManagerParserErrorException

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.

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