Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Exception occurred while reading xml configuration file from windows service

Posted on 2009-04-06
8
Medium Priority
?
1,136 Views
Last Modified: 2013-12-17
We have below xml  configuration file.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
      <SQLServers>
            <add name="PERTRACQADB"/>
            <add name="DBNYC1"/>
            <add name="IRDB"/>
            <add name="IRTRACKERDB"/>
            <add name="LPCAPDB"/>
      </SQLServers>
      <PerTracServices>
            <add name="CMS-Email-Auto-Log"/>
            <add name="CMSImporter3SVC"/>
            <add name="DESVCDIR 2x5"/>
            <add name="SSUPDATES 2.0"/>
      </PerTracServices>
</configuration>
We are using C# code to read the configuration file as in code snippet.

We can successfully run the code to load the configuration file as an individual application but we are getting the following exception while we are running it as windows service and the service has been stopped abnormally.

EventType clr20r3, P1 pertracmonitor.service.exe, P2 1.0.0.0, P3 49d9e873, P4 system.configuration, P5 2.0.0.0, P6 461ef187, P7 1a6, P8 136, P9 ioibmurhynrxkw0zxkyrvfn0boyyufow, P10 NIL.

Service cannot be started. System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized configuration section SQLServers. (C:\Program Files\PerTracMonitor\Setup\CustomActions\PerTracMonitor.Service.exe.config line 3)
   at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
   at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
   at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
   at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
   --- End of inner exception stack trace ---
   at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
   at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
   at System.Configuration.ConfigurationManager.GetSection(String sectionName)
   at System.Configuration....

Can anyone please help me to resolve this.


private static void ConfigReader()
{
          
   try
   {
      string[] splitedPath = System.Reflection.Assembly.GetEntryAssembly().Location.Split(new char[] { '\\' });
      string parentDir = string.Join("\\", splitedPath, 0, splitedPath.Length - 1);
      string configFile = parentDir + "\\PerTracMonitor.xml";
      if (!File.Exists(configFile))
      {
         msgBody = "Configuration file not found.";
         sendEmail();
         return;
      }
              XmlDocument xml_doc = new XmlDocument();
               XmlNodeList childNodes = xml_doc.GetElementsByTagName("SQLServers");                
                foreach (XmlNode cNode in childNodes)                
                     SQLServers.Add(cNode.Attributes["name"].Value);
 
                childNodes = xml_doc.GetElementsByTagName("PerTracServices");
                foreach (XmlNode cNode in childNodes)
                     PerTracServices.Add(cNode.Attributes["name"].Value);
           }
            catch (System.Exception ex)
            {
               msgBody += "Exception occured while reading config file.\n";
                msgBody += ex.Message;
                sendEmail();
            }
}

Open in new window

0
Comment
Question by:deshaw
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
8 Comments
 
LVL 15

Expert Comment

by:angus_young_acdc
ID: 24077994
Why don't you just use ConfigurationManager?  Then you can use the ConnectionString property, or even just appsettings.  EG add this to your XML:
<add key="ConnectionString" value="YourConnectionString"/>

Then just call it:
string connection = ConfigurationManager.AppSettings["ConnectionString"];

Then you have your string easy.
0
 
LVL 1

Author Comment

by:deshaw
ID: 24084156

Thanks for your suggestion.

But I want to have two sections namely "SQLServers" and "PerTracServices" and I did not find the way to have sections in <appSettings>.  Could you please tell me how I can define the sections using <appSettings>.

I would be great full if you can find the reason for the exceptions while I am running the given code as a windows service.
0
 
LVL 15

Accepted Solution

by:
angus_young_acdc earned 2000 total points
ID: 24084790
What is on line 3 of your config file?  It would make life a lot simpler for you to just use the ConfigurationManager from what I can see of your code.

Here would be an example of the App.Config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
  </configSections>
  <appSettings>
    <add key ="SQLServers" value="WhateverValue"/>
    <add key ="PerTracServices" value="WhateverValue"/>
  </appSettings>
</configuration>

You can then read any key you wish, and you can have as many as you want.  EG I changed your code to be like the following snippet, taking the value from the appSetting which you can use at anytime.

        private static void ConfigReader()
        {
 
            try
            {
                if (!File.Exists(configFile))
                {
                    msgBody = "Configuration file not found.";
                    sendEmail();
                    return;
                }
                else
                {
                    _sqlServers = ConfigurationManager.AppSettings["SQLServers"]; // declare _sqlServers as string
                    _perTracServices = ConfigurationManager.AppSettings["PerTracServices"]; // declare _perTracServices as string
                }
            }
            catch (System.Exception ex)
            {
                msgBody += "Exception occured while reading config file.\n";
                msgBody += ex.Message;
                sendEmail();
            }
        }

Open in new window

0
Quick Cloud Training

Looking for some quick training on the cloud in 2 hours or less? Check out these how-to guides in AWS, Linux, OpenStack, Azure, and more!

 
LVL 1

Author Comment

by:deshaw
ID: 24085327
Thank you.
I have tried the code. But it also gives the same problem. It works well if we are using it in an individual application but it is not getting values from the configuration file while running as windows service. It does not give any exceptions.
0
 
LVL 15

Expert Comment

by:angus_young_acdc
ID: 24086720
I have similar code and it works, very odd.   So for each service you have added the App.Config to the solution?  Services wouldn't really throw exceptions, they are more silent annoyances.  

Try declaring this at the top of your service:
private static readonly string _sqlServers =
                ConfigurationManager.AppSettings["SQLServers"]; etc.  
0
 
LVL 1

Author Comment

by:deshaw
ID: 24093501
Service is not throwing any exception but it is getting stopped immediately and I could see the reason for that in Application event log. It says the given exception in my main thread.
Thanks.
0
 
LVL 15

Expert Comment

by:angus_young_acdc
ID: 24146209
Yes, the exception causes your service to stop running.  Is your Config file formatted correctly?
0
 
LVL 1

Author Closing Comment

by:deshaw
ID: 31567009
thanks
0

Featured Post

 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The object model of .Net can be overwhelming at times – so overwhelming that quite trivial tasks often take hours of research. In this case, the task at hand was to populate the datagrid from SQL Server database in Visual Studio 2008 Windows applica…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question