how to override local connection string with azure connection string - azure

I am using appsettings.json in .Net core project for connection string. My connection string is :
"ConnectionStrings": {
"OT_DB_Connection": "Data Source=108.***.**.**;Initial Catalog=O*******s;User ID=O*******s;Password=O*********$"
},
In startup.cs i am accessing connection string with key like this
options.UseSqlServer(Configuration.GetConnectionString("OT_DB_Connection"));
I deployed this code on azure and i have sql database on azure.
After deployment how my website will use the connection string of azure ?
How to override the local connection string with azure connection string at run time.

You should read the following article:
Multiple Environment Configuration Files in ASP.NET Core
You can have multiple appSettings e.g. 1 for you local environment and 1 for Azure etc. When you publish your app to Azure, you can add an application setting called ASPNETCORE_ENVIRONMENT and add a value that maps to your environment for your app to pick up the correct configuration. If you have an appSettings.Azure.json file you can set ASPNETCORE_ENVIRONMENT to Azure and it will use that configuration file.
If you do not want to take this approach, you can also override the connection string directly in Azure as show in the picture below. This is accessible under your app service -> Application Settings -> Connection Strings. You will want to override OT_DB_Connection.

Related

Azure Static Web App - Function App API - How to load IOptions?

Everything is working locally still using storage in Azure. The local settings file to load the IOptions are:
"StorageOptions": {
"ConnectionString": "...xxx..."
}
The static web app is hitting the API and getting a 500 error due to not being able to load the connection string settings from the application settings. Other API calls that do not use Azure storage are working as expected.
I am unable to save the static web app settings in the normal manner of StorageOptions:ConnectionString with the specified value.
Can API settings for Azure static web apps use the IOptions pattern? If yes, how should the application settings be added in Azure to load the IOptions properly?
The static web app is hitting the API and getting a 500 error due to not being able to load the connection string settings from the application settings.
Application settings for the static web app does not allow for ":" in the setting name. So, instead of using "StorageOptions:ConnectionString" it would be "StorageOptions__ConnectionString" for the hierarchical data binding.
Noted here in step 4 of "Configure app settings": https://learn.microsoft.com/en-us/azure/app-service/configure-common?tabs=portal
If yes, how should the application settings be added in Azure to load the IOptions properly?
I found an issue in the SO 70461295 where user #HariKrishna and #GaryChan given that the Application Settings are available only for the Azure Static Web App associated backend APIs.
If using dependency injection for configuring the application settings through Azure Static Web Apps - Azure Functions Context, then Option pattern is available which is returned when the functionality is required.
Your given format of Application Settings:
"StorageOptions": {
"ConnectionString": "...xxx..."
}
Then, you have to configure inside the Startup.Configure method such as:
builder.Services.AddOptions<StorageOptions>()
.Configure<IConfiguration>((settings, configuration) =>
{
configuration.GetSection("StorageOptions").Bind(settings):
});
Updated Answer:
 As #BretOoten mentioned that the hierarchical data binding in azure static web apps configuration is possible with double underscore (__), even in the azure functions the nested objects/configuration from local.settings.json file is called with the double underscore (__) as mentioned in this MS Doc.
 For example:  
"WebApp1": {
"Storage1": {
"ConnString": value
}
}  
configuration will be like: 
WebApp1__Storage1__ConnString

Dummy Connection String Stopped Working When the Azure Web App was Migrated to .Net 6

We have a Web Api 2 application that is using .Net Framework 4.6.1. Since we don't want our connection string to be exposed, the app has a dummy connection string in web.config when deployed to Azure App Service.
That dummy connection string is being overridden by the connection string in Azure App Service Configuration. See this article: https://mohitgoyal.co/2017/07/05/update-connection-string-for-entity-framework-in-azure-web-app-settings/
It stopped working when we migrated to Asp.Net Core using .Net 6.
I have tried moving it to app.config but it still doesn't work.
We are still using Entity Framework 6 on .Net 6 and the connection string is being referenced in the constructor.
public AppDBContext() : base("name=AppDBContext")
{
}
This is why we need to have our connection string in a config xml file rather than in the appsettings.json.
My questions are:
Shouldn't azure app service treat app.config the same way it treats web.config?
Should we change the way we reference the connection string so that we can read from the Azure AppService Configuration?
When we create Asp. Net Core Web App using .Net 6, appsettings.json file will be created.
Add your Connection String in appsettings.json
My appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Your Connection String"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
My Program.cs
var builder = WebApplication.CreateBuilder(args);
string connString = builder.Configuration.GetConnectionString("DefaultConnection");
Shouldn't azure app service treat app.config the same way it treats web.config?
app.config is available in Console and Windows applications, whereas .NET Core Applications will have appsettings.json file to store connection strings and other Environment Variables.
The setting in appsettings.json will be overrided by Environment variables added in Azure App Settings .
Make sure your Connection String name in Azure App settings is same as in appsettings.json file.
Connection String in Azure App Settings

Azure - WebJobs - Use remote connection string

I have WebJobs running under my Azure Web App. For Web App you can set that the Web App will use remote connection strings (that you setup on Azure portal).
Is it possible to do the same for WebJobs?
So they would be looking for remote connection string instead of using a connections string from (for example) "app.config".
Could you add the connection string as Web Config value that can be accessed by either the site or webjob?
Further more details you could refer to this blog:Configuring Azure Web Jobs.
The main steps are as follows:
Install CloudConfigurationManager package Microsoft.WindowsAzure.ConfigurationManager
Set your connection strings to the app setting.
Retrieve connection string using the CloudConfigurationManager:
var myConnectionString = CloudConfigurationManager.GetSetting("MyConnectionString");
I found out that a connection string setup on Azure Portal overwrites connection string with the same name in .config files. Which means that no additional setup is required.
Azure Portal Connection string takes priority over local *.config connection string.
I successfully tested this.

How can I connect my azure function with my azure sql

I developed a cron trigger azure fuction who needs to search for soe data in my database.
Localy i can connect whit sql server, so i change the connection string in loca.settings.json to connect in azure sql and published the function, but the function cant connect with database.
I need to do something more than configure the local.settings.json?
The local.settings.json is only used for local testing. It's not even exported to azure.
You need to create a connection string in your application settings.
In Azure Functions - click Platform features and then Configuration.
Set the connection string
A function app hosts the execution of your functions in Azure. As a best security practice, store connection strings and other secrets in your function app settings. Using application settings prevents accidental disclosure of the connection string with your code. You can access app settings for your function app right from Visual Studio.
You must have previously published your app to Azure. If you haven't already done so, Publish your function app to Azure.
In Solution Explorer, right-click the function app project and choose Publish > Manage application settings.... Select Add setting, in New app setting name, type sqldb_connection, and select OK.
Application settings for the function app.
In the new sqldb_connection setting, paste the connection string you copied in the previous section into the Local field and replace {your_username} and {your_password} placeholders with real values. Select Insert value from local to copy the updated value into the Remote field, and then select OK.
Add SQL connection string setting.
The connection strings are stored encrypted in Azure (Remote). To prevent leaking secrets, the local.settings.json project file (Local) should be excluded from source control, such as by using a .gitignore file.
https://learn.microsoft.com/en-us/azure/azure-functions/functions-scenario-database-table-cleanup
If you are using entity framework core to make a connection, Other Way of connection to SQL is by using dependency injection from .netcore library.
You can keep the connection string in Azure Key-vault or the config file from there you can read the same using azure function startup class. which need below code setup in your function app.
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
[assembly: FunctionsStartup(typeof( TEST.Startup))]
namespace TEST
{
internal class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
Contract.Requires(builder != null);
builder.Services.AddHttpClient();
var configBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddAzureKeyVault($"https://XYZkv.vault.azure.net/");
var configuration = configBuilder.Build();
var conn = configuration["connectionString"];
builder.Services.AddDbContext<yourDBContext>(
options => options.UseSqlServer(configuration["connectionString"]));
}
}
}
after that where ever you are injecting this dbcontext, with context object you can do all CRUD operations by following microsoft's entity framework core library documentation.
Having just dealt with this beast (using a custom handler with Linux), I believe the simple way is to upgrade your App to premium-plan, allowing you to access the "Networking" page from "App Service plans". This should allow you to put both sql-server and app in the same virtual network, which probably makes it easier. (but what do I know?)
Instead, if you don't have the extra cash laying around, you can try what I did, and set up a private endpoint, and use the proxy connection setting for your database:
Create a virtual network
I used Address space: 10.1.0.0/16 (default I think)
Add subnet 10.1.0.0/24 with any name (adding a subnet is required)
Go to "Private link center" and create a private endpoint.
any name, resource-group you fancy
use resource type "Microsoft.Sql/Server" and you should be able to select your sql-server (which I assume you have created already) and also set target sub-resource to "sqlServer" (the only option)
In the next step your virtual network and submask should be auto-selected
set Private DNS integration to yes (or suffer later).
Update your firewall by going to Sql Databases, select your database and click "Set Server Firewall" from the overview tab.
Set Connection Policy to proxy. (You either do this, or upgrade to premium!)
Add existing virtual network (rule with any name)
Whitelist IPs
There probably is some other way, but the azure-cli makes it easy to get all possible IP's your app might use: az functionapp show --resource-group <group_name> --name <app_name> --query possibleOutboundIpAddresses
https://learn.microsoft.com/en-us/azure/app-service/overview-inbound-outbound-ips
whitelist them all! (copy paste exercise)
Find your FQDN from Private link center > Private Endpoints > DNS Configuration. It's probably something like yourdb.privatelink.database.windows.net
Update your app to use this url. You just update your sql server connection string and replace the domain, for example as ADO string: Server=tcp:yourdb.privatelink.database.windows.net,1433;Initial Catalog=somedbname;Persist Security Info=False;User ID=someuser;Password=abc123;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30;
Also note that I at some point during all of this I switched to TrustServerCertificate=True and now I can't bother to figure out if it does a difference or not. So I left it as an exercise to the reader to find out.
So what we have done here...?
We have forced your function app to go outside the "azure-sphere" by connecting to the private endpoint. I think that if you bounce between azure-services directly, then you'll need some sort of authentication (like logging in to your DB using AD), and in my case, using custom handler and linux base for my app, I think that means you need some trust negotiation (kerberos perhaps?). I couldn't figure that out, so I came up with this instead.

Azure WebJobs SDK ServiceBus connection string 'AzureWebJobsAzureSBConnection' is missing or empty

I created an Azure Function App in Visual Studio 2015. The App has a trigger for service bus queues. The app works perfectly when I run it locally. It is able to read the data from the Service Bus queue (configured via a variable named AzureSBConnection) and log it in my database.
But it gives me the following error when deployed in Azure:
Function ($ServiceBusQueueTriggerFunction) Error: Microsoft.Azure.WebJobs.Host: Error indexing method 'Functions.ServiceBusQueueTriggerFunction'. Microsoft.Azure.WebJobs.ServiceBus: Microsoft Azure WebJobs SDK ServiceBus connection string 'AzureWebJobsAzureSBConnection' is missing or empty.
Note that my connection is called AzureSBConnection and not AzureWebJobsAzureSBConnection. Also, the connection works locally. And finally, the deployed file looks exactly like the local file.
The Visual Studio structure looks like the following:
The function.json file has a bunch of settings as shown below:
Then in the Appsettings.json file, I have the following:
For deploying, I FTPed the files to the D:\home\site\wwwroot location for my Function App in Azure. The final structure in Kudu looks like:
And if I go inside my function folder:
Here is the deployed function.json:
And here is the deployed appsettings:
The deployed json files are exactly the same as the local files. But the deployed version is erroring out because of the missing AzureWebJobsAzureSBConnection. What am I doing wrong?
Only environment variables are supported for app settings and connection strings.
You need to make sure that the environment variable AzureWebJobsAzureSBConnection is set on your Function's app settings in the portal:
and then once there, you need to add the AzureWebJobsAzureSBConnection variable with the proper connection string:
and then you can access this via code by:
Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
This will obtain the value from either the appsettings.json or the environment variable depending on where the function is being executed from, (local debugging or deployed on Azure)
It is able to read the data from the Service Bus queue (configured via a variable named AzureSBConnection) But it gives me the following error when deployed in Azure:
After you deployed your application to Azure Function, your application will read the connection string from environment setting. Currently, connection settings in appsettings.json will not update environment setting automatically. We could click [Configure app settings] button as #flyte mentioned to check whether the connection string is configured successfully. If not, you could add it manually in app setting box.
Note that my connection is called AzureSBConnection and not AzureWebJobsAzureSBConnection
Please go to [Integrate] page to check whether the [Service Bus connection] is configured successfully. If not, you could reset it by clicking the [new] link.

Resources