What's wrong with my log4net configuration file? - log4net-configuration

I am trying to write a simple wrapper around log4net for my team, but I cannot get rid of the log4net configuration errors I am getting.
Can someone assist me?
The Wrapper Class
namespace Common
{
public enum LogType
{
Info,Warn,Fatal,Error,Debug
}
public class DtntLogger
{
public static string LOG4NET_CONFIG_FILE = "log4net.xml";
public LogType LogType { get; protected set; }
/******************************************************************************************/
protected static readonly log4net.ILog FileAppenderLog = log4net.LogManager.GetLogger("LogFileAppender1");
protected static readonly log4net.ILog Eventlog = log4net.LogManager.GetLogger("EventLogAppener1");
//protected static readonly log4net.ILog log = log4net.LogManager.GetLogger("LogFileAppender");
//(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/******************************************************************************************/
protected static DtntLogger _info;
public static DtntLogger Info {
get {
return getLogger(LogType.Info, _info);
}
}
protected static DtntLogger _error;
public static DtntLogger Error
{
get
{
return getLogger(LogType.Error, _error);
}
}
protected static DtntLogger _debug;
public static DtntLogger Debug
{
get
{
return getLogger(LogType.Debug, _debug);
}
}
protected static DtntLogger _fatal;
public static DtntLogger Fatal
{
get
{
return getLogger(LogType.Fatal, _fatal);
}
}
protected static DtntLogger _warn;
public static DtntLogger Warn
{
get
{
return getLogger(LogType.Warn, _warn);
}
}
private static DtntLogger getLogger(LogType type, DtntLogger logger)
{
if (logger == null)
logger = new DtntLogger(type);
lock (logger)
{
return logger;
}
}
#region CTORS
protected DtntLogger(LogType type)
{ this.LogType = type;
LoadLoggerConfig();
}
private void LoadLoggerConfig()
{
FileInfo file = new FileInfo(LOG4NET_CONFIG_FILE);
if (!file.Exists)
{
throw new FileLoadException(string.Format("The configuration file for the logger cannot be found in {0}", file.Directory.FullName), file.FullName);
}
log4net.Config.XmlConfigurator.Configure(file);
}
#endregion
public static string EncodeConsole(string message, params object[] args)
{
string content = message;
string pattern = #"{(.*?)}";
MatchCollection mc = Regex.Matches(content, pattern
, RegexOptions.Compiled); //compiled is faster
#region make better Exception that string.format
bool badStringFormat = false;
try { string.Format(message, args); }
catch (FormatException fe)
{
badStringFormat = true;
}
if (badStringFormat || mc.Count > args.Length)
{
string format1 = "you supplied {0} params, but require {1} in the template";
///error message
string err = string.Format(format1, args.Length, "more");
throw new FormatException(err);
}
#endregion
char delimiter = '~';
char filler = '#';
string encoded = message;
foreach (Match item in mc)
encoded = encoded.Replace(item.Value + "", delimiter.ToString() + filler.ToString() + delimiter.ToString() + "").Replace(delimiter.ToString() + delimiter.ToString(), delimiter.ToString());
if (encoded.EndsWith(delimiter.ToString()))
encoded = encoded.Substring(0, encoded.Length - 1);
if (encoded.StartsWith(delimiter.ToString())) encoded = encoded.Substring(1);
var arr = encoded.Split(delimiter);
string out_ = "";
int matchnum = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i][0] == filler)
{
Console.ForegroundColor = ConsoleColor.White;
Console.BackgroundColor = ConsoleColor.Blue;
var oldmatch = mc[matchnum].Value;
var g = oldmatch.Split(':');
var clear = g[0].Replace("{", "").Replace("}", "");
int value = Int32.Parse(clear);
//will always be 0 for data
string match = "{0}";
if (g.Length > 1)
match = "{0:" + g[1];
string args_matchnum = args[value] + "";
var data = string.Format(match, args[value]);
arr[i] = data;
matchnum++;
}
else
Console.ResetColor();
string arr_i = arr[i].ToString();
Console.Write(arr[i]);
out_ += arr[i];
}
Console.WriteLine("");
return out_;
}
public string Write(string message, params object[] args)
{
string s = Write(FileAppenderLog, message, args);
return s;
}
protected string Write(log4net.ILog log, string message, params object[] args)
{
var newmessage = message;
string format = "{2} - {1} | {0}";
string s1 = string.Format(format,
message,
DateTime.Now.ToString("T"),
Thread.CurrentThread.Name
);
string out_ = string.Format(message, args);
logWrite(log, out_);
logWrite(Eventlog, out_);
EncodeConsole(s1, args);
return out_;
}
private void logWrite(ILog log, string message)
{
if (!log.Logger.Repository.Configured)
LoadLoggerConfig();
switch (this.LogType)
{
case LogType.Info:
if (log.IsInfoEnabled)
log.Info(message);
break;
case LogType.Warn:
if (log.IsWarnEnabled)
log.Warn(message);
break;
case LogType.Fatal:
if (log.IsFatalEnabled)
log.Fatal(message);
break;
case LogType.Error:
if (log.IsErrorEnabled)
log.Error(message);
break;
case LogType.Debug:
if (log.IsDebugEnabled)
log.Debug(message);
break;
default:
throw new InvalidOperationException("LogType is an Enum, what are you doing ???");
}
}
}
}
THE XML Configuration file log4net.xml
< ?xml version="1.0" encoding="utf-8" ?>
<log4net>
<root>
<level value="all" />
<!--
<appender-ref ref="EventLogAppender" />
<appender-ref ref="LogFileAppender" />
-->
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<File value="MyApp.log" />
<AppendToFile value="true" />
<staticLogFileName value="true" />
<maximumFileSize value="1000MB" />
<rollingStyle value="Date" />
<datePattern value="yyyMMdd"/>
<maxSizeRollBackups value="10" />
<threshold value="WARN" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%-5p%t%d{yyyy-MM-dd HH:mm:ss} – %m%n" />
</layout>
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="WARN" />
</evaluator>
</appender>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
<applicationName value="MyApp" />
<threshold value="WARN" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<logger name="EventLogAppender1">
<level value="ALL" />
<param value="All" name="Threshold" />
<threshold value="ALL" />
<appender-ref ref="EventLogAppender" />
</logger>
<logger name="LogFileAppender1">
<level value="ALL" />
<maximumfilesize value="1000MB" />
<param value="All" name="Threshold" />
<appender-ref ref="LogFileAppender" />
</logger>
</log4net>
Log4NET Debug data (Console Output)
log4net: log4net assembly [log4net, Version=1.2.11.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a]. Loaded from [C:\XXXYYYXXX\TestResults\DEV1\Out\log4net.dll]. (.NET Runtime [4.0.30319.261] on Microsoft Windows NT 6.1.7601 Service Pack 1)
log4net: defaultRepositoryType [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository for assembly [DtntLogger, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]
log4net: Assembly [DtntLogger, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] Loaded From [C:\XXXYYYXXX\TestResults\DEV1\Out\DtntLogger.dll]
log4net: Assembly [DtntLogger, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] does not have a RepositoryAttribute specified.
log4net: Assembly [DtntLogger, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository [log4net-default-repository] using type [log4net.Repository.Hierarchy.Hierarchy]
log4net: configuring repository [log4net-default-repository] using file [log4net.xml]
log4net: configuring repository [log4net-default-repository] using stream
log4net: loading XML configuration
log4net: Configuring Repository [log4net-default-repository]
log4net: Configuration update mode [Merge].
log4net: Logger [root] Level string is [all].
log4net: Logger [root] level set to [name="ALL",value=-2147483648].
log4net: Retrieving an instance of log4net.Repository.Logger for logger [EventLogAppender1].
log4net: Setting [EventLogAppender1] additivity to [True].
log4net: Logger [EventLogAppender1] Level string is [ALL].
log4net: Logger [EventLogAppender1] level set to [name="ALL",value=-2147483648].
log4net: Loading Appender [EventLogAppender] type: [log4net.Appender.EventLogAppender]
log4net: Setting Property [ApplicationName] to String value [AppApp]
log4net: Setting Property [Threshold] to Level value [WARN]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%date [%thread] %-5level %logger [%property{NDC}] - %message%newline]
log4net: Converter [date] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [thread] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [] ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [level] Option [] Format [min=5,max=2147483647,leftAlign=True]
log4net: Converter [literal] Option [ ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [logger] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [property] Option [NDC] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [] - ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.PatternLayout]
log4net: Source [AppApp] is registered to log []
log4net: reated Appender [EventLogAppender]
log4net: Adding appender named [EventLogAppender] to logger [EventLogAppender1].
log4net: Retrieving an instance of log4net.Repository.Logger for logger [LogFileAppender1].
log4net: Setting [LogFileAppender1] additivity to [True].
log4net: Logger [LogFileAppender1] Level string is [ALL].
log4net: Logger [LogFileAppender1] level set to [name="ALL",value=-2147483648].
log4net: Loading Appender [LogFileAppender] type: [log4net.Appender.RollingFileAppender]
log4net: Setting Property [File] to String value [App.log]
log4net: Setting Property [AppendToFile] to Boolean value [True]
log4net: Setting Property [StaticLogFileName] to Boolean value [True]
log4net: Setting Property [MaximumFileSize] to String value [1000MB]
log4net: Setting Property [RollingStyle] to RollingMode value [Date]
log4net: Setting Property [DatePattern] to String value [yyyMMdd]
log4net: Setting Property [MaxSizeRollBackups] to Int32 value [10]
log4net: Setting Property [Threshold] to Level value [WARN]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%-5p%t%d{yyyy-MM-dd HH:mm:ss} – %m%n]
log4net: Converter [p] Option [] Format [min=5,max=2147483647,leftAlign=True]
log4net: Converter [t] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [d] Option [yyyy-MM-dd HH:mm:ss] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ – ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [m] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [n] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.PatternLayout]
log4net: Type = [0], r0 = [19700101], r1 = [19700101]
log4net: Type = [1], r0 = [19700101], r1 = [19700101]
log4net: Type = [2], r0 = [19700101], r1 = [19700101]
log4net: Type = [3], r0 = [19700101], r1 = [19700102]
log4net: Searched for existing files in [C:\XXXYYYXXX\TestResults\DEV1\Out]
log4net: curSizeRollBackups starts at [0]
log4net: Opening file for writing [C:\XXXYYYXXX\TestResults\DEV1\Out\App.log] append [True]
log4net: reated Appender [LogFileAppender]
log4net: Adding appender named [LogFileAppender] to logger [LogFileAppender1].
log4net: Hierarchy Threshold []
log4net: No appenders could be found for logger [EventLogAppener1] repository [log4net-default-repository]
log4net: Please initialize the log4net system properly.
log4net: Current AppDomain context information:
log4net: BaseDirectory : C:\XXXYYYXXX\TestResults\DEV1\Out
log4net: FriendlyName : TestAppDomain: 5dfd9ec0-bf14-4d65-9b74-b78d054c9ca0
log4net: DynamicDirectory:
Agent: adapter run thread for test 'TestWrite' with id '4f072f2c-d52e-466c-bf4d-87b1a0d3cc40' - 13:02:58 | debugging
Log4NET Debug data (Std Error Output)
log4net:ERROR XmlHierarchyConfigurator: Cannot find Property [Threshold] to set object on [log4net.Repository.Hierarchy.DefaultLoggerFactory+LoggerImpl]
log4net:ERROR XmlHierarchyConfigurator: Cannot find Property [threshold] to set object on [log4net.Repository.Hierarchy.DefaultLoggerFactory+LoggerImpl]
log4net:ERROR XmlHierarchyConfigurator: Cannot find Property [maximumfilesize] to set object on [log4net.Repository.Hierarchy.DefaultLoggerFactory+LoggerImpl]
log4net:ERROR XmlHierarchyConfigurator: Cannot find Property [Threshold] to set object on [log4net.Repository.Hierarchy.DefaultLoggerFactory+LoggerImpl]
log4net:ERROR XmlHierarchyConfigurator: Cannot find Property [evaluator] to set object on [log4net.Appender.RollingFileAppender]
Debug Trace
log4net: log4net assembly [log4net, Version=1.2.11.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a]. Loaded from [C:\XXXYYYXXX\TestResults\DEV1\Out\log4net.dll]. (.NET Runtime [4.0.30319.261] on Microsoft Windows NT 6.1.7601 Service Pack 1)
log4net: defaultRepositoryType [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository for assembly [DtntLogger, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]
log4net: Assembly [DtntLogger, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] Loaded From [C:\XXXYYYXXX\TestResults\DEV1\Out\DtntLogger.dll]
log4net: Assembly [DtntLogger, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] does not have a RepositoryAttribute specified.
log4net: Assembly [DtntLogger, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository [log4net-default-repository] using type [log4net.Repository.Hierarchy.Hierarchy]
log4net: configuring repository [log4net-default-repository] using file [log4net.xml]
log4net: configuring repository [log4net-default-repository] using stream
log4net: loading XML configuration
log4net: Configuring Repository [log4net-default-repository]
log4net: Configuration update mode [Merge].
log4net: Logger [root] Level string is [all].
log4net: Logger [root] level set to [name="ALL",value=-2147483648].
log4net: Retrieving an instance of log4net.Repository.Logger for logger [EventLogAppender1].
log4net: Setting [EventLogAppender1] additivity to [True].
log4net: Logger [EventLogAppender1] Level string is [ALL].
log4net: Logger [EventLogAppender1] level set to [name="ALL",value=-2147483648].
log4net:ERROR XmlHierarchyConfigurator: Cannot find Property [Threshold] to set object on [log4net.Repository.Hierarchy.DefaultLoggerFactory+LoggerImpl]
log4net:ERROR XmlHierarchyConfigurator: Cannot find Property [threshold] to set object on [log4net.Repository.Hierarchy.DefaultLoggerFactory+LoggerImpl]
log4net: Loading Appender [EventLogAppender] type: [log4net.Appender.EventLogAppender]
log4net: Setting Property [ApplicationName] to String value [AppApp]
log4net: Setting Property [Threshold] to Level value [WARN]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%date [%thread] %-5level %logger [%property{NDC}] - %message%newline]
log4net: Converter [date] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [thread] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [] ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [level] Option [] Format [min=5,max=2147483647,leftAlign=True]
log4net: Converter [literal] Option [ ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [logger] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [property] Option [NDC] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [] - ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.PatternLayout]
log4net: Source [AppApp] is registered to log []
log4net: reated Appender [EventLogAppender]
log4net: Adding appender named [EventLogAppender] to logger [EventLogAppender1].
log4net: Retrieving an instance of log4net.Repository.Logger for logger [LogFileAppender1].
log4net: Setting [LogFileAppender1] additivity to [True].
log4net: Logger [LogFileAppender1] Level string is [ALL].
log4net: Logger [LogFileAppender1] level set to [name="ALL",value=-2147483648].
log4net:ERROR XmlHierarchyConfigurator: Cannot find Property [maximumfilesize] to set object on [log4net.Repository.Hierarchy.DefaultLoggerFactory+LoggerImpl]
log4net:ERROR XmlHierarchyConfigurator: Cannot find Property [Threshold] to set object on [log4net.Repository.Hierarchy.DefaultLoggerFactory+LoggerImpl]
log4net: Loading Appender [LogFileAppender] type: [log4net.Appender.RollingFileAppender]
log4net: Setting Property [File] to String value [App.log]
log4net: Setting Property [AppendToFile] to Boolean value [True]
log4net: Setting Property [StaticLogFileName] to Boolean value [True]
log4net: Setting Property [MaximumFileSize] to String value [1000MB]
log4net: Setting Property [RollingStyle] to RollingMode value [Date]
log4net: Setting Property [DatePattern] to String value [yyyMMdd]
log4net: Setting Property [MaxSizeRollBackups] to Int32 value [10]
log4net: Setting Property [Threshold] to Level value [WARN]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%-5p%t%d{yyyy-MM-dd HH:mm:ss} – %m%n]
log4net: Converter [p] Option [] Format [min=5,max=2147483647,leftAlign=True]
log4net: Converter [t] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [d] Option [yyyy-MM-dd HH:mm:ss] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ – ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [m] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [n] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.PatternLayout]
log4net:ERROR XmlHierarchyConfigurator: Cannot find Property [evaluator] to set object on [log4net.Appender.RollingFileAppender]
log4net: Type = [0], r0 = [19700101], r1 = [19700101]
log4net: Type = [1], r0 = [19700101], r1 = [19700101]
log4net: Type = [2], r0 = [19700101], r1 = [19700101]
log4net: Type = [3], r0 = [19700101], r1 = [19700102]
log4net: Searched for existing files in [C:\XXXYYYXXX\TestResults\DEV1\Out]
log4net: curSizeRollBackups starts at [0]
log4net: Opening file for writing [C:\XXXYYYXXX\TestResults\DEV1\Out\App.log] append [True]
log4net: reated Appender [LogFileAppender]
log4net: Adding appender named [LogFileAppender] to logger [LogFileAppender1].
log4net: Hierarchy Threshold []
log4net: No appenders could be found for logger [EventLogAppener1] repository [log4net-default-repository]
log4net: Please initialize the log4net system properly.
log4net: Current AppDomain context information:
log4net: BaseDirectory : C:\XXXYYYXXX\TestResults\DEV1\Out
log4net: FriendlyName : TestAppDomain: 5dfd9ec0-bf14-4d65-9b74-b78d054c9ca0
log4net: DynamicDirectory:

Answered this in my blog http://mperlstein.blogspot.com/2012/04/log4net-configuration-trouble.html
The gist is that log4net uses reflection to update attributes, and Threshold does not exist as a writable property/attribute on the object in question.
Never again

Related

log4net logger not writing my logs to file, but ASP.NET log messages are written

I have an ASP.NET Core 3.1 Razor pages web site, and am trying to add log4net to it, but can't get logging to work properly. I have referenced the Microsoft.Extensions.Logging.Log4Net.AspNetCore Nuget package and associated dependencies.
I added a log4net.config file...
<?xml version="1.0" encoding="utf-8"?>
<log4net>
<appender name="RollingFileAppender"
type="log4net.Appender.RollingFileAppender">
<param name="File"
value="MyWebSite.log" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="2" />
<maximumFileSize value="5MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-7level %logger - %message%newline%exception" />
</layout>
</appender>
<appender name="Console" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>
I changed Program.cs to look like this...
public class Program {
public static void Main(string[] args) =>
CreateHostBuilder(args).Build().Run();
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => {
webBuilder.UseStartup<Startup>();
}).ConfigureLogging(builder => {
builder.SetMinimumLevel(LogLevel.Trace);
builder.AddLog4Net("log4net.config");
});
}
I tried using this on the site home page, as follows...
public class IndexModel : PageModel {
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger) {
_logger = logger;
}
public void OnGet() {
_logger.LogDebug("Home page loading");
}
}
However, the log file did not contain the message I added.
I can see that logging is working to a degree, as the log file was created, and the first three lines were...
2020-10-18 16:27:59,052 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Application started. Press Ctrl+C to shut down.
2020-10-18 16:27:59,065 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Hosting environment: Development
2020-10-18 16:27:59,066 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Content root path:
...but then I don't get anything else.
To check it was all being set up correctly, I added the following lines inside the Onget() method...
ILoggerRepository repository = log4net.LogManager.GetAllRepositories().FirstOrDefault();
RollingFileAppender appender = repository.GetAppenders().OfType<RollingFileAppender>().FirstOrDefault();
string logFile = appender.File;
At run time, the logFile variable is correctly set to the path to the expected log file, so it looks like it has initialised fine.
I tried going the old-fashioned root and newing up an instance of the logger as follows...
log4NetLogger = LogManager.GetLogger(typeof(IndexModel));
...and this worked fine.
So, I can log, but only by creating the logger manually, not by injection.
Anyone any idea what I'm doing wrong here? Thanks
Update Having just found out how to debug log4net, I added the following line in the ConfigureServices method in Startupcs...
log4net.Util.LogLog.InternalDebugging = true;
This resulted in the following being sent to the output panel...
log4net: log4net assembly [log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a]. (.NET Framework [.NET Core 3.1.4] on Microsoft Windows 10.0.18363)
log4net: defaultRepositoryType [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository for assembly [Microsoft.Extensions.Logging.Log4Net.AspNetCore, Version=3.1.0.0, Culture=neutral, PublicKeyToken=5d1104efbd0e675d]
log4net: Assembly [Microsoft.Extensions.Logging.Log4Net.AspNetCore, Version=3.1.0.0, Culture=neutral, PublicKeyToken=5d1104efbd0e675d] Loaded From [Not supported on .NET Core]
log4net: Assembly [Microsoft.Extensions.Logging.Log4Net.AspNetCore, Version=3.1.0.0, Culture=neutral, PublicKeyToken=5d1104efbd0e675d] does not have a RepositoryAttribute specified.
log4net: Assembly [Microsoft.Extensions.Logging.Log4Net.AspNetCore, Version=3.1.0.0, Culture=neutral, PublicKeyToken=5d1104efbd0e675d] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository [log4net-default-repository] using type [log4net.Repository.Hierarchy.Hierarchy]
log4net: configuring repository [log4net-default-repository] using XML element
log4net: Configuring Repository [log4net-default-repository]
log4net: Configuration update mode [Merge].
log4net: Logger [root] Level string is [DEBUG].
log4net: Logger [root] level set to [name="DEBUG",value=30000].
log4net: Loading Appender [RollingFileAppender] type: [log4net.Appender.RollingFileAppender]
log4net: Setting Property [File] to String value [MyWebSite.log]
log4net: Setting Property [AppendToFile] to Boolean value [True]
log4net: Setting Property [LockingModel] to object [log4net.Appender.FileAppender+MinimalLock]
log4net: Setting Property [RollingStyle] to RollingMode value [Size]
log4net: Setting Property [MaxSizeRollBackups] to Int32 value [2]
log4net: Setting Property [MaximumFileSize] to String value [5MB]
log4net: Setting Property [StaticLogFileName] to Boolean value [True]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%date [%thread] %-7level %logger - %message%newline%exception]
log4net: Converter [date] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [thread] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [] ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [level] Option [] Format [min=7,max=2147483647,leftAlign=True]
log4net: Converter [literal] Option [ ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [logger] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ - ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [exception] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.PatternLayout]
log4net: Searched for existing files in [PATHTOPROJECT]
log4net: curSizeRollBackups starts at [0]
log4net: Opening file for writing [PATHTOPROJECT\MyWebSite.log] append [True]
log4net: Created Appender [RollingFileAppender]
log4net: Adding appender named [RollingFileAppender] to logger [root].
log4net: Hierarchy Threshold []
Microsoft.Hosting.Lifetime: Information: Application started. Press Ctrl+C to shut down.
Microsoft.Hosting.Lifetime: Information: Hosting environment: Development
Microsoft.Hosting.Lifetime: Information: Content root path: PATHTOPROJECT
Not sure if this helps, as it doesn't seem to show any errors. The path is correct, and points to the log file that is written.
Have you changed the default logging level set in your appSettings.json to "Debug"? If it's set to "Information" then debug logging messages won't show.

Can't Able to get Instance of ExceptionManager

I am using Enterprise Library 5.0 in Silverlight using mvvm-light Framework.
When I'm going to getInstace of ExceptionManager Class like:
var exceptionManager = EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>();
exceptionManager.HandleException(E.Error, "Policy");
I Got this type of error Message
Activation error occured while trying to get instance of type ExceptionManager, key ""
Resolution of the dependency failed, type = Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionManager", name = "(none)"
Exception occurred while: while resolving.Exception is: InvalidOperationException - The type TraceListener cannot be constructed. You must configure the container to supply this value
-----------------------------------------------
At the time of the exception, the container was:
Resolving Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionManagerImpl,ExceptionManager.__default__ (mapped from Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionManager, (none))
Resolving parameter "exceptionPolicies" of constructor Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionManagerImpl(System.Collections.Generic.IEnumerable`1[[Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyImpl, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Silverlight, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]] exceptionPolicies, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Instrumentation.IDefaultExceptionHandlingInstrumentationProvider instrumentationProvider)
Resolving Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyImpl,Policy
Resolving parameter "policyEntries" of constructor Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyImpl(System.String policyName, System.Collections.Generic.IEnumerable`1[[Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyEntry, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Silverlight, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]] policyEntries)
Resolving Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyEntry,Policy.All Exceptions
Resolving parameter "handlers" of constructor Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyEntry(System.Type exceptionType, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.PostHandlingAction postHandlingAction, System.Collections.Generic.IEnumerable`1[[Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.IExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Silverlight, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]] handlers, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Instrumentation.IExceptionHandlingInstrumentationProvider instrumentationProvider)
Resolving Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler,Policy.All Exceptions.Logging Exception Handler (mapped from Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.IExceptionHandler, Policy.All Exceptions.Logging Exception Handler)
Resolving parameter "writer" of constructor Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler(System.String logCategory, System.Int32 eventId, Microsoft.Practices.EnterpriseLibrary.Logging.Diagnostics.TraceEventType severity, System.String title, System.Int32 priority, System.Type formatterType, Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter writer)
Resolving Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterImpl,LogWriter.__default__ (mapped from Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter, (none))
Resolving parameter "structureHolder" of constructor Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterImpl(Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterStructureHolder structureHolder, Microsoft.Practices.EnterpriseLibrary.Logging.Instrumentation.ILoggingInstrumentationProvider instrumentationProvider, Microsoft.Practices.EnterpriseLibrary.Logging.IAsyncTracingErrorReporter asyncTracingErrorReporter)
Resolving Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterStructureHolder,LogWriterStructureHolder.__default__ (mapped from Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterStructureHolder, (none))
Resolving parameter "traceSources" of constructor Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterStructureHolder(System.Collections.Generic.IEnumerable`1[[Microsoft.Practices.EnterpriseLibrary.Logging.Filters.ILogFilter, Microsoft.Practices.EnterpriseLibrary.Logging.Silverlight, Version=5.0.505.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35]] filters, System.Collections.Generic.IEnumerable`1[[System.String, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]] traceSourceNames, System.Collections.Generic.IEnumerable`1[[Microsoft.Practices.EnterpriseLibrary.Logging.LogSource, Microsoft.Practices.EnterpriseLibrary.Logging.Silverlight, Version=5.0.505.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35]] traceSources, Microsoft.Practices.EnterpriseLibrary.Logging.LogSource allEventsTraceSource, Microsoft.Practices.EnterpriseLibrary.Logging.LogSource notProcessedTraceSource, Microsoft.Practices.EnterpriseLibrary.Logging.LogSource errorsTraceSource, System.String defaultCategory, System.Boolean tracingEnabled, System.Boolean logWarningsWhenNoCategoriesMatch, System.Boolean revertImpersonation)
Resolving Microsoft.Practices.EnterpriseLibrary.Logging.LogSource,General
Resolving parameter "traceListeners" of constructor Microsoft.Practices.EnterpriseLibrary.Logging.LogSource(System.String name, System.Collections.Generic.IEnumerable`1[[Microsoft.Practices.EnterpriseLibrary.Logging.Diagnostics.TraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Silverlight, Version=5.0.505.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35]] traceListeners, Microsoft.Practices.EnterpriseLibrary.Logging.Diagnostics.SourceLevels level, System.Boolean autoFlush, Microsoft.Practices.EnterpriseLibrary.Logging.Instrumentation.ILoggingInstrumentationProvider instrumentationProvider)
Resolving Microsoft.Practices.EnterpriseLibrary.Logging.Diagnostics.TraceListener,Flat File Trace Listener
At Line of
var exceptionManager = EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>();
My Configuration File is:
<?xml version="1.0" encoding="utf-8"?>
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:el="http://schemas.microsoft.com/practices/2011/entlib">
<el:ExceptionHandlingSettings x:Key="exceptionHandling">
<el:ExceptionHandlingSettings.ExceptionPolicies>
<el:ExceptionPolicyData Name="LogPolicy">
<el:ExceptionPolicyData.ExceptionTypes>
<el:ExceptionTypeData Name="All Exceptions" TypeName="System.Exception, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e">
<el:ExceptionTypeData.ExceptionHandlers>
<el:LoggingExceptionHandlerData LogCategory="General" FormatterTypeName="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Silverlight, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Priority="-1" Name="Logging Exception Handler" />
</el:ExceptionTypeData.ExceptionHandlers>
</el:ExceptionTypeData>
</el:ExceptionPolicyData.ExceptionTypes>
</el:ExceptionPolicyData>
</el:ExceptionHandlingSettings.ExceptionPolicies>
</el:ExceptionHandlingSettings>
<el:LoggingSettings DefaultCategory="General" x:Key="loggingConfiguration">
<el:LoggingSettings.TraceSources>
<el:TraceSourceData Name="General">
<el:TraceSourceData.TraceListeners>
<el:TraceListenerReferenceData Name="Flat File Trace Listener" />
</el:TraceSourceData.TraceListeners>
</el:TraceSourceData>
</el:LoggingSettings.TraceSources>
<el:LoggingSettings.SpecialTraceSources>
<el:SpecialTraceSourcesData>
<el:SpecialTraceSourcesData.AllEventsTraceSource>
<el:TraceSourceData Name="All Events" />
</el:SpecialTraceSourcesData.AllEventsTraceSource>
<el:SpecialTraceSourcesData.NotProcessedTraceSource>
<el:TraceSourceData Name="Unprocessed Category" />
</el:SpecialTraceSourcesData.NotProcessedTraceSource>
<el:SpecialTraceSourcesData.ErrorsTraceSource>
<el:TraceSourceData Name="Logging Errors & Warnings">
<el:TraceSourceData.TraceListeners>
<el:TraceListenerReferenceData Name="Flat File Trace Listener" />
</el:TraceSourceData.TraceListeners>
</el:TraceSourceData>
</el:SpecialTraceSourcesData.ErrorsTraceSource>
</el:SpecialTraceSourcesData>
</el:LoggingSettings.SpecialTraceSources>
</el:LoggingSettings>
</ResourceDictionary>
It looks like your configuration is referencing a trace listener called "Flat File Trace Listener" but there is no trace listener defined by that name.
Also, you should be aware that the Enterprise Library Silverlight Logging Application Block does not support a Flat File Trace Listener. Valid actions are:
Logging to a remote WCF Service.
Logging to isolated storage.
Logging to an event.

Applying ServiceKnownTypeAttribute to WCF service with Spring

I am trying to apply the ServiceKnownTypeAttribute to my WCF Service but keep getting the error below my config. Does anyone have any ideas?
<object id="HHGEstimating" type="Spring.ServiceModel.ServiceExporter, Spring.Services">
<property name="TargetName" value="HHGEstimatingHelper"/>
<property name="Name" value="HHGEstimating"/>
<property name="Namespace" value="http://www.igcsoftware.com/HHGEstimating"/>
<property name="TypeAttributes">
<list>
<ref local="wcfErrorBehavior"/>
<ref local="wcfSilverlightFaultBehavior"/>
<object type="System.ServiceModel.ServiceKnownTypeAttribute, System.ServiceModel">
<constructor-arg name="type" value="IGCSoftware.HHG.Business.UserControl.AtlasUser, IGCSoftware.HHG.Business"/>
</object>
</list>
</property>
Error thrown by a dependency of object 'HHGEstimating' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46' : '1' constructor arguments specified but no matching constructor found in object 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' (hint: specify argument indexes, names, or types to avoid ambiguities).
while resolving 'TypeAttributes[2]' to 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46'
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: Spring.Objects.Factory.ObjectCreationException: Error thrown by a dependency of object 'HHGEstimating' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46' : '1' constructor arguments specified but no matching constructor found in object 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' (hint: specify argument indexes, names, or types to avoid ambiguities).
while resolving 'TypeAttributes[2]' to 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46'
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ObjectCreationException: Error thrown by a dependency of object 'HHGEstimating' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46' : '1' constructor arguments specified but no matching constructor found in object 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' (hint: specify argument indexes, names, or types to avoid ambiguities).
while resolving 'TypeAttributes[2]' to 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46']
Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolveInnerObjectDefinition(String name, String innerObjectName, String argumentName, IObjectDefinition definition, Boolean singletonOwner) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\ObjectDefinitionValueResolver.cs:300
Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolvePropertyValue(String name, IObjectDefinition definition, String argumentName, Object argumentValue) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\ObjectDefinitionValueResolver.cs:150
Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolveValueIfNecessary(String name, IObjectDefinition definition, String argumentName, Object argumentValue) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\ObjectDefinitionValueResolver.cs:112
Spring.Objects.Factory.Config.ManagedList.Resolve(String objectName, IObjectDefinition definition, String propertyName, ManagedCollectionElementResolver resolver) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Config\ManagedList.cs:126
Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolvePropertyValue(String name, IObjectDefinition definition, String argumentName, Object argumentValue) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\ObjectDefinitionValueResolver.cs:201
Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolveValueIfNecessary(String name, IObjectDefinition definition, String argumentName, Object argumentValue) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\ObjectDefinitionValueResolver.cs:112
Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.ApplyPropertyValues(String name, RootObjectDefinition definition, IObjectWrapper wrapper, IPropertyValues properties) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\AbstractAutowireCapableObjectFactory.cs:373
Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.PopulateObject(String name, RootObjectDefinition definition, IObjectWrapper wrapper) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\AbstractAutowireCapableObjectFactory.cs:563
Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.ConfigureObject(String name, RootObjectDefinition definition, IObjectWrapper wrapper) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\AbstractAutowireCapableObjectFactory.cs:1844
Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InstantiateObject(String name, RootObjectDefinition definition, Object[] arguments, Boolean allowEagerCaching, Boolean suppressConfigure) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\AbstractAutowireCapableObjectFactory.cs:918
Spring.Objects.Factory.Support.AbstractObjectFactory.CreateAndCacheSingletonInstance(String objectName, RootObjectDefinition objectDefinition, Object[] arguments) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\AbstractObjectFactory.cs:2120
Spring.Objects.Factory.Support.AbstractObjectFactory.GetObjectInternal(String name, Type requiredType, Object[] arguments, Boolean suppressConfigure) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\AbstractObjectFactory.cs:2046
Spring.Objects.Factory.Support.DefaultListableObjectFactory.PreInstantiateSingletons() in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\DefaultListableObjectFactory.cs:505
Spring.Context.Support.AbstractApplicationContext.Refresh() in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Context\Support\AbstractApplicationContext.cs:911
_dynamic_Spring.Context.Support.XmlApplicationContext..ctor(Object[] ) +197
Spring.Reflection.Dynamic.SafeConstructor.Invoke(Object[] arguments) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Reflection\Dynamic\DynamicConstructor.cs:116
Spring.Context.Support.RootContextInstantiator.InvokeContextConstructor(ConstructorInfo ctor) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Context\Support\ContextHandler.cs:550
Spring.Context.Support.ContextInstantiator.InstantiateContext() in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Context\Support\ContextHandler.cs:494
Spring.Context.Support.ContextHandler.InstantiateContext(IApplicationContext parentContext, Object configContext, String contextName, Type contextType, Boolean caseSensitive, String[] resources) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Context\Support\ContextHandler.cs:330
Spring.Context.Support.ContextHandler.Create(Object parent, Object configContext, XmlNode section) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Context\Support\ContextHandler.cs:280
[ConfigurationErrorsException: Error creating context 'spring.root': Error thrown by a dependency of object 'HHGEstimating' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46' : '1' constructor arguments specified but no matching constructor found in object 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' (hint: specify argument indexes, names, or types to avoid ambiguities).
while resolving 'TypeAttributes[2]' to 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46']
System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult) +202
System.Configuration.BaseConfigurationRecord.Evaluate(FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult, Boolean getLkg, Boolean getRuntimeObject, Object& result, Object& resultRuntimeObject) +1061
System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject) +1431
System.Configuration.BaseConfigurationRecord.GetSection(String configKey, Boolean getLkg, Boolean checkPermission) +56
System.Configuration.BaseConfigurationRecord.GetSection(String configKey) +8
System.Web.Configuration.HttpConfigurationSystem.GetApplicationSection(String sectionName) +45
System.Web.Configuration.HttpConfigurationSystem.GetSection(String sectionName) +49
System.Web.Configuration.HttpConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String configKey) +6
System.Configuration.ConfigurationManager.GetSection(String sectionName) +78
Spring.Util.ConfigurationUtils.GetSection(String sectionName) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Util\ConfigurationUtils.cs:69
Spring.Context.Support.ContextRegistry.InitializeContextIfNeeded() in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Context\Support\ContextRegistry.cs:340
Spring.Context.Support.ContextRegistry.GetContext() in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Context\Support\ContextRegistry.cs:206
Spring.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String reference, Uri[] baseAddresses) in l:\projects\spring-net\trunk\src\Spring\Spring.Services\ServiceModel\Activation\ServiceHostFactory.cs:66
System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath) +11687036
System.ServiceModel.HostingManager.ActivateService(String normalizedVirtualPath) +42
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath) +479
[ServiceActivationException: The service '/HHGEstimating.svc' cannot be activated due to an exception during compilation. The exception message is: Error creating context 'spring.root': Error thrown by a dependency of object 'HHGEstimating' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46' : '1' constructor arguments specified but no matching constructor found in object 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' (hint: specify argument indexes, names, or types to avoid ambiguities).
while resolving 'TypeAttributes[2]' to 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46'.]
System.ServiceModel.AsyncResult.End(IAsyncResult result) +11592858
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +194
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.ExecuteSynchronous(HttpApplication context, Boolean flowContext) +176
System.ServiceModel.Activation.HttpModule.ProcessRequest(Object sender, EventArgs e) +275
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
This is a known bug :
https://jira.springsource.org/browse/SPRNET-1262
Attributes are applied to classes at compile time and baked into the metadata. You cannot apply attributes to classes with Spring.NET at runtime. Add the known types to the data contract serializer in your web.config:
<system.runtime.serialization>
<dataContractSerializer>
<declaredTypes>
<add type="BaseType, SomeAssembly">
<knownType type="ConcreteType, SomeAssembly" />
</add>
</declaredTypes>
</dataContractSerializer>
</system.runtime.serialization>

NHibernate.MappingException: No persister No mapped documents found in assembly

I have been doing nhibernate since many days. But Today I stuck at a frustrating issue i.e. mapping exception.
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="IPC.Base.Domains" assembly="IPC">
<class name="MenuItem" table="dbo.COR_MenuItem" default-access="property" default-cascade="save-update" default-lazy="true">
<cache usage="read-only" region="completelyStatic"/>
<id name="Id" type="System.Int32">
<generator class="identity" />
</id>
<property name="Name" type="System.String" />
<property name="Order" column="DisplayOrder" />
<property name="Key" column="KeyChain" />
<property name="Route" />
<property name="ActionMethod" />
<property name="IsHotlink" />
<many-to-one name="ParentMenuItem" column="ParentMenuItemId" class="MenuItem" cascade="none"/>
<bag name="MenuItems" table="dbo.COR_MenuItem" cascade="none">
<cache usage="read-only" region="completelyStatic"/>
<key column="ParentMenuItemId" />
<one-to-many class="MenuItem" />
</bag>
</class>
</hibernate-mapping>
And I do have a mapping class as following:
using System;
using System.Collections.Generic;
namespace IPC.Base.Domain
{
public partial class MenuItem : PersistentObject
{
public MenuItem()
{
MenuItems = new List<MenuItem>();
}
public virtual string Name { get; set; }
public virtual int? Order { get; set; }
public virtual string Key { get; set; }
public virtual string Route { get; set; }
public virtual string ActionMethod { get; set; }
public virtual bool IsHotlink { get; set; }
public virtual IList<MenuItem> MenuItems { get; set; }
public virtual MenuItem ParentMenuItem { get; set; }
/// <summary>
/// only to be used from the menu builder app
/// </summary>
/// <param name="id"></param>
public virtual void SetId(int id)
{
Id = id;
}
}
}
I have the following nHibernate Config running with the application. But as per my experience there is absolutely no issue with the nHibernate Config.
<?xml version="1.0"?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory name="IPC">
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">**************SQL CONNECTION****************/property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
<property name="cache.provider_class">NHibernate.Caches.SysCache.SysCacheProvider, NHibernate.Caches.SysCache</property>
<property name="cache.use_query_cache">true</property>
<property name="show_sql">true</property>
<mapping assembly="IPC"/>
</session-factory>
</hibernate-configuration>
I am using the following line for code for invoking nHibernate session object to system.
static ISessionFactory CurrentFactory
{
get
{
if (factory == null)
{
Configuration cfg = new Configuration();
if (cfgFile == null)
cfg = cfg.Configure();
else
cfg = cfg.Configure(cfgFile);
factory = cfg.BuildSessionFactory();
}
return factory;
}
}
public static ISession Create()
{
var session = CurrentFactory.OpenSession();
return session;
}
Now! When I call the following line of code I am getting:
public virtual T Get(int id)
{
return Session.Get<T>(id);
}
No persister for: IPC.Base.Domain.MenuItem
Exception Details: NHibernate.MappingException: No persister for: IPC.Base.Domain.MenuItem
I have already enabled by nHibernate log. Following are the basic details from log
00:54:40.011 [4] INFO NHibernate.Cfg.Environment - NHibernate 2.1.0.4000 (2.1.0.4000)
00:54:40.055 [4] INFO NHibernate.Cfg.Environment - Bytecode provider name : lcg
00:54:40.057 [4] INFO NHibernate.Cfg.Environment - Using reflection optimizer
00:54:40.682 [4] DEBUG NHibernate.Cfg.Configuration - dialect=NHibernate.Dialect.MsSql2005Dialect
00:54:40.683 [4] DEBUG NHibernate.Cfg.Configuration - connection.driver_class=NHibernate.Driver.SqlClientDriver
00:54:40.683 [4] DEBUG NHibernate.Cfg.Configuration - connection.connection_string=*********************SQL Connection*****************
00:54:40.683 [4] DEBUG NHibernate.Cfg.Configuration - proxyfactory.factory_class=NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu
00:54:40.683 [4] DEBUG NHibernate.Cfg.Configuration - cache.provider_class=NHibernate.Caches.SysCache.SysCacheProvider, NHibernate.Caches.SysCache
00:54:40.683 [4] DEBUG NHibernate.Cfg.Configuration - cache.use_query_cache=true
00:54:40.683 [4] DEBUG NHibernate.Cfg.Configuration - show_sql=true
00:54:40.684 [4] DEBUG NHibernate.Cfg.Configuration - IPC<-IPC
00:54:40.685 [4] INFO NHibernate.Cfg.Configuration - Searching for mapped documents in assembly: IPC
00:54:40.689 [4] WARN NHibernate.Cfg.Configuration - No mapped documents found in assembly: IPC, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
00:54:40.691 [4] INFO NHibernate.Cfg.Configuration - Configured SessionFactory: IPC
00:54:40.691 [4] DEBUG NHibernate.Cfg.Configuration - properties: System.Collections.Generic.Dictionary`2[System.String,System.String]
00:54:45.716 [4] INFO NHibernate.Cfg.Configuration - checking mappings queue
00:54:45.716 [4] INFO NHibernate.Cfg.Configuration - processing one-to-many association mappings
00:54:45.717 [4] INFO NHibernate.Cfg.Configuration - processing one-to-one association property references
00:54:45.717 [4] INFO NHibernate.Cfg.Configuration - processing foreign key constraints
00:54:45.747 [4] INFO NHibernate.Dialect.Dialect - Using dialect: NHibernate.Dialect.MsSql2005Dialect
I have read almost all the post with stack! :) and even doing google for the same. The final words I am getting there is an issue with my assembly naming! I sure that there is a issue with the steps which I have followed. But still searching for that trigger!!!
Thanks!
In advance!!
Probably you forgot to set your hbm mappings as embedded resource to the DLL.
Finally I resolved the issue! Its basically a stupid stuff which normally I tend to do and then forget to get it back on running stage.
Yes, I was related with the assembly issue. Nothing but when I was trying to build then data layer application It was not enbading the xml files inside assembly.
A Fix for solve the problem go to your
*.hbm.xml files and do a right click and change build option of that file
to embedded resource.
Alrite!
Many thanks!

using NetDataContractSerializer throws an exception on client side

I've tried to move WCF to NetDataContractSerializer using the code in this post:
http://lunaverse.wordpress.com/2007/05/09/remoting-using-wcf-and-nhibernate
and adding this code on the client side:
foreach (OperationDescription desc in factory.Endpoint.Contract.Operations)
{
DataContractSerializerOperationBehavior dcsOperationBehavior = desc.Behaviors.Find<DataContractSerializerOperationBehavior>();
if (dcsOperationBehavior != null)
{
int idx = desc.Behaviors.IndexOf(dcsOperationBehavior);
desc.Behaviors.Remove(dcsOperationBehavior);
desc.Behaviors.Insert(idx, new NetDataContractOperationBehavior(desc));
//return true;
}
}
But Eevry time I ivoke my List call, I get this exception:
the formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:ListResult. The InnerException message was 'The deserializer cannot load the type to deserialize because type 'System.Collections.Generic.List`1[[MYPROJ.Framework.Entities.EntityBase, MYPROJ.Framework.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' could not be found in assembly 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Check that the type being serialized has the same contract as the type being deserialized and the same assembly is used.'. Please see InnerException for more details.
The InnerExcption:
The deserializer cannot load the type to deserialize because type 'System.Collections.Generic.List`1[[MYPROJ.Framework.Entities.EntityBase, MYPROJ.Framework.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' could not be found in assembly 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Check that the type being serialized has the same contract as the type being deserialized and the same assembly is used.
The Proxy is generated using svcutils with this flag: /ct:System.Collections.Generic.List`1
so the lists on the other side will not turn into arrays.
The type that the deseriliezer looking is defined in the server. all the entities are derived from this type, but this is not the namespace of the proxy which resides in the client side.
Using Regular default serializer for WCF works fine (there are other problems involving dealing with circular reference the cause me to try a different serializer).
Any Ideas ?
Thanks,
Dani
http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/433ba785-581c-4dfa-861a-f22574c1b463
This article says NetDataContract Doesn't support svcutil generated proxy, and you must use a shared dll.