I'm starting to use the Exception Handling, in my case I use the configuration manager, creating a Null Policie with a Replace Handler, in this case the message that replace to this exception is the next:"Exists some null values: "...my web.config:
<exceptionHandling>
<exceptionPolicies>
<add name="Null Policies">
<exceptionTypes>
<add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="ThrowNewException">
<exceptionHandlers>
<add name="Replace Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
exceptionMessage="Exists some null values" replaceExceptionType="System.NullReferenceException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
In a piece of my code that I know that throw a NullReferenceException I want to add the value that throws this exception, and append to the message previous implemented on the configuration:
try
{
string theValue = anotherThing //this piece of code throw a NullReferenceException
}
catch(Exception ex)
{
if (exManager.HandleException(ex,"Null Policies")) throw; //add 'theValue' to the new Exception
return "";
}
Researching I found about the Configuration class to access to the web.config...and I don't know how to access to this particular piece of the XML -> exceptionPolicies<- and modify the property like: exceptionMessage= "Exists some null values "+ theValue;
Hope you can help me...
Related
I have this peculiar issue with the System.Globalization.CultureInfo class and the System.Globalization namespace. I'm returning an object (Languages) from an API call that has a CultureInfo property. I'm able to successfully pull this on the client side into an IENumerable<Language> languages {get; set;} but when I try to build with a line such as var x = model.languages.First().AssociatedCulture.Name I'm met with the following errors:
Error 489 'System.Globalization.CultureInfo' does not contain a definition for 'EnglishName' and no extension method 'EnglishName' accepting a first argument of type 'System.Globalization.CultureInfo' could be found (are you missing a using directive or an assembly reference?)
Error 488 The type 'System.Globalization.CultureInfo' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Globalization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
Here is the sequence of lines I have run to try this out:
var y = new CultureInfo("en"); //works
var z = y.Name; //works
var x = model.languages.First().AssociatedCulture.EnglishName; //error at this line.
I don't understand this phantom error. If it helps, the project that creates Language.cs uses the .NET portable v.4.5.
I have tried adding this to the web.config assemblies block but no dice.
<compilation defaultLanguage="c#" debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Globalization , Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
<add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Web.Helpers, Version=2.0.0.0, Culture=neutral,PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral,PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=2.0.0.0, Culture=neutral,PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</assemblies>
<buildProviders>
<add extension=".cshtml" type="System.Web.WebPages.Razor.RazorBuildProvider, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</buildProviders>
</compilation>
Has anyone experienced this issue before? Is it somehow caused by .NET portable?
You need a project reference to System.Globalization.
When you edit the web.config file you're adding a reference for the dynamic assembly that's generated from your .aspx/.cshtml files, this is separate and distinct from your project references (which are references for the output DLL from your project).
Add a Project Reference in Visual Studio via Solution Explorer.
Is it possible to dynamically set log folder and file name in C# which overrides the config value(file name) in the Listeners section of logging configuration?
Tried to follow the below link but it is applicable only for EL 5
Log messages going to previously created log file
This is how i Initialize EL Logging:
IConfigurationSource configurationSource = ConfigurationSourceFactory.Create();
LogWriterFactory logWriterFactory = new LogWriterFactory(configurationSource);
Logger.SetLogWriter(logWriterFactory.Create(), false);
ExceptionPolicyFactory factory = new ExceptionPolicyFactory(configurationSource);
ExceptionPolicy.SetExceptionManager(factory.CreateManager());
These are my web.config entries inside the listeners tag:
<add name="RollingFlatFileTraceLog" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
fileName="C:\logs\Trace.log" footer=""
formatter="CustomRollingFlatFileLogFormatter"
header="" rollFileExistsBehavior="Overwrite" rollInterval="Day"
rollSizeKB="2048" maxArchivedFiles="52" />
<add name="RollingFlatFileErrorLog" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
fileName="C:\logs\Error.log" footer="----------------------------------------"
formatter=" CustomRollingFlatFileLogFormatter "
header="----------------------------------------" rollFileExistsBehavior="Overwrite"
rollInterval="Day" rollSizeKB="2048" maxArchivedFiles="52" />
I use Logger.Write and ExceptionPolicy.HandleException to write to the corresponding trace and error logs.
The best (and easiest!) approach would be to use programmatic configuration to set the filename.
However, you can use a similar approach to modify settings at runtime. Setup the configuration in an external file and use a file configuration source in app/web.config. An external file is necessary to avoid a configuration is read-only exception.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="enterpriseLibrary.ConfigurationSource" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection, Microsoft.Practices.EnterpriseLibrary.Common, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<enterpriseLibrary.ConfigurationSource selectedSource="File-based Configuration Source">
<sources>
<add name="File-based Configuration Source" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
filePath="entlib.config" />
</sources>
</enterpriseLibrary.ConfigurationSource>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/>
</startup>
</configuration>
And configure the external file (entlib.config in this case):
<configuration>
<configSections>
<section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<exceptionHandling>
<exceptionPolicies>
<add name="Policy">
<exceptionTypes>
<add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="NotifyRethrow">
<exceptionHandlers>
<add name="Logging Exception Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
logCategory="General" eventId="100" severity="Error" title="Enterprise Library Exception Handling"
formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
priority="0" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
<loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
<listeners>
<add name="Event Log Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
source="Enterprise Library Logging" formatter="Text Formatter"
log="" machineName="." traceOutputOptions="None" />
<add name="Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
fileName="trace.log" />
</listeners>
<formatters>
<add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
template="Timestamp: {timestamp}{newline}
Message: {message}{newline}
Category: {category}{newline}
Priority: {priority}{newline}
EventId: {eventid}{newline}
Severity: {severity}{newline}
Title:{title}{newline}
Machine: {localMachine}{newline}
App Domain: {localAppDomain}{newline}
ProcessId: {localProcessId}{newline}
Process Name: {localProcessName}{newline}
Thread Name: {threadName}{newline}
Win32 ThreadId:{win32ThreadId}{newline}
Extended Properties: {dictionary({key} - {value}{newline})}"
name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Flat File Trace Listener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Event Log Listener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
</configuration>
Use the SerializableConfigurationSource from the blog posting:
public class SerializableConfigurationSource : IConfigurationSource
{
Dictionary<string, ConfigurationSection> sections = new Dictionary<string, ConfigurationSection>();
public SerializableConfigurationSource()
{
}
public ConfigurationSection GetSection(string sectionName)
{
ConfigurationSection configSection;
if (sections.TryGetValue(sectionName, out configSection))
{
SerializableConfigurationSection section = configSection as SerializableConfigurationSection;
if (section != null)
{
using (StringWriter xml = new StringWriter())
using (XmlWriter xmlwriter = System.Xml.XmlWriter.Create(xml))
{
section.WriteXml(xmlwriter);
xmlwriter.Flush();
MethodInfo methodInfo = section.GetType().GetMethod("DeserializeSection", BindingFlags.NonPublic | BindingFlags.Instance);
methodInfo.Invoke(section, new object[] { XDocument.Parse(xml.ToString()).CreateReader() });
return configSection;
}
}
}
return null;
}
public void Add(string sectionName, ConfigurationSection configurationSection)
{
sections[sectionName] = configurationSection;
}
public void AddSectionChangeHandler(string sectionName, ConfigurationChangedEventHandler handler)
{
throw new NotImplementedException();
}
public void Remove(string sectionName)
{
sections.Remove(sectionName);
}
public void RemoveSectionChangeHandler(string sectionName, ConfigurationChangedEventHandler handler)
{
throw new NotImplementedException();
}
public event EventHandler<ConfigurationSourceChangedEventArgs> SourceChanged;
public void Dispose()
{
}
}
Bootstrap the blocks at startup:
IConfigurationSource configSource = ConfigurationSourceFactory.Create();
var loggingSettings = configSource.GetSection(LoggingSettings.SectionName) as LoggingSettings;
var data = loggingSettings.TraceListeners.First(t => t.Name == "Flat File Trace Listener") as FlatFileTraceListenerData;
// Change the file name
data.FileName = "trace_1.txt";
var loggingXmlConfigSource = new SerializableConfigurationSource();
loggingXmlConfigSource.Add(LoggingSettings.SectionName, loggingSettings);
var logFactory = new LogWriterFactory(loggingXmlConfigSource);
Logger.SetLogWriter(logFactory.Create());
IConfigurationSource config = ConfigurationSourceFactory.Create();
ExceptionPolicyFactory factory = new ExceptionPolicyFactory(config);
ExceptionManager exManager = factory.CreateManager();
ExceptionPolicy.SetExceptionManager(exManager);
// This will log to the file trace_1.txt
ExceptionPolicy.HandleException(new Exception(), "Policy");
As you have mentioned in the post, Setup the configuration in an external file. External file means, can you confirm in which path we have to place the Entlib.config file.
I've created a very basic Logging block and Exception Handling block. In my code, I went to go test the Exception Handling (I know the Logging block works) with the following:
public void RunScriptClean()
{
try
{
throw new FileNotFoundException();
}
catch (FileNotFoundException ex)
{
var b = ExceptionPolicy.HandleException(ex, "Logging Policy");
if (b)
throw;
}
}
However, on the very first line of the catch block, I get this long winded exception and my application crashes:
Exception occured: The current build operating (build key Build Key [Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyImpl, Logging Policy]) failed: The type 'Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' cannot be resolved. Please verify the spelling is correct or that the full type name is provided. (Strategy type ConfiguredObjectStrategy, index 2).
I have absolutely no idea what it's referring to when it says the type cannot be resolved. I've added references to Microsoft.Practices.EnterpriseLibrary.Common/ExceptionHandling/Logging and Ms.Practices.ObjectBuilder2. This one class has using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling included at the top.
Added a screenshot of the configuration tool looking at my AppConfig file:
I'm sure I'm missing something basic, but it's tough to find a tutorial for EAB 4.1-- CodeProject has a lot for the original versions but I couldn't make much of them...
Edit I tried creating a new Formatter and naming it TextExceptionFormatter but that didn't change anything. Wasn't sure if maybe some how the FormatterType property on my Logging Handler was tied to that node.
And the actual block of XML from App.config:
<exceptionHandling>
<exceptionPolicies>
<add name="Logging Policy">
<exceptionTypes>
<add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="NotifyRethrow" name="Exception">
<exceptionHandlers>
<add logCategory="General" eventId="100" severity="Error" title="Enterprise Library Exception Handling"
formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
priority="0" useDefaultLogger="false" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="Logging Handler" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
I found this SO question: Cannot resolve type runtime error after registering the Enterprise Library into the GAC but even after changing the Version segment of the fullName attribute my app still behaves the same.
Alright, I was able to find a sample application that used the Logging handlers. Turns out I needed a reference to ExceptionHandling.Logging:
Microsoft.Practices.EnterpriseLibrary.Common
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging ****
Microsoft.Practices.EnterpriseLibrary.Logging
Microsoft.Practices.ObjectBuilder2
Where as I only had a references to:
Microsoft.Practices.EnterpriseLibrary.Common
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling
Microsoft.Practices.EnterpriseLibrary.Logging
Microsoft.Practices.ObjectBuilder2
For the following "project" I am getting a very annoying and inexplicable error when resolving Unity for DI.
InvalidOperationException - The type LogWriter cannot be constructed.
You must configure the container to supply this value.
?ex.Message; "Resolution of the dependency failed, type =
\"WindowsFormsApplication1.Performance\", name =
\"(none)\".\r\nException occurred while: while resolving.\r\nException
is: InvalidOperationException - The type LogWriter cannot be
constructed. You must configure the container to supply this
value.\r\n-----------------------------------------------\r\nAt the
time of the exception, the container was:\r\n\r\n Resolving
WindowsFormsApplication1.Performance,(none)\r\n Resolving parameter
\"lw\" of constructor
WindowsFormsApplication1.Performance(Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter
lw,
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionManager
em)\r\n Resolving
Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter,(none)\r\n"
?ex.StackTrace; " at
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object
existing, String name, IEnumerable1 resolverOverrides) in
e:\\Builds\\Unity\\UnityTemp\\Compile\\Unity\\Unity\\Src\\UnityContainer.cs:line
515\r\n at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type
t, String name, IEnumerable1 resolverOverrides) in
e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\UnityContainer.cs:line
485\r\n at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t,
String name, ResolverOverride[] resolverOverrides) in
e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\UnityContainer.cs:line
173\r\n at
Microsoft.Practices.Unity.UnityContainerExtensions.Resolve[T](IUnityContainer
container, ResolverOverride[] overrides) in
e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\UnityContainerExtensions.cs:line
504\r\n at WindowsFormsApplication1.Form1.OnLoad(EventArgs e) in
D:\Devzone\Tasking\WindowsFormsApplication1\Form1.cs:line 33"
In a form:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
try
{
IUnityContainer container = new UnityContainer();
Performance p = container.Resolve<Performance>();
}
catch (Exception ex)
{
}
}
Dependency class:
public class Performance
{
public Performance(LogWriter lw, ExceptionManager em)
{
}
}
Configuration File:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
<section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
<listeners>
<add name="Event Log Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
source="Enterprise Library Logging" formatter="Text Formatter"
log="" machineName="." traceOutputOptions="None" />
</listeners>
<formatters>
<add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
template="Timestamp: {timestamp}{newline}
Message: {message}{newline}
Category: {category}{newline}
Priority: {priority}{newline}
EventId: {eventid}{newline}
Severity: {severity}{newline}
Title:{title}{newline}
Machine: {localMachine}{newline}
App Domain: {localAppDomain}{newline}
ProcessId: {localProcessId}{newline}
Process Name: {localProcessName}{newline}
Thread Name: {threadName}{newline}
Win32 ThreadId:{win32ThreadId}{newline}
Extended Properties: {dictionary({key} - {value}{newline})}"
name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Event Log Listener" />
</listeners>
</add>
<add switchValue="All" name="Category2" />
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Event Log Listener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
<exceptionHandling>
<exceptionPolicies>
<add name="Policy">
<exceptionTypes>
<add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="NotifyRethrow" />
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
</configuration>
You need to add the Enterprise Library extension to your container. Without it, the container doesn't read the config file and therefore doesn't know how to create Entlib objects, like the LogWriter.
Activation error occured while trying to get instance of type LogWriter, key ""
check your config file it must have correct default 'loggingConfiguration' section
In order for Unity to construct your Performance class, it needs to know how to construct the implementation of ILogWriter.
I cannot see anywhere in your code where you tell Unity what class to create for the ILogWriter interface, so I suspect you may need to add this.
Try this:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
try
{
IUnityContainer container = new UnityContainer();
container.RegisterType<ILogWriter, LogWriter>();
container.RegisterType<ExceptionManager>();
container.RegisterType<Performance>(new InjectionConstructor(typeof(ILogWriter), typeof(ExceptionManager));
Performance p = container.Resolve<Performance>();
}
catch (Exception ex)
{
}
}
LogWriter does not have an empty constructor or a constructor with all concrete types parameters: LogWriter Constructor.
So Unity fails in building it and as it says, it will need your help by configuring the container to provide an implementation.
As a confirmation, ExceptionManager will probably be resolved ok, since it has only one constructor, parameterless as well :)
I am using Logging Application block with C#.Net 2.0. My code is logging the error information to a flat file. I have set all required configuration in web.config like listeners, formatters and categories, etc as described in msdn and it is working fine.
But the problem is, I cannot put more than 50 characters in le.Message property. In my case, the stack trace is more than 500 charactors long which I want to log into the flat file when error occurs.
Is there any limit on number of charactors we can put inside Message Property of LogEntry object? or is there any other way to log the stack trace into logger flat file?
Here is the simple code.
LogEntry le = new LogEntry();
le.Categories.Add("ErrorsToEventLog");
le.Categories.Add("ErrorsToLogFile");
le.Title = "Error message";
le.TimeStamp = System.DateTime.Now;
le.Severity = System.Diagnostics.TraceEventType.Error;
le.Message = "<text of error's stack trace>";
Logger.write(le);
configuration settings
<configSections>
<section name="loggingConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings,
Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral,
PublicKeyToken=null" />
<section name="dataConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,
Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral,
PublicKeyToken=null" />
</configSections>
Here is the formatter I used,
<formatters>
<add template="Timestamp: {timestamp} Message: {message}"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter,
Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0,
Culture=neutral, PublicKeyToken=null" name="Text Formatter" />
</formatters>
And here is the listener,
<add fileName="Logs/ErrorLog_{Date}.log"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.
CustomTraceListenerData,
Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral,
PublicKeyToken=null" traceOutputOptions="None"
type="EnterpriseLibrary.Logging.Extensions.RollingFlatFileTraceListener,
EnterpriseLibrary.Logging.Extensions, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null" name="Custom TraceListener" initializeData="" />
Categories
<categorySources>
<add switchValue="All" name="ErrorsToEventLog">
<listeners>
<add name="Formatted EventLog TraceListener" />
</listeners>
</add>
<add switchValue="All" name="ErrorsToLogFile">
<listeners>
<add name="Custom TraceListener" />
</listeners>
</add>
</categorySources>
To my knowledge, there is no such limit for log message. How do you set the stack trace to the message?
Assuming your analysis is correct (it isn't convenient for me to double-check right now), have you considered creating a subclass for LogEntry that doesn't have the limits that you're running up against?