I am trying to use serilog in my .net 6 App and I am not able to get it working with enrichers. Below is my program.cs file:
using Serilog;
var builder = WebApplication.CreateBuilder(args);
// remove default logging providers (clearing provides then no log appears)
//builder.Logging.ClearProviders();
// Serilog configuration
var logger = new LoggerConfiguration()
.WriteTo.Console()
.Enrich.WithProperty("Property", "MyProperty")
.CreateLogger();
// Register Serilog
builder.Logging.AddSerilog(logger);
var app = builder.Build();
app.MapGet("/", (ILoggerFactory loggerFactory) => {
var logger = loggerFactory.CreateLogger("index");
var position = new { Latitude = 25, Longitude = 134 };
var elapsedMs = 34;
logger.LogInformation("Processed {#Position} in {Elapsed:000} ms.", position, elapsedMs);
return "Hello world";
});
app.Run();
if I Add "builder.Logging.ClearProviders()" then I cannot see any log message. When I remove "builder.Logging.ClearProviders()" I can see the logs but enrichers are not working.
This is happening in .Net 6 App only. Does anyone face the same issue with .net 6?
can anyone please help how to solve this issue ?
Related
Build environment:
Macbook M1
vscode(1.69.0) as well as vs2022 (17.3)
Steps to reproduce:
create new Maui app
add nuget package "Microsoft.Extensions.Http" Version="6.0.0" to project
Modify MauiProgram.cs:
builder.Services.AddHttpClient<EndPointAHttpClient>(client =>
{
var EndPointA = "https://www.montemagno.com/";
client.BaseAddress = new Uri(EndPointA);
});
public class EndPointAHttpClient
{
public EndPointAHttpClient(HttpClient client)
{
Client = client;
}
public HttpClient Client { get; }
}
Publish:
dotnet publish <project.csproj> -f:net6.0-ios -c:Release /p:ServerAddress=<xxx.xxx.xxx.xxx> /p:ServerUser=user /p:TcpPort=58181 /p:ServerPassword=pwd -p:AotAssemblies=false
Install on iphone using Transporter/TestFlight
CRASHES WHEN OPENING THE APP
Please let me know:
1. Is there any demo code that works
2. Kindly provide advise on how I can use HttpClient in a .net Maui app
Use the code found here. https://github.com/dotnet/maui-samples/tree/main/6.0/WebServices/TodoREST/TodoREST/Services
Grab the RestService, IRestService, HttpsClientHandlerService and IHttpsClientHandlerService.
Get the Contstants file as well.
https://github.com/dotnet/maui-samples/blob/main/6.0/WebServices/TodoREST/TodoREST/Constants.cs
Makes sure you add your Url to the HttpsClientHandlerService like so. I was getting a System.Net.WebException: Error: TrustFailure. The only way I was able to catch what was happening was using Sentry.io. I guessed that this might be the problem.
public bool IsSafeUrl(NSUrlSessionHandler sender, string url, Security.SecTrust trust)
{
if (url.StartsWith("https://localhost") || url.StartsWith("https://yourservice.azurewebsites.net"))
return true;
return false;
}
Then change this line.
var handler = new NSUrlSessionHandler
{
TrustOverrideForUrl = IsSafeUrl
};
I'm trying to write a simple HTML to PDF converter with puppeteer-sharp. It is going to be part of MVC.NET project.
var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = true,
ExecutablePath = #"C:\Dev\NewPdfLib\chrome-win\chrome.exe",
Args = new string[] { "--disable-gpu" },
Timeout = 0,
UserDataDir = workingFolder
})
var page = await browser.NewPageAsync();
//await page.GoToAsync("http://www.google.com");
//await page.PdfAsync(output);
When I run this code an exception "WebSocketException: The WebSocket is in an invalid state ('Aborted') for this operation. Valid states are: 'Open, CloseReceived'" is thrown at browser.NewPageAsync() line.
The system is Windows 10 and the project is in .NET Framework 4.8
8/3/2022 13:40:32 NotImplementedError: This is not implemented yet. For currently supported API, see: https://developers.google.com/google-ads/scripts-beta/docs/reference/adsapp/adsapp
at Ha (adsapp_compiled:298:11)
at new $y (adsapp_compiled:13027:5)
at qC.newVideoAd (adsapp_compiled:15250:12)
at Object.<anonymous> (adsapp_compiled:18396:54)
var youtubeVideoId = "youtubeVideoId";
var adGroupName = "adGroupName" // name of my target video ad group
var displayUrl = "display-url.com";
var finalUrl = "https://final-url.com";
var assetOperation = AdsApp.adAssets().newYouTubeVideoAssetBuilder()
.withName(adName)
.withYouTubeVideoId(youtubeVideoId)
.build();
var videoAsset = assetOperation.getResult();
var videoAdGroup = AdsApp.videoAdGroups()
.withCondition(`Name = '${adGroupName}'`)
.withLimit(1)
.get()
.next();
var videoAdOperation = videoAdGroup.newVideoAd().inStreamAdBuilder()
.withVideo(videoAsset)
.withAdName(adName)
.withDisplayUrl(displayUrl)
.withFinalUrl(finalUrl)
.build()
.getResult();
// Code crash before next statement
if(videoAdOperation.isSuccessful()) {
var videoAd = videoAdOperation.getResult();
Logger.log("VideoAd " + videoAd.getName() + " created.");
} else {
Logger.log(videoAdOperation.getErrors());
}
Code breaks after videoAdGroup.newVideoAd().inStreamAdBuilder().
Following the google ads script docs everything should works nice.
But when I compile the script, I always get the next error:
I have just found in a Google ads scripts forum somebody who has the same problem here but no solution.
The problem is that beta mode which is active by default. Must be switched off for this action.
As a negative point, switch off Beta mode will not allow you to use javascript arrow functions, neither js classes.
When implementing OAuth with aqueduct I mistakenly didn't follow the test driven development ideology, and I am paying for it now...
When I run my tests, I get the error:
"No configuration file found. See README.md."
Which is thrown from the initializeApplication method in my AppSink class.
As I understand it, tests make use of the config.src.yaml file so I have configured my test harness accordingly:
application = new Application<OdexSink>();
application.configuration.port = 0;
application.configuration.configurationFilePath = "config.src.yaml";
Since I was able to run the tests before I implemented the AuthServer etc, I suspect it happened along the way.
My test setUp is as follows:
var app = new Application<OdexSink>();
TestClient client;
setUp(() async {
await app.start(runOnMainIsolate: true);
client = new TestClient(app);
var ctx = ManagedContext.defaultContext;
var builder = new SchemaBuilder.toSchema(ctx.persistentStore, new Schema.fromDataModel(ctx.dataModel), isTemporary: true);
for (var cmd in builder.commands) {
await ctx.persistentStore.execute(cmd);
}
});
And my Test harness start() method is:
Future start() async {
RequestController.letUncaughtExceptionsEscape = true;
application = new Application<OdexSink>();
application.configuration.port = 0;
application.configuration.configurationFilePath = "config.src.yaml";
await application.start(runOnMainIsolate: true);
await createDatabaseSchema(ManagedContext.defaultContext, sink.logger);
await addClientRecord();
await addClientRecord(clientID: DefaultClientID, clientSecret: DefaultClientSecret);
client = new TestClient(application)
..clientID = DefaultClientID
..clientSecret = DefaultClientSecret;
}
My config.src.yaml file exits, and contains DB information.
Ah, just one small thing - in your setUp method, you are creating and starting an Application instead of that TestApplication harness. It should look like this
var app = new TestApplication();
setUp(() async {
await app.start();
});
All of the other stuff in setUp is already done in your test harness and you can use the TestClient as app.client:
expect(await app.client.request("/endpoint"), hasStatus(200));
I Am trying to use Quartz.Net so as to Schedule Jobs Within a Windows Service that I developped.
I included the following code on the Onstart Method, scheduler is a Class attribute
private readonly IScheduler scheduler;
logger = LogManager.GetLogger(typeof (TelegestionService));
scheduler = new StdSchedulerFactory().GetScheduler();
var job = new JobDetail("job1", "group1", typeof (HelloJob));
var trigger = new SimpleTrigger("trigger1", "group1", runTime);
scheduler.ScheduleJob(job, trigger);
This works fine for me. I got the Job running.
Now I'am trying to make the scheduler embedded remotely accessible, based en Example12 in the Quartz source Examples (the Console Server/Client works fine).
var properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "RemoteServer";
properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
properties["quartz.threadPool.threadCount"] = "5";
properties["quartz.threadPool.threadPriority"] = "Normal";
properties["quartz.scheduler.exporter.type"] = "Quartz.Simpl.RemotingSchedulerExporter, Quartz";
properties["quartz.scheduler.exporter.port"] = "555";
properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler";
properties["quartz.scheduler.exporter.channelType"] = "tcp";
scheduler = new StdSchedulerFactory(properties).GetScheduler();
The service starts correctly and so does the scheduler but i cannot remotely schedule the Job using a Console/Winform Client (Connection refused).
I checked the LISTENING ports on my server using SysInternals TcpView and I cannot find the 555 port specified above.
Am suspecting an issue related to .Net Remoting but cannot figure out how to resolve this.
Any ideas ?
Thanks in advance.
could use http://topshelf-project.com/ to host Scheduler which will provide hostFactory and using that could shelf host via HttpSelfHostServer, http is better as you could invoke job via controller. sample code as below
hope this helps.
using System;
using System.Configuration;
using System.Web.Http;
using System.Web.Http.SelfHost;
using Topshelf;
class Program
{
static void Main(string[] args)
{
HostFactory.Run(hostConfigurator =>
{
if (!Uri.TryCreate("http://localhost:8080", UriKind.RelativeOrAbsolute, out var hostname))
{
throw new ConfigurationErrorsException($"Could not uri");
}
var serviceName = "my service";
var hostConfiguration = new HttpSelfHostConfiguration(hostname);
hostConfiguration.Routes.MapHttpRoute("API", "{controller}/{action}/{id}", (object)new
{
id = RouteParameter.Optional
});
var httpSelfHostServer = new HttpSelfHostServer(hostConfiguration);
// Impl.Scheduler would be your implementation of scheduler
hostConfigurator.Service<Impl.Scheduler>(s =>
{
s.ConstructUsing(name => new Impl.Scheduler());
s.WhenStarted(tc =>
{
tc.Start();
httpSelfHostServer.OpenAsync().Wait();
});
s.WhenStopped(tc =>
{
tc.Stop();
//dispose scheduler implementation if using IOC container
httpSelfHostServer.CloseAsync().Wait();
});
});
hostConfigurator.RunAsLocalSystem();
hostConfigurator.SetDescription(serviceName);
hostConfigurator.SetDisplayName(serviceName);
hostConfigurator.SetServiceName(serviceName);
});
}
}