Link to home
Start Free TrialLog in
Avatar of shieldguy
shieldguyFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Problem reading the values from <appSetting> from web.config file

I am trying to read some configuration details from my web.config file using the following code:


 private static string getAppSettingsValue(string sKey)
        {
           private static AppSettingsReader m_Reader = new AppSettingsReader();
            string sValue = null;

            try
            {
                sValue = m_Reader.GetValue(sKey, typeof(string)) as string;
               
            }
            catch (InvalidOperationException e)
            {
               
            }

            return sValue;
        }

When it reaches to m_Reader.GetValue, it raises the exception that "the key 'ConfigSiteUrl' (the key I am reading) does not exist in the appSettings configuration section". Although this is present in web.config file under appSettings. Please see the web.config file code below:


<appSettings >
    <add key="FeedCacheTime" value="300" />
    <add key="FeedPageUrl" value="/_layouts/feed.aspx?" />
    <add key="FeedXsl1" value="/Style Library/Xsl Style Sheets/Rss.xsl" />
    <add key="ReportViewerMessages" value="Microsoft.SharePoint.Portal.Analytics.UI.ReportViewerMessages, Microsoft.SharePoint.Portal, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
    <add key="ConfigListName" value="Configuration Store" />
    <add key="ConfigSiteUrl" value="http://MySitecollection" />
    <add key="ConfigWebName" value="" />
  </appSettings>


I have tried the same code through the console application where I added an app.config file in my project and add the same cofig file code there and it did work. With the sharepoint timer job code it doesn't. What web.config file is it looking for?

This is very urgent !!!!!!  
Avatar of Nirmalan Nagenthiran
Nirmalan Nagenthiran
Flag of Australia image

Check this for some suggestions

http://spconfigstore.codeplex.com/discussions/67466
Avatar of shieldguy

ASKER

I have gone through with the above link but no joy. My web.config file does have these keys available but the program still can't find it. Seems like it is reading a different web.config file :(  . Only a guess though.  Could you please help??

thanks
Avatar of Member_6283346
Member_6283346

Hi! As far as I understand you have problem with reading web.config in SPTimerJob? If so, you should consider following: timer job is not running in IIS process, so web.config will not be loaded for this process. You should open it manually to read. I used following code:

 public class MyDailyJob : SPJobDefinition
    {
        [Persisted]
        private string _siteUrl;

        public MyDailyJob()
            : base()
        {
        }

        public MyDailyJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
            : base(jobName, service, server, targetType)
        {
        }

        public MyDailyJob(string jobName, SPWebApplication webApplication, SPSite site)
            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
        {
            this.Title = "MyDaily Job";
          _siteUrl = site.Url;//need to remember site url to read webconfig
        }

        public override void Execute(Guid contentDbId)
        {
            // get a reference to the current site collection's content database
            SPWebApplication webApplication = this.Parent as SPWebApplication;
            SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
            using(SPSite site = new SPSite(_siteUrl))
            {
                KeyValueConfigurationCollection settings = WebConfigurationManager.OpenWebConfiguration("/", site.WebApplication.Name).AppSettings.Settings;
                //now you can read web.config
                string myParam = settings["MyParam"].Value;
            }
        }
   }
               
private static string getAppSettingsValue(string sKey)
        {
            string sValue = null;

            try
            {
                sValue = System.Configuration.ConfigurationManager.AppSettings[sKey];
            }
            catch (InvalidOperationException e)
            {
               
            }

            return sValue;
        }
@ ivan_vagunin:

Doing this will make me hard code site url in my code which I don't want. Infact site url is the one I am reading from web.config file.
@ DaveKeyes

I tried your code with a bit of modification as there is no class called 'ConfigurationManager' under System.Configuration:

sValue = System.Configuration.ConfigurationSettings.AppSettings[sKey];

Anywyas, when I run this code, Although it doesn't raise any exception but returns null although the required key do exist in appsettings under web.config file.

@shieldguy, what version of the Frameworks are you using?  This method is in Frameworks 4.x, sorry.

Here is some code that I am using in an earlier version of the Frameworks:

using System.Web.Configuration;


string strOption = WebConfigurationManager.AppSettings[strKey];


Yeah I am using 3.5

I have tried
string strOption = WebConfigurationManager.AppSettings[strKey];

but this even returns null




Try this:

tring strOption = WebConfigurationManager.AppSettings[strKey].Value;
I am afraid there is no such property called 'Value' with AppSettings.
You're right, no .Value property for the WebConfigurationManager.AppSettings.

I just ran a quick test using your entries in your web.config, and I was able to read and write the values to a text file just fine, using this example:

string strOption = WebConfigurationManager.AppSettings[strKey];
I don't know what's going on. I have tried it again and again but no joy.

I am sick of it now. Can anyone please give me any suggestions?????????
ASKER CERTIFIED SOLUTION
Avatar of Member_6283346
Member_6283346

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Well actually it does. The class with this code to read the appsettings was written by someone else who used to work here before me and he has used it in another timer job. I am trying to use this in my program as well but having problem. What my timer job does that it starts of reading a configuration list on my site collection but to reach to this list, the program needs to know the confgSiteUrl, webName and configListName which are available under <appsettings> section of web config. This way nothing is hard coded in the program.
Since your are using VS 2008 (.NET 3.5), System.Configuration.ConfigurationManager exists but you need to add reference to the System.Configuration framework.  ConfigurationManager does not exist in the default System.Configuration namespace.  Do the following:

1.  In your project, click on References folder, right-click and select "Add Reference".
2.  Under the .NET Tab, find "System.Configuration" and select.  Press "OK".

At this point, the latest framework based on VS2008 should be added to your project references.  Once added the following code, provided by @DaveKeyes, should work.


private static string getAppSettingsValue(string sKey)
{
   string sValue = null;

   try
   {
       sValue = System.Configuration.ConfigurationManager.AppSettings[sKey];
   }
   catch (InvalidOperationException e)
   {
               
   }

   return sValue;
}

Open in new window

@Alfred1:

Yeah I have added the reference and it does recognizes 'ConfigurationManager' but it only returns null.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The timer job is OWSTIMER.EXE process, and site process is W3WP.EXE, so timer job has its own config file (or has not). If your class worked before with timer job. Can you post full code?
You might be accessing the wrong web.config file, please be aware that there is an ASP.NET Configuration Hierarchy.

You might be accessing for example the ASP.NET application subdirectory web.config rather than the web site web.config.  Check the link below for reference:

http://msdn.microsoft.com/en-us/library/ms178685%28v=VS.90%29.aspx
A bit of correction in my previous example, for example, <add key="ConfigSiteUrl" value="http://MySitecollection" /> might be located in an ASP.NET application subdirectory web.config but you are reading the web site (higher level) web.config.  You will get null in this case as the "ConfigSiteUrl key is not in the web site web.config.
Since timer job doesn't work as an IIS application, it wasn't recognizing my web.config file.