Working on a webapp on VS2017 using MVC framework on .NET 4.5. In my local dev environment, I use the web.config file something like this:
<appSettings>
<add key="GOOGLE_APPLICATION_CREDENTIALS"
value="C:\\Work\\Services-abcd.json" />
</appSettings>
But when I run the webapp I still get the error that GOOGLE_APPLICATION_CREDENTIALS is undefined.
So my question specifically is:
Where am I going wrong? Do I need to define it somewhere else?
When I deploy this to staging/production, on my azure web service, how will I share the json file and how will the web.config file need to change for that?
I know this question answers how to get the variables in web.config, but somehow I am not able to set it there.
Edit 1: Since I was asked, here is where I am getting the error of missing environment variable-
using Google.Cloud.Translation.V2;
TranslationClient client = TranslationClient.Create();
I am unable to declare TranslationClient.
Where am I going wrong? Do I need to define it somewhere else?
According to your codes and description, I found you have defined the app setting not the environment variables. Notice: app setting isn't as same as environment variables.
If you want to set environment variables in the azure web app, I suggest you could set it in your web application codes and upload the application to the app service as below:
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Server.MapPath("test/test.txt"));
When I deploy this to staging/production, on my azure web service, how will I share the json file and how will the web.config file need to change for that?
I suggest you could create a folder to store the json file in your web application, then you could use Server.MapPath to get the right path of your json file.
Since I don't have the google cloud app credentials json file, so I add a txt file in my test demo to test the code could work well.
More details about my test demo, you could refer to below codes.
protected void Page_Load(object sender, EventArgs e)
{
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Server.MapPath("test/test.txt"));
}
protected void Button1_Click(object sender, EventArgs e)
{
string path = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");
Response.Write(path + "\n");
string[] lines = System.IO.File.ReadAllLines(path);
foreach (string line in lines)
{
Response.Write(line);
}
}
Result(111 is the txt file content):
Related
I am confused on how to modify the web.config appSettings values at runtime. For example, I have this appSettings section:
<appSettings>
<add key="productspagedesc" value="TODO: Edit this default message" />
<add key="servicespagedesc" value="TODO: Edit this default message" />
<add key="contactspagedesc" value="TODO: Edit this default message" />
<add key="aboutpagedesc" value="TODO: Edit this default message" />
<add key="homepagedesc" value="TODO: Edit this default message" />
</appSettings>
Let's say, I want to modify the "homepagedesc" key at runtime. I tried ConfigurationManager and WebConfigurationManager static classes, but the settings are "read-only". How do I modify appSettings values at runtime?
UPDATE:
Ok, so here I am 5 years later. I would like to point out that experience has told me, we should not put any configuration that intentionally is editable at runtime in the web.config file but instead we should put it in a separate XML file as what one of the users commented below. This will not require any of edit of web.config file to restart the App which will result with angry users calling you.
You need to use WebConfigurationManager.OpenWebConfiguration():
For Example:
Dim myConfiguration As Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~")
myConfiguration.ConnectionStrings.ConnectionStrings("myDatabaseName").ConnectionString = txtConnectionString.Text
myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text
myConfiguration.Save()
I think you might also need to set AllowLocation in machine.config. This is a boolean value that indicates whether individual pages can be configured using the element. If the "allowLocation" is false, it cannot be configured in individual elements.
Finally, it makes a difference if you run your application in IIS and run your test sample from Visual Studio. The ASP.NET process identity is the IIS account, ASPNET or NETWORK SERVICES (depending on IIS version).
Might need to grant ASPNET or NETWORK SERVICES Modify access on the folder where web.config resides.
Changing the web.config generally causes an application restart.
If you really need your application to edit its own settings, then you should consider a different approach such as databasing the settings or creating an xml file with the editable settings.
And if you want to avoid the restart of the application, you can move out the appSettings section:
<appSettings configSource="Config\appSettings.config"/>
to a separate file. And in combination with ConfigurationSaveMode.Minimal
var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.Save(ConfigurationSaveMode.Minimal);
you can continue to use the appSettings section as the store for various settings without causing application restarts and without the need to use a file with a different format than the normal appSettings section.
2012
This is a better solution for this scenario (tested With Visual Studio 2008):
Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
config.AppSettings.Settings.Remove("MyVariable");
config.AppSettings.Settings.Add("MyVariable", "MyValue");
config.Save();
Update 2018 =>
Tested in vs 2015 - Asp.net MVC5
var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.AppSettings.Settings["MyVariable"].Value = "MyValue";
config.Save();
if u need to checking element exist, use this code:
var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
if (config.AppSettings.Settings["MyVariable"] != null)
{
config.AppSettings.Settings["MyVariable"].Value = "MyValue";
}
else { config.AppSettings.Settings.Add("MyVariable", "MyValue"); }
config.Save();
I know this question is old, but I wanted to post an answer based on the current state of affairs in the ASP.NET\IIS world combined with my real world experience.
I recently spearheaded a project at my company where I wanted to consolidate and manage all of the appSettings & connectionStrings settings in our web.config files in one central place. I wanted to pursue an approach where our config settings were stored in ZooKeeper due to that projects maturity & stability. Not to mention that fact that ZooKeeper is by design a configuration & cluster managing application.
The project goals were very simple;
get ASP.NET to communicate with ZooKeeper
in Global.asax, Application_Start - pull web.config settings from ZooKeeper.
Upon getting passed the technical piece of getting ASP.NET to talk to ZooKeeper, I quickly found and hit a wall with the following code;
ConfigurationManager.AppSettings.Add(key_name, data_value)
That statement made the most logical sense since I wanted to ADD new settings to the appSettings collection. However, as the original poster (and many others) mentioned, this code call returns an Error stating that the collection is Read-Only.
After doing a bit of research and seeing all the different crazy ways people worked around this problem, I was very discouraged. Instead of giving up or settling for what appeared to be a less than ideal scenario, I decided to dig in and see if I was missing something.
With a little trial and error, I found the following code would do exactly what I wanted;
ConfigurationManager.AppSettings.Set(key_name, data_value)
Using this line of code, I am now able to load all 85 appSettings keys from ZooKeeper in my Application_Start.
In regards to general statements about changes to web.config triggering IIS recycles, I edited the following appPool settings to monitor the situation behind the scenes;
appPool-->Advanced Settings-->Recycling-->Disable Recycling for Configuration Changes = False
appPool-->Advanced Settings-->Recycling-->Generate Recycle Event Log Entry-->[For Each Setting] = True
With that combination of settings, if this process were to cause an appPool recycle, an Event Log entry should have be recorded, which it was not.
This leads me to conclude that it is possible, and indeed safe, to load an applications settings from a centralized storage medium.
I should mention that I am using IIS7.5 on Windows 7. The code will be getting deployed to IIS8 on Win2012. Should anything regarding this answer change, I will update this answer accordingly.
Who likes directly to the point,
In your Config
<appSettings>
<add key="Conf_id" value="71" />
</appSettings>
in your code(c#)
///SET
ConfigurationManager.AppSettings.Set("Conf_id", "whateveryourvalue");
///GET
string conf = ConfigurationManager.AppSettings.Get("Conf_id").ToString();
Try This:
using System;
using System.Configuration;
using System.Web.Configuration;
namespace SampleApplication.WebConfig
{
public partial class webConfigFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Helps to open the Root level web.config file.
Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
//Modifying the AppKey from AppValue to AppValue1
webConfigApp.AppSettings.Settings["ConnectionString"].Value = "ConnectionString";
//Save the Modified settings of AppSettings.
webConfigApp.Save();
}
}
}
I am trying to run a program on a Citrix VM located at \\site.local\shares\Agent_console\AC_Launch\AC_Launcher.exe /env=PROD
I am currently using the code below and it is stating the following
private void button13Chromatix_Launcher_Click(object sender, EventArgs e)
{
Process.Start(#"\\plumbedford.local\shares\Agent_Console\AC_Launch\AC_Launcher.exe",
"/Env=PROD");
}
But that fails with the following error:
Unable to access Agent Console XML network share. Try again?
This is a desktop shortcut that works using the same directory.
Thank you in advance.
Try using a literal string (with an # prefix), to ensure that backslashes are not misinterpreted.
It also looks like you have some typos in the location.
Try this:
Process.Start(#"\\site.local\shares\Agent_Console\AC_Launch\AC_Launcher.exe", "/env=PROD");
I am trying to edit a config file of another application with my Web Service.
Currently I have:
[WebMethod]
public string EditConfig(string path)
{
string cfgPath = Path.Combine(path, "Compressor.exe.config");
var configMap = new ExeConfigurationFileMap { ExeConfigFilename = cfgPath };
var cf = ConfigurationManager.OpenMappedExeConfiguration(configMap,
ConfigurationUserLevel.None);
string hello = cf.AppSettings.Settings["SaveTo"].Value;
return hello;
//cf.AppSettings.Settings["RandomAddedKey"].Value = "Hello World!";
//cf.Save();
}
I have also tried:
var config = ConfigurationManager.OpenExeConfiguration(path);
var hello = config.AppSettings.Settings["SaveTo"].Value;
return hello;
Sadly I haven't had success with any of these, and before resorting to the XML Editor I needed to make sure that this isn't possible or I am doing something wrong?
I have searched through StackOverFlow and the best results returned me an "Object reference not set to an instance of an object." Exception.
I have tried feeding the exe to the path the config and only the directory in several different applications.
In this case I want the Web Service to tell the Compressor what to compress and where to save it, but in the code I am just experimenting to get it working.
I am using .NET Framework 3.5 (Latest for web services).
I have tried editing apps in different kinds of framework versions and the end result was the same.
Thank you in advance.
If I get it right, what you want to do is manipulate a configuration file of another application programmatically. Your problems have nothing to do with doing your manipulation inside a web service application. While I think it is relatively easy to manipulate a configuration file through the very same application, it is not such an easy task to do it from another application. I would suggest two approaches:
Use the .NET API to do it. Here you can find an example of manipulating configuration files remotely.
You could manipulate the specific configuration file, as every other XML file using the respective .NET libraries. Here you can see how to do it.
Hope I helped!
I have developed a c# desktop application that needs to be hosted on a server and will be scheduled to fetch data based on queries stored in XML files. while developing, I was using the following code to read XML files:
var query = new XPathDocument(#"C:\\Documents and Settings\\XYZ\\Desktop\\productplanningquery.xml");
as you can see I had put the XML file conveniently on my desktop and it worked fine while development. What I want to do now, is to give at a path such that where ever I host the application plus the XML files, it does not throw an exception. One way i thought could be to have a folder in a directory where the application will be installed but for that i will have to figure out the path to current directory dynamically (which i could not figure out).
Please help.
You could pass the location of you XML using args this way you're code would look like so:
var query = new XPathDocument(args[0])
You can also use relative path. Make sure that when deploying your code you keep the location of the file in the same relative location. For example if you place the XML in the same directory as the application
var query = new XPathDocument("productplanningquery.xml")
I am not sure what you want to achieve whether you want to read xml using winform app and do some operation and then pass it web app or some thing else. But here is my understandings:
Case 1: If you need to create XML outside the IIS and that XML will be consumed by ASP.Net app, then :
For using a desktop application with IIS server , you need to have full administrative access to the Live Machine. If its not then you should consider building windows services to operate on the XML files or any task that will run behind the scenes to decrease the load of the asp.net app.
Still in this case if you dont own a server then you need some Virtual Private Hosting or similar kind of hosting where you have almost all previleges to access the system. Then deploy the Windows Service, set the output path in such a manner so that it can be accessed by asp.net app too. And do whatever you want.
Case 2: If you want o read XML in ASP.Net Solely, then
In this case you case read it easily by using XDocument.But note, XML should in the same application directory or under the reach of the ASP.Net app
MSDN Article for Web-Windows Services with ASP.Net
You can use something like this:
var path = string.Format("{0}\\{1}", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "productplanningquery.xml");
var pathForCurrentApp = string.Format("{0}\\{1}", Environment.CurrentDirectory, "productplanningquery.xml");
I want to expose some of the web.config settings to a user via the front end of the web app. I can retrieve the settings without a problem, but when I save I either get an error or the changes are not persisted to the web.config file. I am debugging in VS.
If I run this:
private void SaveWebConfig()
{
Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~//Web.config");
webConfig.AppSettings.Settings["DocumentPath"].Value = this.txtDocumentsDirectory.Text;
webConfig.Save();
}
I get the following error:
A configuration file cannot be created for the requested Configuration object.
If I run this code, nothing happens:
private void SaveWebConfig()
{
Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~//Web.config");
webConfig.AppSettings.Settings["DocumentPath"].Value = this.txtDocumentsDirectory.Text;
webConfig.SaveAs("~//Web.config");
}
To my knowledge the web.config should not be altered by the consuming web application. ASP.NET and IIS are built to restart the whole application every time the web.config is updated.
Instead of exposing it expose settings from the database and persist these settings in the db, your front end should not change much only the way you load and save data does.
It can be done, and it is rather easy. Whether it works depends on the privileges of the user account that your App runs under.
You are using double forward slashes, and the SaveAs is wrong too. Try:
private void SaveWebConfig()
{
Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~");
webConfig.AppSettings.Settings["DocumentPath"].Value =
this.txtDocumentsDirectory.Text;
webConfig.Save();
}
But you probably should avoid changing the (root) web.config as much as possible. I've only seen this in special pages for the SiteManager to make config changes.