Debug Blazor circuit errors - asp.net-core

I have stuck for a couple days now.. There is an error in my Blazor server application, no errors get thrown in Visual Studio, it appears in the console debug tools..
Error: System.AggregateException: One or more errors occurred. (TypeError: i.parentNode is null)
---> System.InvalidOperationException: TypeError: i.parentNode is null
at Microsoft.AspNetCore.Components.RenderTree.Renderer.InvokeRenderCompletedCallsAfterUpdateDisplayTask(Task updateDisplayTask, Int32[] updatedComponents)
--- End of inner exception stack trace ---
This gives me no clue.. I dont know what else to try to get to where the error is happening
I have tried Stepping through the code, but it happens even on pages where there is no code (I suspect startup.cs but no errors thrown)
I have also made bare MainLayout, still error
AppSettings
{
"DetailedErrors": true,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
startup.cs / configure services
services.AddServerSideBlazor().AddCircuitOptions(options => { options.DetailedErrors = true; });
but still I only get those three lines

Related

IConfiguration does not retrieve values from appsettings.json but from Azure Key Vault

Inside the Program.cs file of a .NET Core 3.1 Web API i got the following:
public class Program
{
private static string _someValue;
public Program(IConfiguration configuration)
{
_someValue = configuration["SOME_VALUE"]
}
inside the appsettings.json i got:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"SOME_VALUE": "value"
}
The problem is, i am not able to get the value "SOME_VALUE" from the appsettings.json. But i got this same value inside an Azure Key Vault and for some reason it gets the values from there. Can someone explain why that is the case?
Configuration providers are executed in a specific order
In your case, the Azure KeyVault will be at the top (or, to be more precise it is between AddUserSecrets and AddEnvironmentVariables)
See docs
Order configuration providers in code to suit the priorities for the underlying configuration sources that the app requires or use different variable name

Console logger with json formatter does not serialize objects

I try to use default .NET core logging tools without any third party libs. So, question.
Does console logger with Json formatter support json serialization of objects?
I have the following config in appsettings
"Logging": {
"Console": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information",
"Microsoft.Hosting.Lifetime": "Information"
},
"FormatterName": "json",
"FormatterOptions": {
"SingleLine": true,
"JsonWriterOptions": {
"Indented": true
}
}
}
},
The following line
logger.LogDebug("RequestId:{requestId} ResponseInfo: {#response} ", requestName, response);
produces the output with string representation of #response object, internally it still invokes ToString(), but docs in Caution section says that
The logging infrastructure itself already manages the serialization of log messages, so if you're to pass in a log message that is already serialized—it will be double serialized
docs
And this point me that it should serialize object.
I think the build-in ILogger don't support this. That's why we can try the new System.Text.Json source generator.
The new System.Text.Json source generator can improve logging performance.
I think we also can choose third-party package, like Serilog. That should be more easy to do this.

ASP.NET Web API not logging exception in application insights when deployed in Azure

I have enabled application insights logging in my ASP.NET Web API project which is done from a class implementing IExceptionLogger. In debug mode it's logging exceptions to application insights using TrackException().
But when the same code is deployed in an Azure App Service, it's not sending exception to application insights, but it's able to send data using traces.
After trying lot of different ways (flush also), I have added one method which will log exception in SharePoint list, after that Web API is also able to send data to Application Insights. When commenting out the SharePoint code, the Web API stopped sending exception to Application Insights.
I am not sure whether its happening due to some extra time that TelemetryClient is getting due to SharePoint code.
Anyone faced this issue?
Here is the Microsoft doc link which I have followed: LINK
Make sure you have added the Application Insights logging level in appsettings.json
{
"Logging": {
"ApplicationInsights": {
"LogLevel": {
"Default": "Trace",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ApplicationInsights": {
"ConnectionString": "< App insights connection string>"
}
}
After adding the log level of application insights I can able to see the custom logs and exceptions.
Here you can see the security level to verify the logging level
Refer here

ASP.NET Core 3.1 HttpClient to log only warnings and errors

I've noticed that my application(service) that supposed to run in a backgraund creates a log of garbage logging information because of HttpClient, like so:
info: System.Net.Http.HttpClient.Default.LogicalHandler[100]
Start processing HTTP request POST https://localhost:44317/programmatic/getcontent info:
System.Net.Http.HttpClient.Default.ClientHandler[100]
Sending HTTP request POST https://localhost:44317/programmatic/getcontent info:
System.Net.Http.HttpClient.Default.ClientHandler[101]
Received HTTP response after 3027.6345ms - OK info: System.Net.Http.HttpClient.Default.LogicalHandler[101]
End processing HTTP request after 3028.2987ms - OK info: System.Net.Http.HttpClient.Default.ClientHandler[101]
Received HTTP response after 3052.4709ms - OK info: System.Net.Http.HttpClient.Default.LogicalHandler[101]
End processing HTTP request after 3053.467ms - OK
Is there a way to configure it anywhere?
I inject client factory like this:
serviceCollection.AddHttpClient();
And then create a client like this:
HttpClient client = _clientFactory.CreateClient();
You can configure Logging in .NET Core through the Appsettings file. You should find a section in the appsettings.json file along the lines
{
"Logging": {
"Debug": {
"LogLevel": {
"Default": "Information"
}
}
}
}
You can add an additional Log Level filter to specify the minimum log level required to log.
{
"Logging": {
"Debug": {
"LogLevel": {
"Default": "Information",
"System.Net.Http.HttpClient": "Debug"
}
}
}
}
Documentation for Logging with filters in .NET Core can be found here.
Documemtation for Logging with filters in the IHttpClientFactory library can be found here. This documentation also includes examples of log filtering with a named HttpClient.
You can override log level in appsettings.json by adding, for example, a new row to the Logging object:
"Logging": {
"LogLevel": {
"System.Net.Http.HttpClient": "Warning"
}
},
This will log anything from Warning level and above.

How to make gRPC client comunicate with a gRPC server in a different machine? Both in Aspnet Core 3.0. Possible SSL problem

So, by the title you know what I'm trying to build.
I already have one gRPC server and 3 clients talking together in the same machine. The server is accessible on http://localhot:5001. Everything runs smoothly but if I run the clients on another machine they cannot access the server. So I installed IIS and placed the server there for it to get served to outside with the domain beta.server.com. I altered the hosts file on the client machine to go to the computer ip(192.168.5.49) where the server is running on IIS.
When I try to access with the browser by http i get a message saying i can only connect with a gRPC client. By https says NET::ERR_CERT_COMMON_NAME_INVALID. Maybe this is the problem...(found out after writing the rest).
By trying to connect with a gRPC client to http(http://beta.server.com) I get an error saying http/1.1 is not supported, which is true, this service works only on http2.
When try to connect to the server ip with https(https://beta.server.com) I get the error that the ssl connection could not be established. As follows:
PS C:\Users\Farm\Desktop\GrpcSierConsole\Viewer> dotnet run
Entered task
Unhandled exception. System.AggregateException: One or more errors occurred. (Status(StatusCode=Internal, Detail="Error starting gRPC call: The SSL connection could not be established, see inner exception."))
---> Grpc.Core.RpcException: Status(StatusCode=Internal, Detail="Error starting gRPC call: The SSL connection could not be established, see inner exception.")
at Grpc.Net.Client.Internal.HttpContentClientStreamReader`2.MoveNextCore(CancellationToken cancellationToken)
at Grpc.Core.AsyncStreamReaderExtensions.ReadAllAsync[T](IAsyncStreamReader`1 streamReader, CancellationToken cancellationToken)+MoveNext()
at Grpc.Core.AsyncStreamReaderExtensions.ReadAllAsync[T](IAsyncStreamReader`1 streamReader, CancellationToken cancellationToken)+System.Threading.Tasks.Sources.IValueTaskSource<System.Boolean>.GetResult()
at Viewer.Program.<>c.<<Main>b__0_0>d.MoveNext() in C:\Users\Farm\Desktop\GrpcSierConsole\viewer\Program.cs:line 24
--- End of stack trace from previous location where exception was thrown ---
at Viewer.Program.<>c.<<Main>b__0_0>d.MoveNext() in C:\Users\Farm\Desktop\GrpcSierConsole\viewer\Program.cs:line 24
--- End of inner exception stack trace ---
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 Viewer.Program.Main() in C:\Users\Farm\Desktop\GrpcSierConsole\viewer\Program.cs:line 29
The error is on line 29 on the program.cs in the server. The code I have there is the following:
Line 29 is webBuilder.UseStartup():
//Additional configuration is required to successfully run gRPC on macOS.
// For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
I've tried to use the Visual Studio localhost certificate and a self signed certificate within the IIS in both the client computer and the server computer running IIS.
Also I've used this line in the client to trust all certificates:
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
Which I got from: How to ignore the certificate check when ssl
I don't know what more to do. Anyone can help?
##################### UPDATE ######################
I've added this code to the client
var httpClientHandler = new HttpClientHandler();
// Return `true` to allow certificates that are untrusted/invalid
httpClientHandler.ServerCertificateCustomValidationCallback =
HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
var httpClient = new HttpClient(httpClientHandler);
var channel = GrpcChannel.ForAddress("https://localhost:5001",
new GrpcChannelOptions { HttpClient = httpClient });
var client = new QueueManagement.QueueManagementClient(channel);
...
Now I don't have the SSL error but this one:
PS C:\Users\Farm\Desktop\GrpcSierConsole\Viewer> dotnet run
Entered task
Unhandled exception. System.AggregateException: One or more errors occurred. (Status(StatusCode=Internal, Detail="Error starting gRPC call: An error occurred while sending the request."))
---> Grpc.Core.RpcException: Status(StatusCode=Internal, Detail="Error starting gRPC call: An error occurred while sending the request.")
at Grpc.Net.Client.Internal.HttpContentClientStreamReader`2.MoveNextCore(CancellationToken cancellationToken)
at Grpc.Core.AsyncStreamReaderExtensions.ReadAllAsync[T](IAsyncStreamReader`1 streamReader, CancellationToken cancellationToken)+MoveNext()
at Grpc.Core.AsyncStreamReaderExtensions.ReadAllAsync[T](IAsyncStreamReader`1 streamReader, CancellationToken cancellationToken)+System.Threading.Tasks.Sources.IValueTaskSource<System.Boolean>.GetResult()
at Viewer.Program.<>c.<<Main>b__0_0>d.MoveNext() in C:\Users\Farm\Desktop\GrpcSierConsole\Viewer\Program.cs:line 32
--- End of stack trace from previous location where exception was thrown ---
at Viewer.Program.<>c.<<Main>b__0_0>d.MoveNext() in C:\Users\Farm\Desktop\GrpcSierConsole\Viewer\Program.cs:line 32
--- End of inner exception stack trace ---
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 Viewer.Program.Main() in C:\Users\Farm\Desktop\GrpcSierConsole\Viewer\Program.cs:line 37
And at line 37 i have the task.wait() because this runs inside a task.
var channel = GrpcChannel.ForAddress("https://beta.server.com",
new GrpcChannelOptions { HttpClient = httpClient });
var client = new QueueManagement.QueueManagementClient(channel);
var request = client.QueueNumberChanged(new SendQueueId { QueueId = "2" });
await foreach (var response in request.ResponseStream.ReadAllAsync())
{
Console.WriteLine($"Senha {response.Number} -> fila 2");
}
});
t.Wait();
After a great research and many messages exchanged in Issues at Microsoft official GitHub Repository for .Net Core kestrel documentation i found it.
It can be done with this settings on appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Kestrel": {
"EndpointDefaults": {
"Protocols": "Http2"
},
"EndPoints": {
"Https": {
"Url": "https://*:5002",
"Certificate": {
"Path": "c:\\test.pfx",
"Password": "password1234"
}
}
}
},
}