Can somebody tell me how to set the global system.net/mailSettings configuration in ASP.NET?
If I change it in the GUI of IIS Manager the file:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
is changed.
Is there a way to access this file via the Microsoft.Web.Administration namespace?
I got it:
System.Configuration.Configuration webconfig = System.Web.Configuration.WebConfigurationManager.OpenMachineConfiguration();
System.Net.Configuration.MailSettingsSectionGroup mailSection = webconfig.GetSectionGroup("system.net/mailSettings") as System.Net.Configuration.MailSettingsSectionGroup;
mailSection.Smtp.From = "aspx#defaultmail.com";
mailSection.Smtp.Network.Host = Service.Config.SMTP_SERVER;
mailSection.Smtp.Network.Port = Service.Config.SMTP_PORT;
webconfig.Save(System.Configuration.ConfigurationSaveMode.Modified);
Related
I create release pipeline on Azure DevOps server and i have a some problem.
How i can change properties in .net core configuration file (appsettings.EnvName.json).
When I create application on framework I had parameters.xml where I set XPath to value, default value and property name. And on pipeline I set key-value. But on net core app this method don't work =)
I want to use about the same approach. What would I indicate the path to the value and its value. For example:
ConnectionStrings.Db1="Server={DB1.Server};Database={DB1.DbName};Trusted_Connection = True;"
ConnectionStrings.Db2="Server={DB2.Server};Database={DB2.DbName};Trusted_Connection = True;"
Now I have added a step to execute an arbitrary powershell script on a remote server
$jsonFile = 'appsettings.Template.json'
$jsonFileOut = 'appsettings.Production.json'
$configValues =
'ConnectionStrings.Db1="Server={DB1.Server};Database={DB1.DbName};Trusted_Connection = True;"',
'ConnectionStrings.Db2="Server={DB2.Server};Database={DB2.DbName};Trusted_Connection = True;"'
$config = Get-Content -Path $jsonFile | ConvertFrom-Json
ForEach ($item in $configValues)
{
$kv = $item -split "="
Invoke-Expression $('$config.' + $kv[0] + '="' + $kv[1] + '"')
}
$config | ConvertTo-Json | Out-File $jsonFileOut
But I don’t really like this solution, how can I do the same in a more beautiful way
dotnet core handles this in a different way. Full framework based on app.config transformation. It means that you defined one file which later was trasnformed for given build configuration (like Debug, Release, or your own). In dotnet core you define appsettings.json for each environment. This works very well because all settings are in your compiled app. And then at runtime bases on ASPNETCORE_ENVIRONMENT environment variable a proper settings is selected. Thus you may have one package for your all environments without recompilation. To benefit from that you must define file per each enviroment, but this is not transformation. This is full file.
For instance file for your local development may look like this:
{
"ConnectionStrings": {
"BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
},
}
And file for your dev enviroment appsettings.dev.json like this:
{
"ConnectionStrings": {
"BloggingDatabase": "Server=102.10.10.12\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
},
}
And then to configure loading this file you have to have configured Startup method:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
This will load all your appsettings file and later use proper file based on enviroment variable.
To set this variable you may use this command in command prompt setx ASPNETCORE_ENVIRONMENT Dev or this in Powershell [Environment]::SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Dev", "Machine")
I hope it help you understand how settings works on dotnet core. If you need more guidance please check this links:
Configuration in ASP.NET Core
Use multiple environments in ASP.NET Core
To sum up you don't need to change your settings in release pipeline. You need to preapre full file per enviromnet where you are going to host your app. You can be interested in replacing some values in file based on variables in your pipeline. You can consider few options here like
token replacement
JSON variable substitution example
This is usefult when you don't want to keep your secrets directly in source code.
EDIT
If you want to replace values in you appsettings file one of the option is token replace. For this you must first instead of values keep token in your file. For instance #{SomeVariable}# will be replaced with value of SomeVariable` from your pipeline for this confirguration of token replace task.
I am trying to create wordpress web application on Azure with Terraform. Each web app has own database. I manage to create resource groups, database server and databases but i cannot create wordpress web app. I can create a web app and all works fine but not wordpress. When i make wordpress web app manually and import data to see what is different i see that wordpress has repo_url and branch pointing to wordpress-azure repo on github. When i try to incorporate this in code i get error message.
resource "azurerm_mysql_database" "testtt" {
name = "testtt"
resource_group_name = azurerm_resource_group.RG_mok_2024.name
server_name = azurerm_mysql_server.wp-db-mok-2024.name
charset = "utf8"
coll`enter code here`ation = "utf8_unicode_ci"
}
resource "azurerm_app_service" "testtt" {
name = "testtt"
location = azurerm_resource_group.RG_mok_2024.location
resource_group_name = azurerm_resource_group.RG_mok_2024.name
app_service_plan_id = azurerm_app_service_plan.appserviceplan-wordpress-mok-6.id
site_config {
dotnet_framework_version = "v4.0"
scm_type = "GitHub"
default_documents = ["Default.htm","Default.html","Default.asp","index.htm","index.html","iistart.htm","default.aspx","index.php","hostingstart.html"]
}
source_control {
repo_url = "https://github.com/azureappserviceoss/wordpress-azure"
branch = "master"
}
connection_string {
name = "defaultConnection"
type = "MySQL"
value = "Database=testtt;Data Source=wp-db-mok-2024.mysql.database.azure.com;User Id=mysqladminun#wp-db-mok-2024;Password=password"
}
}
The error message i get when i am using source_control part of a code is
Error: "source_control": this field cannot be set
The source_control field is only exported. It cannot be used to connect a deploymentsource.
To execute an automated deployment directly, there is currently only the workaround via a local-exec null_resource.
The sourcecontrol integration can be created using an azure cli / powershell script which is then executed by the local-exec provisioner.
This works as follows:
resource "null_resource" "scm_integration" {
provisioner "local-exec" {
command = "${path.module}/enable_scm.ps1 -webAppName ${azurerm_app_service.testtt.name} -appResourceGroupName ${azurerm_resource_group.RG_mok_2024.name} -scmBranch master -repoUrl https://github.com/azureappserviceoss/wordpress-azure"
interpreter = ["pwsh", "-Command"]
}
}
In addition you need the powershell script enable_scm.ps1.
In this GitHub Issue the workaround incl. script is described completely
According to terraform doc about azurerm app service, the field source_control is only exported. And it is ONLY exported when the scm_type is set to LocalGit. You have set it to GitHub, and it is an output value, so according to the documentation, you dont need that.
Furthermore in line 6 there is enter code here but I guess that this was pasted here by accident.
Finally, I hope that in the connection string value, your database password is not "password".
Can you try to set the source_control section before the site_config? There is an open issue for the Terraform azurerm_app_service provider that suggests this might be a work-around.
https://github.com/terraform-providers/terraform-provider-azurerm/issues/3696
How to find the Config File location via ConfigurationManager?
I have the ConfigurationManager class in code and I'm debugging it. I'd like to know to which config file it's pointing to (web.config or app.config, etc).
Is there any property or method on the ConfigurationManager that can help with this?
The configuration file itself is represented by Configuration object. To get this object, run this:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Then you can view the file path via config.FilePath.
Update. As pointed out by Schadensbegrenzer for web application you will need another code to load the config file:
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
I have the following code to read the 'loggingConfiguration' from web.config file that is using EntLib 4.0
Configuration entLibConfig =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration
(#"/Web.config");
LoggingSettings loggingSettings =
(LoggingSettings)entLibConfig.GetSection(LoggingSettings.SectionName);
The loggingSettings object is null after the 2nd line executes.
Any suggestions on what is going wrong here?
ExeConfigurationFileMap exc = new ExeConfigurationFileMap();
exc.ExeConfigFilename = #"Web.exe.config";
Configuration _config = ConfigurationManager.OpenMappedExeConfiguration(exc,ConfigurationUserLevel.None);
LoggingSettings log = _config.GetSection("loggingConfiguration") as LoggingSettings;
Try this, it works for me.
The reason why you get null returned for LoggingSettings is that there is no LoggingSettings configured in the web.config that you are opening. This is probably because the path specified is incorrect.
I have a web appliation set up with 2 web.configs: The first in the root and the second in a Config folder.
/Root
web.config
/Root/Config
web.config
The web.config in the Config folder contains the LoggingSettings. The code to read the LoggingSettings from a page that is not located in the Config folder is:
Configuration entLibConfig =
WebConfigurationManager.OpenWebConfiguration(#"~/Config");
LoggingSettings loggingSettings =
(LoggingSettings)entLibConfig.GetSection(LoggingSettings.SectionName);
This should work in the Development Web Server as well as IIS.
OK so we have something that is currently using OpenExeConfiguration for reading a config file, however this doesn't work when running in the web context.
I've tried a variety of different ways of opening the web.config programmatically but I can't seem to get it to read the correct web.config file. In case it matters I am currently debugging it in VS 2008.
1. config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(System.Web.HttpContext.Current.Request.ApplicationPath);
2. config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = "web.config" }, ConfigurationUserLevel.None);
3. config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
4. config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
5. System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
It either opens up the wrong config file (either the machine config, or the VS /IDE/Web.config) or complains about the error:
{System.Configuration.ConfigurationErrorsException: An error occurred loading a configuration file: Failed to map the path '/'. ---> System.InvalidOperationException: Failed to map the path '/'.
Edit -
OK so a combination of
config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
AND running Visual Studio 2008 As Administrator worked. Am hoping we don't run into security/permission issues when we deploy to our web server / client environments!
So in the end I used this code (had to handle whether the web application was running, or if our unit test code was running).
System.Configuration.Configuration config = null;
if (System.Web.HttpContext.Current != null && !System.Web.HttpContext.Current.Request.PhysicalPath.Equals(string.Empty))
config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
else
config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Also have to be running Visual Studio in Administrator mode - which I found out you can set as a property on your shortcut so you don't need to remember each time in Windows 7 to right click and run as administrator :)