Mango
Mango
CC#
Created by Mango on 6/27/2024 in #help
MudBlazor exception with MudDataGrid
Getting the following exception when trying out MudDataGrid component
System.InvalidOperationException: Cannot provide a value for property 'EventListener' on type 'MudBlazor.MudDataGrid`1[[BlazorVsaTemplate.Features.Weather.WeatherForecast, BlazorVsaTemplate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'. There is no registered service of type 'MudBlazor.IEventListener'.
at Microsoft.AspNetCore.Components.ComponentFactory.<>c__DisplayClass9_0.<CreatePropertyInjector>g__Initialize|1(IServiceProvider serviceProvider, IComponent component)
at Microsoft.AspNetCore.Components.ComponentFactory.InstantiateComponent(IServiceProvider serviceProvider, Type componentType, IComponentRenderMode callerSpecifiedRenderMode, Nullable`1 parentComponentId)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.InstantiateChildComponentOnFrame(RenderTreeFrame[] frames, Int32 frameIndex, Int32 parentComponentId)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewComponentFrame(DiffContext& diffContext, Int32 frameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewSubtree(DiffContext& diffContext, Int32 frameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(DiffContext& diffContext, Int32 newFrameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange(DiffContext& diffContext, Int32 oldStartIndex, Int32 oldEndIndexExcl, Int32 newStartIndex, Int32 newEndIndexExcl)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.ComputeDiff(Renderer renderer, RenderBatchBuilder batchBuilder, Int32 componentId, ArrayRange`1 oldTree, ArrayRange`1 newTree)
at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment, Exception& renderFragmentException)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
at Microsoft.AspNetCore.Components.RenderTree.Renderer.AddToRenderQueue(Int32 componentId, RenderFragment renderFragment)
at Microsoft.AspNetCore.Components.ComponentBase.StateHasChanged()
at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.<WaitForQuiescence>g__ProcessAsynchronousWork|54_0()
at Microsoft.AspNetCore.Components.RenderTree.Renderer.WaitForQuiescence()
at Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderRootComponentAsync(Int32 componentId, ParameterView initialParameters)
at Microsoft.AspNetCore.Components.Endpoints.EndpointHtmlRenderer.SendStreamingUpdatesAsync(HttpContext httpContext, Task untilTaskCompleted, TextWriter writer)
System.InvalidOperationException: Cannot provide a value for property 'EventListener' on type 'MudBlazor.MudDataGrid`1[[BlazorVsaTemplate.Features.Weather.WeatherForecast, BlazorVsaTemplate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'. There is no registered service of type 'MudBlazor.IEventListener'.
at Microsoft.AspNetCore.Components.ComponentFactory.<>c__DisplayClass9_0.<CreatePropertyInjector>g__Initialize|1(IServiceProvider serviceProvider, IComponent component)
at Microsoft.AspNetCore.Components.ComponentFactory.InstantiateComponent(IServiceProvider serviceProvider, Type componentType, IComponentRenderMode callerSpecifiedRenderMode, Nullable`1 parentComponentId)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.InstantiateChildComponentOnFrame(RenderTreeFrame[] frames, Int32 frameIndex, Int32 parentComponentId)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewComponentFrame(DiffContext& diffContext, Int32 frameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewSubtree(DiffContext& diffContext, Int32 frameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(DiffContext& diffContext, Int32 newFrameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange(DiffContext& diffContext, Int32 oldStartIndex, Int32 oldEndIndexExcl, Int32 newStartIndex, Int32 newEndIndexExcl)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.ComputeDiff(Renderer renderer, RenderBatchBuilder batchBuilder, Int32 componentId, ArrayRange`1 oldTree, ArrayRange`1 newTree)
at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment, Exception& renderFragmentException)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
at Microsoft.AspNetCore.Components.RenderTree.Renderer.AddToRenderQueue(Int32 componentId, RenderFragment renderFragment)
at Microsoft.AspNetCore.Components.ComponentBase.StateHasChanged()
at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.<WaitForQuiescence>g__ProcessAsynchronousWork|54_0()
at Microsoft.AspNetCore.Components.RenderTree.Renderer.WaitForQuiescence()
at Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderRootComponentAsync(Int32 componentId, ParameterView initialParameters)
at Microsoft.AspNetCore.Components.Endpoints.EndpointHtmlRenderer.SendStreamingUpdatesAsync(HttpContext httpContext, Task untilTaskCompleted, TextWriter writer)
I've tried all the steps here: https://blazorstrap.io/V5/V5 as answered in https://stackoverflow.com/questions/70667806/blazor-unhandled-exception-cannot-provide-a-value-for-property-blazorstrapsrc
8 replies
CC#
Created by Mango on 6/10/2024 in #help
Could not load file or assembly…
Could not load file or assembly 'System.Diagnostics.DiagnosticSource, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.
41 replies
CC#
Created by Mango on 4/29/2024 in #help
How to resolve this exception
System.TypeInitializationException: The type initializer for 'Azure.Core.ClientOptions' threw an exception.
---> System.IO.FileLoadException: Could not load file or assembly 'System.Memory, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
at Azure.Core.ClientOptions..ctor(ClientOptions clientOptions, DiagnosticsOptions diagnostics)
at Azure.Core.DefaultClientOptions..ctor()
at Azure.Core.ClientOptions..cctor()
--- End of inner exception stack trace ---
at Azure.Identity.TokenCredentialOptions..ctor()
at Core.Communication.MsGraphEmailService.d__6.MoveNext()
System.TypeInitializationException: The type initializer for 'Azure.Core.ClientOptions' threw an exception.
---> System.IO.FileLoadException: Could not load file or assembly 'System.Memory, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
at Azure.Core.ClientOptions..ctor(ClientOptions clientOptions, DiagnosticsOptions diagnostics)
at Azure.Core.DefaultClientOptions..ctor()
at Azure.Core.ClientOptions..cctor()
--- End of inner exception stack trace ---
at Azure.Identity.TokenCredentialOptions..ctor()
at Core.Communication.MsGraphEmailService.d__6.MoveNext()
I don’t know what version to redirect to and I don’t see this assembly listed as a transient package or otherwise in the executing or calling assembly.
1 replies
CC#
Created by Mango on 3/30/2024 in #help
Need to make an IO call to register a service
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Erp.Core.Extensions;

public static class ServiceCollectionExtensions
{
/// <summary>
/// Adds the Tenant API for retrieving the <see cref="TenantContext"/>.
/// <br />
/// This is required by the ASP.Net application to run. Requires the following value set in appsettings.json in the Configuration section.
/// - TenantEndpoint
/// </summary>
/// <param name="services"></param>
/// <exception cref="HttpRequestException"></exception>
public static void AddTenantContext(this IServiceCollection services)
{
services.AddScoped(sp =>
{
var cache = sp.GetRequiredService<IMemoryCache>();
var configuration = sp.GetRequiredService<IConfiguration>();
var factory = sp.GetRequiredService<IHttpClientFactory>();
var accessor = sp.GetRequiredService<IHttpContextAccessor>();

var host = accessor.HttpContext!.Request.Host.Host;

return cache.GetOrCreate($"tenant.{host}", cacheEntry =>
{
cacheEntry.SlidingExpiration = TimeSpan.FromHours(8);

var endpoint = configuration.GetValue<string>("Configuration:TenantEndpoint");
ArgumentException.ThrowIfNullOrEmpty(endpoint);

using var client = factory.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, $"{endpoint}/api/retrieve-tenant/{host}");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "");

var response = client.Send(request);

if (!response.IsSuccessStatusCode)
throw new HttpRequestException(response.StatusCode.ToString());

var content = response.Content.ToString();
ArgumentException.ThrowIfNullOrEmpty(content);

return new Tenant(Guid.Parse(content));
});
});
}
}
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Erp.Core.Extensions;

public static class ServiceCollectionExtensions
{
/// <summary>
/// Adds the Tenant API for retrieving the <see cref="TenantContext"/>.
/// <br />
/// This is required by the ASP.Net application to run. Requires the following value set in appsettings.json in the Configuration section.
/// - TenantEndpoint
/// </summary>
/// <param name="services"></param>
/// <exception cref="HttpRequestException"></exception>
public static void AddTenantContext(this IServiceCollection services)
{
services.AddScoped(sp =>
{
var cache = sp.GetRequiredService<IMemoryCache>();
var configuration = sp.GetRequiredService<IConfiguration>();
var factory = sp.GetRequiredService<IHttpClientFactory>();
var accessor = sp.GetRequiredService<IHttpContextAccessor>();

var host = accessor.HttpContext!.Request.Host.Host;

return cache.GetOrCreate($"tenant.{host}", cacheEntry =>
{
cacheEntry.SlidingExpiration = TimeSpan.FromHours(8);

var endpoint = configuration.GetValue<string>("Configuration:TenantEndpoint");
ArgumentException.ThrowIfNullOrEmpty(endpoint);

using var client = factory.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, $"{endpoint}/api/retrieve-tenant/{host}");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "");

var response = client.Send(request);

if (!response.IsSuccessStatusCode)
throw new HttpRequestException(response.StatusCode.ToString());

var content = response.Content.ToString();
ArgumentException.ThrowIfNullOrEmpty(content);

return new Tenant(Guid.Parse(content));
});
});
}
}
39 replies
CC#
Created by Mango on 3/26/2024 in #help
Warning CA1848 : For improved performance, use the LoggerMessage delegates...
Can someone show me how implement LoggerMessage into here? My brain is not connecting the dots:
public class ExceptionFilterMiddleware
{
private readonly ILogger<ExceptionFilterMiddleware> _logger;
private readonly RequestDelegate _next;

public ExceptionFilterMiddleware(ILogger<ExceptionFilterMiddleware> logger, RequestDelegate next)
{
_logger = logger;
_next = next;
}

public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
_logger.LogError("An exception occurred processing the request: {ex}", ex); <-- rule violation here
context.Response.ContentType = MediaTypeNames.Application.Json;
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

var json = JsonSerializer.Serialize(new { Message = ex.Message }, context.RequestServices.GetRequiredService<JsonSerializerOptions>());
await context.Response.WriteAsync(json);
}
}
}
public class ExceptionFilterMiddleware
{
private readonly ILogger<ExceptionFilterMiddleware> _logger;
private readonly RequestDelegate _next;

public ExceptionFilterMiddleware(ILogger<ExceptionFilterMiddleware> logger, RequestDelegate next)
{
_logger = logger;
_next = next;
}

public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
_logger.LogError("An exception occurred processing the request: {ex}", ex); <-- rule violation here
context.Response.ContentType = MediaTypeNames.Application.Json;
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

var json = JsonSerializer.Serialize(new { Message = ex.Message }, context.RequestServices.GetRequiredService<JsonSerializerOptions>());
await context.Response.WriteAsync(json);
}
}
}
23 replies
CC#
Created by Mango on 3/6/2024 in #help
JsonSerializerOptions
To be continued
147 replies
CC#
Created by Mango on 1/25/2024 in #help
Getting error when running dotnet command
No description
2 replies
CC#
Created by Mango on 1/19/2024 in #help
DateTimeOffset vs DateTime
All of the dates in our tables are DateTime (sql version mainly) and all the dates are stored as local time (dumb design mainly). I am slowly modernizing the backend and slowly copying all the domain logic into .NET Standard libs so we can transition the app from .NET Framework to .NET 8+. Since none of the new code is being used by the app yet, I figured now might be a good time to fix our local DateTime dumb design. 1) keep new entities using DateTime properties and table stays u changed 2) new domain models uses DateTimeOffset for those properties 3) mapping layer handles converting DateTime to DateTimeOffset and vice versa when moving data in/out of persistence. That way when we can transition the tables to be DateTimeOffset we can support that by just updating the entities and patching the mapping layer. How does this sound?
23 replies
CC#
Created by Mango on 12/21/2023 in #help
✅ Getting error when installing CSharpier globally
C:\Users\mango\AppData\Local\Temp\c9a0f2f7-6b74-4505-bfe2-8c9a0efe4d18\restore.csproj : error NU1301: Unable to load the service index for source https://nuget.telerik.com/v3/index.json.
The tool package could not be restored.
Tool 'csharpier' failed to install. This failure may have been caused by:
* You are attempting to install a preview release and did not use the --version option to specify the version.
* A package by this name was found, but it was not a .NET tool.
* The required NuGet feed cannot be accessed, perhaps because of an Internet connection problem.
* You mistyped the name of the tool.
For more reasons, including package naming enforcement, visit https://aka.ms/failure-installing-tool
C:\Users\mango\AppData\Local\Temp\c9a0f2f7-6b74-4505-bfe2-8c9a0efe4d18\restore.csproj : error NU1301: Unable to load the service index for source https://nuget.telerik.com/v3/index.json.
The tool package could not be restored.
Tool 'csharpier' failed to install. This failure may have been caused by:
* You are attempting to install a preview release and did not use the --version option to specify the version.
* A package by this name was found, but it was not a .NET tool.
* The required NuGet feed cannot be accessed, perhaps because of an Internet connection problem.
* You mistyped the name of the tool.
For more reasons, including package naming enforcement, visit https://aka.ms/failure-installing-tool
21 replies
CC#
Created by Mango on 10/27/2023 in #help
❔ How to specify Basic authentication scheme with NetworkCredentials?
Title. Getting an exception about client sending Ntlm when server is expecting NTLM. Trying to connect to an SSRS server. Is this something I have to set on the SSRS server as well?
4 replies
CC#
Created by Mango on 10/26/2023 in #help
❔ NET 6 breaking changes
82 replies
CC#
Created by Mango on 10/24/2023 in #help
❔ EF Core LINQ translation document
In the process of upgrading a .NET Core 1.1 to 6 app, our EF Core LINQ queries are now hitting some translation issues with the usage of String.Equals(String, StringComparison) method in the IQueryable<DbSet<T>>.Where() method. I’m going through those to clean them up but I was wondering if anyone knew of a blog/SO post that has a list of all the LINQ translation gotchas we may run into?
5 replies
CC#
Created by Mango on 10/10/2023 in #help
❔ Configuring ILogger to log to database.
Does this look right to have ILogger configured to log to database? https://learn.microsoft.com/en-us/answers/questions/805842/how-to-save-logs-into-db
16 replies