Format of Tracing output in System.Diagnostics.TraceSource - c#

The following code:
static void Main(string[] args)
{
TraceSource ts = new TraceSource("MyApplication");
ts.Switch = new SourceSwitch("MySwitch");
ts.Switch.Level = SourceLevels.All;
ts.Listeners.Add(new TextWriterTraceListener(Console.Out));
ts.TraceInformation("Hello World");
Console.ReadKey();
}
generates the following output:
MyApplication Information: 0 : Hello World
The part "MyApplication Information: 0 :" at the beginning of the trace output is coming from the TraceSource class itself.
However, I need to have a timestamp at the beginning of the line and I would like to change "Information" to "Info" also.
Is there any way to get more freedom in trace output such that I can configure it to be like:
13:03:00 - MyApplication Info: Hello World
I tried for a couple of hours, but with no success. Whatever I do, at the beginning of the output line, there is always this constant predefined "MyApplication Information: 0 : Hello World" output.
MSDN documentation did also not reveal any helpful information.

Coming in late also but in case someone else lands here...
I like keeping it simple. I use one static Trace method within my App.cs which ties to a single TraceSource that I create at start up. This allows me access it throughout my app and keep the app.config simple:
public static void Trace(TraceEventType eventType, string message)
{
if (_TraceSource.Switch.ShouldTrace(eventType))
{
string tracemessage = string.Format("{0}\t[{1}]\t{2}", DateTime.Now.ToString("MM/dd/yy HH:mm:ss"), eventType, message);
foreach (TraceListener listener in _TraceSource.Listeners)
{
listener.WriteLine(tracemessage);
listener.Flush();
}
}
}
My app.config entries:
<system.diagnostics>
<sources>
<source name="mytracesource" switchValue="All">
<listeners>
<add name="mytracelistener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="trace.log">
</add>
</listeners>
</source>
</sources>
</system.diagnostics>

Set the TraceOutputOptions property on the trace listener. The format is predefined, but you can opt-in for the additional pieces of data defined by the TraceOptions enum.

TraceSource.TraceInformation ends up calling TraceListener.TraceEvent on each listener which adds in the header. Fortunately, TraceListener has a WriteLine method which you can use to produce custom output.
static void Main(string[] args)
{
TraceSource ts = new TraceSource("MyApplication");
ts.Switch = new SourceSwitch("MySwitch");
ts.Switch.Level = SourceLevels.All;
ts.Listeners.Add(new TextWriterTraceListener(Console.Out));
for (int i = 0; i < ts.Listeners.Count; i++)
{
var listener = ts.Listeners[i];
listener.WriteLine(
string.Format("{0} - {1} Info: {2}",
DateTime.Now.ToString("HH:mm:ss"), ts.Name, "Hello World"));
listener.Flush();
}
Console.ReadKey();
}
Output:
13:52:05 - MyApplication Info: Hello World

Maybe a bit late but if you want an easy and versatile solution you should have a look at the Essentials Diagnostics project on CodePlex (also available through NuGet).
It defines a wide range of listeners (with custom formatting allowed) that output to the console, rolling text and XML files, event logs, email, etc. and comes with configuration samples also.

Related

Simple way to perform error logging?

I've created a small C# winforms application, as an added feature I was considering adding some form of error logging into it. Anyone have any suggestions for good ways to go about this? This is a feature I've never looked into adding to previous projects, so I'm open to suggestions from Developers who have more experience.
I was considering something along the lines of writing exceptions to a specified text file, or possibly a database table. This is an application that will be in use for a few months and then discarded when a larger product is finished.
I wouldn't dig too much on external libraries since your logging needs are simple.
.NET Framework already ships with this feature in the namespace System.Diagnostics, you could write all the logging you need there by simply calling methods under the Trace class:
Trace.TraceInformation("Your Information");
Trace.TraceError("Your Error");
Trace.TraceWarning("Your Warning");
And then configure all the trace listeners that fit your needs on your app.config file:
<configuration>
// other config
<system.diagnostics>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="consoleListener" type="System.Diagnostics.ConsoleTraceListener"/>
<add name="textWriterListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="YourLogFile.txt"/>
<add name="eventLogListener" type="System.Diagnostics.EventLogTraceListener" initializeData="YourEventLogSource" />
<remove name="Default"/>
</listeners>
</trace>
</system.diagnostics>
// other config
</configuration>
or if you prefer, you can also configure your listeners in your application, without depending on a config file:
Trace.Listeners.Add(new TextWriterTraceListener("MyTextFile.log"));
Remember to set the Trace.AutoFlush property to true, for the Text log to work properly.
You could use SimpleLog.
It's a simple, but robust and powerful one-class logging solution, easy to understand, easy to integrate and easy to use. No need to spend days for setting up and customize log4Net, with that class, you're done in minutes.
Though it currently logs to a file, it should be easily customizable to log to a database.
http://www.codeproject.com/Tips/585796/Simple-Log
An optimal solution, in my opinion, would be to use NLog: http://nlog-project.org/
Just install the config package from NuGet: http://www.nuget.org/packages/NLog.Config/ and you will end up with the library and a pre-configured file logger...
Then in your code you just need:
// A logger member field:
private readonly Logger logger = LogManager.GetCurrentClassLogger(); // creates a logger using the class name
// use it:
logger.Info(...);
logger.Error(...);
// and also:
logger.ErrorException("text", ex); // which will log the stack trace.
In the config file you get, you need to uncomment the sections that you need:
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!--
See http://nlog-project.org/wiki/Configuration_file
for information on customizing logging rules and outputs.
-->
<targets>
<!-- add your targets here -->
<!-- UNCOMMENT THIS!
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
-->
</targets>
<rules>
<!-- add your logging rules here -->
<!-- UNCOMMENT THIS!
<logger name="*" minlevel="Trace" writeTo="f" />
-->
</rules>
</nlog>
Edit the properties of the nlog.config file to
Copy to Output Directory: Copy always
Create a class called Log.cs
I am using Linq To SQl to save to the database
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
public static partial class Log
{
/// <summary>
/// Saves the exception details to ErrorLogging db with Low Priority
/// </summary>
/// <param name="ex">The exception.</param>
public static void Save(this Exception ex)
{
Save(ex, ImpactLevel.Low, "");
}
/// <summary>
/// Saves the exception details to ErrorLogging db with specified ImpactLevel
/// </summary>
/// <param name="ex">The exception.</param>
/// <param name="impactLevel">The Impact level.</param>
public static void Save(this Exception ex, ImpactLevel impactLevel)
{
Save(ex, impactLevel,"");
}
/// <summary>
/// Saves the exception details to ErrorLogging db with specified ImpactLevel and user message
/// </summary>
/// <param name="ex">The exception</param>
/// <param name="impactLevel">The impact level.</param>
/// <param name="errorDescription">The error Description.</param>
public static void Save(this Exception ex, ImpactLevel impactLevel, string errorDescription)
{
using (var db = new ErrorLoggingDataContext())
{
Log log = new Log();
if (errorDescription != null && errorDescription != "")
{
log.ErrorShortDescription = errorDescription;
}
log.ExceptionType = ex.GetType().FullName;
var stackTrace = new StackTrace(ex, true);
var allFrames = stackTrace.GetFrames().ToList();
foreach (var frame in allFrames)
{
log.FileName = frame.GetFileName();
log.LineNumber = frame.GetFileLineNumber();
var method = frame.GetMethod();
log.MethodName = method.Name;
log.ClassName = frame.GetMethod().DeclaringType.ToString();
}
log.ImpactLevel = impactLevel.ToString();
try
{
log.ApplicationName = Assembly.GetCallingAssembly().GetName().Name;
}
catch
{
log.ApplicationName = "";
}
log.ErrorMessage = ex.Message;
log.StackTrace = ex.StackTrace;
if (ex.InnerException != null)
{
log.InnerException = ex.InnerException.ToString();
log.InnerExceptionMessage = ex.InnerException.Message;
}
log.IpAddress = ""; //get the ip address
if (System.Diagnostics.Debugger.IsAttached)
{
log.IsProduction = false;
}
try
{
db.Logs.InsertOnSubmit(log);
db.SubmitChanges();
}
catch (Exception eex)
{
}
}
}
}
Create the following table
USE [database Name]
GO
/****** Object: Table [dbo].[Log] Script Date: 9/27/2016 11:52:32 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Log](
[LogId] [INT] IDENTITY(1,1) NOT NULL,
[ErrorDate] [DATETIME] NOT NULL CONSTRAINT [DF_Log_Date] DEFAULT (GETDATE()),
[ErrorShortDescription] [VARCHAR](1000) NULL,
[ExceptionType] [VARCHAR](255) NULL,
[FileName] [VARCHAR](1000) NULL,
[LineNumber] [INT] NULL,
[MethodName] [VARCHAR](255) NULL,
[ClassName] [VARCHAR](150) NULL,
[ImpactLevel] [VARCHAR](50) NOT NULL,
[ApplicationName] [VARCHAR](255) NULL,
[ErrorMessage] [VARCHAR](4000) NULL,
[StackTrace] [VARCHAR](MAX) NULL,
[InnerException] [VARCHAR](2000) NULL,
[InnerExceptionMessage] [VARCHAR](2000) NULL,
[IpAddress] [VARCHAR](150) NULL,
[IsProduction] [BIT] NOT NULL CONSTRAINT [DF_Log_IsProduction] DEFAULT ((1)),
[LastModified] [DATETIME] NOT NULL CONSTRAINT [DF_Log_LastModified] DEFAULT (GETDATE()),
CONSTRAINT [PK_Log] PRIMARY KEY CLUSTERED
(
[LogId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
EXEC sys.sp_addextendedproperty #name=N'MS_Description', #value=N'This table holds all the exceptions.
ErrorData = when error happened
,[ErrorShortDescription] == short desc about the error entered by the developers
,[FileName] = file where error happened full path
,[LineNumber] = line number where code failed
,[MethodName] = method name where exception happened
,[ClassName] = class where exception happened
,[ImpactLevel] = high, medium, low
,[ApplicationName] = name of the application where error came from
,[ErrorMessage] = exception error messge
,[StackTrace] = C# stack trace
,[InnerException] = inner exception of strack trace
,[InnerExceptionMessage] = inner message
,[IpAddress]
,[IsProduction]' , #level0type=N'SCHEMA',#level0name=N'dbo', #level1type=N'TABLE',#level1name=N'Log'
GO
Impact Level is basically Enum
public enum ImpactLevel
{
High = 0,
Medium = 1,
Low = 2,
}
You can use it as following
try
{
}
catch(Exception ex)
{
//this will save the exception details and mark exception as low priority
ex.Save();
}
try
{
}
catch(Exception ex)
{
//this will save the exception details with priority you define: High, Medium,Low
ex.Save(ImpactLevel.Medium);
}
try
{
}
catch(Exception ex)
{
//this will save the exception details with priority you define: High, Medium,Low
ex.Save(ImpactLevel.Medium, "You can enter an details you want here ");
}
Well log4net works like a brick. It may be a bit hard to configure, but its worth it. It also allows you to configure file locking of those log files etc.
http://www.codeproject.com/Articles/140911/log4net-Tutorial
After reading the suggestions here, I ended up using the following:
private void LogSystemError(string message)
{
EventLog.WriteEntry("YourAppName", message, EventLogEntryType.Error);
}
The EventLog class is available using System.Diagnostics.
I avoided the options of logging into files (e.g. "yourLogFile.txt") to avoid issues of concurrency of multiple threads logging errors, location of the file and access security, and the possible issues of having a file that grows too large.
Heres example for log4net:
Create a new console project called Log4NetTest
Add log4net [1.2.13] nuget package into project
Write following program:
using System.Threading.Tasks;
using log4net;
using System.Text;
using System.CollectionsGeneric;
using System;
namespace Log4NetTest
{
class Program
{
private static readonly ILog _logger = LogManager.GetLogger("testApp.LoggingExample");
static void Main(string[] args)
{
// Configure from App.config. This is marked as obsolete so you can also add config into separate config file
// and use log4net.Config.XmlConfigurator method to configure from xml file.
log4net.Config.DOMConfigurator.Configure();
_logger.Debug("Shows only at debug");
_logger.Warn("Shows only at warn");
_logger.Error("Shows only at error");
Console.ReadKey();
}
}
}
Change your app.config to following:
<!-- language: xml -->
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<log4net debug="false">
<appender name="LogFileAppender" type="log4net.Appender.FileAppender,log4net" >
<param name="File" value="myLog.log" />
<param name="AppendToFile" value="true" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%date [%thread] %-5level %logger %ndc - %message%newline" />
</layout>
</appender>
<root>
<priority value="ALL" />
<appender-ref ref="LogFileAppender" />
</root>
<category name="testApp.LoggingExample">
<priority value="ALL" />
</category>
</log4net>
</configuration>
5.Run application and you should find following file from bin\Debug folder:
2013-12-13 13:27:27,252 [8] DEBUG testApp.LoggingExample (null) - Shows only at debug
2013-12-13 13:27:27,280 [8] WARN testApp.LoggingExample (null) - Shows only at warn
2013-12-13 13:27:27,282 [8] ERROR testApp.LoggingExample (null) - Shows only at error
You just write out your exception errors to a text file. Write to Text File. One suggestion is to put the file you create in a userdata or appdata directory though, so you do not have to struggle with permissions.
Since this is only needed for a few months and will be discarded there is no reason to go overboard with DB. A simple text file should suffice.
Instead of using log4net which is an external library I have created my own simple class, highly customizable and easy to use (edit YOURNAMESPACEHERE with the namespace that you need).
CONSOLE APP
using System;
using System.IO;
namespace YOURNAMESPACEHERE
{
enum LogEvent
{
Info = 0,
Success = 1,
Warning = 2,
Error = 3
}
internal static class Log
{
private static readonly string LogSession = DateTime.Now.ToLocalTime().ToString("ddMMyyyy_HHmmss");
private static readonly string LogPath = AppDomain.CurrentDomain.BaseDirectory + "logs";
internal static void Write(LogEvent Level, string Message, bool ShowConsole = true, bool WritelogFile = true)
{
string Event = string.Empty;
ConsoleColor ColorEvent = Console.ForegroundColor;
switch (Level)
{
case LogEvent.Info:
Event = "INFO";
ColorEvent = ConsoleColor.White;
break;
case LogEvent.Success:
Event = "SUCCESS";
ColorEvent = ConsoleColor.Green;
break;
case LogEvent.Warning:
Event = "WARNING";
ColorEvent = ConsoleColor.Yellow;
break;
case LogEvent.Error:
Event = "ERROR";
ColorEvent = ConsoleColor.Red;
break;
}
if (ShowConsole)
{
Console.ForegroundColor = ColorEvent;
Console.WriteLine(" [{0}] => {1}", DateTime.Now.ToString("HH:mm:ss"), Message);
Console.ResetColor();
}
if (WritelogFile)
{
if (!Directory.Exists(LogPath))
Directory.CreateDirectory(LogPath);
File.AppendAllText(LogPath + #"\" + LogSession + ".log", string.Format("[{0}] => {1}: {2}\n", DateTime.Now.ToString("HH:mm:ss"), Event, Message));
}
}
}
}
NO CONSOLE APP (ONLY LOG)
using System;
using System.IO;
namespace YOURNAMESPACEHERE
{
enum LogEvent
{
Info = 0,
Success = 1,
Warning = 2,
Error = 3
}
internal static class Log
{
private static readonly string LogSession = DateTime.Now.ToLocalTime().ToString("ddMMyyyy_HHmmss");
private static readonly string LogPath = AppDomain.CurrentDomain.BaseDirectory + "logs";
internal static void Write(LogEvent Level, string Message)
{
string Event = string.Empty;
switch (Level)
{
case LogEvent.Info:
Event = "INFO";
break;
case LogEvent.Success:
Event = "SUCCESS";
break;
case LogEvent.Warning:
Event = "WARNING";
break;
case LogEvent.Error:
Event = "ERROR";
break;
}
if (!Directory.Exists(LogPath))
Directory.CreateDirectory(LogPath);
File.AppendAllText(LogPath + #"\" + LogSession + ".log", string.Format("[{0}] => {1}: {2}\n", DateTime.Now.ToString("HH:mm:ss"), Event, Message));
}
}
Usage:
CONSOLE APP
Log.Write(LogEvent.Info, "Test message"); // It will print an info in your console, also will save a copy of this print in a .log file.
Log.Write(LogEvent.Warning, "Test message", false); // It will save the print as warning only in your .log file.
Log.Write(LogEvent.Error, "Test message", true, false); // It will print an error only in your console.
NO CONSOLE APP (ONLY LOG)
Log.Write(LogEvent.Info, "Test message"); // It will print an info in your .log file.

How to read AppSettings from app.config in WinForms

I usually use a text file as a config. But this time I would like to utilize app.config to associate a file name (key) with a name (value) and make the names available in combo box
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Scenario1.doc" value="Hybrid1"/>
<add key="Scenario2.doc" value="Hybrid2"/>
<add key="Scenario3.doc" value="Hybrid3"/>
</appSettings>
</configuration>
will this work? how to retrieve the data ?
Straight from the docs:
using System.Configuration;
// Get the AppSettings section.
// This function uses the AppSettings property
// to read the appSettings configuration
// section.
public static void ReadAppSettings()
{
try
{
// Get the AppSettings section.
NameValueCollection appSettings = ConfigurationManager.AppSettings;
// Get the AppSettings section elements.
Console.WriteLine();
Console.WriteLine("Using AppSettings property.");
Console.WriteLine("Application settings:");
if (appSettings.Count == 0)
{
Console.WriteLine("[ReadAppSettings: {0}]",
"AppSettings is empty Use GetSection command first.");
}
for (int i = 0; i < appSettings.Count; i++)
{
Console.WriteLine("#{0} Key: {1} Value: {2}",i, appSettings.GetKey(i), appSettings[i]);
}
}
catch (ConfigurationErrorsException e)
{
Console.WriteLine("[ReadAppSettings: {0}]", e.ToString());
}
}
So, if you want to access the setting Scenario1.doc, you would do this:
var value = ConfigurationManager.AppSettings["Scenario1.doc"];
Edit:
As Gabriel GM said in the comments, you will have to add a reference to System.Configuration.
app settings in app.config are to store application/environment specific settings not to store data which binds to UI.
If you cant avoid storing in config because of weird business requests I would rather stick to one single setting
<add key="FileDropDown" value="File1-Value|File2-Value" />
and write C# code to get this setting ConfigurationManager.AppSettings["FileDropDown"] and do some string Splits ('|') and ('-') to create kvp collection and bind it to UI.

C#: What is System.Configuration.Configuration looking for?

I have the following test method:
[TestMethod]
public void TestHarvestMethod()
{
HarvestTargetTimeRangeUTC time = new HarvestTargetTimeRangeUTC();
time.StartTimeUTC = new DateTime(2008, 01, 01, 00, 00, 00, DateTimeKind.Utc);
time.EndTimeUTC = DateTime.UtcNow;
XElement lIntelexReport = XElement.Parse(rawXml);
Harvester target = new Harvester();
target.ConfigureHarvester((System.Configuration.Configuration)null);
var res = target.Harvest(time);
Console.WriteLine(res);
}
That works in conjunction with this method:
public void ConfigureHarvester(System.Configuration.Configuration configuration)
{
reportId = Int32.Parse(configuration.AppSettings.Settings["IncidentReport"].Value);
}
to test this method:
public XElement Harvest(HarvestTargetTimeRangeUTC ranges)
{
XElement lIntelexReport = IntelexServiceCall();
return XMLConversion(QueryData(ranges, lIntelexReport));
}
The problem is that I receive Null Exception error stating that "Object reference not set to an instance of an object." on this line:
reportId = Int32.Parse(configuration.AppSettings.Settings["IncidentReport"].Value);
which I am almost positive is caused by the null value here:
target.ConfigureHarvester((System.Configuration.Configuration)null);
The System.Configuration in the above line is one used commonly in this shop, but normally for a method such as this:
public void ConfigureHarvester(System.Configuration.Configuration configuration)
{
context = new PlannedOutageFactorDataContext();
}
So my reportid field is obviously looking for something other than a null value, the problem is I don't know exactly WHAT it's looking for. Ive read the MSDN for System.Configuration but it was really no help. I would appreciate it if some one could point me in the right direction.
Its looking for you to pass it a copy of your web.config or app.config value so it can extract the information it requires from this (held in the AppSettings section)
For example
<configuration>
<appSettings>
<add key="IncidentReport" value="1" />
</appSettings>
</configuration>
If your testing a webpage, a lot of the time you need to set the location of the webservice so that it can grab a copy of the web.config from your website.
If your developing a console/desktop app then make sure you have an app.config file
Alternativly you can manually pass it in using
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(exePath);
In your test assembly you'll need to have a app.config file. Within this file you'll need a key named 'IncidentReport" with an integer value.

Custom Trace Listener with the Enterprise Application Blocks

The project I'm currently working on uses Enterprise Libraries V3.1 framework for logging.
I need to take the log file that's generated and archive it off at specific points. The built in Trace Listeners seem to keep the file open in-between logging events. I've set up a custom Trace Listener which will append to a file and close it, so that the file is always shiftable.
It looks like this (minus error handling for clarity):
[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class AlwaysClosedTextFileTraceListener : CustomTraceListener
{
private string logFilePath;
public AlwaysClosedTextFileTraceListener ()
{
logFilePath = #"hardcodedpath\log.txt";
}
public override void Write(string message)
{
using (StreamWriter logFile = File.AppendText(logFilePath))
{
logFile.Write(message);
logFile.Flush();
logFile.Close();
}
}
public override void WriteLine(string message)
{
using (StreamWriter logFile = File.AppendText(logFilePath))
{
logFile.WriteLine(message);
logFile.Flush();
}
}
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
{
if (data is LogEntry && this.Formatter != null)
{
WriteLine(this.Formatter.Format(data as LogEntry));
}
else
{
WriteLine(data.ToString());
}
}
}
This works fine, but I'd much rather be passing in the path as a parameter somehow, rather than hardcoding it.
For fun, I tried adding it to the constructor, to see what happens:
public LogFolderTraceListener(string logFilePath)
{
this.logFilePath = logFilePath;
}
When I do this, I get returned an error message hinting towards what I'm doing wrong:
System.InvalidOperationException : The type 'AlwaysClosedTextFileTraceListener' specified for custom trace listener named 'MyLogFile' does not a default constructor, which is required when no InitData is specified in the configuration.
From here on in, my investigations have very much come to, the opposite of dead ends, infinite probability problems.
I have found this thumbing through the source code for the inbuilt RollingTraceListener
There is a class RollingFlatFileTraceListenerData : TraceListenerData which seems to contain all the settings passed into the constructor
Camped out at the bottom of the file for RollingFlatFileTraceListenerData is the class RollingTraceListenerAssembler : TraceListenerAsssembler which seems to be a factory
There is another class SystemDiagnosticsTraceListenerNode : TraceListenerNode which seems to make the Data class presentable to the configuration application
My question is this: how do I create a CustomTraceListener with a configurable parameter of path?
The CustomTraceListener derives from TraceListener, this has a StringDictionary called Attributes.
This will contain all the attributes in the configuration line for your TraceListener and can be gotten out by name, eg.
string logFileName= Attributes["fileName"]
I suspect that perhaps the Enterprise Application Blocks although (probably) wonderful, seem unnecessarily complicated and ultimately more trouble than their worth for this kind of customisation.
the problem is typical microsoft .. (add your own adjectives here) ..
1) when you add a custom trace listener, the 'raw' app.config statement added is:
name="Custom Trace Listener" initializeData="" formatter="Text Formatter" />
2) notice the 'initializeData' - this is what the cryptic error message is calling'InitData'.
3) So what its all saying is that you need to have a constructor that accepts initialization data - in vb parlance:
sub new (byval initstuff as string)
4) OR remove the 'initializeData=""' and have a default constructor:
sub new()
I suspect the P&P folks live in a bubble.
riix.
For what it is worth this is how I implemented it. In my this.buildCurrPath() I can read from a config file or in this case I just get the "launch pad" for the web app. But it works fine for me. I have not put it into any production code yet, but it should go out soon.
[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class CustomListener: CustomTraceListener
{
#region Fields (3) 
private int logSize;
StreamWriter sw;
#endregion Fields 
#region Constructors (1) 
public CustomListener ():base()
{
string startPath = this.buildCurrPath();
sw = new StreamWriter(startPath + "\\Logs\\test.log");
sw.AutoFlush = true;
}
I have just had the same issue (except with Enterprise Library v4.1).
The solution I've found is to remove the default constructor and the only have a constructor with a string parameter for the filename i.e.
public AlwaysClosedTextFileTraceListener (string pathParameter)
{
logFilePath = pathParameter;
}
Then in the app.config put your path in the initializeData parameter
<add ... initializeData="C:\Logs\myLog.log" />
Whilst this isn't recognised by the Entriprise Library configuration editor and isn't as neat as it could be, it works as long as there is only one parameter.
If someone works out how to do it properly, please post and let us know - it's not supposed to be this difficult, surely.

Variables within app.config/web.config

Is it is possible to do something like the following in the app.config or web.config files?
<appSettings>
<add key="MyBaseDir" value="C:\MyBase" />
<add key="Dir1" value="[MyBaseDir]\Dir1"/>
<add key="Dir2" value="[MyBaseDir]\Dir2"/>
</appSettings>
I then want to access Dir2 in my code by simply saying:
ConfigurationManager.AppSettings["Dir2"]
This will help me when I install my application in different servers and locations wherein I will only have to change ONE entry in my entire app.config.
(I know I can manage all the concatenation in code, but I prefer it this way).
A slightly more complicated, but far more flexible, alternative is to create a class that represents a configuration section. In your app.config / web.config file, you can have this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- This section must be the first section within the <configuration> node -->
<configSections>
<section name="DirectoryInfo" type="MyProjectNamespace.DirectoryInfoConfigSection, MyProjectAssemblyName" />
</configSections>
<DirectoryInfo>
<Directory MyBaseDir="C:\MyBase" Dir1="Dir1" Dir2="Dir2" />
</DirectoryInfo>
</configuration>
Then, in your .NET code (I'll use C# in my example), you can create two classes like this:
using System;
using System.Configuration;
namespace MyProjectNamespace {
public class DirectoryInfoConfigSection : ConfigurationSection {
[ConfigurationProperty("Directory")]
public DirectoryConfigElement Directory {
get {
return (DirectoryConfigElement)base["Directory"];
}
}
public class DirectoryConfigElement : ConfigurationElement {
[ConfigurationProperty("MyBaseDir")]
public String BaseDirectory {
get {
return (String)base["MyBaseDir"];
}
}
[ConfigurationProperty("Dir1")]
public String Directory1 {
get {
return (String)base["Dir1"];
}
}
[ConfigurationProperty("Dir2")]
public String Directory2 {
get {
return (String)base["Dir2"];
}
}
// You can make custom properties to combine your directory names.
public String Directory1Resolved {
get {
return System.IO.Path.Combine(BaseDirectory, Directory1);
}
}
}
}
Finally, in your program code, you can access your app.config variables, using your new classes, in this manner:
DirectoryInfoConfigSection config =
(DirectoryInfoConfigSection)ConfigurationManager.GetSection("DirectoryInfo");
String dir1Path = config.Directory.Directory1Resolved; // This value will equal "C:\MyBase\Dir1"
You can accomplish using my library Expansive. Also available on nuget here.
It was designed with this as a primary use-case.
Moderate Example (using AppSettings as default source for token expansion)
In app.config:
<configuration>
<appSettings>
<add key="Domain" value="mycompany.com"/>
<add key="ServerName" value="db01.{Domain}"/>
</appSettings>
<connectionStrings>
<add name="Default" connectionString="server={ServerName};uid=uid;pwd=pwd;Initial Catalog=master;" provider="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Use the .Expand() extension method on the string to be expanded:
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
connectionString.Expand() // returns "server=db01.mycompany.com;uid=uid;pwd=pwd;Initial Catalog=master;"
or
Use the Dynamic ConfigurationManager wrapper "Config" as follows (Explicit call to Expand() not necessary):
var serverName = Config.AppSettings.ServerName;
// returns "db01.mycompany.com"
var connectionString = Config.ConnectionStrings.Default;
// returns "server=db01.mycompany.com;uid=uid;pwd=pwd;Initial Catalog=master;"
Advanced Example 1 (using AppSettings as default source for token expansion)
In app.config:
<configuration>
<appSettings>
<add key="Environment" value="dev"/>
<add key="Domain" value="mycompany.com"/>
<add key="UserId" value="uid"/>
<add key="Password" value="pwd"/>
<add key="ServerName" value="db01-{Environment}.{Domain}"/>
<add key="ReportPath" value="\\{ServerName}\SomeFileShare"/>
</appSettings>
<connectionStrings>
<add name="Default" connectionString="server={ServerName};uid={UserId};pwd={Password};Initial Catalog=master;" provider="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Use the .Expand() extension method on the string to be expanded:
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
connectionString.Expand() // returns "server=db01-dev.mycompany.com;uid=uid;pwd=pwd;Initial Catalog=master;"
Good question.
I don't think there is. I believe it would have been quite well known if there was an easy way, and I see that Microsoft is creating a mechanism in Visual Studio 2010 for deploying different configuration files for deployment and test.
With that said, however; I have found that you in the ConnectionStrings section have a kind of placeholder called "|DataDirectory|". Maybe you could have a look at what's at work there...
Here's a piece from machine.config showing it:
<connectionStrings>
<add
name="LocalSqlServer"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
Usally, I end up writing a static class with properties to access each of the settings of my web.config.
public static class ConfigManager
{
public static string MyBaseDir
{
return ConfigurationManager.AppSettings["MyBaseDir"].toString();
}
public static string Dir1
{
return MyBaseDir + ConfigurationManager.AppSettings["Dir1"].toString();
}
}
Usually, I also do type conversions when required in this class. It allows to have a typed access to your config, and if settings change, you can edit them in only one place.
Usually, replacing settings with this class is relatively easy and provides a much greater maintainability.
I thought I just saw this question.
In short, no, there's no variable interpolation within an application configuration.
You have two options
You could roll your own to substitute variables at runtime
At build time, massage the application configuration to the particular specifics of the target deployment environment. Some details on this at dealing with the configuration-nightmare
You have a couple of options. You could do this with a build / deploy step which would process your configuration file replacing your variables with the correct value.
Another option would be to define your own Configuration section which supported this. For example imagine this xml:
<variableAppSettings>
<variables>
<add key="#BaseDir" value="c:\Programs\Widget"/>
</variables>
<appSettings>
<add key="PathToDir" value="#BaseDir\Dir1"/>
</appSettings>
</variableAppSettings>
Now you would implement this using custom configuration objects which would handle replacing the variables for you at runtime.
You can use environment variables in your app.config for that scenario you describe
<configuration>
<appSettings>
<add key="Dir1" value="%MyBaseDir%\Dir1"/>
</appSettings>
</configuration>
Then you can easily get the path with:
var pathFromConfig = ConfigurationManager.AppSettings["Dir1"];
var expandedPath = Environment.ExpandEnvironmentVariables(pathFromConfig);
Inside <appSettings> you can create application keys,
<add key="KeyName" value="Keyvalue"/>
Later on you can access these values using:
ConfigurationManager.AppSettings["Keyname"]
I would suggest you DslConfig. With DslConfig you can use hierarchical config files from Global Config, Config per server host to config per application on each server host (see the AppSpike).
If this is to complicated for you you can just use the global config Variables.var
Just configure in Varibales.var
baseDir = "C:\MyBase"
Var["MyBaseDir"] = baseDir
Var["Dir1"] = baseDir + "\Dir1"
Var["Dir2"] = baseDir + "\Dir2"
And get the config values with
Configuration config = new DslConfig.BooDslConfiguration()
config.GetVariable<string>("MyBaseDir")
config.GetVariable<string>("Dir1")
config.GetVariable<string>("Dir2")
I don't think you can declare and use variables to define appSettings keys within a configuration file. I've always managed concatenations in code like you.
I'm struggling a bit with what you want, but you can add an override file to the app settings then have that override file set on a per environment basis.
<appSettings file="..\OverrideSettings.config">
For rolling out products where we need to configure a lot of items with similar values, we use small console apps that read the XML and update based on the parameters passed in. These are then called by the installer after it has asked the user for the required information.
I would recommend following Matt Hamsmith's solution. If it's an issue to implement, then why not create an extension method that implements this in the background on the AppSettings class?
Something like:
public static string GetValue(this NameValueCollection settings, string key)
{
}
Inside the method you search through the DictionaryInfoConfigSection using Linq and return the value with the matching key. You'll need to update the config file though, to something along these lines:
<appSettings>
<DirectoryMappings>
<DirectoryMap key="MyBaseDir" value="C:\MyBase" />
<DirectoryMap key="Dir1" value="[MyBaseDir]\Dir1"/>
<DirectoryMap key="Dir2" value="[MyBaseDir]\Dir2"/>
</DirectoryMappings>
</appSettings>
I came up with this solution:
In the application Settings.settings I defined a variable ConfigurationBase (with type=string Scope=Application)
I introduced a variable in the target attributes in the Settings.settings, all those attributes had to be set to Scope=User
In the app.xaml.cs I read out the value if the ConfigurationBase
In the app.xaml.cs I replaced all variables with the ConfigurationBase value. In order to replace the values at run-time the attributes had to be set to Scopr=User
I'm not really happy with this solution because I have to change all attributes manually, if I add a new one I have to regard it in the app.xaml.cs.
Here a code snippet from the App.xaml.cs:
string configBase = Settings.Default.ConfigurationBase;
Settings.Default.CommonOutput_Directory = Settings.Default.CommonOutput_Directory.Replace("${ConfigurationBase}", configBase);
UPDATE
Just found an improvement (again a code snippet from the app.xaml.cs):
string configBase = Settings.Default.ConfigurationBase;
foreach (SettingsProperty settingsProperty in Settings.Default.Properties)
{
if (!settingsProperty.IsReadOnly && settings.Default[settingsProperty.Name] is string)
{
Settings.Default[settingsProperty.Name] = ((string)Settings.Default[settingsProperty.Name]).Replace("${ConfigurationBase}", configBase);
}
}
Now the replacements work for all attributes in my settings that have Type=string and Scope=User. I think I like it this way.
UPDATE2
Apparently setting Scope=Application is not required when running over the properties.
Three Possible Solutions
I know I'm coming late to the party, I've been looking if there were any new solutions to the variable configuration settings problem. There are a few answers that touch the solutions I have used in the past but most seem a bit convoluted. I thought I'd look at my old solutions and put the implementations together so that it might help people that are struggling with the same problem.
For this example I have used the following app setting in a console application:
<appSettings>
<add key="EnvironmentVariableExample" value="%BaseDir%\bin"/>
<add key="StaticClassExample" value="bin"/>
<add key="InterpollationExample" value="{0}bin"/>
</appSettings>
1. Use environment variables
I believe autocro autocro's answer touched on it. I'm just doing an implementation that should suffice when building or debugging without having to close visual studio. I have used this solution back in the day...
Create a pre-build event that will use the MSBuild variables
Warning: Use a variable that will not be replaced easily so use your project name or something similar as a variable name.
SETX BaseDir "$(ProjectDir)"
Reset variables; using something like the following:
Refresh Environment Variables on Stack Overflow
Use the setting in your code:
'
private void Test_Environment_Variables()
{
string BaseDir = ConfigurationManager.AppSettings["EnvironmentVariableExample"];
string ExpandedPath = Environment.ExpandEnvironmentVariables(BaseDir).Replace("\"", ""); //The function addes a " at the end of the variable
Console.WriteLine($"From within the C# Console Application {ExpandedPath}");
}
'
2. Use string interpolation:
Use the string.Format() function
`
private void Test_Interpollation()
{
string ConfigPath = ConfigurationManager.AppSettings["InterpollationExample"];
string SolutionPath = Path.GetFullPath(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, #"..\..\"));
string ExpandedPath = string.Format(ConfigPath, SolutionPath.ToString());
Console.WriteLine($"Using old interpollation {ExpandedPath}");
}
`
3. Using a static class, This is the solution I mostly use.
The implementation
`
private void Test_Static_Class()
{
Console.WriteLine($"Using a static config class {Configuration.BinPath}");
}
`
The static class
`
static class Configuration
{
public static string BinPath
{
get
{
string ConfigPath = ConfigurationManager.AppSettings["StaticClassExample"];
string SolutionPath = Path.GetFullPath(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, #"..\..\"));
return SolutionPath + ConfigPath;
}
}
}
`
Project Code:
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="EnvironmentVariableExample" value="%BaseDir%\bin"/>
<add key="StaticClassExample" value="bin"/>
<add key="InterpollationExample" value="{0}bin"/>
</appSettings>
</configuration>
Program.cs
using System;
using System.Configuration;
using System.IO;
namespace ConfigInterpollation
{
class Program
{
static void Main(string[] args)
{
new Console_Tests().Run_Tests();
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
}
internal class Console_Tests
{
public void Run_Tests()
{
Test_Environment_Variables();
Test_Interpollation();
Test_Static_Class();
}
private void Test_Environment_Variables()
{
string ConfigPath = ConfigurationManager.AppSettings["EnvironmentVariableExample"];
string ExpandedPath = Environment.ExpandEnvironmentVariables(ConfigPath).Replace("\"", "");
Console.WriteLine($"Using environment variables {ExpandedPath}");
}
private void Test_Interpollation()
{
string ConfigPath = ConfigurationManager.AppSettings["InterpollationExample"];
string SolutionPath = Path.GetFullPath(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, #"..\..\"));
string ExpandedPath = string.Format(ConfigPath, SolutionPath.ToString());
Console.WriteLine($"Using interpollation {ExpandedPath}");
}
private void Test_Static_Class()
{
Console.WriteLine($"Using a static config class {Configuration.BinPath}");
}
}
static class Configuration
{
public static string BinPath
{
get
{
string ConfigPath = ConfigurationManager.AppSettings["StaticClassExample"];
string SolutionPath = Path.GetFullPath(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, #"..\..\"));
return SolutionPath + ConfigPath;
}
}
}
}
Pre-build event:
Project Settings -> Build Events

Categories

Resources