Data8.PowerPlatform.Dataverse.Client OnPremiseClient On Linux - c#

I've implemented dynamics 365 sdk using Data8.PowerPlatform.Dataverse.Client with OnPremiseClient. It works on windows platform perfectly.
But when I deployed it on linux server using docker image mcr.microsoft.com/dotnet/aspnet:7.0 which uses Debian 11 Bullseye it requires to install gss-ntlmssp package.
I installed it on the image but when I want to make use of the service the error with bellow stacktrace happens:
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Net.Security.SafeDeleteNegoContext.Dispose(Boolean disposing)
at System.Runtime.InteropServices.SafeHandle.Dispose()
at System.Net.Security.SafeDeleteNegoContext..ctor(SafeFreeNegoCredentials credential, String targetName)
at System.Net.Security.NegotiateStreamPal.EstablishSecurityContext(SafeFreeNegoCredentials credential, SafeDeleteContext& context, ChannelBinding channelBinding, String targetName, ContextFlagsPal inFlags, ReadOnlySpan`1 incomingBlob, Byte[]& resultBuffer, ContextFlagsPal& outFlags)
at System.Net.Security.NegotiateStreamPal.InitializeSecurityContext(SafeFreeCredentials& credentialsHandle, SafeDeleteContext& securityContext, String spn, ContextFlagsPal requestedContextFlags, ReadOnlySpan`1 incomingBlob, ChannelBinding channelBinding, Byte[]& resultBlob, Int32& resultBlobLength, ContextFlagsPal& contextFlags)
at System.Net.NTAuthentication.GetOutgoingBlob(ReadOnlySpan`1 incomingBlob, Boolean throwOnError, SecurityStatusPal& statusCode)
at System.Net.Security.NegotiateAuthentication.GetOutgoingBlob(ReadOnlySpan`1 incomingBlob, NegotiateAuthenticationStatusCode& statusCode)
at Data8.PowerPlatform.Dataverse.Client.ADAuthClient.Authenticate()
at Data8.PowerPlatform.Dataverse.Client.ADAuthClient.Execute(OrganizationRequest request)
at Data8.PowerPlatform.Dataverse.Client.OnPremiseClient.Execute(OrganizationRequest request)
at Ahanonline.Common.DynamicsClient.DynamicsClientService.SetStatus(SetStatusParam param) in /src/Common/DynamicsClient/DynamicsClientService.cs:line 112
at Ahanonline.Services.OnlineQuotes.OnlineQuotesService.UpdateStatus(UpdateOnlineQuoteStatusRequest body, Requester requester) in /src/Services/OnlineQuotes/OnlineQuotesService.cs:line 48
at Ahanonline.App.Controllers.OnlineQuotesController.UpdateStatus(UpdateOnlineQuoteStatusRequest dto, Requester requester) in /src/App/Controllers/OnlineQuotesController.cs:line 30
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Ahanonline.Common.Exceptions.Middlewares.AppExceptionHandlerMiddleware.Invoke(HttpContext context) in /src/Common/Exceptions/Middlewares/AppExceptionHandlerMiddleware.cs:line 24
Anyone got any idea how to resolve this issue ?
I added an implementation on my github repository. The requirements is that you have an on-premise dynamics 365 to test it.
https://github.com/nimasfl/dotnet7-dynamics-test

Related

.NET Core 3.1 The JSON value of length n is too large and not supported

I have an application that uses two .NET Core 3.1 applications. The first .NET Core 3.1 application sends a REST HttpPost request to the second .NET Core 3.1 application.
When my second .NET Core solution returns a response to the HttpPost request, I see an exception : The JSON value of length 806376078 is too large and not supported.
I have tried adding to the App.config file :
1)
2)
3)
I also tried to add to my startup services :
services.Configure(options =>
{
options.ValueCountLimit = 10; //default 1024
options.ValueLengthLimit = int.MaxValue;
options.MultipartBodyLengthLimit = long.MaxValue;
options.MemoryBufferThreshold = Int32.MaxValue;
});
services.AddMvc(options =>
{
options.MaxModelBindingCollectionSize = int.MaxValue;
});
or
services.AddControllersWithViews().
AddJsonOptions(options =>
{
options.JsonSerializerOptions.MaxDepth = Int32.MaxValue;
});
But nothing worked, I still get the exception :
An unhandled exception was thrown by the application.
System.ArgumentException: The JSON value of length 806376078 is too
large and not supported.
when I try to return an 806376078 byte array from the second .Net Core 3.1 web service.
Can you recommend some solution or approach for me to try to fix this exception?
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HMJQ9OLIK5S4", Request id "0HMJQ9OLIK5S4:00000003": An unhandled exception was thrown by the
application. System.ArgumentException: The JSON value of length
806376078 is too large and not supported. at
System.Text.Json.ThrowHelper.ThrowArgumentException_ValueTooLarge(Int32
tokenLength) at
System.Text.Json.Utf8JsonWriter.WriteBase64StringValue(ReadOnlySpan1 bytes) at System.Text.Json.Serialization.Converters.JsonConverterByteArray.Write(Utf8JsonWriter writer, Byte[] value, JsonSerializerOptions options) at System.Text.Json.JsonPropertyInfoNotNullable4.OnWriteEnumerable(WriteStackFrame&
current, Utf8JsonWriter writer) at
System.Text.Json.JsonPropertyInfo.WriteEnumerable(WriteStack& state,
Utf8JsonWriter writer) at
System.Text.Json.JsonSerializer.HandleEnumerable(JsonClassInfo
elementClassInfo, JsonSerializerOptions options, Utf8JsonWriter
writer, WriteStack& state) at
System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer, Int32
originalWriterDepth, Int32 flushThreshold, JsonSerializerOptions
options, WriteStack& state) at
System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, Object
value, Type inputType, JsonSerializerOptions options,
CancellationToken cancellationToken) at
Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext
context, Encoding selectedEncoding) at
Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext
context, Encoding selectedEncoding) at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker
invoker, Task lastTask, State next, Scope scope, Object state, Boolean
isCompleted) at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed
context) at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State&
next, Scope& scope, Object& state, Boolean& isCompleted) at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location where exception was thrown --- at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker
invoker, Task lastTask, State next, Scope scope, Object state, Boolean
isCompleted) at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed
context) at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State&
next, Scope& scope, Object& state, Boolean& isCompleted) at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown --- at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker
invoker, Task task, IDisposable scope) at
Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint
endpoint, Task requestTask, ILogger logger) at
Microsoft.AspNetCore.Watch.BrowserRefresh.BrowserRefreshMiddleware.InvokeAsync(HttpContext
context) at
Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext
context) at
Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1
application)

error while get very large amount of documents in one collection in FireStore - asp.net c#

i try to get about hundred of thousands data from FireStore, but i encounter this kinds of error.
am i reach the limmit of read documents in 1 execution ?
here's the error statement
Grpc.Core.RpcException: Status(StatusCode="Unavailable", Detail="The datastore operation timed out, or the data was temporarily unavailable.", DebugException="Grpc.Core.Internal.CoreErrorDetailException: {"created":"#1648103323.710000000","description":"Error received from peer ipv4:34.101.5.42:443","file":"..\..\..\src\core\lib\surface\call.cc","file_line":1067,"grpc_message":"The datastore operation timed out, or the data was temporarily unavailable.","grpc_status":14}")
at Grpc.Core.Internal.ClientResponseStream`2.MoveNext(CancellationToken token)
at Google.Api.Gax.Grpc.AsyncResponseStream`1.MoveNextAsync(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.<ForEachAsync>g__Core|295_0[TSource](IAsyncEnumerable`1 source, Action`1 action, CancellationToken cancellationToken) in d:\a\1\s\Ix.NET\Source\System.Linq.Async\System\Linq\Operators\ForEach.cs:line 31
at System.Linq.AsyncEnumerable.<ForEachAsync>g__Core|295_0[TSource](IAsyncEnumerable`1 source, Action`1 action, CancellationToken cancellationToken) in d:\a\1\s\Ix.NET\Source\System.Linq.Async\System\Linq\Operators\ForEach.cs:line 31
at Google.Cloud.Firestore.Query.GetSnapshotAsync(ByteString transactionId, CancellationToken cancellationToken)
at vgr_data.Services.PesertaService.GetWithFilterFaskesExternalAsync(PesertaFilter filter) in D:\Projects\VGR-Data-API\vgr-data\vgr-data\Services\PesertaService.cs:line 994
at vgr_data.Controllers.PesertaController.ExportFaskesExternal(PesertaFilter filter) in D:\Projects\VGR-Data-API\vgr-data\vgr-data\Controllers\PesertaController.cs:line 2980
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
i tried to get this data with chunk the amount of OFFSET [[ query.OFFSET().GetsnapshotAsync() ]], at first it worked, but since the data is still growing, but now it comes to an error.
int pageCount = 0;
int dataCount = 1;
List<MyModel> listItem = new List<MyModel>();
while (dataCount > 0)
{
dataCount = 0;
QuerySnapshot querySnapshot = await _query.Offset(40000 * pageCount).Limit(40000).GetSnapshotAsync();
dataCount = querySnapshot.Count();
foreach (DocumentSnapshot documentSnapshot in querySnapshot.Documents)
{
if (documentSnapshot.Exists)
{
Dictionary<string, object> obj = documentSnapshot.ToDictionary();
MyModel item = _mapper.Map<MyModel>(obj);
item.Id = documentSnapshot.Id;
listItem.Add(item);
}
}
System.Diagnostics.Debug.WriteLine("Total List : "+ listItem.Count());
pageCount += 1;
}
but at the end, i still get the error after reaching about 400k of data
Firestore query pagination is based on query cursors is based on query cursors, and the documentation recommends against using offsets:
Do not use offsets. Instead, use cursors. Using an offset only avoids returning the skipped documents to your application, but these documents are still retrieved internally. The skipped documents affect the latency of the query, and your application is billed for the read operations required to retrieve them.
It looks like your read operation is timing out on the Firestore side, and I suspect this offset call may be involved:
_query.Offset(40000 * pageCount).Limit(40000)
I recommend rewriting your code to use cursor-based queries for pagination.

Getting SqlException and ObjectDisposedException in Asp.net core 5 webapi

I have a repository for albums table (album entity) and I do filtering and paging in repository as you see:
public IQueryable<Album> GetAllAlbums(AlbumQueryParameters queryParameters)
{
var albums = _cache.Get<IQueryable<Album>>("_AllAlbums");
if(albums == null){
albums = _context.Albums;
_cache.Set<IQueryable<Album>>("_AllAlbums", albums, ApplicationDefaults.MemoryCachingOption);
}
if(queryParameters.ArtistId != null)
{
albums = albums.Include(a => a.ArtistToAlbums)
.SelectMany(a => a.ArtistToAlbums)
.Where(a => a.ArtistId == Convert.ToInt32(queryParameters.ArtistId))
.Select(a => a.Album);
}
if(queryParameters.GenreId != null)
{
albums = albums.Include(a => a.AlbumToGenres)
.SelectMany(a => a.AlbumToGenres)
.Where(a => a.GenreId == Convert.ToInt32(queryParameters.GenreId))
.Select(a => a.Album);
}
// Pagination
albums = albums.Skip(queryParameters.Size * (queryParameters.Page - 1))
.Take(queryParameters.Size);
return albums;
}
And here is my controller:
[HttpGet]
public async Task<IActionResult> GetAllAlbums([FromQuery] AlbumQueryParameters queryParameters)
{
var albums = _albumRepository.GetAllAlbums(queryParameters);
return Ok(await albums.ToListAsync());
}
When I try to get data from this action I get this error:
Microsoft.Data.SqlClient.SqlException (0x80131904): The number of rows provided for a FETCH clause must be greater then zero.
at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at Microsoft.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows)
at Microsoft.Data.SqlClient.SqlDataReader.TryReadInternal(Boolean setTimeout, Boolean& more)
at Microsoft.Data.SqlClient.SqlDataReader.ReadAsyncExecute(Task task, Object state)
at Microsoft.Data.SqlClient.SqlDataReader.InvokeAsyncCall[T](AAsyncCallContext`1 context)
--- End of stack trace from previous location ---
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
at StoreApi.Controllers.AlbumController.GetAllAlbums(AlbumQueryParameters queryParameters) in /home/nalien/Projects/albumshop/StoreApi/Controllers/AlbumController.cs:line 27
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
ClientConnectionId:66426711-f9b4-470a-898d-a0a0bd3082d1
Error Number:10744,State:1,Class:15
HEADERS
=======
Connection: keep-alive
Accept: */*
Accept-Encoding: gzip, deflate, br
Host: localhost:5001
Referer: http://localhost:5000/api/album?artistId=1
User-Agent: PostmanRuntime/7.26.8
Postman-Token: 317f1fb0-a03b-4c15-a6da-87b69934bf57
And when I comment the Pagination I get a new error:
System.ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'ApplicationDbContext'.
at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
at Microsoft.EntityFrameworkCore.DbContext.get_ChangeTracker()
at Microsoft.EntityFrameworkCore.Query.CompiledQueryCacheKeyGenerator.GenerateCacheKeyCore(Expression query, Boolean async)
at Microsoft.EntityFrameworkCore.Query.RelationalCompiledQueryCacheKeyGenerator.GenerateCacheKeyCore(Expression query, Boolean async)
at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerCompiledQueryCacheKeyGenerator.GenerateCacheKey(Expression query, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetAsyncEnumerator(CancellationToken cancellationToken)
at System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable`1.GetAsyncEnumerator()
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
at StoreApi.Controllers.AlbumController.GetAllAlbums(AlbumQueryParameters queryParameters) in /home/nalien/Projects/albumshop/StoreApi/Controllers/AlbumController.cs:line 27
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
HEADERS
=======
Connection: keep-alive
Accept: */*
Accept-Encoding: gzip, deflate, br
Host: localhost:5001
Referer: http://localhost:5000/api/album?artistId=2
User-Agent: PostmanRuntime/7.26.8
Postman-Token: 6291c9cf-87cd-45a8-bc84-8d796efbed03
And here is the way I registered my services:
services.AddDbContext<ApplicationDbContext>(options => {options.UseSqlServer(configuration.GetConnectionString("MainDatabase"));});
services.AddTransient<IAlbumRepository, AlbumRepository>();
services.AddMemoryCache();
I don't know what to do to fix my problem.
The first exception happened when Skip and Take is zero, so you can check it before add pagination to query:
if(queryParameters.Size>0)
albums = albums.Skip(queryParameters.Size * (queryParameters.Page - 1)) .Take(queryParameters.Size);
The second exception is about object life time you add ApplicationDbContext as Scope means it lives in request life time but you add IAlbumRepository as Transient means a new instance is provided to every call interface so when you call this line:
var albums = _albumRepository.GetAllAlbums(queryParameters);
One instance of IAlbumRepository created and when respond and return albums, it will disposed and any objects in it will disposed (includes ApplicationDbContext), for prevent this exception just add IAlbumRepository as Scoped like this:
services.AddScoped<IAlbumRepository, AlbumRepository>();
I think it's better to return List instead of IQueryable some thing like this:
public async List<Album> GetAllAlbums(AlbumQueryParameters queryParameters)
{
//do some stuff
return await ablums.ToListAsync();
}
And in the controller:
return Ok(await _albumRepository.GetAllAlbums(queryParameters));

Get An existing connection was forcibly closed by the remote host When Send File Request

When client call API some of request make server login this error "An existing connection was forcibly closed by the remote host."
stack trace: at System.IO.Pipelines.PipeCompletion.ThrowLatchedException()
at System.IO.Pipelines.Pipe.GetReadResult(ReadResult& result)
at System.IO.Pipelines.Pipe.GetReadAsyncResult()
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1ContentLengthMessageBody.ReadAsyncInternal(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.ReadAsyncInternal(Memory`1 buffer, CancellationToken cancellationToken)
at Microsoft.AspNetCore.WebUtilities.FileBufferingReadStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
at Microsoft.AspNetCore.WebUtilities.BufferedReadStream.EnsureBufferedAsync(Int32 minCount, CancellationToken cancellationToken)
at Microsoft.AspNetCore.WebUtilities.MultipartReaderStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
at Microsoft.AspNetCore.WebUtilities.StreamHelperExtensions.DrainAsync(Stream stream, ArrayPool`1 bytePool, Nullable`1 limit, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Http.Features.FormFeature.InnerReadFormAsync(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Mvc.ModelBinding.FormValueProviderFactory.AddValueProviderAsync(ValueProviderFactoryContext context)
at Microsoft.AspNetCore.Mvc.ModelBinding.CompositeValueProvider.CreateAsync(ActionContext actionContext, IList`1 factories)
at Microsoft.AspNetCore.Mvc.ModelBinding.CompositeValueProvider.TryCreateAsync(ActionContext actionContext, IList`1 factories)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
--- end stack trace
How can I fix this error?
This error logged some of the requests, not all requests.

Web api with two gets that do different actions

I have two get statements in a controller
[HttpGet("{projectId:int}")]
public async Task<ActionResult<Models.Project>> GetById(int projectId)
{
var project = await _context.Projects.FindAsync(projectId);
if (project == null)
{
return NotFound();
}
return project;
}
// GET: api/project/5
[HttpGet("{projectCode}")]
public async Task<ActionResult<Project>> GetProjectByProjectCode(string projectCode)
{
var projects = await _context.Projects.FindAsync(projectCode);
if (projects == null)
{
return NotFound();
}
return projects;
}
The first get works perfectly and does what it is supposed to do pass in an ID and return the project associated with that ID
The second get does not work like it is supposed to. What it is supposed to do is pass in a projectCode parameter (string) and return the project associated with that project code.
The project codes are formatted like this --7000316139.13.01-- so that is why I am passing it using a string parameter
When I run the api with swagger I get the following error
System.ArgumentException: The key value at position 0 of the call to 'DbSet.Find' was of type 'string', which does not match the
property type of 'int'. at
Microsoft.EntityFrameworkCore.Internal.EntityFinder1.FindTracked(Object[] keyValues, IReadOnlyList1& keyProperties) at
Microsoft.EntityFrameworkCore.Internal.EntityFinder1.FindAsync(Object[] keyValues, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.FindAsync(Object[]
keyValues) at
Mcr.PRT.PM.Service.Controllers.ProjectController.GetProjectByProjectCode(String
projectCode) in
C:\Users\MaxGay\Source\Repos\PRT2\ProjectManagementService\Controllers\ProjectController.cs:line
98 at lambda_method(Closure , Object ) at
Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
at
Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper
mapper, ObjectMethodExecutor executor, Object controller, Object[]
arguments) at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker
invoker, ValueTask`1 actionResultValueTask) at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker
invoker, Task lastTask, State next, Scope scope, Object state, Boolean
isCompleted) at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed
context) at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State&
next, Scope& scope, Object& state, Boolean& isCompleted) at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown --- at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker
invoker, Task lastTask, State next, Scope scope, Object state, Boolean
isCompleted) at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed
context) at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State&
next, Scope& scope, Object& state, Boolean& isCompleted) at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown --- at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker
invoker, Task task, IDisposable scope) at
Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint
endpoint, Task requestTask, ILogger logger) at
Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext
httpContext) at
Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext
httpContext, ISwaggerProvider swaggerProvider) at
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext
context) at
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext
context) at
Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext
httpContext) at
Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext
httpContext, ISwaggerProvider swaggerProvider) at
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext
context)
HEADERS
======= Accept: text/plain Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Host: localhost Referer:
https://localhost/index.html User-Agent: Mozilla/5.0 (Windows NT 10.0;
Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83
Safari/537.36 Edg/85.0.564.41 :method: GET :authority: localhost
:scheme: https :path: /api/Project/7000316139.13.01 sec-fetch-site:
same-origin sec-fetch-mode: cors sec-fetch-dest: empty
I am not sure what the error is and why it is happening?
I have tried to switch the GetProjectsByProjectCode to public IActionResult but that did not help either
As ChiefTwoPencils pointed out the issue here is the primary key is an int and I am passing a string. I think I should probably get some sleep

Categories