firebase and spring boot configuration - firebase

How to fix that error?
Exception in thread "main" java.io.FileNotFoundException: E:\n\demo%20(1)\demo\target\classes\serviceAccountKey.json (The system cannot find the path specified)
File file = new File(Objects.requireNonNull(classLoader.getResource("serviceAccountKey.json")).getFile());
FirebaseOptions options;
try (FileInputStream serviceAccount = new FileInputStream(file.getAbsolutePath())) {
options = new Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://springboot-c7d7e-default-rtdb.firebaseio.com")
.build();
}

Related

How to upload file to AWS?

Project: .NET Framework 4.6.
I added a file in sln directory and it works fine on localhost:
var clientSettings = MongoClientSettings.FromUrl(new MongoUrl($"{GlobalVariable.MongoDBConnection}?ssl=false&ssl_ca_certs=rds-combined-ca-bundle.pem&retryWrites=false"));
clientSettings.SslSettings = new SslSettings();
clientSettings.UseSsl = true;
clientSettings.SslSettings.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Default;
string pathToCAFile = Path.Combine(Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName, "rds-combined-ca-bundle.pem");
// this line throws exception: "The system cannot find the file"
clientSettings.SslSettings.ClientCertificates = new List<X509Certificate>()
{
new X509Certificate(pathToCAFile)
};
clientSettings.SslSettings.ClientCertificateSelectionCallback =
(sender, host, certificates, certificate, issuers) => clientSettings.SslSettings.ClientCertificates.ToList()[0];
clientSettings.SslSettings.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
Exception Message:
The system can not find the file specified
File placed same directory with sln file, it works fine in localhost, how to upload this file to AWS web server?

How to pass connection string to Application Insights?

I have a .NET Core 3.1 console application and would like to configure it using a connection string specified in appsettings.json.
This is the code for a test app:
static void Main(string[] args)
{
var configurationBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
// To be able to read configuration from .json files
var configuration = configurationBuilder.Build();
// Create the DI container.
IServiceCollection services = new ServiceCollection();
services.AddApplicationInsightsTelemetryWorkerService();
// Build ServiceProvider.
IServiceProvider serviceProvider = services.BuildServiceProvider();
// Obtain TelemetryClient instance from DI, for additional manual tracking or to flush.
var telemetryClient = serviceProvider.GetRequiredService<TelemetryClient>();
telemetryClient.TrackTrace("Hello, world 3!");
// Explicitly call Flush() followed by sleep is required in Console Apps.
// This is to ensure that even if application terminates, telemetry is sent to the back-end.
telemetryClient.Flush();
Task.Delay(5000).Wait();
}
The problem is that it seems like Application Insight is not picking up the connection string. I do not see any Trace messages in Application Insights. If I pass the instrumentation key to AddApplicationInsightsTelemetryWorkerService it works.
This is the content of appsettings.json:
{
"ApplicationInsights": {
"ConnectionString": "<my connection string>"
}
}
What am I missing?
I don't know if the issue is still exist, but you can pass the Connection String straight to the TelemetryConfiguration.
var telemetryConfiguration = TelemetryConfiguration.CreateDefault();
telemetryConfiguration.ConnectionString = Configuration["AzureApplicationInsightsConnectionString"];
Or, you can add it to the servicecollection:
var options = new ApplicationInsightsServiceOptions { ConnectionString = Configuration["AzureApplicationInsightsConnectionString"] };
services.AddApplicationInsightsTelemetry(options: options);

How to get files from Serilog [duplicate]

Hello I am having trouble writing logs to file on Android device using Xamarin.Forms (.NET Core shared project) and Serilog.
So far I have installed Serilog in Shared project. Installed Serilog, Serilog.Sinks.File, and Serilog.Sinks.Xamarin to my Android project and initialized logger in MainActivity:
Log.Logger = new LoggerConfiguration()
.WriteTo.File(Path.Combine(Environment.ExternalStorageDirectory.AbsolutePath,"XamarinLib-{Date}.txt"),
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] {Message}{NewLine}{Exception}",
fileSizeLimitBytes: 100000000,
rollingInterval: RollingInterval.Day,
rollOnFileSizeLimit: true,
shared: false,
retainedFileCountLimit: 31,
encoding: Encoding.UTF8)
.WriteTo.AndroidLog()
.CreateLogger();
Afterwards I call the logger from shared project like:
Log.Information("Test writing to log file");
I can see the log command being executed in Visual Studio debug output, but the file is simply not created.
I've tried multiple locations on both emulator and actual device (no root access).
I've also tried to use RollingFile sink in similar manner with no success.
Any ideas?
First, you have to allow permissions in your AndroidManifest.xml file.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Next, The user either must, approve that on runtime in which you have to code this in your code behind. NOTE Remember to add Plugin.Permissions on your NUGET package:
InitializeComponent();
Task.Run(async () =>
{
try
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
if (status != PermissionStatus.Granted)
{
var accepted = await DisplayAlert("Storage Permission Required",
"Please enable your storage permission, it will be used to store logs and crashes",
"ACCEPT",
"CANCEL");
if(accepted)
{
var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Storage);
status = results[Permission.Storage];
}
}
}
catch (Exception ex)
{
await DisplayAlert("Exception ex", "Exception ex", "OK");
}
});
OR
let them change the permissions in the settings -> app -> permissions.
Finally,
change the filename that will link to the storage/emulated/0/[your added directory].
After the closing the app, you can see it in the Android File Manager.
as pointed out by Ruben Bartelink the problem is that Android can't simply write to external storage (ie /storage/emulated/0... etc..).
I was able to log to a file on a Xamarin.Forms project in both Android and iOS.
_Tmp = System.IO.Path.GetTempPath();
_Path = System.IO.Path.Combine(_Tmp, "Serilog.txt");
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.File(_Path, rollingInterval: RollingInterval.Day, retainedFileCountLimit: 7)
.CreateLogger();
Log.Information("Started new serilogger {SERILOG} on file {FILE}", this, _Path);
Log.CloseAndFlush();
//test
foreach (string log in System.IO.Directory.GetFiles(_Tmp, "*.txt"))
{
string test = System.IO.File.ReadAllText(log);
System.Diagnostics.Debug.WriteLine($"Test[{log}] -> {test}");
}
which printed on the debug console:
[0:] Test[/data/user/0/com.******/cache/Serilog20190819.txt] -> 2019-08-19 16:00:36.997 +02:00 [INF] Started new serilogger ******.Functions.Serilogger on file /data/user/0/com.******/cache/Serilog.txt

Serilog different levels for different sinks

I have the following piece of c# code for writing logs with multiple sinks (console and file), how do i restrict the console to log only (info, warn and error) and file to log everything.
var outputTemplate = "[{Level:u3}] {Message:lj}{NewLine}{Exception}";
// Logger
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.Console(outputTemplate: outputTemplate, theme:SystemConsoleTheme.Literate)
.WriteTo.File($"logs/log-{DateTime.Now:yyyy-MM-dd_HH:mm:ss.fff}.log")
.CreateLogger();
You can set a value for restrictedToMinimumLevel for each sink, to raise the minimum level that it should log.
It's explained in the documentation with examples:
https://github.com/serilog/serilog/wiki/Configuration-Basics#overriding-per-sink
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.File("log.txt")
.WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Information)
.CreateLogger();

Unable to get Core Service client working

I am trying to publish the component using core service, to do this, I just created a console application, and executed from the server. I am getting the below error message.
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'Tridion.ContentManager.CoreService.Client, Version=6.1.0.996, Culture=neutral, PublicKeyToken=ddfc895746e5ee6b' or one of its dependencies. The system cannot find the file specified.
The below is my code, can anyone faced this issue?
static void Main(string[] args)
{
try
{
string compid = "tcm:56-935";
var client = new SessionAwareCoreServiceClient();
var readoption = new ReadOptions();
var component = (ComponentData)client.Read(compid, readoption);
var ItemToPublish = new List<string>();
ItemToPublish.Add(component.Id);
var instruction = new PublishInstructionData();
var pubtarget = (PublicationTargetData)client.Read(
"tcm:0-21-65537", readoption);
List<string> target = new List<string>();
target.Add(pubtarget.Id);
client.Publish(ItemToPublish.ToArray(), instruction, target.ToArray(),
PublishPriority.Normal, readoption);
Console.WriteLine("component published");
Console.WriteLine(component.Title);
Console.WriteLine(pubtarget.Title);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
The error is clear, it says that you don't have dependency in place. You must place Tridion.ContentManager.CoreService.Client.dll into the same directory where your executable is (alternatively, you can place in GAC). Usually there is an option in Visual Studio on referenced assembly on your project "Copy Local", you can try to to set it to true and try to execute your code again.
Looks like (based on your comment to Igor's answer) you're missing some config. Check out Frank's wiki post on the Tridion Practice site - https://code.google.com/p/tridion-practice/wiki/GetCoreServiceClientWithoutConfigFile

Resources