WebRequest time out error - windows

I tried to build an application in Mono using the setting "Mono 2.10.2", but the the following errors.
Unhandled Exception: System.Net.WebException: The request timed out
at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00046] in C:\cygwin\tmp\monobuild\build\BUILD\mono-2.6.7\mcs\class\System\System.Net\HttpWebRequest.cs:813
at System.Net.HttpWebRequest.GetResponse () [0x0000e] in C:\cygwin\tmp\monobuild\build\BUILD\mono-2.6.7\mcs\class\System\System.Net\HttpWebRequest.cs:825
The bit of code causing this issue is:
string url = "http://webFarm/config.prop";
WebRequest req = WebRequest.Create(url);
WebResponse resp = req.GetResponse();
It failed immediately. But if I switch the setting to "Default Runtime" instead of "Mono 2.10.2", everything is OK. Could anyone help me with this?
Regards,
David

I'm also getting this error using the code:
HttpWebRequest objRequest =
(HttpWebRequest)WebRequest.Create("https://api-3t.sandbox.paypal.com/nvp");
objRequest.Timeout =15000;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
using (StreamWriter myWriter = new
StreamWriter(objRequest.GetRequestStream()))
myWriter.Write(strPost);
causes exception at GetRequestStream() :
System.Net.WebException: The request timed out
at System.Net.HttpWebRequest.GetRequestStream () [0x0005f] in
/usr/src/redhat/BUILD/mono-2.10.2/mcs/class/System/System.Net/HttpWebRequest.cs:752
at NVPAPICaller.HttpCall (System.String NvpRequest) [0x00000] in <filename
unknown>:0
--------------------------------------------------------------------------------
Version information: Mono Runtime Version: 2.10.2 (tarball Mon Apr 18
18:57:39 UTC 2011); ASP.NET Version: 2.0.50727.1433
You should revert back to older Mono 2.10 , 2.10.1 will probably work.

Related

elasticsearch fails VerifyRepositoryRequest in C# Nest client

After updating to elasticsearch 7.5.1 following code is now causing an exception
"Entry point not found"
//old code worked just fine
var verifyRepositoryResponse = this.elasticClient.VerifyRepository(new VerifyRepositoryRequest("C__MYFOLDER_Backup"));
//new code throws
var verifyRepositoryResponse = this.elasticClient.Snapshot.VerifyRepository(new VerifyRepositoryRequest("C__MYFOLDER_Backup"));
Note that making following request via fiddler
POST http://localhost:9200/_snapshot/C__MYFOLDER_Backup/_verify HTTP/1.1
User-Agent: Fiddler
Host: localhost:9200
Content-Type: application/json
Content-Length: 0
returns
{"nodes":{"1cWG9trDRi--6I-46lOlBw":{"name":"DESKTOP-5L01F6I"}}}
any ideas what causes the problem here?
Unfortunately there is zero documentation on that matter.
UPDATE:
Calling the code with a non existing directory as argument
var verifyRepositoryResponse = this.elasticClient.Snapshot.VerifyRepository(new VerifyRepositoryRequest("C__DOESNOTEXIST_Backup"));
I will get a 4xx response as expected in this scenario.
Before all tests, repositories and db have been cleaned.
Update:
Adavanced error information:
"# FailureReason: Unrecoverable/Unexpected BadResponse while attempting POST on http://localhost:9200/_snapshot/C__MYFOLDER_Backup/_verify\r\n - [1] BadResponse: Node: http://localhost:9200/ Exception: EntryPointNotFoundException Took: 00:00:00.1859931\r\n# Audit
exception in step 1 BadResponse:\r\nSystem.EntryPointNotFoundException: Entry point was not found.\r\n at Elasticsearch.Net.Utf8Json.IJsonFormatter`1.Deserialize(JsonReader& reader, IJsonFormatterResolver formatterResolver)\r\n at Deserialize(Object[] ,
JsonReader& , IJsonFormatterResolver )\r\n at Elasticsearch.Net.Utf8Json.JsonSerializer.Deserialize[T](Byte[] bytes, Int32 offset, IJsonFormatterResolver resolver)\r\n at Elasticsearch.Net.Utf8Json.JsonSerializer.Deserialize[T](Stream stream,
IJsonFormatterResolver resolver)\r\n at Elasticsearch.Net.DiagnosticsSerializerProxy.Deserialize[T](Stream stream)\r\n at Elasticsearch.Net.ResponseBuilder.SetBody[TResponse](ApiCallDetails details, RequestData requestData, Stream responseStream, String
mimeType)\r\n at Elasticsearch.Net.ResponseBuilder.ToResponse[TResponse](RequestData requestData, Exception ex, Nullable`1 statusCode, IEnumerable`1 warnings, Stream responseStream, String mimeType)\r\n at
Elasticsearch.Net.HttpWebRequestConnection.Request[TResponse](RequestData requestData)\r\n at Elasticsearch.Net.RequestPipeline.CallElasticsearch[TResponse](RequestData requestData)\r\n at Elasticsearch.Net.Transport`1.Request[TResponse](HttpMethod method,
String path, PostData data, IRequestParameters requestParameters)\r\n# Inner Exception: Entry point was not found.\r\nSystem.EntryPointNotFoundException: Entry point was not found.\r\n at Elasticsearch.Net.Utf8Json.IJsonFormatter`1.Deserialize(JsonReader&
reader, IJsonFormatterResolver formatterResolver)\r\n at Deserialize(Object[] , JsonReader& , IJsonFormatterResolver )\r\n at Elasticsearch.Net.Utf8Json.JsonSerializer.Deserialize[T](Byte[] bytes, Int32 offset, IJsonFormatterResolver resolver)\r\n at
Elasticsearch.Net.Utf8Json.JsonSerializer.Deserialize[T](Stream stream, IJsonFormatterResolver resolver)\r\n at Elasticsearch.Net.DiagnosticsSerializerProxy.Deserialize[T](Stream stream)\r\n at
Elasticsearch.Net.ResponseBuilder.SetBody[TResponse](ApiCallDetails details, RequestData requestData, Stream responseStream, String mimeType)\r\n at Elasticsearch.Net.ResponseBuilder.ToResponse[TResponse](RequestData requestData, Exception ex, Nullable`1
statusCode, IEnumerable`1 warnings, Stream responseStream, String mimeType)\r\n at Elasticsearch.Net.HttpWebRequestConnection.Request[TResponse](RequestData requestData)\r\n at Elasticsearch.Net.RequestPipeline.CallElasticsearch[TResponse](RequestData
requestData)\r\n at Elasticsearch.Net.Transport`1.Request[TResponse](HttpMethod method, String path, PostData data, IRequestParameters requestParameters)\r\n# Exception:\r\nElasticsearch.Net.UnexpectedElasticsearchClientException: Entry point was not found. --->
System.EntryPointNotFoundException: Entry point was not found.\r\n at Elasticsearch.Net.Utf8Json.IJsonFormatter`1.Deserialize(JsonReader& reader, IJsonFormatterResolver formatterResolver)\r\n at Deserialize(Object[] , JsonReader& , IJsonFormatterResolver
)\r\n at Elasticsearch.Net.Utf8Json.JsonSerializer.Deserialize[T](Byte[] bytes, Int32 offset, IJsonFormatterResolver resolver)\r\n at Elasticsearch.Net.Utf8Json.JsonSerializer.Deserialize[T](Stream stream, IJsonFormatterResolver resolver)\r\n at
Elasticsearch.Net.DiagnosticsSerializerProxy.Deserialize[T](Stream stream)\r\n at Elasticsearch.Net.ResponseBuilder.SetBody[TResponse](ApiCallDetails details, RequestData requestData, Stream responseStream, String mimeType)\r\n at
Elasticsearch.Net.ResponseBuilder.ToResponse[TResponse](RequestData requestData, Exception ex, Nullable`1 statusCode, IEnumerable`1 warnings, Stream responseStream, String mimeType)\r\n at Elasticsearch.Net.HttpWebRequestConnection.Request[TResponse](RequestData
requestData)\r\n at Elasticsearch.Net.RequestPipeline.CallElasticsearch[TResponse](RequestData requestData)\r\n at Elasticsearch.Net.Transport`1.Request[TResponse](HttpMethod method, String path, PostData data, IRequestParameters requestParameters)\r\n ---
End of inner exception stack trace ---\r\n at Elasticsearch.Net.Transport`1.Request[TResponse](HttpMethod method, String path, PostData data, IRequestParameters requestParameters)\r\n at
Nest.Specification.SnapshotApi.SnapshotNamespace.VerifyRepository(IVerifyRepositoryRequest request)\r\n at InforsHT.Genesis.Infrastructure.Data.Repositories.ElasticBackupAndRestoreProxy.IsBackupLocationPresent(String backupLocation) in
C:\\work\\eve\\Source\\InforsHT.Genesis.Infrastructure.Data\\Repositories\\ElasticBackupAndRestoreProxy.cs:line 44\r\n"
This is a bug. VerifyRepositoryResponse's Node property is attributed with a JsonFormatterAttribute that expects to deserialize an IDictionary<string, CompactNodeInfo> when the property type is IReadOnlyDictionary<string, CompactNodeInfo>. This is problematic for the underlying JSON serializer which uses strongly typed formatters, IJsonFormatter<T>, where the type T must match exactly.
I've opened an issue to track and a pull request to fix the issue. For now, you'd be able to workaround the bug by using the low level client exposed on the high level client
var response = client.LowLevel.Snapshot.VerifyRepository<DynamicResponse>("C__MYFOLDER_Backup");
and traverse DynamicResponse. Alternatively, use StringResponse and parse using JObject or JsonDocument and traverse.

Exist-db parallel request(bulk request) failed on exist db restxq (post,put)

I am facing a problem on restxq multiple parallel request of post, put. When request from web application as async bulk request (approx. more then 5 ).
I am using exist db 5.1.0 or 5.1.1
I am sending request through angular forkjoin because of i want to submit more then 20 or 50 request in parallel
declare
%rest:path("/docs/{$doc-id}")
%rest:PUT("{$body}")
%rest:consumes("application/json")
%output:method("json")
function doc-rx:update-docs($doc-id as xs:string, $body) {
try{
let $request:= parse-json(util:binary-to-string( $body))
return
<result>Success</result>
}catch * {
<error>Caught error {$err:description}</error>
}
};
Some request will failed with below message, some request got cancelled
Failed Message:
The underlying InputStream has been closed. Unable to encode string value: The underlying InputStream has been closed Some Request got cancelled.
Please advise how can I resolve this issue.

Kestrel server slow on "bad request data"

I have an IOT device (black box, can't reprogram it) that sends http POST requests (136 bytes of JSON, a string) over wired ethernet to my .NET core 2.2 very simple server console application.
I just output the string to the console.
[HttpPost]
public void Post([FromBody] RootObject root)
{
string adv = root.prt;
Console.WriteLine(adv);
}
I get to display less than 1 line per second, sometimes 2.
Using Fiddler as a reverse proxy, instead I receive between 5 and 10 http req per second, that is the correct behavior of the device.
So I enabled Information logs, and get this, every second, with that "Invalid request line" error:
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 POST http://192.168.0.92/api/values application/json 136
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
Executing endpoint 'BluepycWeb.Controllers.ValuesController.Post (BluepycWeb)'
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Route matched with {action = "Post", controller = "Values"}. Executing action BluepycWeb.Controllers.ValuesController.Post (BluepycWeb)
02003F002293831000010033FF0006EFAA256B6D1A001E010201061AFF4C000215476C6F62616C2D54616700000000000000000000CD0101CC0001FF001FCC
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Executing action method BluepycWeb.Controllers.ValuesController.Post (BluepycWeb) with arguments (BluepycWeb.Controllers.RootObject) - Validation state: Valid
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action method BluepycWeb.Controllers.ValuesController.Post (BluepycWeb), returned result Microsoft.AspNetCore.Mvc.EmptyResult in 0.2158ms.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action BluepycWeb.Controllers.ValuesController.Post (BluepycWeb) in 9.4032ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint 'BluepycWeb.Controllers.ValuesController.Post (BluepycWeb)'
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 24.5625ms 200
info: Microsoft.AspNetCore.Server.Kestrel[17]
Connection id "0HLMO99UNQBGM" bad request data: "Invalid request line: '\x0D\x0A'"
Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Invalid request line: '\x0D\x0A'
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpParser`1.RejectRequestLine(Byte* requestLine, Int32 length)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpParser`1.GetUnknownMethod(Byte* data, Int32 length, Int32& methodLength)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpParser`1.ParseRequestLine(TRequestHandler handler, Byte* data, Int32 length)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpParser`1.ParseRequestLine(TRequestHandler handler, ReadOnlySequence`1& buffer, SequencePosition& consumed, SequencePosition& examined)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpParser`1.Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.IHttpParser<TRequestHandler>.ParseRequestLine(TRequestHandler handler, ReadOnlySequence`1& buffer, SequencePosition& consumed, SequencePosition& examined)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1Connection.TakeStartLine(ReadOnlySequence`1 buffer, SequencePosition& consumed, SequencePosition& examined)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1Connection.ParseRequest(ReadOnlySequence`1 buffer, SequencePosition& consumed, SequencePosition& examined)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1Connection.TryParseRequest(ReadResult result, Boolean& endConnection)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequestsAsync[TContext](IHttpApplication`1 application)
If I send the same JSON paylod through Postman continuosly, no errors, no delays.
That error, that I don't know how to avoid nor by what is originated (but it seems it doesn't distub Fiddler) seems to hang my server for a second.
Any suggestion on how can I solve this problem?
Discard/correct the error?
Keep the error but not slowing down the data receive?
UPDATE:
Hosting with IISExpress, no problem, no "Invalid request line: '\x0D\x0A'" error, very fast.
Problem is only using Kestrel.
Thanks!
Yesterday I had same issue with my ASP .NETCore service.
Then realized I was sending HTTPS requests to my Kestrel server while it isn't configured to listen at HTTPS protocol, that's why Kestrel complaining.
If you want to use HTTPS in your kestrel you have multiple options to configure it, for example :
With assigned server certificate :
var host = new WebHostBuilder()
.UseKestrel(options =>
options.Listen(IPAddress.Any, 443, listenOptions =>
listenOptions.UseHttps("MyCert.pfx")))
With multiple hostnames and certificates :
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureKestrel((context, options) =>
{
options.ListenAnyIP(5005, listenOptions =>
{
listenOptions.UseHttps(httpsOptions =>
{
var localhostCert = CertificateLoader.LoadFromStoreCert(
"localhost", "My", StoreLocation.CurrentUser,
allowInvalid: true);
var exampleCert = CertificateLoader.LoadFromStoreCert(
"example.com", "My", StoreLocation.CurrentUser,
allowInvalid: true);
var subExampleCert = CertificateLoader.LoadFromStoreCert(
"sub.example.com", "My", StoreLocation.CurrentUser,
allowInvalid: true);
var certs = new Dictionary<string, X509Certificate2>(
StringComparer.OrdinalIgnoreCase);
certs["localhost"] = localhostCert;
certs["example.com"] = exampleCert;
certs["sub.example.com"] = subExampleCert;
httpsOptions.ServerCertificateSelector = (connectionContext, name) =>
{
if (name != null && certs.TryGetValue(name, out var cert))
{
return cert;
}
return exampleCert;
};
});
});
});

Intermittent Server cannot set status after HTTP headers have been sent

I am getting an intermittent error in the event logs "Server cannot set status after HTTP headers have been sent". The webapi site is working fine and delivering the correct output even when this happens.
Exception information:
Exception type: HttpException
Exception message: Server cannot set status after HTTP headers have been sent. at System.Web.HttpResponse.set_StatusCode(Int32
value) at System.Web.HttpResponseWrapper.set_StatusCode(Int32
value) at
System.Web.Http.WebHost.HttpControllerHandler.d__25.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
System.Web.Http.WebHost.HttpControllerHandler.d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
System.Web.Http.WebHost.HttpControllerHandler.d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at System.Web.TaskAsyncHelper.EndTask(IAsyncResult ar) at
System.Web.HttpTaskAsyncHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult
result) at
System.Web.HttpApplication.CallHandlerExecutionStep.InvokeEndHandler(IAsyncResult
ar) at
System.Web.HttpApplication.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult
ar)
The response object is manipulated directly (the format of the json is not known until runtime) as follows.
var response= HttpContext.Current.Response;
response.StatusCode = (int) HttpStatusCode.OK;
response.Headers.Add("X-Robots-Tag", "noindex, nofollow");
response.Write("Some json");
response.Flush();
response.End();
response.End is required, I do not understand why, a similar error occurs if this line is missed out.
Why does this happen, and is there a better way of doing it?
Since you tagged your question with asp.net-web-api I assume that you are using that code in an api controller method. If so, I suggest returning the unknown Json like this:
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("Some json", System.Text.Encoding.UTF8, "application/json")
};
response.Headers.Add("X-Robots-Tag", "noindex, nofollow");
return response;
Above code was taken from the following links and adapted:
Put content in HttpResponseMessage object
and
Add a custom response header in ApiController (questions and answers on SO)

Google Custom Search API error

I used Google Cloud Platform for Free trial
https://cloud.google.com/free-trial/
to use custom search API in my java application
I write the following code in my application
URL url = new URL("https://www.googleapis.com/customsearch/v1?key="+key+
"&cx=013036536707430787589:_pqjad5hr1a&q="+ qry + "&alt=json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
if(output.contains("\"link\": \"")){
String link=output.substring(output.indexOf("\"link\": \"")+("\"link\": \"").length(), output.indexOf("\","));
System.out.println(link); //Will print the google search links
}
}
conn.disconnect();
it some times gave me a result and after that it gave me the following error , and this error occurred regardless the query string
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: https://www.googleapis.com/customsearch/v1?key=????&cx=013036536707430787589:_pqjad5hr1a&q=?????
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1839)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1440)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
Where is the problem please?
403 is specifically Google's forbidden error - it means your sending too many requests too quickly and they think you using a bot or automation
If you load that query in your browser and watch the requests - keep hitting refresh quickly until you see an html response that says
We're sorry...
... but your computer or network may be sending automated queries. To protect our users, we can't process your request right now.
See Google Help for more information.

Resources