In an Azure Websites I was always using the following code to fetch some values from the config's app settings:
string property = WebConfigurationManager.AppSettings["property"];
Just a couple of days ago I stublemd upon CloudConfigurationManager, and with it I can get the property like so:
string property = CloudConfigurationManager.GetSetting("property");
Although CloudConfigurationManager seems like it's better fitted to cloud use, I never had any issues with WebConfigurationManager.
Should I be using CloudConfigurationManager?
What are the differences between the two?
In what cases CloudConfigurationManager will behave diffrent from
WebConfigurationManager?
CloudConfigurationManager enables us to read configuration file regardless of the environment we are in.
So instead of writing environment specific code statements e.g., for web.config file:
WebConfigurationManager.AppSettings["MySetting"]
For ServiceConfiguration.cscfg file:
RoleEnvironment.GetConfigurationSettingValue("MySetting")
We can write the below statement, which will read values from all the configuration files i.e., app.config, web.config and ServiceConfiguration.cscfg.
CloudConfigurationManager.GetSetting("MySetting")
CloudConfigurationManager requires Microsoft.WindowsAzure.Configuration assembly, part of Azure SDK or separate NuGet.
WebConfigurationManager requires System.Web.Configuration assembly, part of .NET Framework.
WebConfigurationManager and CloudConfigurationManager manage different configuration files.
WebConfigurationManager is for managing website's web.config file(s) and it's appsettings and connections strings
CloudConfigurationManager is for managing .cscfg files (for cloud services). His benefit is that you can manage configurations and connections from the azure portal directly.
I think you're better off using WebConfigurationManager.
With it, you have access to ConnectionStrings as well as AppSettings.
Both sets of settings you can update via the Azure Portal. They can then further be used in other Azure facilities/services, such as when configuring website backup.
Check this out for more information: https://azure.microsoft.com/en-us/blog/windows-azure-web-sites-how-application-strings-and-connection-strings-work/
Related
I have working web client, it uses "wwwroot/appsettings.json" file for its configuration.
Now I would like to override just single settings using environment variable for it (as an example, in reality there will be many, arbitrary, overrides). Is there ready to use mechanism, similar to ASP.NET Core server (all it takes is calling extension method and combining json, env. variables)?
I am not asking about multiple .json files and switching between them depending on ENVIRONMENT variable, it is completely different scenario.
So far I didn't find anything even close, so thinking about DIY approach I see an ugly path -- moving client configuration file into hosting server, adding main node in client .json file like "client", using environment variables with prefix "client", merging those data using ASP.NET server mechanism, dumping it back to file for the client usage. And hoping it will work :-).
So I followed DIY path :-) If anyone like it here are the steps:
create 3 files with empty JSON at web client wwwroot -- appsettings.json, appsettings.Development.json and Production version as well
put your entire web client config in appsettings.json at hosting server at "CLIENT" node for example
in your server Startup constructor create configuration as usual, but then fetch entire "CLIENT" section and "jsonize" it back (see: https://stackoverflow.com/a/62533775/6734314) -- convert it to string and write to $"wwwroot/appsettings.{env.EnvironmentName}.json" (where env is IWebHostEnvironment)
And that's it -- I tested it in Development mode and in Production. The only drawbacks I see are:
it looks weird :-)
when executed using VS the written file is put not relative to binary file, but relative to project -- so when you are done you have to delete newly created file (otherwise on the next run VS will complain about conflict between two static files)
You override the settings using env. variables at server side using "CLIENT" prefix, and the rest is as usual.
For the record, I am not saying this is perfect, but I didn't look for anything more than I asked in my question. What I would like to do however is to reduce the number of steps, or even better to use some already existing mechanism. I will be grateful for the improvements/tips within those areas.
I am trying to configure some key/value pairs for my Azure web application using app settings section on Windows Azure preview portal.
Now I am trying to read values like below
ConfigurationManager.AppSettings["MyWebApp.DbConnectionString"];
but it returns null values.
Reading app settings from Web.config in my web application works fine.
I found the solution.
Keep values in web.config as well as in Azure App setting. When you are running/debugging application on your local environment it picks values from web.config.
When you deploy application on Azure it picks values from App setting.
//Below code work for both.
ConfigurationManager.AppSettings["KeyName"]
Keep key name same in web.config as well as in Azure app setting.
In Azure, there are a few different ways of retrieving Application Settings and Connection Strings. However, connection strings work a little differently than vanilla application settings.
Application Settings can be retrieved by any method, regardless of whether or not they are present in the Web.config file.
Connection Strings can also be retrieved by any method if the string is defined in Web.config. However, if the connection string is NOT defined in Web.config, then it can only be retrieved using the Environment Variable method.
Retrieving as Environment Variable
Environment.GetEnvironmentVariable("APPSETTING_my-setting-key");
Environment.GetEnvironmentVariable("SQLAZURECONNSTR_my-connection-string-key");
Note that the keys must be prepended with a string designating their type when using this method.
All Application Settings use the APPSETTING_ prefix.
Connection Strings have a different prefix depending on the type of database selected when creating the string in the portal:
"Sql Databases" --> "SQLAZURECONNSTR_my-connection-string-key"
"SQL Server" --> "SQLCONNSTR_my-connection-string-key"
"MySQL" --> "MYSQLCONNSTR_my-connection-string-key"
"Custom" --> "CUSTOMCONNSTR_my-connection-string-key"
For a full overview, see the Windows Azure Web Sites documentation.
System.Environment.GetEnvironmentVariable("SERVICEBUS_CONNECTION")
works great!
We use WCF client in our project which is an Azure functions app, to communicate with an external web service. We need to change the xmlSerializer's tempFilesLocation because of the permission issue. I searched online and found the following configuration that we can use in our web.config which will solve the problem.
<system.xml.serialization>
<xmlSerializer tempFilesLocation="an absolute path of your choice"/>
</system.xml.serialization>
But in Azure Functions app, we don't have access to web.config, so we need to find a way to do it in the code. Is there any way to change tempFilesLocation in the code?
It's not possible to modify the web.config for functions running on the dynamic sku (where you pay-per-invocation).
However, if you create your function on the non-dynamic/classic sku (where you pay per vm, the pricing model for regular web apps) then you can modify the web.config settings via an applicationHost.xdt file. More details on how to work with xdt file here: https://github.com/projectkudu/kudu/wiki/Xdt-transform-samples
We have a static html/webform site, the site lacks search functionality, I was able to get yahoo BOSS (Build your Own Search Service) after a few hours yesterday, i got it working (still working on adding missing features like pagination) , I was wondering about the configuration options of the class, as I have a BossSearch.cs in App_Code, with some fields that are set at the top:
public class BossSearch
{
String sResultsPage = "~/searchResults.aspx";
String sSearchString="";
String sApiKey = ConfigurationSettings.AppSettings["BossApiKey"];
String sSite = "www.oursite.com"; //without http://
String sQuery = "http://boss.yahooapis.com/ysearch/web/v1/{0}%20+site:{1}?appid={2}&format=xml&start={3}&count={4}";
String sStart = "0";
Uri address;
WebProxy webproxy = new WebProxy("http://192.168.4.8:8080");
bool bUseProxy = true;
int nResultsPerPage = 10;
int nTotalResults = 0;
...
As you can see, i get the BossApiKey from the web.config file, but all others I have them in the declared in the class, should I put all of them in the web.config file? if I'm thinking of reusing the class (should i say class library?) in other websites as well? can I turn it into a dll and what would the advantages be? i read somewhere that a dll has its own config file, is this the way to store those settings?
Apologies for my ignorance, since I'm not that familiar with developing applications (still studying)
What you read about .NET assemblies having their own config files is not absolutely correct; a web site has web.config files, one in the root and zero/one in each subdirectory. If a .NET assembly that is in the application calls into the standard config API, it will get its data from that web.config.
The same goes for WinForms apps and the [appname].exe.config file; any assemblies included that use the standard config API will be getting their data from that.
All of that is not to say that any assembly could not define its own configuration mechanism which pulls its data from wherever it wants.
And yes; if you intend to reuse this code a good bit, you are thinking along the right lines; put the code in its own assembly, and have it get its data from Config files so you do not need to recompile it for each application.
If you declare all of them in a database or web.config, you don't need to recompile each time you reconfigure the search engine
I you're striving for reuse and ease of use, then I would recommend writing a custom configuration section for your control. This can be part of the dll you distribute to other application and will allow you to have the ultimate in flexibility and explicit portability to other .net apps.
Enjoy!
You should only store the value in a single place in your application. For an ASP.NET application, the web.config file is an appropriate place for these kind of things. You won't need to recompile your application if this value changes.
If you decide to put your code into a separate class library and still want to use a config file to store your api key, you should note that your appSetting key needs to be entered in the application or web site's config file - you can't define a config file for a class library.
One other approach that you might find useful would be to make a wrapper class to store your settings. You could have class with static methods to look up your appSettings key so that you get a nice, compile time, way to get the api key, rather than typing out the name of your appSettings key everywhere.
What is the best practice to store application settings (such as user name and password, database location ...) in C# ?
Hint: I am new to .net and C#
Application Configuration Settings that are application wide (non-user specific) belong in either app.config (for Desktop apps) or web.config (for Web apps).
Encrypting sections of a web.config file is quite simple as outlined in this Super Simple Example.
If you need to store User specific settings (like application settings, etc.) or Application wide settings not related to application configuration you can use a Settings file as described here:
User Settings in C#
I'm not sure what version of .net/Visual Studio it was introduced in, but you can right click on your project, choose 'Add New Item' and select 'Settings File' from the "Add New Item" window. This provides your project with a (named by default) Settings.settings file that you can configure all the settings you want to expose in.
You can define settings that you create to be either Application or User which means you can use this single interface to control global and user settings. Once you've created a setting in the Settings.settings file using the editor that Visual Studio provides, you can access it in code like this:
// Get a Setting value
var valueOfSetting1 = Settings1.Default.Setting1;
// Modify and save a Setting value
Settings1.Default.Setting1 = "New Value";
Settings1.Default.Save();
First option is the registry. It is easy, but it is not too safe for passwords. Another option is using a file that you create. This too isn't safe, unless you want to implement cryption.
Next option is using the Application Settings. This is also quite simple, but there are a few catches. First, right click on your project and go to Properties. There, under the Settings tab, you can store variables to which you can access from your program by
string password = Properties.Settings.Default.Password
You can also change them the same way, but ONLY IF the scope is set the User. WHen the scope is application-wide, VS does not allow you to change these variables for some odd reason. To save changes, you must call Save() as follows:
Properties.Settings.Default.Save();
These are saved in the User Data folder under C:\Documents and Settings\'Current User'\Local Settings\Application Data\
Another option would be to include them in your database, but since you are also storing your database location, this might not work for you.
I think app.config (non web app) or web.config (web app).
These sorts of settings usually land in Application Configuration Files (web.config, app.config).
http://www.devasp.net/net/articles/display/679.html
If you are storing passwords, you might also need to encrypt the configuration section in question.
http://msdn.microsoft.com/en-us/library/53tyfkaw.aspx
http://msdn.microsoft.com/en-us/library/ff650304.aspx
Note if you use app.config, you will see it get renamed to ..config, depending on if your output produces a DLL or an EXE.
As with the above replies suggest, app.config or the web.config is the best place for app settings.
If you need a more robust way of xml style tags for database, server settings and the like, you can use the configurationSection and create custom sections.
http://www.codeproject.com/KB/cs/CustomConfigurationSectio.aspx
For database passwords, the way i do it is have an encrypted string in the xml tag value and decrypt then when reading them, that way you dont expose the passwords.
appsettings config file, ini file(nini), embeddable database(sqlite,berkelydb/etc..),whatever method you like, it depends on your application size/performance consideration and design.