WCF stops responding after some requests - c#

I have built wcf. it is working well
The issue is when I call it many times it displays the following error:
The server encountered an error processing the request. See server
logs for more details
I configured a WCF Tracing File but it remains always empty. what can be the reason of this sudden stop of the service and how to fix it?
Here is the code that I use at the client's side every 20 seconds:
string url = "http://host/Service.svc/method";
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.Method = "GET";
ASCIIEncoding encoding = new ASCIIEncoding();
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
StreamReader loResponseStream =
new StreamReader(webresponse.GetResponseStream(), enc);
string strResult = loResponseStream.ReadToEnd();
loResponseStream.Close();
webresponse.Close();

I fixed the issue. it was due to open database connections. I missed to close, at the server side, the database connections. Thank you for answer

It could be a working memory issue on the server/host. If there's less than 5% available you get no response.

Related

WebRequest.Create Exception on DMZ server

I'm not positive my issue is entirely code or a network issue, though not likely as my site works otherwise. In a round-about description, I've created a website that is hosted in the DMZ of my employer. It's an MVC asp.net C# webform that submits test payment transaction data to a test production environment within the company. A user fills in some fields, and presses the submit button in IE and IE takes over from there and displays the response from the internal test production server. So far, so good. Now..., I'm changing it so the submission goes through a Controller I have, grabbing the data and sending it to the same internal test production server where I'm now getting an exception on the 'Stream datastream...' line.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(selectedServer); // Create a request using a URL that can receive a post.
request.Method = "POST"; // Set the Method property of the request to POST.
byte[] byteArray = Encoding.UTF8.GetBytes(TransactionData);
request.ContentType = "application/x-www-form-urlencoded"; // Set the ContentType property of the WebRequest.
request.ContentLength = byteArray.Length; // Set the ContentLength property of the WebRequest.
Stream dataStream = request.GetRequestStream(); // Get the request stream.
dataStream.Write(byteArray, 0, byteArray.Length); // Write the data to the request stream.
dataStream.Close(); // Close the Stream object.
WebResponse response = request.GetResponse(); // Get the response.
The exception is: System.Net.Sockets.SocketException
"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 'some.ip.address.255:7969' at System.Net"
The TransactionData is a string.
Thanks in advance and let me know if more information is needed.
Solved. Turns out I needed to add a host entry pointing to the internal server!
Maybe someone in the future will find this just as useful?

The underlying connection was closed: An unexpected error occurred

I have a very simple service which calls to a URL and captures a status that is written out by that service;
// Service call used to determine availability
System.Net.WebClient client = new System.Net.WebClient();
// I need this one (sorry, cannot disclose the actual URL)
Console.WriteLine(client.DownloadString(myServiceURL + ";ping"));
// I added this for test purposes
Console.WriteLine(client.DownloadString("https://www.google.com"));
The "DownloadString" for myServiceURL line throws the error "The underlying connection was closed: An unexpected error occurred" and there's nothing showing in Fiddler for this line, whereas the "DownloadString" for google.com works and I see the console output for that.
Following other suggestions for the error, I have tried combinations of setting UseDefaultCredentials, Encoding options, adding appropriate headers to the request, none of which make any difference.
client.UseDefaultCredentials = true;
client.Encoding = Encoding.UTF8;
When I navigate to the myServiceURL in a browser, it works and shows "OK", as expected.
Another method from the same service has been coded as follows:
// Request
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(myServiceURL + ";login");
// Set the request configuration options
req.Method = "POST";
req.ContentType = "text/xml";
req.ContentLength = bytes.Length;
req.Timeout = -1;
// Call for the request stream
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
// ....snip
// This line fails with the same error as before
WebResponse resp = req.GetResponse()
This is all being run on a Windows 7 (64-bit) PC using .NET Framework 4.0; the service at myServiceURL is a 3rd-party service for which I have no control over.
Have finally got to the bottom of this and whilst the answer may not apply to everyone with the same problem; I would suggest that the clue was in the fact that we could pull information from some HTTPS site, but not all and tracing events through a combination of Fiddler, WireShark and our Firewall.
Opening the sites in Google Chrome and clicking the padlock for 'https' in the URL address for the site, to view the 'Security Overview' we see that for most of the sites we tried that there are entries listed for 'Valid Certificate' and for 'Secure Resources', but this one site also had an entry for 'Secure TLS Connection' and WireShark confirmed that the handshake (from Chrome) was using TLS v1.2
TLS v1.2 appears to only be supported with .NET Framework 4.5 (or above), which therefore needs Visual Studio 2012 (or above)
We are currently running .NET Framework 4.0 with Visual Studio 2010
Downloaded Visual Studio 2015 Community Edition to test the "same" code within a project using .NET Framework 4.5.2 and it worked straight away.
//assuming this is set
byte[] Data;
string url = string.Format("{0};{1}" ,myServiceURL, "login");
// Request
HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(url);
wreq.Method = "POST";
wreq.Proxy = WebProxy.GetDefaultProxy();
(wreq as HttpWebRequest).Accept = "text/xml";
if (Data != null && Data.Length > 0)
{
wreq.ContentType = "application/x-www-form-urlencoded";
System.IO.Stream request = wreq.GetRequestStream();
request.Write(Data, 0, Data.Length);
request.Close();
}
WebResponse wrsp = wreq.GetResponse();

API woes with .Net in C#

I am new to .net and APIs and am currently using .Net 4.5 to connect to an API using rest. The problem I am having is I get an exception thrown back in the return xml that says "Cannot forward request to server with name", "Cannot read data from connection", Connection reset", full error below.
What is odd is this script works fine on smaller datasets but when the response is large enough, I get that exception from the server thrown back. What has helped setting the keep alive to true, using httpversion10, and specifying gzip and sendchunked. I am using advanced rest client to test the server in chrome addins and it returns data fine on there with these larger dataset. It will not with the script below. I am suspecting there is a difference in the way I am telling the server to handle my response verses the chrome add in. Any suggestions on how I improve the performance of this?
This is what the advanced rest client settings look like that work for the Chrome add in.
This is the code I have which appears to need changes to make it handle the request/response better.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(#"magicalwebsite");
req.KeepAlive = true;
req.ProtocolVersion = HttpVersion.Version10;
req.ServicePoint.ConnectionLimit = 24;
req.Timeout = 2000000000;
req.Method = "Post";
req.Accept = "*/*";
req.SendChunked = true;
req.AutomaticDecompression = DecompressionMethods.GZip;
//Xml request file for data
string postData = System.IO.File.ReadAllText(#"C:\Users\yo\Desktop\testtest.txt");
//sending header and content
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
req.ContentType = "text/xml";
req.ContentLength = byteArray.Length;
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("xxxx:xxxxx"));
Stream dataStream = req.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//Requesting response of data
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
//Grabbing response
using (Stream stream = resp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
This is the exception I am getting in the xml being thrown back.
<?xml version="1.0" encoding="UTF-8"?>
<response success="false">
<messages>
<message key="exception-caught">Caught Exception: Caught Exception:
Cannot forward request to server with name=prod-euapp01
com.magicalpony.exception.APException: Cannot forward request to server with name=prod-euapp01
at com.magicalpony.webservices.APIForwarder.forward(APIForwarder.java:105)
at com.magicalpony.webservices.APIServlet.forwardRequest(APIServlet.java:270)
at com.magicalpony.webservices.APIServlet.wrongServer(APIServlet.java:253)
at com.magicalpony.webservices.APIServlet.service(APIServlet.java:124)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:210)
at com.magicalpony.system.WebServiceMonitor.doFilter(WebServiceMonitor.java:61)
at org.apache.catalina.core.
ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.magicalpony.system.HitTracer.doFilter(HitTracer.java:133)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399)
at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:303)
at org.apache.coyote.ajp.AjpProtocol$AjpConnectionHandler.process(AjpProtocol.java:183)
at org.apache.coyote.ajp.AjpProtocol$AjpConnectionHandler.process(AjpProtocol.java:169)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.magicalpony.exception.APException:
Cannot read data from connection
at com.magicalpony.webservices.NetUtil.readData(NetUtil.java:61)
at com.magicalpony.webservices.APIForwarder.forward(APIForwarder.java:102)
... 26 more
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:196)
at
java.net.SocketInputStream.read(SocketInputStream.java:122)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:687)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:633)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1323)
at com.magicalpony.webservices.NetUtil.readData(NetUtil.java:58)
... 27 more</message>
</messages>
</response>
The problem is with DNS resolution.
Step 1: Enter your domain name in a browser and see if Server is available.
Step 2: If server is available with domain name then you got to fix the IP Address or DNS resolution.
You can fix this by updating the IP Address in your PC (Follow steps below)
Go to a folder: C:\Windows\System32\drivers\etc
Copy and paste "hosts" file to desktop.
Update your host file with your IP Address and domain name.
Step 3: Copy and Paste hosts file in original folder (C:\Windows\System32\drivers\etc).
Step 4: Test your API.

C# GetRequestStream() outlook add-in "The operation has timed out"

Good day.
I really need help on this issue. I have tried every possible option here.
I use a REST API in an Outlook add-in using C#. The code links outlook items to CRM records, one way. The add-in works 100% fine but after a couple of calls outs i keep on getting the error "The operation has timed out".
When I use the Google Chrome App "Advanced REST Client" I can post the same request 50 times after each other with no time out error.
From within the add-in I use POST, GET and PATCH HttpWebRequest and I get the error for all of them. The error happens at the code line System.IO.Stream os = req.GetRequestStream();
Below is the method:
public static string HttpPatch(string URI, string Parameters)
{
var req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(URI);
if (GlobalSettings.useproxy.Equals("true"))
{
req.Proxy = WebRequest.DefaultWebProxy;
req.Credentials = new NetworkCredential(GlobalSettings.proxyusername, GlobalSettings.proxypassword, GlobalSettings.proxydomain);
req.Proxy.Credentials = new NetworkCredential(GlobalSettings.proxyusername, GlobalSettings.proxypassword, GlobalSettings.proxydomain);
}
req.Headers.Add("Authorization: OAuth " + GlobalSettings.token.access_token);
req.ContentType = "application/json";
req.Method = "PATCH";
byte[] data = System.Text.Encoding.Unicode.GetBytes(Parameters);
req.ContentLength = data.Length;
using (System.IO.Stream os = req.GetRequestStream())
{
os.Write(data, 0, data.Length);
os.Close();
}
WebResponse resp;
try
{
resp = req.GetResponse();
}
catch (WebException ex)
{
if (ex.Message.Contains("401"))
{
}
}
}
I suspect the problem is that you're not disposing of the WebResponse. That means the connection pool thinks that the connection is still in use, and will wait for the response to be disposed before reusing it for another request. The connection is needed in order to get a request stream, and it won't become available unless the finalizer happens to kick in at a useful time, hence the timeout.
Simply change your code using the response to use a using statement - or in your case, potentially something a little more complicated using a finally block as you're assigning it within a try block. (We can't really see how you're using the response, which makes it hard to give sample code around that. But fundamentally, you need to dispose it.)

WebRequest fails with "414 Request URI too long" in ASP.NET application

We have an ASP.NET application that requests an SSRS 2005 report in HTML format after passing the parameters for the report as a WebRequest. The application only fails when a report with a large number of multi-select parameters is requested, throwing a "414: Request URI too long" error at the webRequest.GetResponse() line.
The code used to make the request is:
HttpWebRequest webRequest = null;
HttpWebResponse webResponse = null;
string webRequestURL = _ReportManager.GetRSUrl(reportID); //this passes the report link on the SSRS server
//make the request
Byte[] bytes = Encoding.UTF8.GetBytes("xml_doc=" + HttpUtility.UrlEncode(webRequestURL));
webRequest = (HttpWebRequest)WebRequest.Create(webRequestURL);
webRequest.Method = "POST";
webRequest.ContentLength = bytes.Length;
webRequest.Timeout = Configuration.WebRequestTimeOut;
RSExecution2005.ReportExecutionService rsE = new RSExecution2005.ReportExecutionService();
rsE.Url = Configuration.ReportExecutionServiceUrl2005;
rsE.Credentials = System.Net.CredentialCache.DefaultCredentials;
webRequest.Credentials = rsE.Credentials;
Stream reqStream = null;
reqStream = webRequest.GetRequestStream();
reqStream.Write(bytes, 0, bytes.Length);
reqStream.Close();
webResponse = (HttpWebResponse)webRequest.GetResponse();
As the report fails on the server side, I have looked into IIS and ReportServer properties to increase the maxUrl, maxRequestLength, MaxQueryString, etc. in terms of bytes (as per this article) but the application still throws an error. I have tried this in the web.config files and directly on the IIS manager.
The reporting server version in 2005 and it is hosted on Windows Server 2008, which is running IIS 7.
On David Lively's advise I tried requesting the URI by putting the parameters in the body. This works for smaller requests, but still fails for large multi-select parameters. The amended code is as follows:
HttpWebRequest webRequest = null;
HttpWebResponse webResponse = null;
string webRequestURL = _ReportManager.GetRSUrl(reportID); //this passes the report link on the SSRS server
string postData = string.Empty;
string URIrequest = string.Empty;
URIrequest = webRequestURL.Substring(0, webRequestURL.IndexOf("&"));
int requestLen = webRequestURL.Length;
int postDataStart = webRequestURL.IndexOf("&") + 1;
postData = webRequestURL.Substring(postDataStart, (requestLen - postDataStart));
Byte[] bytes1 = Encoding.UTF8.GetBytes(postData);
webRequest = (HttpWebRequest)WebRequest.Create(URIrequest);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = bytes1.Length;
webRequest.Timeout = Configuration.WebRequestTimeOut;
RSExecution2005.ReportExecutionService rsE = new RSExecution2005.ReportExecutionService();
rsE.Url = Configuration.ReportExecutionServiceUrl2005;
rsE.Credentials = System.Net.CredentialCache.DefaultCredentials;
webRequest.Credentials = rsE.Credentials;
Stream reqStream = webRequest.GetRequestStream();
reqStream.Write(bytes1, 0, bytes1.Length);
reqStream.Close();
webResponse = (HttpWebResponse)webRequest.GetResponse();
Even though the requestURI of the webRequest does not store parameters, it seems that the GetReponse() function adds the parameters to the 'address' property of the webRequest. could this be the problem? if so, how can it be fixed.
Is it possible for you to use POST variables instead of GET? That way, there are no limits that I'm aware of, as all of your data will be sent in packets instead of HTTP headers.
Actually it looks like you might be using POST from what's in your code. Can you look in the server logs to verify the URI that is causing this to fail? If you're sending POST data, the request uri shouldn't be an issue unless it's unrelated to the data you're POSTing.
Check your service's binding settings. I guess the service will allow the string upto 8192 length. Set te readerQuotas to a larger size. Might help.
...
<basicHttpBinding>
<binding name="largeBuffer">
<readerQuotas
maxDepth="2147483647"
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647" />
<security mode="None"></security></binding>
</basicHttpBinding>
.....
Since you're already using POST to fetch the report, I'd suggest putting the parameters that you're currently passing in the query string in the request body, instead. Querystring parameters work fine for a limited number of parameters, but aren't appropriate for a large number of items.
Can you show the value of webRequestURL?
It's going to be "too big".
If you are passing parameters to this URL, can they be in the POST body instead?
webRequestURL.IndexOf("&") ... Is this meant to be "?" instead of "&"? I'm guessing you construct a valid URL for querying the page and then reverse engineer it to be a POST request by looking for the URL before the first '&'...
However, it's possible the GetResponse is appending the body to the URL because it sees the Question Mark in the URL and assumes that the parameters must go in the URL? Try doing a more exact URL match with zero parameters and no '?'.
I got this at work on my IIS7 site. Got it fixed with a registry hack, i can search it up but won't work before 3/1. Meanwhile, try if you get the error when you use the ip-address in stead of the normal URL, when you don't, chances are high it is the same problem.
Had a similar issue, except that POST was working, but second POST with exactly same parameters returned 414.
Setting req.KeepAlive = false; solved the problem, God knows why.

Categories

Resources