NLog in different versions for multiple projects - c#

In my project I am using NLog assembly with file version 4.6.6. My application is being loaded by the external app (no access to the source code) which also uses NLog with file version 4.7.2.
Everything from the external app and my app is being logged correctly. The strange thing that I am facing is that in my app I add the logging rules:
var uniqueLogName = "mylogger" + Guid.NewGuid();
var rule = new LoggingRule(uniqueLogName, ConvertLogLevel(SelectedLogLevel), myFileTarget);
LogConfig.LoggingRules.Add(rule);
var uniqueObjectsLogName = "myObjectslogger" + Guid.NewGuid();
var objectsRule = new LoggingRule(uniqueObjectsLogName, ConvertLogLevel(SelectedLogLevel), myObjectTarget);
LogConfig.LoggingRules.Add(objectsRule);
And for some reason I am getting folders with these rule names created on C drive (see the link below) and honestly, I don't even know where to look for the issue. Can this be some sort of configuration on the NLog?

Related

Could not load file or assembly Microsoft.IdentityModel.Tokens problem

I am trying to verify users with a JWT token. The code I used below works perfectly fine in a console application. But when I want to apply it in my Azure function it gives me the error:
Could not load file or assembly Microsoft.IdentityModel.Tokens
I do have one other Azure function in my solution but it doesn't use this NuGet package. I already took a look at this link:
Could not load file or assembly 'Microsoft.IdentityModel.Tokens, Version=5.2.0.0
I can't get anything out of that. So what am I doing wrong? Thanks in advance
string key = "";
var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
var header = new JwtHeader(credentials);
var payload = new JwtPayload
{
{ "some ", "hello "},
{ "scope", "http://dummy.com/"},
};
var secToken = new JwtSecurityToken(header, payload);
var handler = new JwtSecurityTokenHandler();
var tokenString = handler.WriteToken(secToken);
var token = handler.ReadJwtToken(tokenString);
log.LogInformation(token.ToString());
Solved it by adding a line of code in the .csproj file
<PropertyGroup>
<_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
</PropertyGroup>
I had this problem not when running in development, but on deployed projects. This did not relate to Azure project, but to a web application deployed onto a remote windows web server
I took these steps to resolve it:
Get the files names of the DLLs from references
Find these DLLS in the packages subfolder of your vs project.
Make sure you have the right version for your .net framework version
Copy the DLLs to a folder, we called it "deployments"
Remove the Nuget packages
Reference the DLLs directly with copylocal=true
You may or may not need to add the DLLs to the bin folder in your deployment package. The packages we needed are shown below

.Net Core Worker Service cannot find log4net.config when it runs as a windows service

I have these projects in my solution:
.Net Core 3.1 Worker Service
.Net Core 3.1 Class library - for configure the log4net
But my log4net.config file is inside my worker service project. When I'm debugging, it is logging to the file which is configured in the log4net.config.
But when I install the Worker Service as a Windows service, it doesn't log to the file.
And when I checked the log4net.config location it has these values:
When debugging: D:\myrepos\webapicore\Development\Message.Consumer\log4net.config
When running as a service: C:\WINDOWS\system32\log4net.config
So I believe, since the log4net.config is not available in C:\WINDOWS\system32\ it cannot do the logging.
UPDATE:
I'm using following code to retrieve the log4net.config
var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
Any idea to solve this?
Thanks.
I have installed and configured log4net in a different class library.
So when I was getting the Assembly.GetEntryAssembly() it was actually not giving the assembly location of where log4net has been installed.
Therefore I changed the this code part:
var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
Into:
var dirname = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
XmlConfigurator.Configure(new FileInfo(string.Format("{0}{1}", dirname, #"\log4net.config")));
This worked for me.
This worked for me too with my .NET 5 WorkerService.
You could also use AppDomain.CurrentDomain.BaseDirectory, instead.
However, I then found out that you can simply create an AssemblyInfo.cs file (Add new item ...) and add
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
Just like before with .NET Framework 4.5, etc.

Xamarin Forms +Entity Framework Core + SQLite - Calling migration on production breaks application

First I run the following setup
Xamarin Forms - Entity Framework Core 2.2 - SQLite - Android - DEBUG
And everything works fine. The .db file is generated properly and queries are executed on the database.
Then I prepared the application for production and I changed the DEBUG to RELEASE compiled, and packed into an apk. As installed on the device the application always crashes when calling either Database.Migrate() or Database.EnsureCreated()
The scenario is the same on every application I tried. App runs properly in emulator and on the device being in DEBUG mode. App crashes on every Android device when creating the database.
This is the instantiation of the DbContext
public ItemContext(DbContextOptions<ItemContext> options)
: base(options)
{
//Database.Migrate();
Database.EnsureCreated();
}
This is how the constructor is called
public void Load()
{
string databasePath = DependencyService.Get<ILocalFileStorageService>().GetDatabaseFilePath("ItemSQLite.db");
string connectionString = $"Filename={databasePath}";
DbContextOptions<ItemContext> options = new DbContextOptionsBuilder<ItemContext>()
.UseSqlite(connectionString)
.Options;
dataService = new DataService(new ItemContext(options));
}
This is how I retrieve the filepath on Android.
public string GetDatabaseFilePath(string fileName)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
return Path.Combine(path, fileName);
}
When looking on the Android Device Monitor a very long error is displayed
The beginning is
somewhere later there is the EnsureCreated method listed
The Question: Why is this happening and how to make the application runnable on production?
Do you have linking enabled in your release build configuration? According to this https://github.com/aspnet/EntityFrameworkCore/issues/10963 the compiler requires hints to not link assemblies accessed through reflection internally in EF Core. You can try switching to "Link sdk assemblies only" to see if that fixes the issue. If it does then you will need to identify the assemblies and mark them to be preserved. There's some more info on that here: Xamarin iOS Linker Issue and here: https://learn.microsoft.com/en-us/xamarin/android/deploy-test/linker#linkskip.
I can't personally test at the moment but I think putting [assembly: Preserve (typeof (System.Linq.Queryable), AllMembers = true)] (or whatever assembly might be causing it) in your App.xaml.cs should do it.

Cybersource Simple Order Api. The system cannot find the file specified Error Message

I have a .Net website (not a Web Application) project running in framework version 4.6.2
My implementation of the Cybersource simple order api works correctly on the development machine. However when i deploy my website to stage or product i receive the error The system cannot find the file specified when attempting the following code below.
NVPClient.RunTransaction(_cyberSourceConfig, request);
I have checked that the keys are valid. The _cyberSourceConfig contains the correct Currency, MerchantId, KeyFile, Key Directory and the locations are valid within the file system.
Check that the following DLL's are included within the projects bin directory
I have also checked that the following DLL's are in my projects bin directory.
CyberSource.Base.dll
CyberSource.Clients.dll
CyberSource.Clients.xml
_cyberSourceConfig consists of the the following
private CyberSource.Clients.Configuration _cyberSourceConfig = new CyberSource.Clients.Configuration();
_cyberSourceConfig.ConnectionLimit = -1;
_cyberSourceConfig.KeyFilename = "setting for key file"
_cyberSourceConfig.KeysDirectory = "path to keys directory"
_cyberSourceConfig.MerchantID = "My merchant id"
_cyberSourceConfig.SendToProduction = false;
_cyberSourceConfig.ServerURL = "https://ics2wstesta.ic3.com/commerce/1.x/transactionProcessor/";
Based on your provided information, I would suspect that you are specifying a file that is resolvable on your development machine, but is not resolving properly on your staging / production server.
_cyberSourceConfig.KeyFilename = #"keys.foo";
_cyberSourceConfig.KeysDirectory = #"C:\KeysDirectory\MyKeys\"; // <-- are you sure?
You need to make sure that either the relative or absolute paths are the same or are resolving to the file properly when using different enviornments.
Set your App Pool to Load User Profile: True
http://www.daves-blog.net/post/2014/06/16/X509Certificate-The-System-cannot-find-the-file-specified.aspx
That link is going to a 404 now, but the more general answer is fleshed out in this question.
CryptographicException was unhandled: System cannot find the specified file

Azure SDK Storage assembly not found exception when publishing

I try to publish a demo application to Windows Azure using Cloud Service and Azure SDK 2.9. In my service I have a Web Role and a Worker Role. Both use Azure Storage. Everything works fine on local hosting (Emulator) but when I try to publish the app I get the following error on Web Role:
Unhandled Exception: System.Runtime.Serialization.SerializationException,
Details: Exception: Unable to find assembly 'Microsoft.WindowsAzure.Storage, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf385)
In the Worker Role project everything is OK, it's using Storage too.
I tried to convert the Web Role to a standard Web Application and everything works fine but I want to resolve this problem on Cloud Application.
What I've tried:
set local copy in references to true
changed .Net Framework to 4.5.1 and 4.6 (default 4.5)
removed and added reference to Storage again
reinstalled all libraries by nuget
published with Storage 7.0 and 6.2
published by VS and by portal (package)
added dependentAssembly to web.config
On my VM I checked the bin folder, Microsoft.WindowsAzure.Storage exists.
Any ideas what is wrong?
After two days I found a solution for that problem.
In my WebRole.cs I had this:
public override bool OnStart()
{
var csa = CloudStorageAccount.Parse(RoleEnvironment
.GetConfigurationSettingValue("Credentials"));
var cqc = csa.CreateCloudQueueClient();
var inputQueue = cqc.GetQueueReference("inputqueue");
inputQueue.CreateIfNotExists();
var outputQueue = cqc.GetQueueReference("outputqueue");
outputQueue.CreateIfNotExists();
var ctc = csa.CreateCloudTableClient();
var ct = ctc.GetTableReference("last");
ct.CreateIfNotExists();
return base.OnStart();
}
When I moved this initialization to other place e.g. to RouteConfig.cs everything works perfect. I don't know why but every references to Storage from WebRole throws errors after publishing to Azure.
I hope this solution helps.

Categories

Resources