views:

285

answers:

3

I have a web application deployed in production which references an external web service. Looking at the source code in Visual Studio, I see that the web referebce was statically linked. In the proxy reference.cs, it is hardcode to the url. this.Url = "http://server/WebService/Service.asmx";

I can change the url. But, I would like the proxy to pick up the url from web.config file. How do I enhance proxy code without using Visual Studio to set url behavior to dynamic? would love to get some code samples in C#.

+1  A: 

You can use the same code generated by Visual Studio when you change the behavior to dynamic:

public Service1() {
    string urlSetting = System.Configuration.ConfigurationSettings.AppSettings["WebApplication1.localhost.Service1"];
    if ((urlSetting != null)) {
        this.Url = string.Concat(urlSetting, "");
    }
    else {
        this.Url = "http://localhost/WebService1/Service1.asmx";
    }
}
Gulzar
What happens if the resource.cs file is re-generated? Or does setting the url to dynamic keep these settings. I ran into an issue where I have custom configuration reader class, re-generated the resource file and it reset the call to the appSettings to go directly to the config file instead of using my custom class. Is there any other circumstance that would cause this code to change since it specifically says in the autogenerted code not to update the file as your changes could be lost?
TampaRich
A: 

In your properties folder of the project with Settings.settings add a web service URL setting to one of the properties.

Then modify this.Url = Properties.Settings.YourWebServiceUrlName

This will create a configuration in your web.config that you can change on a per server basis. I usually set the property settings to my production server settings and then modify the web.config for my local dev environment.

Nick Berardi
+1  A: 

I think the online docs for Web References sums it up fairly well:

If you leave the URL behavior set to the default value of static, the proxy class sets the URL property using a hard-coded URL when you create an instance of the class.

If you set the URL behavior of the Web reference to dynamic, the application obtains the URL at run time from the appSettings element of your application's configuration file.

Source: MSDN, Web References in Visual Studio

In other words, yes, you have to change it to dynamic in Visual Studio (or another editor) if you want to set it from a config file.

R. Bemrose