Execute PostAsync with empty response - c#

For my UPW App with MS Store integration, my ASP.NET application does some calls to the Microsoft Store collection API:
https://learn.microsoft.com/de-de/windows/uwp/monetize/report-consumable-products-as-fulfilled
This API method has no return at all:
"Response:
No content will be returned if the consumption was executed successfully."
Which causes my following code:
HttpClient httpClient = new HttpClient();
String content = "...";
var res = httpClient.PostAsync("https://collections.mp.microsoft.com/v6.0/collections/consume", content).Result;
To throw an exception. Unfortunately I only have it in german, but it tells that from the connection no data could be read, and that the remote host has closed the connection.
I think this is basically a "feature" and not a bug, because there really is no content to return. But I dont know how to get rid of the exception.
Exception:
System.Net.Http.HttpRequestException: Fehler beim Senden der Anforderung. ---> System.Net.WebException: Die zugrunde liegende Verbindung wurde geschlossen: Unbekannter Fehler beim Empfangen.. ---> System.IO.IOException: Von der Übertragungsverbindung können keine Daten gelesen werden: Eine vorhandene Verbindung wurde vom Remotehost geschlossen. ---> System.Net.Sockets.SocketException: Eine vorhandene Verbindung wurde vom Remotehost geschlossen
bei System.Net.Sockets.Socket.BeginReceive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, AsyncCallback callback, Object state)
bei System.Net.Sockets.NetworkStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
--- Ende der internen Ausnahmestapelüberwachung ---
bei System.Net.Security._SslStream.EndRead(IAsyncResult asyncResult)
...

That is a network error.
The documentation (this is the English version) does say:
No content will be returned if the consumption was executed successfully.
However, it also gives an example of a response:
HTTP/1.1 204 No Content
Content-Length: 0
MS-CorrelationId: 386f733d-bc66-4bf9-9b6f-a1ad417f97f0
MS-RequestId: e488cd0a-9fb6-4c2c-bb77-e5100d3c15b1
MS-CV: 5.1
MS-ServerId: 030011326
Date: Tue, 22 Sep 2015 20:40:55 GMT
So it does respond, but with HTTP 204.
If you are not getting that response, then you have a network problem.

Related

Analyzers error in Visual Studio 2022 Preview

The Release version of Visual Studio works with C# 11, but the required keyword isn’t even recognized as such, which I wanted to try out. So I installed the Preview version of Visual Studio 2022 (Preview 5.0, upadted to 6.0 today).
When starting VS 2022 Preview, I get a lot of errors in analyzers and similar features (see image below). Their stack traces (also below) are all telling essentially the same story: The method ImmutableArray is cannot be found.
Clicking on “Enable”, the error re-appears after a few seconds.
Looking it up, I added the NuGet package ImmutableArray to the soulution. That seemed like an odd thing to have do, but if it had worked, I’d have been fine with it.
Both a fresh C# console application project and an existing project (one that perfectly works in the latest Release version of VS 2022) crash the analyzers.
Closing and re-opening VS did not help.
Restarting the PC did not help.
Using the “Repair” option in Visual Studio Installer did not help.
Manually uninstalling and re-installing the Preview version (not yet tried with 6.0) did not help.
It seems nobody but me has encountered this. I suspect that there’s something missing in the installation. Below is a screenshot of the installed components.
Stitched-together screenshot of the errors:
The stack trace of the first:
(Note: Methode nicht gefunden is German for Method not found. My Visual Studio UI is switched to English, but some German slips through for some reason. I did not alter the other strack trace where it is English.)
StreamJsonRpc.RemoteInvocationException: Methode nicht gefunden: "System.Collections.Immutable.ImmutableArray`1<Microsoft.Cci.ICustomModifier> Microsoft.Cci.IFieldReference.get_RefCustomModifiers()".
at StreamJsonRpc.JsonRpc.<InvokeCoreAsync>d__143`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.CodeAnalysis.Remote.BrokeredServiceConnection`1.<TryInvokeAsync>d__18`1.MoveNext()
RPC server exception:
System.MissingMethodException: Methode nicht gefunden: "System.Collections.Immutable.ImmutableArray`1<Microsoft.Cci.ICustomModifier> Microsoft.Cci.IFieldReference.get_RefCustomModifiers()".
bei Microsoft.CodeAnalysis.CSharp.CSharpCompilation..ctor(String assemblyName, CSharpCompilationOptions options, ImmutableArray`1 references, CSharpCompilation previousSubmission, Type submissionReturnType, Type hostObjectType, Boolean isSubmission, ReferenceManager referenceManager, Boolean reuseReferenceManager, SyntaxAndDeclarationManager syntaxAndDeclarations, IReadOnlyDictionary`2 features, SemanticModelProvider semanticModelProvider, AsyncQueue`1 eventQueue)
bei Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create(String assemblyName, CSharpCompilationOptions options, IEnumerable`1 syntaxTrees, IEnumerable`1 references, CSharpCompilation previousSubmission, Type returnType, Type hostObjectType, Boolean isSubmission)
bei Microsoft.CodeAnalysis.CSharp.CSharpCompilationFactoryService.Microsoft.CodeAnalysis.Host.ICompilationFactoryService.CreateCompilation(String assemblyName, CompilationOptions options)
bei Microsoft.CodeAnalysis.SolutionState.CompilationTracker.<BuildDeclarationCompilationFromScratchAsync>d__34.MoveNext()
--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
bei Microsoft.CodeAnalysis.SolutionState.CompilationTracker.<BuildCompilationInfoFromScratchAsync>d__33.MoveNext()
--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
bei Microsoft.CodeAnalysis.SolutionState.CompilationTracker.<BuildCompilationInfoAsync>d__32.MoveNext()
--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
bei Microsoft.CodeAnalysis.SolutionState.CompilationTracker.<GetOrBuildCompilationInfoAsync>d__31.MoveNext()
--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
bei Microsoft.CodeAnalysis.SolutionState.CompilationTracker.<GetCompilationSlowAsync>d__29.MoveNext()
--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
bei Microsoft.CodeAnalysis.Document.<GetSemanticModelAsync>d__23.MoveNext()
--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
bei Microsoft.CodeAnalysis.Shared.Extensions.DocumentExtensions.<GetRequiredSemanticModelAsync>d__7.MoveNext()
--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
bei Microsoft.CodeAnalysis.DocumentHighlighting.AbstractDocumentHighlightsService.<GetDocumentHighlightsInCurrentProcessAsync>d__2.MoveNext()
--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
bei Microsoft.CodeAnalysis.DocumentHighlighting.AbstractDocumentHighlightsService.<GetDocumentHighlightsAsync>d__1.MoveNext()
--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
bei Microsoft.CodeAnalysis.Remote.RemoteDocumentHighlightsService.<>c__DisplayClass2_0.<<GetDocumentHighlightsAsync>b__0>d.MoveNext()
--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
bei Microsoft.CodeAnalysis.Remote.RemoteWorkspace.<>c__DisplayClass10_0`1.<<RunWithSolutionAsync>g__TryFastGetSolutionAndRunAsync|0>d.MoveNext()
--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
bei Microsoft.CodeAnalysis.Remote.RemoteWorkspace.<RunWithSolutionAsync>d__10`1.MoveNext()
--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
bei Microsoft.CodeAnalysis.Remote.BrokeredServiceBase.<RunWithSolutionAsync>d__11`1.MoveNext()
--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
bei Microsoft.CodeAnalysis.Remote.BrokeredServiceBase.<RunServiceImplAsync>d__14`1.MoveNext()
Of the third:
System.MissingMethodException : Method not found: 'System.Collections.Immutable.ImmutableArray`1<Microsoft.Cci.ICustomModifier> Microsoft.Cci.IFieldReference.get_RefCustomModifiers()'.
at Microsoft.CodeAnalysis.CSharp.CSharpCompilation..ctor(String assemblyName,CSharpCompilationOptions options,ImmutableArray`1 references,CSharpCompilation previousSubmission,Type submissionReturnType,Type hostObjectType,Boolean isSubmission,ReferenceManager referenceManager,Boolean reuseReferenceManager,SyntaxAndDeclarationManager syntaxAndDeclarations,IReadOnlyDictionary`2 features,SemanticModelProvider semanticModelProvider,AsyncQueue`1 eventQueue)
at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create(String assemblyName,CSharpCompilationOptions options,IEnumerable`1 syntaxTrees,IEnumerable`1 references,CSharpCompilation previousSubmission,Type returnType,Type hostObjectType,Boolean isSubmission)
at Microsoft.CodeAnalysis.CSharp.CSharpCompilationFactoryService.Microsoft.CodeAnalysis.Host.ICompilationFactoryService.CreateCompilation(String assemblyName,CompilationOptions options)
at async Microsoft.CodeAnalysis.SolutionState.CompilationTracker.BuildDeclarationCompilationFromScratchAsync(<Unknown Parameters>)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at async Microsoft.CodeAnalysis.SolutionState.CompilationTracker.BuildCompilationInfoFromScratchAsync(<Unknown Parameters>)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at async Microsoft.CodeAnalysis.SolutionState.CompilationTracker.BuildCompilationInfoAsync(<Unknown Parameters>)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at async Microsoft.CodeAnalysis.SolutionState.CompilationTracker.GetOrBuildCompilationInfoAsync(<Unknown Parameters>)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at async Microsoft.CodeAnalysis.SolutionState.CompilationTracker.GetCompilationSlowAsync(<Unknown Parameters>)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at async Microsoft.CodeAnalysis.Document.GetSemanticModelAsync(<Unknown Parameters>)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at async Microsoft.CodeAnalysis.SemanticDocument.CreateAsync(<Unknown Parameters>)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at async Microsoft.CodeAnalysis.IntroduceVariable.AbstractIntroduceVariableService`6.IntroduceVariableAsync[TService,TExpressionSyntax,TTypeSyntax,TTypeDeclarationSyntax,TQueryExpressionSyntax,TNameSyntax](<Unknown Parameters>)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at async Microsoft.CodeAnalysis.IntroduceVariable.IntroduceVariableCodeRefactoringProvider.ComputeRefactoringsAsync(<Unknown Parameters>)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at async Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringService.GetRefactoringFromProviderAsync(<Unknown Parameters>)
Installation Details (sorry for German, I don’t know how to change it):
I (seem to) have the latest SDK installed (Win+R, “cmd”, Enter):
C:\Users\user>dotnet --version
7.0.100-preview.6.22352.1
Edit: After updating the release version of Visual Studio 2022 to 17.3.1, I have the problems in the release version. On the other hand, the 17.4 Preview seems to have the issue solved.

gRPC connect to Concordium blockchain API with C#

I realize that this a rather service specific subject, but I think that the reason for my problem is a general one, since I'm a novice in the gRPC arena.
I'm attempting to call a simple method PeerVersion in the Concordium blockchain gRPC API (https://github.com/Concordium/concordium-grpc-api) from a .NET Core 3.1 app, but I get what seems to be a rather general error in regard to SSL.
I can add that I have testet this call and others with BloomRPC (https://github.com/uw-labs/bloomrpc) and it works just fine.
You wont be able to call the API successfully without access to a Concordium node, but I recon that someone with better insight into gRPC than me, could maybe see what I'm doing wrong.
C# code
static async Task Main(string[] args)
{
using var channel = GrpcChannel.ForAddress("https://192.168.1.18:10001"); // my local node running on the Concordium testnet
var client = new Concordium.P2P.P2PClient(channel);
var metadata = new Grpc.Core.Metadata() // required token for the API
{
{ "authentication", "rpcadmin" }
};
var request = new Concordium.Empty();
var reply = client.PeerVersion(request, metadata);
Console.WriteLine("peer version: " + reply.Value);
Console.WriteLine("press any key to exit...");
Console.ReadKey();
}
When I run this I get the following exception. (Danish text reads "An existing connection was forcibly disconnected by an external host" or something like that).
- $exception {"Status(StatusCode=\"Unavailable\", Detail=\"Error starting gRPC call. HttpRequestException: The SSL connection could not be established, see inner exception. IOException: Unable to read data from the transport connection: En eksisterende forbindelse blev tvangsafbrudt af en ekstern vært.. SocketException: En eksisterende forbindelse blev tvangsafbrudt af en ekstern vært.\", DebugException=\"System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
---> System.IO.IOException: Unable to read data from the transport connection: En eksisterende forbindelse blev tvangsafbrudt af en ekstern vært..
---> System.Net.Sockets.SocketException (10054): En eksisterende forbindelse blev tvangsafbrudt af en ekstern vært.
--- End of inner exception stack trace ---
at System.Net.FixedSizeReader.ReadPacketAsync(Stream transport, AsyncProtocolRequest request)
at System.Net.Security.SslStream.ThrowIfExceptional()
at System.Net.Security.SslStream.InternalEndProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.Security.SslStream.EndProcessAuthentication(IAsyncResult result)
at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult)
at System.Net.Security.SslStream.<>c.<AuthenticateAsClientAsync>b__65_1(IAsyncResult iar)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.GetHttp2ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at Grpc.Net.Client.Internal.GrpcCall`2.RunCall(HttpRequestMessage request, Nullable`1 timeout)\")"} Grpc.Core.RpcException
Is anyone able to give me some pointers as to what could be the problem here?
For anyone that knows BloobRPC, here is a screenshot of request and response.
Ah, I got the answer to my problem elsewhere. It turns out that my assumption that the Concordium node requires a secure connection was wrong, in fact it doesn't support secure connections, so the URL was the wrong part.
So to fix the problem, I needed to create the client like this:
// to allow non secure connections
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
using var channel = GrpcChannel.ForAddress("http://192.168.1.18:10001");

iam getting this error 28000: no pg_hba.conf entry for host "XXX.xx.xx.192" while applying migrations in .Net Core Project

I'm Getting This Error While Applying Migrations To Create New Database Hosted in database Cluster in Digitalocean.
my connection string is:
var conn = "User ID=test;Password=testPassword;Server=db-postgresql-tor1-xxxxx-do-user-xxxxxxxxx-0.b.db.ondigitalocean.com;port=25060;Database=TestAuthentication;Integrated Security=false;Pooling=true;";
Npgsql.PostgresException (0x80004005): 28000: no pg_hba.conf entry for host "XXX.xx.xx.192", user "test", database "TestAuthentication", SSL off
at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<g__ReadMessageLong|0>d.MoveNext() in C:\projects\npgsql\src\Npgsql\NpgsqlConnector.cs:line 933
--- End of stack trace from previous location ---
at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<g__ReadMessageLong|0>d.MoveNext() in C:\projects\npgsql\src\Npgsql\NpgsqlConnector.cs:line 973
--- End of stack trace from previous location ---
at Npgsql.NpgsqlConnector.Authenticate(String username, NpgsqlTimeout timeout, Boolean async) in C:\projects\npgsql\src\Npgsql\NpgsqlConnector.Auth.cs:line 22
at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken) in C:\projects\npgsql\src\Npgsql\NpgsqlConnector.cs:line 389
at Npgsql.NpgsqlConnection.<>c__DisplayClass32_0.<g__OpenLong|0>d.MoveNext() in C:\projects\npgsql\src\Npgsql\NpgsqlConnection.cs:line 240
--- End of stack trace from previous location ---
at Npgsql.NpgsqlConnection.Open() in C:\projects\npgsql\src\Npgsql\NpgsqlConnection.cs:line 119
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists()
at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Exception data:
Severity: FATAL
SqlState: 28000
MessageText: no pg_hba.conf entry for host "XXX.xx.xx.192", user "test", database "TestAuthentication", SSL off
File: auth.c
Line: 496
Routine: ClientAuthentication
28000: no pg_hba.conf entry for host "XXX.xx.xx.192", user "test", database "TestAuthentication", SSL off
That's a PostgreSQL error. You are trying to access a database in another computer but the client is not authorised by the server. If you have access to the server, you can edit the pg_hba.conf file and add an entry to XXX.xx.xx.192. There are plenty of examples in the same file.

Running out of sockets when re-using a single HttpClient amongst multiple threads - 1000's of TIMED_WAIT connections remain

Environment: Windows Server 2012 R2 64-bit.
C# .NET Framework version 4.5.1.
I am trying to use this program to download a bunch of files from a SharePoint 2013 site: https://github.com/nddipiazza/Sharepoint-Exporter
In this project there is a [FileDownloader.cs][1] file that pulls requests to download files from a BlockingCollection and downloads them to file.
When I run this I pretty quickly get hit with socket errors:
System.AggregateException: One or more errors occurred. ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted 10.5.50.2:443
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at SpPrefetchIndexBuilder.FileDownloader.attemptToDownload(FileToDownload toDownload, Int32 numRetry)
---> (Inner Exception #0) System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted 10.5.50.2:443
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
--- End of inner exception stack trace ---<---
Basically it seems like I am hitting this code too hard:
public void AttemptToDownload(FileToDownload toDownload, int numRetry)
{
try
{
var responseResult = client.GetAsync(SpPrefetchIndexBuilder.topParentSite + toDownload.serverRelativeUrl);
if (responseResult.Result != null && responseResult.Result.StatusCode == System.Net.HttpStatusCode.OK)
{
using (var memStream = responseResult.Result.Content.ReadAsStreamAsync().GetAwaiter().GetResult())
{
using (var fileStream = File.Create(toDownload.saveToPath))
{
memStream.CopyTo(fileStream);
}
}
Console.WriteLine("Thread {0} - Successfully downloaded {1} to {2}", Thread.CurrentThread.ManagedThreadId, toDownload.serverRelativeUrl, toDownload.saveToPath);
}
else
{
Console.WriteLine("Got non-OK status {0} when trying to download url {1}", responseResult.Result.StatusCode, SpPrefetchIndexBuilder.topParentSite + toDownload.serverRelativeUrl);
}
}
catch (Exception e)
{
if (numRetry >= NUM_RETRIES)
{
Console.WriteLine("Gave up trying to download url {0} to file {1} after {2} retries due to error: {3}", SpPrefetchIndexBuilder.topParentSite + toDownload.serverRelativeUrl, toDownload.saveToPath, NUM_RETRIES, e);
}
else
{
AttemptToDownload(toDownload, numRetry + 1);
}
}
}
Is there something wrong with how I'm using HttpClient? I read all the forums and it says to re-use a static reference, and I am doing that. All of my threads share the same static HttpClient reference.
Here is a netstat -a -o -n from when the downloads have been running for a few minutes. There are a lot of TIMED_WAIT sitting there. https://pastebin.com/GTYmqwue In this test i was using SharePoint on port 80. Why is that?
When I run it again a couple minutes later, the number of TIMED_WAIT have increased hundreds more. There must be a leak of some sort going on?
Why is HttpClient leaving 1000's of TIMED_WAIT connections sitting there? How can I get them to close?
I tried to set ServiePointManager.DefaultConnectionLimit = numThreads but it still grows to 1000's of connections.
I think I figured it out finally
I accidentally had a really aggressive client.Timeout = TimeSpan.FromMinutes(5);
I changed this to client.Timeout = TimeSpan.FromSeconds(15);
Now I think the connections aren't leaking anymore.

C# SignalR within a class library

I've been developing a Web Service (C# WebAPI2) so can simply send messages using SignalR and then store the message transcript within a TSQL database. However, after moving the SignalR hubs within a class library I can't seem to access them now. I have developed a very simply console application to communicate with the Web Service but I am getting a strange exception being thrown.
Here is the exception which is being thrown:
"StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1,
Content: System.Net.Http.StreamContent, Headers:\r\n{\r\n
Transfer-Encoding: chunked\r\n X-SourceFiles:
=?UTF-8?B?QzpcRGV2ZWxvcG1lbnRcU291cmNlQ29kZVxTVVBTZXJ2aWNlXFNVUC5TZXJ2aWNlXHNpZ25hbHJcbmVnb3RpYXRl?=\r\n
Cache-Control: private\r\n Date: Wed, 11 Mar 2015 10:50:18 GMT\r\n
Server: Microsoft-IIS/8.0\r\n X-AspNet-Version: 4.0.30319\r\n
X-Powered-By: ASP.NET\r\n Content-Type: text/html;
charset=utf-8\r\n}"
An unhandled exception of type 'System.AggregateException' occurred
in SignalR Client Connection.exe
The Owin Startup file is placed within the Web Service App_Start folder, here is what it looks like:
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using Microsoft.AspNet.SignalR;
[assembly: OwinStartup(typeof(Service.App_Start.Startup))]
namespace Service.App_Start
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Map("/signalr", map =>
{
var hubConfiguration = new HubConfiguration
{
EnableDetailedErrors = true,
EnableJSONP = true
};
map.RunSignalR(hubConfiguration);
});
}
}
}
Many thanks.
I am not sure the details in your case, but for me I found that I was receiving the System.AggregationException:
System.AggregateException was unhandled
HResult=-2146233088
Message=One or more errors occurred.
Source=mscorlib
StackTrace:
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at Client.CommunicationHandler.AddMessage(String method, String args, String serverUri, String hubName) in c:\Workspace\EnvisionRealTimeRemoteOps\CodeProjectSelfHostedBroadcastServiceSignalRSample\Client\CommunicationHandler.cs:line 24
at Client.Program.Main(String[] args) in c:\Workspace\EnvisionRealTimeRemoteOps\CodeProjectSelfHostedBroadcastServiceSignalRSample\Client\Program.cs:line 15
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Net.Http.HttpRequestException
HResult=-2146233088
Message=An error occurred while sending the request.
InnerException: System.Net.WebException
HResult=-2146233079
Message=Unable to connect to the remote server
Source=System
StackTrace:
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
InnerException: System.Net.Sockets.SocketException
HResult=-2147467259
Message=No connection could be made because the target machine actively refused it 127.0.0.1:8083
Source=System
ErrorCode=10061
NativeErrorCode=10061
StackTrace:
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
InnerException:
Until I added a call to the following:
WebApp.Start("http://localhost:8083"); // Put your desired URL in...
Please note that in my case my application is using Self-Hosted SignalR.

Categories

Resources