不同的应用程序设置取决于配置模式

时间:2021-10-05 13:56:50

Is anyone aware of a way that I can set application (or user) level settings in a .Net application that are conditional on the applications current development mode? IE: Debug/Release

是否有人知道我可以在.Net应用程序中设置应用程序当前开发模式的应用程序(或用户)级别设置? IE:调试/发布

To be more specific, I have a url reference to my webservices held in my application settings. During release mode I would like those settings to point to http://myWebservice.MyURL.com during debug mode I would love those settings to be http://myDebuggableWebService.MyURL.com.

更具体地说,我有一个url引用我的应用程序设置中保存的webservices。在发布模式期间,我希望这些设置在调试模式期间指向http://myWebservice.MyURL.com我希望这些设置为http://myDebuggableWebService.MyURL.com。

Any ideas?

6 个解决方案

#1


15  

I know this was asked years ago, but just in case anyone is looking for a simple and effective solution that I use.

我知道这是多年前提出来的,但以防万一有人在寻找我使用的简单而有效的解决方案。

  1. Go to project properties, Settings tab (you'll see your web service URL or any other settings already listed here).

    转到项目属性,“设置”选项卡(您将看到您的Web服务URL或此处已列出的任何其他设置)。

  2. Click the "View Code" button available on the Settings page.

    单击“设置”页面上的“查看代码”按钮。

  3. Type this in the constructor.

    在构造函数中键入this。

    this.SettingsLoaded += Settings_SettingsLoaded;
    
  4. Add the following function under the constructor:

    在构造函数下添加以下函数:

    void Settings_SettingsLoaded(object sender, System.Configuration.SettingsLoadedEventArgs e)
    {
        #if(DEBUG)
        this["YOUR_SETTING_NAME"] = VALUE_FOR_DEBUG_CONFIGURATION;
        #else
        this["YOUR_SETTING_NAME"] = VALUE_FOR_RELEASE_CONFIGURATION;
        #endif
    }
    

Now whenever you run your project, it will compile only the line that matches the current build configuration.

现在,无论何时运行项目,它都只编译与当前构建配置匹配的行。

#2


15  

This is somewhat late to the party, but I stumbled upon a nice way of implementing the web.transform approach for app.config files. (i.e. it makes use of the namespace http://schemas.microsoft.com/XML-Document-Transform)

这对派对来说有些晚了,但我偶然发现了一种为app.config文件实现web.transform方法的好方法。 (即它使用命名空间http://schemas.microsoft.com/XML-Document-Transform)

I think it is "nice" because it is a pure xml approach and doesn't require 3rd party software.

我认为这很“好”,因为它是纯xml方法,不需要第三方软件。

  • A parent / default App.config file is descended from, according to your various build configurations.
  • 根据您的各种构建配置,父/默认App.config文件来自。

  • These descendants then only override what they need to.
  • 这些后代只会覆盖他们需要的东西。

In my opinion this is much more sophisticated and robust than having to maintain x number of config files which get copied in their entirety, such as in other answers.

在我看来,这比必须维护x个完整复制的配置文件要复杂得多,比如在其他答案中。

A walkthrough has been posted here: http://mitasoft.wordpress.com/2011/09/28/multipleappconfig/

这里发布了一个演练:http://mitasoft.wordpress.com/2011/09/28/multipleappconfig/


Look, Mom - No explicit post-build events in my IDE!

看,妈妈 - 我的IDE中没有明确的构建后事件!

#3


6  

There is, as far as I know, no built in way of doing this. In our project we maintain 4 different settings files, and switch between them by copying each into the active file in the prebuild step of the build.

据我所知,没有内置的方法可以做到这一点。在我们的项目中,我们维护了4个不同的设置文件,并通过在构建的预构建步骤中将每个文件复制到活动文件中来切换它们。

copy "$(ProjectDir)properties\settings.settings.$(ConfigurationName).xml" "$(ProjectDir)properties\settings.settings"
copy "$(ProjectDir)properties\settings.designer.$(ConfigurationName).cs" "$(ProjectDir)properties\settings.Designer.cs"

This has worked flawlessly for us for a few years. Simply change the target and the entire config file is switched as well.

几年来,这对我们来说是完美无缺的。只需更改目标,即可切换整个配置文件。

Edit: The files are named e.g. settings.settings.Debug.xml, settings.settings.Release.xml etc..

编辑:文件名为例如settings.settings.Debug.xml,settings.settings.Release.xml等。

Scott Hanselman has described a slightly 'smarter' approach, the only difference is that we don't have the check to see if the file has changed: http://www.hanselman.com/blog/ManagingMultipleConfigurationFileEnvironmentsWithPreBuildEvents.aspx

Scott Hanselman描述了一种稍微“聪明”的方法,唯一的区别是我们没有检查文件是否发生了变化:http://www.hanselman.com/blog/ManagingMultipleConfigurationFileEnvironmentsWithPreBuildEvents.aspx

#4


4  

If you want to keep everything in one configuration file you can introduce a custom configuration section to your app.settings to store properties for debug and release modes.

如果要将所有内容保存在一个配置文件中,可以在app.settings中引入自定义配置部分,以存储调试和发布模式的属性。

You can either persist the object in your app that stores dev mode specific settings or override an existing appsetting based on the debug switch.

您可以在应用程序中保留对象,该对象存储开发模式特定设置,也可以基于调试开关覆盖现有应用程序集。

Here is a brief console app example (DevModeDependencyTest):

这是一个简短的控制台应用程序示例(DevModeDependencyTest):

App.config :

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="DevModeSettings">
      <section name="debug" type="DevModeDependencyTest.DevModeSetting,DevModeDependencyTest" allowLocation="true" allowDefinition="Everywhere" />
      <section name="release" type="DevModeDependencyTest.DevModeSetting,DevModeDependencyTest" allowLocation="true" allowDefinition="Everywhere" />
    </sectionGroup>
  </configSections>
  <DevModeSettings>
    <debug webServiceUrl="http://myDebuggableWebService.MyURL.com" />
    <release webServiceUrl="http://myWebservice.MyURL.com" />
  </DevModeSettings>
  <appSettings>
    <add key="webServiceUrl" value="http://myWebservice.MyURL.com" />
  </appSettings>
</configuration>

The object to store your custom configuration (DevModeSettings.cs):

存储自定义配置的对象(DevModeSettings.cs):

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace DevModeDependencyTest
{
    public class DevModeSetting : ConfigurationSection
    {
        public override bool IsReadOnly()
        {
            return false;
        }

        [ConfigurationProperty("webServiceUrl", IsRequired = false)]
        public string WebServiceUrl
        {
            get
            {
                return (string)this["webServiceUrl"];
            }
            set
            {
                this["webServiceUrl"] = value;
            }
        }
    }
}

A handler to access your custom configuration settings (DevModeSettingsHandler.cs) :

用于访问自定义配置设置的处理程序(DevModeSettingsHandler.cs):

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace DevModeDependencyTest
{
    public class DevModeSettingsHandler
    {
        public static DevModeSetting GetDevModeSetting()
        {
            return GetDevModeSetting("debug");
        }

        public static DevModeSetting GetDevModeSetting(string devMode)
        {
            string section = "DevModeSettings/" + devMode;

            ConfigurationManager.RefreshSection(section); // This must be done to flush out previous overrides
            DevModeSetting config = (DevModeSetting)ConfigurationManager.GetSection(section);

            if (config != null)
            {
                // Perform validation etc...
            }
            else
            {
                throw new ConfigurationErrorsException("oops!");
            }

            return config;
        }
    }
}

And finally your entry point to the console app (DevModeDependencyTest.cs) :

最后你进入控制台应用程序(DevModeDependencyTest.cs)的入口点:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace DevModeDependencyTest
{
    class DevModeDependencyTest
    {
        static void Main(string[] args)
        {
            DevModeSetting devMode = new DevModeSetting();

            #if (DEBUG)
                devMode = DevModeSettingsHandler.GetDevModeSetting("debug");
                ConfigurationManager.AppSettings["webServiceUrl"] = devMode.WebServiceUrl;
            #endif

            Console.WriteLine(ConfigurationManager.AppSettings["webServiceUrl"]);
            Console.ReadLine();
        }
    }
}

#5


3  

SlowCheetah adds the functionality you ask for not only for App.config but for any XML file in your project - http://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5

SlowCheetah不仅为App.config添加了您要求的功能,还为项目中的任何XML文件添加了这些功能 - http://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5

#6


1  

I had a similar problem to solve and ended up using the XDT (web.config) transform engine, that was already suggested in the answer from ne1410s that can be found here: https://*.com/a/27546685/410906

我有一个类似的问题要解决并最终使用XDT(web.config)转换引擎,这已经在ne1410s的答案中提出,可以在这里找到:https://*.com/a/27546685/410906

But instead of doing it manually as described in his link I used this plugin: https://visualstudiogallery.msdn.microsoft.com/579d3a78-3bdd-497c-bc21-aa6e6abbc859

但不是像他的链接中所描述的那样手动操作,而是使用了这个插件:https://visualstudiogallery.msdn.microsoft.com/579d3a78-3bdd-497c-bc21-aa6e6abbc859

The plugin is only helping to setup the configuration, it's not needed to build and the solution can be built on other machines or on a build server without the plugin or any other tools being required.

该插件仅帮助设置配置,不需要构建,并且可以在其他计算机或构建服务器上构建解决方案,而无需插件或任何其他工具。

#1


15  

I know this was asked years ago, but just in case anyone is looking for a simple and effective solution that I use.

我知道这是多年前提出来的,但以防万一有人在寻找我使用的简单而有效的解决方案。

  1. Go to project properties, Settings tab (you'll see your web service URL or any other settings already listed here).

    转到项目属性,“设置”选项卡(您将看到您的Web服务URL或此处已列出的任何其他设置)。

  2. Click the "View Code" button available on the Settings page.

    单击“设置”页面上的“查看代码”按钮。

  3. Type this in the constructor.

    在构造函数中键入this。

    this.SettingsLoaded += Settings_SettingsLoaded;
    
  4. Add the following function under the constructor:

    在构造函数下添加以下函数:

    void Settings_SettingsLoaded(object sender, System.Configuration.SettingsLoadedEventArgs e)
    {
        #if(DEBUG)
        this["YOUR_SETTING_NAME"] = VALUE_FOR_DEBUG_CONFIGURATION;
        #else
        this["YOUR_SETTING_NAME"] = VALUE_FOR_RELEASE_CONFIGURATION;
        #endif
    }
    

Now whenever you run your project, it will compile only the line that matches the current build configuration.

现在,无论何时运行项目,它都只编译与当前构建配置匹配的行。

#2


15  

This is somewhat late to the party, but I stumbled upon a nice way of implementing the web.transform approach for app.config files. (i.e. it makes use of the namespace http://schemas.microsoft.com/XML-Document-Transform)

这对派对来说有些晚了,但我偶然发现了一种为app.config文件实现web.transform方法的好方法。 (即它使用命名空间http://schemas.microsoft.com/XML-Document-Transform)

I think it is "nice" because it is a pure xml approach and doesn't require 3rd party software.

我认为这很“好”,因为它是纯xml方法,不需要第三方软件。

  • A parent / default App.config file is descended from, according to your various build configurations.
  • 根据您的各种构建配置,父/默认App.config文件来自。

  • These descendants then only override what they need to.
  • 这些后代只会覆盖他们需要的东西。

In my opinion this is much more sophisticated and robust than having to maintain x number of config files which get copied in their entirety, such as in other answers.

在我看来,这比必须维护x个完整复制的配置文件要复杂得多,比如在其他答案中。

A walkthrough has been posted here: http://mitasoft.wordpress.com/2011/09/28/multipleappconfig/

这里发布了一个演练:http://mitasoft.wordpress.com/2011/09/28/multipleappconfig/


Look, Mom - No explicit post-build events in my IDE!

看,妈妈 - 我的IDE中没有明确的构建后事件!

#3


6  

There is, as far as I know, no built in way of doing this. In our project we maintain 4 different settings files, and switch between them by copying each into the active file in the prebuild step of the build.

据我所知,没有内置的方法可以做到这一点。在我们的项目中,我们维护了4个不同的设置文件,并通过在构建的预构建步骤中将每个文件复制到活动文件中来切换它们。

copy "$(ProjectDir)properties\settings.settings.$(ConfigurationName).xml" "$(ProjectDir)properties\settings.settings"
copy "$(ProjectDir)properties\settings.designer.$(ConfigurationName).cs" "$(ProjectDir)properties\settings.Designer.cs"

This has worked flawlessly for us for a few years. Simply change the target and the entire config file is switched as well.

几年来,这对我们来说是完美无缺的。只需更改目标,即可切换整个配置文件。

Edit: The files are named e.g. settings.settings.Debug.xml, settings.settings.Release.xml etc..

编辑:文件名为例如settings.settings.Debug.xml,settings.settings.Release.xml等。

Scott Hanselman has described a slightly 'smarter' approach, the only difference is that we don't have the check to see if the file has changed: http://www.hanselman.com/blog/ManagingMultipleConfigurationFileEnvironmentsWithPreBuildEvents.aspx

Scott Hanselman描述了一种稍微“聪明”的方法,唯一的区别是我们没有检查文件是否发生了变化:http://www.hanselman.com/blog/ManagingMultipleConfigurationFileEnvironmentsWithPreBuildEvents.aspx

#4


4  

If you want to keep everything in one configuration file you can introduce a custom configuration section to your app.settings to store properties for debug and release modes.

如果要将所有内容保存在一个配置文件中,可以在app.settings中引入自定义配置部分,以存储调试和发布模式的属性。

You can either persist the object in your app that stores dev mode specific settings or override an existing appsetting based on the debug switch.

您可以在应用程序中保留对象,该对象存储开发模式特定设置,也可以基于调试开关覆盖现有应用程序集。

Here is a brief console app example (DevModeDependencyTest):

这是一个简短的控制台应用程序示例(DevModeDependencyTest):

App.config :

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="DevModeSettings">
      <section name="debug" type="DevModeDependencyTest.DevModeSetting,DevModeDependencyTest" allowLocation="true" allowDefinition="Everywhere" />
      <section name="release" type="DevModeDependencyTest.DevModeSetting,DevModeDependencyTest" allowLocation="true" allowDefinition="Everywhere" />
    </sectionGroup>
  </configSections>
  <DevModeSettings>
    <debug webServiceUrl="http://myDebuggableWebService.MyURL.com" />
    <release webServiceUrl="http://myWebservice.MyURL.com" />
  </DevModeSettings>
  <appSettings>
    <add key="webServiceUrl" value="http://myWebservice.MyURL.com" />
  </appSettings>
</configuration>

The object to store your custom configuration (DevModeSettings.cs):

存储自定义配置的对象(DevModeSettings.cs):

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace DevModeDependencyTest
{
    public class DevModeSetting : ConfigurationSection
    {
        public override bool IsReadOnly()
        {
            return false;
        }

        [ConfigurationProperty("webServiceUrl", IsRequired = false)]
        public string WebServiceUrl
        {
            get
            {
                return (string)this["webServiceUrl"];
            }
            set
            {
                this["webServiceUrl"] = value;
            }
        }
    }
}

A handler to access your custom configuration settings (DevModeSettingsHandler.cs) :

用于访问自定义配置设置的处理程序(DevModeSettingsHandler.cs):

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace DevModeDependencyTest
{
    public class DevModeSettingsHandler
    {
        public static DevModeSetting GetDevModeSetting()
        {
            return GetDevModeSetting("debug");
        }

        public static DevModeSetting GetDevModeSetting(string devMode)
        {
            string section = "DevModeSettings/" + devMode;

            ConfigurationManager.RefreshSection(section); // This must be done to flush out previous overrides
            DevModeSetting config = (DevModeSetting)ConfigurationManager.GetSection(section);

            if (config != null)
            {
                // Perform validation etc...
            }
            else
            {
                throw new ConfigurationErrorsException("oops!");
            }

            return config;
        }
    }
}

And finally your entry point to the console app (DevModeDependencyTest.cs) :

最后你进入控制台应用程序(DevModeDependencyTest.cs)的入口点:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace DevModeDependencyTest
{
    class DevModeDependencyTest
    {
        static void Main(string[] args)
        {
            DevModeSetting devMode = new DevModeSetting();

            #if (DEBUG)
                devMode = DevModeSettingsHandler.GetDevModeSetting("debug");
                ConfigurationManager.AppSettings["webServiceUrl"] = devMode.WebServiceUrl;
            #endif

            Console.WriteLine(ConfigurationManager.AppSettings["webServiceUrl"]);
            Console.ReadLine();
        }
    }
}

#5


3  

SlowCheetah adds the functionality you ask for not only for App.config but for any XML file in your project - http://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5

SlowCheetah不仅为App.config添加了您要求的功能,还为项目中的任何XML文件添加了这些功能 - http://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5

#6


1  

I had a similar problem to solve and ended up using the XDT (web.config) transform engine, that was already suggested in the answer from ne1410s that can be found here: https://*.com/a/27546685/410906

我有一个类似的问题要解决并最终使用XDT(web.config)转换引擎,这已经在ne1410s的答案中提出,可以在这里找到:https://*.com/a/27546685/410906

But instead of doing it manually as described in his link I used this plugin: https://visualstudiogallery.msdn.microsoft.com/579d3a78-3bdd-497c-bc21-aa6e6abbc859

但不是像他的链接中所描述的那样手动操作,而是使用了这个插件:https://visualstudiogallery.msdn.microsoft.com/579d3a78-3bdd-497c-bc21-aa6e6abbc859

The plugin is only helping to setup the configuration, it's not needed to build and the solution can be built on other machines or on a build server without the plugin or any other tools being required.

该插件仅帮助设置配置,不需要构建,并且可以在其他计算机或构建服务器上构建解决方案,而无需插件或任何其他工具。