Search code examples
c#dynamicweb-configweb-reference

C# Changing Web Reference url


I'm trying to change a web reference path depending on whether the site is live or not.

The application settings are in the web.config

<applicationSettings>
<WebReferenceName.Properties.Settings>
  <setting name="WebReferenceName_Service_TBService"
    serializeAs="String">
    <value>http://localhost:50711/Service.svc</value>
  </setting>
</WebReferenceName.Properties.Settings>

I've tried the following:

Properties.Settings.Default.WebReferenceName_Service_TBService.Equals("http://www.newurl.com/service.svc");

which although doesn't error, checking it later, shows it hasn't changed.

and

var config = WebConfigurationManager.OpenWebConfiguration("~/web.config");
config.AppSettings["WebReferenceName_Service_TBService"] = "http://www.newurl2.com/service.svc";
config.Save(); 

but this errors saying I don't have permissions

Is there another way of doing this?

I'd rather not have to use if statements all over the place, as my types are namespaced differently. e.g.

using (var service = new WebServiceLocal.TheWebServiceService())
{
     WebServiceLocal.blah();
}

Thanks


Solution

  • The preferred way to do this is to use config transformations. So your default web.config would contain:

    <applicationSettings>
        <WebReferenceName.Properties.Settings>
            <setting name="WebReferenceName_Service_TBService" serializeAs="String">
                <value>http://localhost:50711/Service.svc</value>
            </setting>
        </WebReferenceName.Properties.Settings>
    </applicationSettings>
    

    And in your transform, you would have something like this (note the xdt:Transform="Replace"):

    <applicationSettings>
        <WebReferenceName.Properties.Settings>
            <setting name="WebReferenceName_Service_TBService" serializeAs="String">
                <value xdt:Transform="Replace">http://www.newurl2.com/service.svc</value>
            </setting>
        </WebReferenceName.Properties.Settings>
    </applicationSettings>
    

    A point to note, if you are doing something similar for an app.config (as opposed to web.config) you will need to install an addon like SlowCheetah.