Click here to Skip to main content
15,891,907 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I need to get the listeners information's section (name, toAddress,fromAddress, subjectLineStarter, subjectLineEnder, smtpServer,smtpPort, filter, rollSizeKB, fileName) from a third party app.config and save them into collection (example: array, List...), so I can modify the different attributes values by changing the corresponding textBox.text in my WinForm What's the best way to do that?


XML
<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=45fr1254ee458e89" requirePermission="true" />
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="Dds.BiBoard.Proxies.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <loggingConfiguration name="ITE Logging Application Block" tracingEnabled="true" defaultCategory="Info" logWarningsWhenNoCategoriesMatch="true">
    <listeners>
      <add name="IteProjectEmailAdministrator" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.EmailTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=45fr1254ee458e89" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.EmailTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=45fr1254ee458e89" toAddress="aa@zz.com" fromAddress="noreply-ddsproject@zz.com" subjectLineStarter="ITEProject Critical Logs" subjectLineEnder="Urgent" smtpServer="smtp.zz.net" smtpPort="25" formatter="Text Formatter" traceOutputOptions="None" filter="Off" />
      <add name="IteProjectErrorRollingFlatFile" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=45fr1254ee458e89" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=45fr1254ee458e89" fileName="C:\logs\LogIteProjectError.log" footer="" formatter="Text Formatter" header="" rollFileExistsBehavior="Increment" rollInterval="None" rollSizeKB="100" timeStampPattern="yyyy-MM-dd" traceOutputOptions="None" filter="Error" />
      <add name="IteProjectExceptionRollingFlatFile" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=45fr1254ee458e89" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=45fr1254ee458e89" fileName="C:\logs\LogIteProjectException.log" footer="" formatter="Text Formatter" header="" rollFileExistsBehavior="Increment" rollInterval="None" rollSizeKB="100" timeStampPattern="yyyy-MM-dd" traceOutputOptions="None" filter="All" />
      <add name="IteProjectInformationRollingFlatFile" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=45fr1254ee458e89" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=45fr1254ee458e89" fileName="C:\logs\LogIteProjectInfo.log" footer="" formatter="Text Formatter" header="" rollFileExistsBehavior="Increment" rollInterval="None" rollSizeKB="100" timeStampPattern="yyyy-MM-dd" traceOutputOptions="None" filter="Information" />
      <add name="IteProjectWarningRollingFlatFile" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=45fr1254ee458e89" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=45fr1254ee458e89" fileName="C:\logs\LogIteProjectWarning.log" footer="" formatter="Text Formatter" header="" rollFileExistsBehavior="Increment" rollInterval="None" rollSizeKB="100" timeStampPattern="yyyy-MM-dd" traceOutputOptions="None" filter="Warning" />
      <add name="IteProjectCriticalRollingFlatFile" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=45fr1254ee458e89" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=45fr1254ee458e89" fileName="C:\logs\LogIteProjectCritical.log" footer="" formatter="Text Formatter" header="" rollFileExistsBehavior="Increment" rollInterval="None" rollSizeKB="100" timeStampPattern="yyyy-MM-dd" traceOutputOptions="None" filter="Critical" />
      <add name="IteProjectDebugRollingFlatFile" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=45fr1254ee458e89" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=45fr1254ee458e89" fileName="C:\logs\LogIteProjectDebug.log" footer="" formatter="Text Formatter" header="" rollFileExistsBehavior="Increment" rollInterval="None" rollSizeKB="100" timeStampPattern="yyyy-MM-dd" traceOutputOptions="None" filter="Verbose" />
    </listeners>
    <formatters>
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=45fr1254ee458e89" template="{timestamp(local)} - {severity} -  {message}" name="Text Formatter" />
    </formatters>
    <logFilters>
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.LogEnabledFilter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=45fr1254ee458e89" enabled="true" name="LogEnabled Filter" />
    </logFilters>
    <categorySources>
      <add switchValue="All" name="Critical">
        <listeners>
          <add name="IteProjectEmailAdministrator" />
          <add name="IteProjectCriticalRollingFlatFile" />
        </listeners>
      </add>
      <add switchValue="All" name="Error">
        <listeners>
          <add name="IteProjectErrorRollingFlatFile" />
        </listeners>
      </add>
      <add switchValue="All" name="Exception">
        <listeners>
          <add name="IteProjectExceptionRollingFlatFile" />
        </listeners>
      </add>
      <add switchValue="All" name="Info">
        <listeners>
          <add name="IteProjectInformationRollingFlatFile" />
          <add name="IteProjectWarningRollingFlatFile" />
        </listeners>
      </add>
      <add switchValue="All" name="Warning">
        <listeners>
          <add name="IteProjectWarningRollingFlatFile" />
          <add name="IteProjectInformationRollingFlatFile" />
        </listeners>
      </add>
      <add switchValue="All" name="Verbose">
        <listeners>
          <add name="IteProjectDebugRollingFlatFile" />
        </listeners>
      </add>
    </categorySources>
    <specialSources>
      <allEvents switchValue="All" name="All Events" />
      <notProcessed switchValue="All" name="Unprocessed Category">
        <listeners>
          <add name="IteProjectWarningRollingFlatFile" />
        </listeners>
      </notProcessed>
      <errors switchValue="All" name="Logging Errors & Warnings">
        <listeners>
          <add name="IteProjectErrorRollingFlatFile" />
        </listeners>
      </errors>
    </specialSources>
  </loggingConfiguration>
  <connectionStrings>
    <add name="ITE_key" connectionString="Data Source=ITE;Persist Security Info=True;User ID=ITE_FIT;Password=*****;Unicode=True;" providerName="System.Data.OracleClient" />
  </connectionStrings>
  <appSettings>
    <add key="ServiceName" value="test_Board-Serv" />
    <add key="ProcessInterval" value="32" />
    <add key="InsertArg" value="/I" />
    <add key="UpdateArg" value="/U" />
    <add key="DeleteArg" value="/D" />
    <add key="ConsoleModeArg" value="/C" />
    <add key="StartCountBeforeKill" value="3" />
    <add key="ITE.Board.WcfService.BoardService.Url" value="http://localhost:83/BoardService.svc/" />
    <add key="Default" value=" *" />
    <add key="DIR_my_log" value="C:\Users\IT\Desktop\Log" />
    
    <add key="FILE_my_fileLog" value="C:\Users\IT\Desktop\TestConfig\ITE-SV_Config.log" />
  </appSettings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
  </startup>
  <system.serviceModel><big></big>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_BoardContract" />
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="Ite.Board.WcfService.BoardService.Url" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_BoardContract" contract="IteBoard.Bunisess.Proxy.ITeBoardContract" name="BasicHttpBinding_IteBoardContract" />
    </client>
  </system.serviceModel>
</configuration>



Berst regards,
IT
Posted
Updated 23-Apr-15 6:00am
v3

The easiest way is to simply parse the configuration file like a normal XML document.

If you are looking for a more elegant solution, then there is a class defined to use and access this information. In the configSections, there are a series of entries that define classes that represent data in the configuration file. In the case of your configuration file, the class Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings was build to directly pull settings out of the configuration file. I personally have never worked with that class, so you will need to research the MSDN documentation on it and figure out how to make use of it.
 
Share this answer
 
Comments
tek001 22-Apr-15 17:13pm    
Hi,

Thanks for this reply but how can I access to a third party configSections since the targeted app.config doesn't belong to my application?

I've tried this but there's no result: which is a regular behavior cause I'm looking in my own app.config!



class LoggingConfiguration : ConfigurationSection
{


private static readonly ConfigurationProperty Name;


private static readonly ConfigurationPropertyCollection ConfigurationProperties;

static LoggingConfiguration()
{
// configuration properties here
Name = new ConfigurationProperty("name", typeof(string), null, ConfigurationPropertyOptions.IsRequired);

ConfigurationProperties = new ConfigurationPropertyCollection { Name };
}

[ConfigurationProperty("name", IsRequired = true)]
public string name
{
get { return (string)base[Name]; }
}

protected override ConfigurationPropertyCollection Properties
{
get { return ConfigurationProperties; }
}
}



and then in my main program:



void showListenersName()
{
var loggingConfiguration = ConfigurationManager.GetSection("loggingConfiguration") as LoggingConfiguration;
if (loggingConfiguration != null)
{
MessageBox.Show(loggingConfiguration.name);
}

}

PS: I can read a third party app.config from my application by using this:

public static Configuration configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationManager.AppSettings["configFileExe"]);

with this in my application app.config:

<add key="configFileExe" value="C:\Users\Tek001\Desktop\TestConfig\Test.exe">

Best regards
tek001 22-Apr-15 17:45pm    
Now I've tried this:

void showListeners()
{

Configuration MyConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationManager.AppSettings["configFileExe"]);
var section = (AppSettingsSection)MyConfig.GetSection("loggingConfiguration");
string results = section.Settings["name"].Value;
MessageBox.Show(results);

}

but I get the ConfigurationErrorsException below at the second line - var section = (AppSettingsSection)MyConfig.GetSection("loggingConfiguration"); :

An error occurred creating the configuration section handler for loggingConfiguration: Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies.


I don't understand, I just want to read information...

Best regards,
Tek001
tek001 23-Apr-15 12:15pm    
I did this to get the chlidNode of the node <listeners>

<add name="... traceOutputOptions=" none"="" ...=""> :

public void getListeners(string appName)
{
try

{


string FILE_NAME = string.Concat(appName, ".config");

XmlTextReader reader = new XmlTextReader(FILE_NAME);

XmlDocument doc = new XmlDocument();

doc.Load(reader);

reader.Close();

string nodeRoute = string.Concat("loggingConfiguration");


XmlNodeList elemList = doc.GetElementsByTagName(nodeRoute);

{
foreach (XmlNode elem in elemList)
{

foreach (XmlNode elemChild in elem.ChildNodes)
{
if (elemChild.Name.ToString() == "listeners")
{
int cpt = 0;

foreach (XmlNode item in elemChild.ChildNodes)
{
MessageBox.Show(item.OuterXml.ToString());

cpt++;
}

}
}

}



}





}
catch (Exception ex)
{

errorHandler(ex);

}


}
Now how can I get the different attributes separately?
And since the OuterXml property is read only, how can I do to set values?


Thanks for your help.

Best regards,
Tek001
virusstorm 24-Apr-15 8:58am    
I think the better question to ask right now is why are you trying to read and write to a configuration file you don't own? I would not recommend doing this as it can quickly have undesired effects. You should always let the application handle it's configuration file unless your vendor tells you to make manual modifications.
tek001 24-Apr-15 9:34am    
Hello,

My company asked me to create a WinForm Enterprise Library like graphical interface so that the end users can easily configure their own application’s app.config without working directly with the xml files.
Opening my application and pointing and .exe file, will dynamically creates labels for keys and textboxes for values and so they can browse for logfiles paths, enter the required connection strings information and so on.

Best regards,
Tek001
I's solved by using Linq to xml
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900