I'm using programmatic configuration with NLog and am encountering the following error whenever the log file should be written to:
ArgumentOutOfRangeException: Argument is out of range.
System.Security.AccessControl.AuthorizationRule..ctor
(System.Security.Principal.IdentityReference identity, Int32
accessMask, Boolean isInherited, InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags) (at
/Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Security.AccessControl/AuthorizationRule.cs:61)
System.Security.AccessControl.AccessRule..ctor
(System.Security.Principal.IdentityReference identity, Int32
accessMask, Boolean isInherited, InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags, AccessControlType type)
System.Security.AccessControl.MutexAccessRule..ctor
(System.Security.Principal.IdentityReference identity, MutexRights
eventRights, AccessControlType type)
NLog.Internal.FileAppenders.BaseFileAppender.CreateSharableMutex
(System.String mutexNamePrefix)
NLog.Internal.FileAppenders.BaseFileAppender.CreateSharableArchiveMutex
()
NLog.Internal.FileAppenders.RetryingMultiProcessFileAppender.CreateArchiveMutex
() NLog.Internal.FileAppenders.BaseFileAppender..ctor (System.String
fileName, ICreateFileParameters createParameters)
NLog.Internal.FileAppenders.RetryingMultiProcessFileAppender..ctor
(System.String fileName, ICreateFileParameters parameters)
NLog.Internal.FileAppenders.RetryingMultiProcessFileAppender+Factory.NLog.Internal.FileAppenders.IFileAppenderFactory.Open
(System.String fileName, ICreateFileParameters parameters)
NLog.Internal.FileAppenders.FileAppenderCache.AllocateAppender
(System.String fileName) NLog.Targets.FileTarget.WriteToFile
(System.String fileName, NLog.LogEventInfo logEvent, System.Byte[]
bytes, Boolean justData) NLog.Targets.FileTarget.ProcessLogEvent
(NLog.LogEventInfo logEvent, System.String fileName, System.Byte[]
bytesToWrite) NLog.Targets.FileTarget.Write (NLog.LogEventInfo
logEvent) NLog.Targets.Target.Write (AsyncLogEventInfo logEvent)
Google doesn't know anything about this error, as far as I can see. The following is my configuration code:
public static void SetupLogging()
{
// Can unity debug be redirected to go through Nlog?
var config = new LoggingConfiguration();
var consoleTarget = new ConsoleTarget("console");
config.AddTarget("console", consoleTarget);
//var logsPath = UtilsIO.GetResourcesPath(UtilsIO.ResourceType.Logs, "_logs");
var logsPath = #"d:\jem\temp\_logs";
var dir = logsPath + "\\app" + "\\" + Environment.UserName;
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
var filepath = Path.Combine(dir, Guid.NewGuid() + ".log");
var fileTarget = new FileTarget("file")
{
FileName = filepath,
Layout = "${date:format=yyyyMMddHHmmss} ${message}"
};
config.AddTarget("file", fileTarget);
var rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget);
config.LoggingRules.Add(rule1);
var rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget);
config.LoggingRules.Add(rule2);
InternalLogger.LogToConsole = true;
LogManager.ThrowExceptions = true;
LogManager.Configuration = config;
}
This is how I instantiate the logger:
private static NLog.Logger logger = LogManager.GetLogger("file");
And this is how I use that instantiation:
logger.Debug("Hello world????");
I've tried using the ImpersonatingTargetWrapper but get the same error. I've given 'Everyone' full rights to the root directory. I've also tried configuration file to get started, but that didn't help either. I've banged my head for a while against this one - anyone have any suggestions?
NLog 4.4.1 now performs runtime detection of MONO version, and avoids using named mutex if not running MONO ver. 4 or newer (Unity is running MONO ver. 2)
Related
We're using NLog for our application. I have set up the logger in the code using mostly the documentation. Yet the logger object gets disposed of while the app is about to write to it causing an error. I use the logger in .NET CORE 3.1 in the Middlewares that handles exceptions globally and authentication. The funniest part is that the error itself is logged to the file by NLog. Error from the logs:
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'LoggerFactory'.
at Microsoft.Extensions.Logging.LoggerFactory.CreateLogger(String categoryName)
at Microsoft.Extensions.Logging.Logger`1..ctor(ILoggerFactory factory)
at Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger[T](ILoggerFactory factory)
Configuration in the code:
public static class NLogConfig
{
public static void CreateLogger(IConfiguration configuration)
{
var logName = configuration.GetSection("LoggerConfig").GetSection("LogName").Get<string>();
var logPath = configuration.GetSection("LoggerConfig").GetSection("Directory").Get<string>();
var infoLogLayout = configuration.GetSection("LoggerConfig").GetSection("InfoLayout").Get<string>();
var errorLogLayout = configuration.GetSection("LoggerConfig").GetSection("ErrorLayout").Get<string>();
var config = new NLog.Config.LoggingConfiguration();
var infoLog = new NLog.Targets.FileTarget("FileLog") { FileName = logPath + logName, Layout = infoLogLayout };
var errorLog = new NLog.Targets.FileTarget("FileLog") { FileName = logPath + logName, Layout = errorLogLayout };
config.AddRule(LogLevel.Trace, LogLevel.Info, infoLog);
config.AddRule(LogLevel.Warn, LogLevel.Fatal, errorLog);
NLog.LogManager.Configuration = config;
}
}
JSON configuration file:
"LoggerConfig": {
"LogName": "MY_API_${shortdate}.log",
"Directory": "C:\\Logs\\MY_API\\",
"InfoLayout": "${longdate} | INFO | ${logger} | ${message}",
"ErrorLayout": "------------------\n${longdate} | ERROR | ${logger} | ${message:withexception=true} \n------------------"
}
In the classes that use the log I do this as it is in documentation:
private static readonly NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
The "disposed" error happens randomly and not frequently, but often enough to be a slight concern. How can I avoid this problem? I've read that NLog should be thread-safe so calls to the API shouldn't cause such a problem. Especially when it was only one person using the API at the time
While I am trying to run python code from C# with Iron Python I get some exceptions tried writing code inside C# but it didn't change anything. Is there any other option to run python code inside C#? or Am I doing something wrong with my code? In python everything works great Until I run it from C#
private static string GetBitcoinPrivateKeyFromMnemonic(string mnemonic)
{
var engine = Python.CreateEngine();
ICollection<string> paths = engine.GetSearchPaths();
var dir1 = #"/home/hackslash/.local/lib/python3.7/site-packages";
var dir2 = #"/usr/lib/python3.7";
paths.Add(dir1);
paths.Add(dir2);
engine.SetSearchPaths(paths);
dynamic py = engine.ExecuteFile(#"/home/hackslash/Magnify/MagnifyDevelopment/Python/bitcoin.py");
dynamic bitcoin = py.Bitcoin();
var bitcoinPrivateWIF = bitcoin.generate_bitcoin_private_wif(mnemonic);
return bitcoinPrivateWIF;
}
and I have this file in Python
from btctools import *
import hashlib
class Bitcoin:
#classmethod
def generate_bitcoin_address_from_wif(cls, private_key_wif):
private_key = PrivateKey.from_wif(private_key_wif)
public_key = private_key.to_public()
public_address = public_key.to_address('P2PKH', compressed=False)
return public_address
#classmethod
def generate_bitcoin_private_wif(cls, mnemonic):
hashed_words = hashlib.sha256(mnemonic.encode()).hexdigest()
private_key = PrivateKey.from_hex(hashed_words)
private_wif = private_key.wif(compressed=False)
return private_wif
I get this Exception:
Unhandled Exception:
Microsoft.Scripting.SyntaxErrorException: invalid syntax
at IronPython.Runtime.ThrowingErrorSink.Add (Microsoft.Scripting.SourceUnit sourceUnit, System.String message, Microsoft.Scripting.SourceSpan span, System.Int32 errorCode, Microsoft.Scripting.Severity severity) [0x0001a] in <0569a20e5dd94f74a766cc11c6214b7c>:0
at IronPython.Compiler.Parser.ReportSyntaxError (System.Int32 start, System.Int32 end, System.String message, System.Int32 errorCode) [0x0003a] in <0569a20e5dd94f74a766cc11c6214b7c>:0
at IronPython.Compiler.Parser.ReportSyntaxError (System.Int32 start, System.Int32 end, System.String message) [0x00000] in <0569a20e5dd94f74a766cc11c6214b7c>:0
at IronPython.Compiler.Parser.ReportSyntaxError (System.String message) [0x00027] in <0569a20e5dd94f74a766cc11c6214b7c>:0
at IronPython.Compiler.Parser.AddTrailers (IronPython.Compiler.Ast.Expression ret, System.Boolean allowGeneratorExpression) [0x00103] in <0569a20e5dd94f74a766cc11c6214b7c>:0
I develop a WPF application that uses NLog. It has been deployed to a few prospective customers, and in one of them, the application worked fine for a week and now it doesn't even open. That is, you double click the app icon, and nothing happens, literally. Not even the logging inside a AppDomain.CurrentDomain.UnhandledException catch clause.
I was able to identify an event in the Windows Event Viewer (see message below).
What bogs me down is the sudden appearence of this error after a week of flawless operation, and my inability to interpret this message or finding info about it online.
Aplicativo: ForceViewer.exe
Versão do Framework: v4.0.30319
Descrição: O processo foi terminado devido a uma exceção sem tratamento.
Informações da Exceção: System.Xml.XmlException
em System.Xml.XmlTextReaderImpl.Throw(System.Exception)
em System.Xml.XmlTextReaderImpl.ParseDocumentContent()
em System.Xml.XmlTextReaderImpl.Read()
em System.Xml.XmlTextReader.Read()
em System.Configuration.XmlUtil..ctor(System.IO.Stream, System.String, Boolean, System.Configuration.ConfigurationSchemaErrors)
em System.Configuration.BaseConfigurationRecord.InitConfigFromFile()
Informações da Exceção: System.Configuration.ConfigurationErrorsException
em System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean)
em System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(System.Configuration.ConfigurationSchemaErrors)
em System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
em System.Configuration.ClientConfigurationSystem.OnConfigRemoved(System.Object, System.Configuration.Internal.InternalConfigEventArgs)
Informações da Exceção: System.Configuration.ConfigurationErrorsException
em System.Configuration.ConfigurationManager.PrepareConfigSystem()
em System.Configuration.ConfigurationManager.get_AppSettings()
em NLog.Common.InternalLogger.GetSettingString(System.String, System.String)
em NLog.Common.InternalLogger.GetSetting[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.String, System.String, Boolean)
em NLog.Common.InternalLogger.Reset()
em NLog.Common.InternalLogger..cctor()
Informações da Exceção: System.TypeInitializationException
em NLog.Common.InternalLogger.Log(System.Exception, NLog.LogLevel, System.String)
em NLog.Internal.ExceptionHelper.MustBeRethrown(System.Exception)
em NLog.LogFactory.get_Configuration()
em NLog.LogFactory.GetLogger(LoggerCacheKey)
em NLog.LogFactory.GetLogger(System.String)
em NLog.LogManager.GetLogger(System.String)
em Miotec.ForceViewer.App..cctor()
Informações da Exceção: System.TypeInitializationException
em Miotec.ForceViewer.App.Main(System.String[])
Here is my App.xaml.cs:
public partial class App : Application
{
static string AppName = "ForceViewer 1.1";
static readonly Mutex mutex = new Mutex(true, AppName);
// APPARENTLY the exception happens in the line below:
static readonly Logger logger = LogManager.GetLogger(typeof(App).FullName);
[STAThread]
public static void Main(string[] args)
{
SplashScreen splashScreen = new SplashScreen("Splash.png");
splashScreen.Show(true);
if (mutex.WaitOne(TimeSpan.Zero, true))
{
var app = new App();
app.InitializeComponent();
app.Run();
mutex.ReleaseMutex();
}
else
{
Extensions.EnviaMensagemPraAtivarOutraJanela();
}
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
WpfLauncher.Launch(this, new ForceViewerBootstrapper(AppName));
logger.Info($"Aplicação {AppName} iniciada");
}
}
UPDATE (with additional, possibly relevant info):
Some people mentioned NLog XML config file, but I am using a runtime configuration, as follows:
var dirname = Path.Combine(#"C:\\AppFolder", appName, "logs");
Directory.CreateDirectory(dirname);
var filename = Path.Combine(dirname, $"{appName}.log");
var filetarget = new FileTarget("app")
{
FileName = filename,
Encoding = Encoding.UTF8,
Layout = "${longdate}|${level:uppercase=true}|${message} (${logger:shortName=true})",
AutoFlush = true,
MaxArchiveFiles = 8,
ArchiveAboveSize = 1048576,
ArchiveEvery = FileArchivePeriod.Friday,
ConcurrentWrites = true
};
var asyncTarget = new AsyncTargetWrapper("app", filetarget);
var config = new LoggingConfiguration();
config.AddRuleForAllLevels(asyncTarget);
config.AddTarget(asyncTarget);
LogManager.Configuration = config;
Additionally, the "stack trace" (which in the case of a Windows Event seems to be printed sort of backwards) suggests NLog itself is getting an exception from the System.Configuration classes, as seen from decompilation of InternalLogger:
namespace NLog.Common
{
//...
public static class InternalLogger
{
//...
private static string GetSettingString(string configName, string envName)
{
// Line below seems to be throwing an exception
string str = System.Configuration.ConfigurationManager.AppSettings[configName];
//..
Probably there is a config mistake in your NLog (XML) config.
So why do you get a TypeInitializationException and not a helpful message? That's because your initializing NLog before starting your program. The line:
static readonly Logger logger = LogManager.GetLogger(typeof(App).FullName);
will be run before the Main because it's a static field. Unfortunately NLog cannot throw a better exception (see: Better TypeInitializationException (innerException is also null))
Recommendation: in this case is recommend to have a non-static Logger, or, a static Lazy<Logger>:
static readonly Lazy<Logger> logger = new Lazy<Logger>(() => LogManager.GetLogger(typeof(App).FullName));
I tried to use firewallAPI.dll to add a rule. It works fine for calc.exe (or some other files) as described bellow but fails for msdtc.exe with the following exception:
System.IO.FileNotFoundException: 'The system cannot find the file
specified. (Exception from HRESULT: 0x80070002)'
Example:
static void Main(string[] args)
{
var manager = GetFirewallManager();
if (manager.LocalPolicy.CurrentProfile.FirewallEnabled)
{
var path = #"C:\Windows\System32\calc.exe";
//var path = #"C:\Windows\System32\msdtc.exe"; // System.IO.FileNotFoundException: 'The system cannot find the file specified.
AuthorizeApplication("Test", path, NET_FW_SCOPE_.NET_FW_SCOPE_ALL, NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY);
}
}
private const string CLSID_FIREWALL_MANAGER =
"{304CE942-6E39-40D8-943A-B913C40C9CD4}";
private static NetFwTypeLib.INetFwMgr GetFirewallManager()
{
Type objectType = Type.GetTypeFromCLSID(
new Guid(CLSID_FIREWALL_MANAGER));
return Activator.CreateInstance(objectType)
as NetFwTypeLib.INetFwMgr;
}
private const string PROGID_AUTHORIZED_APPLICATION =
"HNetCfg.FwAuthorizedApplication";
public static bool AuthorizeApplication(string title, string applicationPath,
NET_FW_SCOPE_ scope, NET_FW_IP_VERSION_ ipVersion)
{
// Create the type from prog id
Type type = Type.GetTypeFromProgID(PROGID_AUTHORIZED_APPLICATION);
INetFwAuthorizedApplication auth = Activator.CreateInstance(type)
as INetFwAuthorizedApplication;
auth.Name = title;
auth.ProcessImageFileName = applicationPath;
auth.Scope = scope;
auth.IpVersion = ipVersion;
auth.Enabled = true;
INetFwMgr manager = GetFirewallManager();
manager.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(auth);
return true;
}
Note: I checked the folder and see the file is located properly...
Could anybody help to add firewall rule for Distributed Transaction Coordinator? Maybe I should try to add another file to firewall (not msdtc.exe)?
Project > Properties > Build tab, untick the "Prefer 32-bit" checkbox. You don't prefer it, there is no 32-bit version of msdtc.exe.
Why the file system redirector caused the FileNotFoundException is explained well in this MSDN article.
I'm new to MonoTouch development and I would like to embed some PDF Viewing functionality in my app. I have found several resources for doing that, however, I also see enough remarks about all the additional implementations to make it stable and fast.
I now see that there is a good ObjectiveC library which already implements a lot of functionality (CATiledLayer, multi-threading, page scrolling, thumb nails, device rotation ...): https://github.com/vfr/Reader
The last days, after reading the monotoch binding documentation, I'm trying to bind this in MonoTouch, but without success.
I'm able to export it to a library (.a) file and I've created a binding API.
//#interface ReaderDocument : NSObject <NSObject, NSCoding>
[BaseType (typeof (NSObject))]
interface ReaderDocument {
//- (id)initWithFilePath:(NSString *)fullFilePath password:(NSString *)phrase;
[Export("initWithFilePath:password")]
IntPtr Constructor (string path, string phrase);
//Properties
[Export("guid")]
string Guid { get;}
[Export("fileDate")]
NSDate FileDate { get;}
[Export("lastOpen")]
NSDate LastOpen { get;set;}
[Export("fileSize")]
NSNumber FileSize{ get;}
[Export("pageCount")]
NSNumber PageCount { get;}
[Export("pageNumber")]
NSNumber PageNumber { get;set;}
[Export("bookmarks")]
NSMutableIndexSet Bookmarks { get;}
[Export("fileName")]
string FileName { get;}
[Export("password")]
string Password { get;}
[Export("fileURL")]
NSUrl FileURL { get;}
//Methods
//+ (ReaderDocument *)withDocumentFilePath:(NSString *)filename password:(NSString *)phrase;
[Static, Export("withDocumentFilePath:password")]
ReaderDocument WithDocumentFilePath(string filename, string phrase);
//+ (ReaderDocument *)unarchiveFromFileName:(NSString *)filename password:(NSString *)phrase;
[Static, Export("unarchiveFromFileName:password")]
ReaderDocument UnarchiveFromFileName(string filename, string phrase);
//- (void)saveReaderDocument;
[Export("saveReaderDocument")]
void SaveReaderDocument();
//- (void)updateProperties;
[Export("updateProperties")]
void updateProperties();
}
I'm very unsure about following line btw:
//#interface ReaderDocument : NSObject <NSObject, NSCoding>
[BaseType (typeof (NSObject))]
interface ReaderDocument
Not sure if I have to do something with the ""?
I can now create following code in MonoTouch
ReaderDocument doc = ReaderDocument.withDocumentFilePath("Tamarin.pdf","");
or
ReaderDocument doc = new ReaderDocument("Tamarin.pdf","yrt");
Both are resulting in "unrecognized selector" error
2012-11-04 22:15:05.731 PFDTest1[4149:1507] +[ReaderDocument withDocumentFilePath:password]: unrecognized selector sent to class 0x2f7738
[ERROR] FATAL UNHANDLED EXCEPTION: MonoTouch.Foundation.MonoTouchException: Objective-C exception thrown. Name: NSInvalidArgumentException Reason: +[ReaderDocument withDocumentFilePath:password]: unrecognized selector sent to class 0x2f7738
at (wrapper managed-to-native) MonoTouch.ObjCRuntime.Messaging:IntPtr_objc_msgSend_IntPtr_IntPtr (intptr,intptr,intptr,intptr)
at VFRBinding4.ReaderDocument.withDocumentFilePath (System.String filename, System.String phrase) [0x00000] in <filename unknown>:0
at PFDTest1.AppDelegate.FinishedLaunching (MonoTouch.UIKit.UIApplication app, MonoTouch.Foundation.NSDictionary options) [0x00030] in /Users/matthiasvalcke/Projects/PFDTest1/PFDTest1/AppDelegate.cs:39
at (wrapper managed-to-native) MonoTouch.UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
at MonoTouch.UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x0004c] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:38
at PFDTest1.Application.Main (System.String[] args) [0x00000] in /Users/matthiasvalcke/Projects/PFDTest1/PFDTest1/Main.cs:17
Any ideas?
There could be other issues but your bindings are wrong for the constructors, i.e.
//- (id)initWithFilePath:(NSString *)fullFilePath password:(NSString *)phrase;
[Export("initWithFilePath:password")]
void InitWithFilePath(string path, string password);
ObjectiveC init* selectors should be binded as C# constructors. E.g.
[Export("initWithFilePath:password")]
IntPtr Constructor (string path, string password);
and that should be what you use to create the instance, e.g.
ReaderDocument doc = new ReaderDocument ("sample.pdf", "");
// ...
I could be entirely wrong, but I think your selectors are wrong:
e.g. "withDocumentFilePath:password" should be "withDocumentFilePath:password:"