The remote host closed the connection. The error code is 0x80070057 - asp.net

I'm getting a lot of these error messages in my logs on one of my servers and intermittently on two others.
Googling didn't reveal very much information, mostly related to file uploads or downloads being interrupted.
My pages are basically just text files with "ok" in them that only have .aspx extension for future plans, there's no actual code powering the pages. Servers are all Windows Server 2008 RC2 x64 running IIS7 / ASP.NET 4.
Statistically it's happening well under 1% of the time but because of the volume of traffic that still clutters my event log with 2 or 3 of these messages per minute.
Edit:
I tracked down the problem, setting buffering to true stopped it occurring.

I know this has been answered, but on the off chance this helps someone else, it happened in my MVC project sometimes when I had one dbContext set at the top of a repository. When I switched to a using statement for database connections, the error never appeared again.
So, I went from this at the top of each repository:
DbContext db = new DbContext();
To this for each individual connection:
using (DbContext db = new DbContext())
{
//db connection stuff here....
}
Worth saying that no one ever reported seeing the error and no error was ever shown to the browser, but nice to get it off the logs all the same!

Are you returning a Stream?
You might need to close it after the method finishes.
Check out this: Closing Returned Streams in WCF
Here is the code this blog suggests:
public Stream GetFile(string path)
{
Stream fileStream = null;
try
{
fileStream = File.OpenRead(path);
}
catch(Exception)
{
return null;
}
OperationContext clientContext = OperationContext.Current;
clientContext.OperationCompleted +=
new EventHandler(delegate(object sender, EventArgs args)
{
if (fileStream != null) fileStream.Dispose();
});
return fileStream;
}

Related

Creating a new MobileServiceClient() freezes VS and Android app

Working on a Xamarin Forms app (Android & iOS)
When trying to create my connection to an easy table I have in an Azure Mobile App my Visual Studio Freezes for around 7 seconds and then when it comes back it has exited the code and the Android app, running in debug is permanently frozen.
When stepping through the code it steps over
client = new MobileServiceClient(appUrl);
and then when it hits the next line it freezes. But it doesn't matter what the next line is. I have put many different things after and it still freezes. Also, this is in a try/catch block, yet no exception is thrown.
I also wanted to see if the problem was server side. But both Post and Get with PostMan works fine. So I think my server is fine. Not completely sure though...
Here is some of the code:
public class ChatStorageAzureService : IChatStorageAzureService
{
public MobileServiceClient client { get; set; }
private IMobileServiceSyncTable<MessageViewModel> chatTable;
public static bool UseAuth { get; set; } = false;
private static ChatStorageAzureService instance;
public static ChatStorageAzureService Instance => instance ?? (instance = new ChatStorageAzureService());
public async Task InitializeAsync()
{
if (client?.SyncContext?.IsInitialized ?? false)
return;
var appUrl = "http://"MY-WEBSITE".azurewebsites.net/";
try
{
client = new MobileServiceClient(appUrl);
var path = "syncstore.db";
var store = new MobileServiceSQLiteStore(path);
store.DefineTable<MessageViewModel>();
await client.SyncContext.InitializeAsync(store);
chatTable = client.GetSyncTable<MessageViewModel>();
}
catch (Exception e)
{
Debug.WriteLine("Exception thrown in Initialize: " + e);
throw;
}
}
The InitializeAsync has been called in Async methods. It has been called with .Wait() method in a constructor. It has been called with button presses or in page creations. I have tried a ton of different ways to call. But it always freezes.
One thing that I think is weird is that my server code, is one project containing both the SignalR hub code and the Easy Table, yet you access them through different web addresses, For example
"http://"SignalR".azurewebsites.net/"
and
"http://"EasyTable".azurewebsites.net/"
Again PostMan is able to access both the tables and the SignalR and the SignalR works on the Android project. But I dont know if having to domains is bad. I am new... if you could not tell already, lol!
I followed this Tutorial for the Easy Table integration and when I did it in a separate project it worked fine. I am trying to integrate it into my actual project and that is where I am having all these problems.
I also turned on debugging with Azure and it doesnt seem like my app ever even reaches the service. No call is ever met. I think. But again I am new to debugging with Azure, so I might not know how to do it right. I followed this Tutorial for setting up Azure debugging
Thanks for any and all help!
Your path is incorrect. It needs to be a directory path, for example on iOS it is /<AppHome>/Library/<YourAppName>/syncstore.db.
We can leverage MobileServiceClient.DefaultDatabasePath to get the default database path in a cross-platform manner.
var path = Path.Combine(MobileServiceClient.DefaultDatabasePath, "syncstore.db");
Feel free to reference this Xamarin.Forms Sample App that uses Azure Mobile Service Client:
https://github.com/brminnick/UITestSampleApp/blob/master/Src/UITestSampleApp/Services/AzureService.cs
So I finally got it to work!!! "How?" you ask. I went on 2 week vacation, came back, started a again. Copied the new URL of the tut project into my actual project, did some testing. And then this is the big thing, I then put the same address I had been using back into my app, and... it just worked.... I did NOTHING to the code, and now it seems to work... So almost a month of work time lost and all I had to do was just put a different URL in, run it, and then put the original URL back in.... Lovely. I am guessing it cleared out some weird temp file that was messing up the program or something... even though I erased the temp files countless times... I don't get it, but onward I go!

Pre-Load Web Application Pages After Deployment to Prevent Slow Loading

We build and deploy our web application to our dev environment automatically every night (using VSTS). When we come into the office in the morning, the first person to access the application has to wait an extended period for each page to load the first time. Subsequent loads are very fast.
The problem has a greater impact in our live environment where, after a deployment, it is potentially an end-user who is the first person to access the application and complain of slowness. To mitigate for this, a member of the team is currently accessing every page of the application manually after deployment to the live environment so that they 'pre-load' every page, which works, but is obviously time-consuming!
I've done a fair bit of searching on the subject, and have configured the appropriate Application Pool in our IIS server (IIS 8.5) so that its Start Mode is set to "AlwaysRunning". I've also edited our applicationHost file and set the appropriate Sites with the preloadEnabled="true" attribute. I did this after reading the instructions in this very helpful Microsoft documentation.
However, if I'm reading that documentation correctly, any pre-loading of the website which might alleviate the issue we're having (and I'm not even certain that this is the kind of pre-loading that I'm thinking of) only takes place when the server, the IIS service of the Application Pool are restarted. This isn't happening in our case. We need the pre-loading to take place following a deployment of the application to the IIS server.
Is there a way to automate this pre-loading?
One way of doing this would be to perform a HTTP request automatically:
As soon as the app was deployed (by running a task from the deploying machine)
Before the application pool has the chance to shut itself down (using Task Scheduler for instance)
Personally, I use a tool that is run in both cases to keep the site warmed up.
Advantages
Robust control over how and when this warm-up is executed.
It's completely independent from any IIS or web.config setup.
Disadvantages
Generates "bogus" log information.
Keeps the app permanently in memory (the Pool would never time-out, essentially wasting server resources for sites with a low # of visitors).
Sample
Such a tool could be a simple console app written as follows:
var taskInfo = new {
Url = "http://www.a-website-to-keep-warm.url",
UseHostHeader = true,
HostHeader = "www.a-website-to-keep-warm.url",
HttpMethod = "head"
};
HttpStatusCode statusCode = HttpStatusCode.Unused;
long contentLength = 0;
try
{
Dictionary<string, string> headers = new Dictionary<string, string>();
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(taskInfo.Url);
webRequest.Method = taskInfo.HttpMethod.ToUpper();
if(taskInfo.UseHostHeader)
webRequest.Host = taskInfo.HostHeader;
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
//did we warm-up the site successfully?
statusCode = webResponse.StatusCode;
contentLength = webResponse.ContentLength;
//optionally read response headers
foreach (string header in webResponse.Headers)
{
headers.Add(header, webResponse.Headers[header]);
}
}
decimal kilobytes = Math.Round(contentLength / 1024M, 1);
Debug.WriteLine($"Got {kilobytes:F1} kB with statuscode: \"{statusCode} \" ...");
}
catch (Exception ex)
{
Debug.WriteLine($"taskInfo failed with exception: {ex.Message}");
}
In my case, I read a bunch of taskInfo objects from a json file and execute them asynchronously every X minutes, making sure X is lower than the Pool-timeout value. It is also run immediately after every deploy.
Because we're not interested in getting the entire content, it uses a HTTP HEAD request instead of GET. Lastly, it supports multiple sites on the same host by adding a Host header to the request.

struts 2 Closing network connections after result

I use network connection from a struts application to connect to a network resource and download a file directly to the browser without storing it on the struts running server (need to avoid polluting the struts server with transported files). I use the result type stream to actually download the inputstream from the network resource directly to the user's browser and the inputstream is automatically closed but the network connection that carries the stream is never returned (there is a connection pool as I use httpclient for the network connection).
is there any way anyone can see to actually get code called after the result (of type stream) is finished (file has downloaded to the browser)?
In fact this is indeed solved by an interceptor:
I have written the following in an interceptor of the Action:
public String intercept(ActionInvocation invocation) throws Exception {
try {
return invocation.invoke();
} finally {
DownloadAction da = (DownloadAction) invocation.getAction();
if (null != da && null != da.getResponse()) {
logger.debug("###### connection releasing");
da.getResponse().releaseConnection();
}else{
logger.error("###### connection cannot be released");
}
}
}
Contrary to my previous belief this actually runs only after all results are executed (stream downloaded). It turns out I had been releasing the connection way to soon so I was getting a confusing error in the logs that I thought it was because the interceptor was running too soon. I was wrong.
I hope this may one day help someone else out there.

"An existing connection was forcibly closed by the remote host" sporadic error from HttpWebRequest

I'm having an odd, sporadic problem with a simple test app (Visual Studio console application) that acts as a watchdog for a hosted aspx web site (not app) by sending it simple http requests and timing the response times. I've used this for many weeks in the past without this particular problem. At seemingly random times during the day, my http requests start failing with the above error. They appear to be timeouts since the requests that fail are all taking 60 seconds. After a period of consistent errors as per above (random time periods from a few minutes to 90 minutes in one case) the errros stop and http responses start coming back with no errors at the normal speed (usually about .25s). The watchdog client requests triggers a very simple database lookup, just 1-2 lines of code on the server side. This is hosted at a shared windows hosting web host.
I can also trigger this behavior at will by updating any .cs file on my host site, which, among other things, causes the app pool to recycle. Immediately my watchdog app starts timing out again with the above error.
It smells like some kind of recycled connection problem, since if I simply restart the watchdog app, it works fine and responses start coming back at the normal delay.
I've tried setting request.KeepAlive = false and request.ServicePoint.ConnectionLimit = 1, those did not help.
Another clue, I cannot connect with IIS manager to either of two different websites hosted on this server, which has always worked fine. I'm getting "The underlying connection was closed" trying to connect via IIS Manager. Every time. I have not updated either of the sites in a while, so it wasn't any change of mine.
This is an asp.net 4 website on the backend running on IIS7 with a dedicated app pool in integrated pipeline mode.
Also if I change the sleeptime variable in the watchdog app to something like 30 seconds, the problem doesn't show up. There's some magic number in the range of I believe 10-20 seconds where if the requests are pausing more than that, they never fail.
I think the fact that IIS Manager can't connect is good evidence that something is wrong on the host side independant of my test app but I wanted to cover my bases before opening a support incident... especially since a simple restart of my console app fixes the problem... at least for a while.
class Program
{
//make a simple web request and just return the status code
static string SendHttpMsg(string url, string postData)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
request.ContentLength = byte1.Length;
//request.KeepAlive = false; //no effect
//request.ServicePoint.ConnectionLimit = 1; //no effect
Stream requestStream = request.GetRequestStream();
requestStream.Write(byte1, 0, byte1.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Close();
return ((int)response.StatusCode).ToString();
}
static void Main(string[] args)
{
int sleeptime = 5000;
string result = "";
while (true)
{
DateTime start = DateTime.Now;
try
{
//this is a very simple call that results in a very simple, fast query in the database
result = SendHttpMsg("http://example.com/somepage.aspx", "command=test");
}
catch (Exception ex)
{
//fancy exception handling here, removed
}
DateTime end = DateTime.Now;
TimeSpan calltime = end - start;
Console.WriteLine(end.ToString() + ", " + calltime.TotalSeconds.ToString("F") + " seconds " + result);
Thread.Sleep(sleeptime);
}
}
}
You could have dangling connections, and in HTTP 1.1 you are limited to 2 connections.
Try changing the HTTP Protocol Version used in the request:
request.ProtocolVersion = HttpVersion.Version10;
If that doesn't work, it could be taking a long time to resolve the proxy settings, which can be fixed by disabling the proxy settings in your application by adding the following to the .config file:
<system.net>
<defaultProxy enabled="false">
<proxy/>
<bypasslist/>
<module/>
</defaultProxy>
</system.net>
If either of the above fixes the problem, I'd recommend adding a try...catch...finally block around your request code, to ensure that each request is properly closed and disposed of (try setting request = null in your finally statement inside the method).

Silverlight's WebClient isn't connecting to my server

I've got a problem here.
I've got an ASP.net website hosting a silverlight 2 application.
I'd like the site to communicate to and fro from the silverlight app, and I'm doing this via http requests. Incidentally, if anyone knows a better way, please do tell me.
My server's got the following http listener set up. I copied this from a tutorial site somewhere, since it's mainly experimentation at the moment :
HttpListener listener = new HttpListener ( );
listener.Prefixes.Add("http://localhost:4531/MyApp/");
listener.Start( );
// Wait for a client request:
HttpListenerContext context = listener.GetContext( );
// Respond to the request:
string msg = "You asked for: " + context.Request.RawUrl;
context.Response.ContentLength64 = Encoding.UTF8.GetByteCount (msg);
context.Response.StatusCode = (int) HttpStatusCode.OK;
using (Stream s = context.Response.OutputStream)
using (StreamWriter writer = new StreamWriter (s))
writer.Write (msg);
listener.Stop( );
I'm using the following code to send a request :
private void MyButton_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
b.Content = "Hello World";
Uri serviceUri = new Uri("http://localhost:4531/MyApp/");
WebClient downloader = new WebClient();
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(TestDownloadStoriesCompleted);
downloader.DownloadStringAsync(serviceUri);
}
void TestDownloadStoriesCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
TextBox1.Text = e.Result;
}
}
My problem is that I can connect to the webserver from a console application using pretty much the same code (I tested it by setting a breakpoint in the code), however nothing happens when I click the button in silverlight. (I've added the "Hello World" to test that I am indeed connecting the delegate to the button.)
I've read that silverlight needs policies to connect via webclient, but it shouldn't be the case if I'm using the same server and the same domain for both the server and the silverlight application!
Thanks for all your replies!
EDIT : I am recieving this exception :
System.Security.SecurityException ---> System.Security.SecurityException: Security error.
Also, based on what I'm reading apparently to be site-of-origin, the deployment URI of the xap and the request URI must also be of the same port.
However, when I set the properties for the server to be hosted on a specific port, and I set the listener to listen to that same port, it fails with the message that The process cannot access the file because it is being used by another process. I assume it is because the http listener can't listen to the same port being used to host it :|
But then how can I make Silverlight perform host of origin webclient requests?
Since this is only a test add an "else TextBox1.Text=e.Error.ToString();" in your TestDownloadStoriesCompleted handler to see what error you get.
EDIT:
You can't host both the asp.net app and your listener on the same port - you could fix this by using a different port and serving a clientaccesspolicy.xml from your httplistener.
However I think it would make more sense for you to take a look at WCF web services (you add the svc to your asp.net app). Here's a sample.
you can use tools like http://www.fiddler2.com/fiddler2/
to actually see what is going on during the request....
This can give some help for further debugging...
I am now using HTTP handlers for communication. It seems that they will work fine enough for my purpose, although I still want to try out some WCF.

Resources