0

I have a project with some classes that act according to the parameters that can be configured in the app.config or web.config.

The project/classes interact as much in web environments as in Windows app environments. The question is: how can I detect what type of project it is, to know if I should read an app.config or a web.config?

At the moment, I have two classes that load the data, one web and one Windows app; how can I make a single one that decides which to use? I have to modify my code to use one or the other, and it impacts my maintenance of the common classes.

I am attaching the classes as reference:

namespace MyAppSetting.Windows
{
    public class MyGetConfig
    {
        private static Assembly currentAssembly = Assembly.GetCallingAssembly();
        private static Configuration FileAppConfig = ConfigurationManager.OpenExeConfiguration(AppDomain.CurrentDomain.BaseDirectory + AppDomain.CurrentDomain.FriendlyName.Replace(".svhost", ""));
        private static AppSettingsSection App_Config = FileAppConfig.AppSettings;

        public static string getValue(string Key, string DefaultValue = "")
        {
            // If it's null it doesn't exist ... if it's not null and Update Default if it's blank And there is a default value, and the config is blank
            if (App_Config.Settings[Key] == null || App_Config.Settings[Key].Value == null || App_Config.Settings[Key].Value.Trim() == "")
                return DefaultValue;
            return App_Config.Settings[Key].Value;
        }
    }
}

namespace MyAppSetting.Web
{
    public class MyGetConfig
    {
        private static System.Collections.Specialized.NameValueCollection App_Config = System.Web.Configuration.WebConfigurationManager.AppSettings;

        public static string getValue(string Key, string DefaultValue = "")
        {
            // If it's null it doesn't exist ... if it's not null and Update Default if it's blank And there is a default value, and the config is blank
            if (App_Config[Key] == null || App_Config[Key].Trim() == "")
                return DefaultValue;
            else
                return App_Config[Key];
        }
    }
}

MY SOLUTION

My Final Solution is this:

    #region Win App Resources 4 Read Configuration
    private static Configuration FileAppConfig = null;
    private static AppSettingsSection winApp_Config = null; 
    #endregion Win App Resources 4 Read Configuration

    #region WEB App Resources 4 Read Configuration
    private static System.Collections.Specialized.NameValueCollection webApp_Config = null;
    #endregion WEB App Resources 4 Read Configuration

    public static void Inicialize()
    {
        FileAppConfig = null;
        winApp_Config = null;
        webApp_Config = null;
        try
        {
            FileAppConfig = ConfigurationManager.OpenExeConfiguration(AppDomain.CurrentDomain.BaseDirectory + AppDomain.CurrentDomain.FriendlyName.Replace(".vshost", ""));
            winApp_Config = FileAppConfig.AppSettings;
            TipoDeApp = TipoApp.Win;
        }
        catch
        {
            try
            {
                webApp_Config = System.Web.Configuration.WebConfigurationManager.AppSettings;
                TipoDeApp = TipoApp.Web;
            }
            catch { TipoDeApp = TipoApp.Desconocido; }
        }
    }

And next... Read the Settings by XMLDocument.... (based on Read config file using XMl reader)

    public static string getValueFromSection(string Key, string DefaultValue = "", string Section = "appSettings")
    {
        Section = Section.Trim() == "" ? "appSettings" : Section.Trim();
        try
        {
            var dic = new Dictionary<string, string>();

            if (AllwaysLoadFromConfigFile || FileAppConfig == null)
                Inicialize();

            // Idea original: https://stackoverflow.com/questions/3868179/read-config-file-using-xml-reader
            XmlDocument xdoc = new XmlDocument();

            if (TipoDeApp == TipoApp.Win)
                xdoc.Load(FileAppConfig.FilePath);
            else if (TipoDeApp == TipoApp.Web)
                xdoc.Load(AppDomain.CurrentDomain.BaseDirectory + "web.config");
            else
                return DefaultValue;

            foreach (XmlNode node in xdoc.SelectSingleNode("/configuration/" + Section))
                if ((node.NodeType != XmlNodeType.Comment) && node.Attributes["key"] != null && node.Attributes["key"].Value != null)
                    if (!dic.ContainsKey(node.Attributes["key"].Value.ToUpper()))
                        dic.Add(node.Attributes["key"].Value.ToUpper(), node.Attributes["value"] == null || node.Attributes["value"].Value == null ? "" : node.Attributes["value"].Value);
                    else
                        dic[node.Attributes["key"].Value.ToUpper()] = node.Attributes["value"] == null || node.Attributes["value"].Value == null ? "" : node.Attributes["value"].Value;

            if (dic != null && dic[Key.ToUpper()] != null)
                return dic[Key.ToUpper()];
        }
        catch { }
        return DefaultValue;
    }

And finnaly, my Config file is:

  <configSections>
    <sectionGroup name="MySectionGroup">
      <section name="MySection1" type="System.Configuration.NameValueSectionHandler" />
      <section name="MySection1" type="System.Configuration.NameValueSectionHandler" />
    </sectionGroup>
  </configSections>

  <MySectionGroup>
    <MySection1>
      <add key="MyParam1" value="Hello" />
      <add key="MyParam2" value="3.1416" />
    </MySection1>
    <MySection2>
      <add key="MyParam1" value="true" />
      <add key="MyParam2" value="Another value" />
    </MySection2>
  </MySectionGroup>

1 Answers1

1

You don't have to know what type of project you are in. Just reference your app settings with:

  ConfigurationManager.AppSettings["key"]

This works in the same way in both web app and desktop application.

Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106