14

In my Azure Function I am using a Library which establishes a connection to an SQL server via the ConnectionString from the ConfigurationManager like this:

var cs = System.Configuration.ConfigurationManager.ConnectionStrings["DbConString"].ConnectionString;
DbConnection connection = new SqlConnection(cs);

Now when i set the connection string DbConString in the portal via the Application Settings everything is working fine. But for local development I use the azure-functions-cli and unfortunately I have no idea where i should place the connection string to have it loaded correctly via the ConfigurationManager.

I've tried to place it in the appsettings.json file but without success.

Edit: My appsettings.json currently looks like this:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "AzureWebJobsDashboard": "",
    "MyServiceBusReader": "Endpoint=sb://xxxx=",
    "DbConStr1": "data source=(localdb)\\MSSQLLocalDB;initial catalog=MyDb;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework",
    "ConnectionStrings": {
      "DbConStr2": "data source=(localdb)\\MS..." 
    } 
  }
}

But I am not able to access "DbConStr1" via the ConfigurationManager. Adding "DbConStr2" within "ConnectionStrings" like described here leads to a compilation error. Maybe because I am not using .NET Core?

Edit2: I messed up the nesting of "ConnectionStrings". It has to be on the same nesting level as "Values":

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "AzureWebJobsDashboard": "",
    "MyServiceBusReader": "Endpoint=sb://xxxx="
  },
  "ConnectionStrings": {
    "DbConStr": "data source=(localdb)\\MS..." 
  }
}
officer
  • 2,080
  • 1
  • 20
  • 29
  • Are you using .NET Core? I assume if you are using an `application.json` file you are. – awh112 Jan 30 '17 at 19:36
  • No I don't use .NET Core. I thought that using application.json is just how Azure Functions work? – officer Jan 30 '17 at 19:41
  • 1
    Actually, it looks like, at least for me, spinning up a .NET function uses v4.6 so you are correct in that it is not yet .NET Core. – awh112 Jan 30 '17 at 19:53
  • Does that mean, that it should also be possible to use an app.config instead of application.json? – officer Jan 30 '17 at 20:05
  • Azure Functions uses `.json` files by default/convention. I don't think using XML `app.config` configuration files is supported. – awh112 Jan 30 '17 at 20:10
  • 1
    Per your edit, your connection strings should definitely be under the `ConnectionStrings` node. Can you access any settings at all? I might try making sure the file is named appropriately `appsettings.json` in case your function is configured to look for that filename by convention. – awh112 Jan 30 '17 at 20:14
  • Okay, than the application.json file should be the right way. But unfortunately I can't figure out in which format i have to specify the connection string to behave identically as when setting it in the Azure portal. – officer Jan 30 '17 at 20:16
  • Maybe try using the cli commands? Looking at the official documentation it looks like `add` adds a setting to the `appsettings.json` file. Reference here: https://www.npmjs.com/package/azure-functions-cli – awh112 Jan 30 '17 at 20:32
  • First of all: thank you for your time, I appreciate your help. Now I got the connection string in the application.json to work. "ConnectionStrings" has to be in the same hierarchy as "Values". The problem that is still present is, that I don't know how to define the providerName (as in app.config) for EntityFramework. It seems that there is no possibility in application.json... – officer Jan 30 '17 at 20:45
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/134411/discussion-between-awh112-and-officer). – awh112 Jan 30 '17 at 20:59

6 Answers6

5

Add file local.setting.json

enter image description here

  {
    {
      "IsEncrypted": false,
       "Values": {
      "AzureWebJobsStorage": "UseDevelopmentStorage=true",
      "AzureWebJobsDashboard": "UseDevelopmentStorage=true",

      "tenantId": "You tenantId",
      "resource": "https://management.azure.com/",
      "ClientSecret": "You ClientSecret, Key from App Registry",
      "ClientId": "You ClientId, Application ID from App registry",

      "subscriptionId": "You subscriptionId",
      "resourceGroupName": "Your resourceGroupName",
      "serverName": " Your SQL Server",
      "databaseNameDW": "Your Database",
      "apiversion": "2017-10-01-preview"      
    }
}

In C# Code use:

private readonly static string tenantId = ConfigurationManager.AppSettings["tenantId"];
awh112
  • 1,466
  • 4
  • 22
  • 34
Israel Calderon
  • 173
  • 1
  • 2
  • 8
  • How do you push the local.setting.json ? I have deployment my azure function from a github repo so I am going to add this file in my repo. – Yassir S Oct 20 '18 at 16:32
  • 1
    in azure function v2 the ConfigurationManager.AppSettings does load NOTHING from the local.settings.json file! – HelloWorld Jul 03 '20 at 11:21
5
// C# Environment Variables example for Azure Functions v1 or v2 runtime
// This works all the way up to but not including .NET Core 2.0
var clientId = Environment.GetEnvironmentVariable("ClientId");
var clientSecret = Environment.GetEnvironmentVariable("ClientSecret");
var aadDomain = Environment.GetEnvironmentVariable("AADDomain");

Please do remember the settings you do in local.settings.json will not be reflected in azure. Please add your values in app setting from Azure portal follow the link- https://learn.microsoft.com/en-us/azure/azure-functions/functions-how-to-use-azure-function-app-settings

reach2saurabh
  • 153
  • 1
  • 11
3

I had this same issue and am using .net standard (as opposed to core). I added my settings to the Application Settings section of my Azure function (in Azure Portal):-

enter image description here

I then downloaded a zip of the function:- enter image description here

Included in this download is a copy of local.settings.json that includes my app settings in the correct json format. I then access them via ConfigurationManager.Appsettings["mysetting"]

Stephen Garside
  • 1,185
  • 10
  • 15
3

I've found a method which feels hacky, but works: if you do evaluate Environment.GetEnvironmentVariables() you can spot that all Connection Strings from your local.settings.json are available as Environment Variables with a "ConnectionStrings:" prefix if run locally, or one from several "xxxCONNSTR_" if running on Azure, so you can define this helper function:

    private static Array ConnectionStringKeyPrefixes = new[] { "ConnectionStrings:", "SQLCONNSTR_", "SQLAZURECONNSTR_", "MYSQLCONNSTR_", "POSTGRESQLCONNSTR_", "CUSTOMCONNSTR_" };
    public static string GetConnectionStringFromSettings(string connectionStringName)
    {
        string connectionString = null;

        foreach(string prefix in ConnectionStringKeyPrefixes) {
            connectionString = Environment.GetEnvironmentVariable($"{prefix}{connectionStringName}");

            if (!string.IsNullOrWhiteSpace(connectionString))
            {
                break;
            }
        }

        return connectionString;
    }
Sebastián Vansteenkiste
  • 2,234
  • 1
  • 19
  • 29
2

The problem was, that a connection string known from e.g. a Web.config file consists of two parts:

  • The connection string itself and
  • the provider name.

But since the configuration file uses the JSON format it was not possible to specify both parameters.

At the time when the question was asked, it was not possible to set the provider name in the appsetings.json (now renamed to local.settings.json). But the Azure-Functions-team change this and set a default value for providerName to System.Data.SqlClient, which solved the problem.

The providerName defaults to System.Data.SqlClient. You don't have to set it manually. Just add your connection string X and read it via ConfigurationManager.ConnectionStrings["X"].

officer
  • 2,080
  • 1
  • 20
  • 29
  • 7
    Can you provide some code or a link to show us exactly how this is achieved? – Aran Mulholland Jan 22 '18 at 07:20
  • 2
    How what is achieved? The `providerName` defaults to `System.Data.SqlClient`. You don't have to set it manually. Just add your connection string _X_ and read it via ConfigurationManager.ConnectionStrings["X"] – officer Jun 14 '18 at 10:47
  • ConfigurationManager from which namespace? – Md Aslam Oct 18 '21 at 12:11
0

You should be able to manage your configuration settings with an appsettings.json file in your project structure. You can take a look here for an example of the folder structure for Azure Functions.

Additionally, this link will have some details about how to manage configuration settings with .NET Core.

awh112
  • 1,466
  • 4
  • 22
  • 34
  • Azure Functions does not use .net core. – Wavel Mar 06 '17 at 22:25
  • 1
    It's not .NET Core yet, but it's .NET Standard 2.0 as of RTM. https://blogs.msdn.microsoft.com/appserviceteam/2017/08/14/azure-functions-tools-released-for-visual-studio-2017-update-3/ see 'Functions project type' – David De Sloovere Aug 16 '17 at 16:21