0% found this document useful (0 votes)
32 views16 pages

Aspnet Azure Build Pipeline

The document outlines methods to inject a connection string into an ASP.NET application running on Azure, specifically during the Azure DevOps Build Pipeline. It details three methods: using Azure DevOps Variable Substitution, modifying web.config with a PowerShell script, and utilizing Azure App Service Configuration for better security and flexibility. Additionally, it provides guidance on reading app settings from environment variables and dynamically modifying the Initial Catalog in the connection string.

Uploaded by

Kamran Qadir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views16 pages

Aspnet Azure Build Pipeline

The document outlines methods to inject a connection string into an ASP.NET application running on Azure, specifically during the Azure DevOps Build Pipeline. It details three methods: using Azure DevOps Variable Substitution, modifying web.config with a PowerShell script, and utilizing Azure App Service Configuration for better security and flexibility. Additionally, it provides guidance on reading app settings from environment variables and dynamically modifying the Initial Catalog in the connection string.

Uploaded by

Kamran Qadir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

aspnet azure build pipeline, inject webconfig connection string

ChatGPT said:

ChatGPT

In an ASP.NET application running on Azure, you can inject a connection string into the
web.config file dynamically during your Azure DevOps Build Pipeline using one of the following
methods:

Method 1: Use Variable Substitution in Azure DevOps

Azure DevOps provides a built-in way to replace values in web.config without modifying the file
manually.

Steps:

1. Define the Connection String in Azure DevOps

o Go to Azure DevOps → Pipelines → Library → Variable Groups (or define it directly


in the pipeline).

o Add a new variable (e.g., MyConnectionString) with your database connection


string.

o Make sure to mark it as a secret if it contains sensitive information.

2. Enable Variable Substitution in the Pipeline

o Add a "File Transform" task in your Azure DevOps pipeline:

yaml

CopyEdit

- task: FileTransform@1

inputs:

folderPath: '$(Build.ArtifactStagingDirectory)'

xmlTransformation: false

xmlVariableSubstitution: true

3. Ensure Your web.config Has a Placeholder Modify your web.config to have a


placeholding connection string:

xml

CopyEdit

<connectionStrings>
<add name="DefaultConnection" connectionString="__MyConnectionString__"
providerName="System.Data.SqlClient"/>

</connectionStrings>

4. Define a Variable in the Pipeline In Azure DevOps → Pipelines, set the variable:

yaml

CopyEdit

variables:

MyConnectionString: "Server=myserver.database.windows.net;Database=mydb;User
Id=myuser;Password=mypassword;"

The pipeline will automatically replace __MyConnectionString__ with the actual value.

Method 2: Modify web.config Using a PowerShell Script

If you need more control, you can use PowerShell to update web.config dynamically.

Add a PowerShell Task in Your Pipeline

yaml

CopyEdit

- task: PowerShell@2

displayName: "Update web.config Connection String"

inputs:

targetType: 'inline'

script: |

[xml]$xml = Get-Content "$(Build.SourcesDirectory)/YourProject/web.config"

$xml.configuration.connectionStrings.add | Where-Object { $_.name -eq "DefaultConnection" } |


ForEach-Object { $_.connectionString = "$(MyConnectionString)" }

$xml.Save("$(Build.SourcesDirectory)/YourProject/web.config")

Make sure to define MyConnectionString as a secret variable in Azure DevOps.

Method 3: Use Azure App Service Configuration (Recommended)

If you are deploying to Azure App Service, a better approach is to override the connection string
at runtime instead of modifying web.config.
Steps:

1. Go to Azure Portal → Your App Service → Configuration.

2. Under Connection Strings, add a new setting:

o Name: DefaultConnection

o Value: Server=myserver.database.windows.net;Database=mydb;User
Id=myuser;Password=mypassword;

o Type: SQLAzure

3. Azure will automatically inject this value into your application at runtime, overriding
web.config.

Which Method to Choose?

Method Use Case

Simple and built-in, works well for build-time


Azure DevOps Variable Substitution
updates

PowerShell Script More control if you need custom logic

Azure App Service Configuration Best for security and flexibility, no need to modify
(Recommended) web.config

Let me know which approach works best for you, or if you need any clarifications!

4o

You said:

show code to load from Azure App Service Configuration in case of Entity Framework

ChatGPT said:

ChatGPT

If you are using Entity Framework in your ASP.NET application and want to load the connection
string from Azure App Service Configuration, you don’t need to modify web.config. Azure
automatically injects connection strings set in Azure App Service → Configuration at runtime.

However, in an Entity Framework DbContext, you should ensure it reads from


ConfigurationManager or IConfiguration.

Option 1: For ASP.NET MVC / Web API (.NET Framework)

If you are using Entity Framework 6 (EF6) or earlier in a .NET Framework application:
1. Set the connection string in Azure App Service:

o Go to Azure Portal → App Service → Configuration → Connection Strings.

o Add a new connection string with:

 Name: DefaultConnection

 Value: Server=myserver.database.windows.net;Database=mydb;User
Id=myuser;Password=mypassword;

 Type: SQLAzure (This ensures it is injected into web.config at runtime).

2. Modify web.config to use the name:

xml

CopyEdit

<connectionStrings>

<add name="DefaultConnection" connectionString="" providerName="System.Data.SqlClient"


/>

</connectionStrings>

3. Load it in your DbContext class:

csharp

CopyEdit

using System.Data.Entity;

using System.Configuration;

public class MyDbContext : DbContext

public MyDbContext() :
base(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)

public DbSet<MyEntity> MyEntities { get; set; }

Since Azure injects the connection string at runtime, ConfigurationManager will load it.
Option 2: For ASP.NET Core (EF Core)

If you are using Entity Framework Core (EF Core) in an ASP.NET Core application:

1. Set the connection string in Azure App Service:

o Go to Azure Portal → App Service → Configuration → Connection Strings.

o Add a new connection string:

 Name: DefaultConnection

 Value: Server=myserver.database.windows.net;Database=mydb;User
Id=myuser;Password=mypassword;

 Type: SQLAzure.

2. Modify appsettings.json (optional, just a placeholder for local development):

json

CopyEdit

"ConnectionStrings": {

"DefaultConnection":
"Server=(localdb)\\mssqllocaldb;Database=MyLocalDb;Trusted_Connection=True;"

3. Load the connection string in Program.cs:

csharp

CopyEdit

using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Load from Azure App Configuration (overrides appsettings.json)

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");


builder.Services.AddDbContext<MyDbContext>(options =>

options.UseSqlServer(connectionString));

var app = builder.Build();

app.Run();

Which Method Should You Use?

Framework Code

.NET
Framework Use
(MVC/Web ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString
API, EF6)

ASP.NET Core
Use builder.Configuration.GetConnectionString("DefaultConnection")
(EF Core)

This ensures your application reads the Azure-injected connection string at runtime instead of
hardcoding it.

Let me know if you need further refinements!

4o

You said:

ASP.NET MVC .NET Framework read appsetting from enviroment variable

ChatGPT said:

ChatGPT

In an ASP.NET MVC (.NET Framework) application, you can read app settings from environment
variables instead of web.config. This is useful when deploying to Azure App Service, as it allows
you to override settings without modifying the web.config file.

1. Set the Environment Variable in Azure App Service

1. Go to Azure Portal → Your App Service → Configuration.

2. Under Application settings, click New application setting.

3. Add a new setting:

o Name: MySetting
o Value: SomeValue

4. Click Save.

2. Read the Environment Variable in ASP.NET MVC (.NET Framework)

Modify your code to read from the environment variable instead of web.config.

Using Environment.GetEnvironmentVariable

csharp

CopyEdit

string mySetting = Environment.GetEnvironmentVariable("MySetting");

This reads MySetting from environment variables.

3. Fallback to web.config (Optional)

If the environment variable is not set, you may want to fallback to web.config:

csharp

CopyEdit

string mySetting = Environment.GetEnvironmentVariable("MySetting")

?? ConfigurationManager.AppSettings["MySetting"];

Modify web.config (Optional)

If you want a fallback, ensure web.config has:

xml

CopyEdit

<appSettings>

<add key="MySetting" value="DefaultValue"/>

</appSettings>

4. Example: Using in a Controller

csharp

CopyEdit

using System;
using System.Configuration;

using System.Web.Mvc;

public class HomeController : Controller

public ActionResult Index()

string mySetting = Environment.GetEnvironmentVariable("MySetting")

?? ConfigurationManager.AppSettings["MySetting"];

ViewBag.MySetting = mySetting;

return View();

5. Using it in Dependency Injection (e.g., for a Service)

If you have a service that needs this setting:

csharp

CopyEdit

public class MyService

private readonly string _mySetting;

public MyService()

_mySetting = Environment.GetEnvironmentVariable("MySetting")

?? ConfigurationManager.AppSettings["MySetting"];

}
public string GetSetting()

return _mySetting;

Why Use Environment Variables?

More Secure – No sensitive info in web.config


Easier Deployment – Change settings in Azure without redeploying
Better CI/CD Integration – Works well with DevOps pipelines

Let me know if you need further refinements!

4o

You said:

For ASP.NET MVC / Web API (.NET Framework), instead of connection string tranform initial catalog

ChatGPT said:

ChatGPT

If you want to transform only the Initial Catalog (database name) in your connection string
dynamically at runtime without modifying the entire connection string, you can update it using
environment variables or configuration settings.

Method 1: Modify Only Initial Catalog at Runtime (Recommended)

Instead of replacing the full connection string, extract it from web.config, modify only the Initial
Catalog, and use it in Entity Framework.

1. Define the Connection String in web.config

xml

CopyEdit

<connectionStrings>

<add name="DefaultConnection"

connectionString="Server=myserver.database.windows.net;Initial Catalog=OldDatabase;User
Id=myuser;Password=mypassword;"

providerName="System.Data.SqlClient" />
</connectionStrings>

2. Modify Initial Catalog in DbContext Constructor

In your DbContext class, dynamically change the database name:

csharp

CopyEdit

using System;

using System.Configuration;

using System.Data.SqlClient;

using System.Data.Entity;

public class MyDbContext : DbContext

public MyDbContext() : base(GetUpdatedConnectionString())

public DbSet<MyEntity> MyEntities { get; set; }

private static string GetUpdatedConnectionString()

// Read the connection string from web.config

string connStr =
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

// Get the new database name from an environment variable or app setting

string newDatabaseName = Environment.GetEnvironmentVariable("NewDatabaseName")

?? ConfigurationManager.AppSettings["NewDatabaseName"];
if (!string.IsNullOrEmpty(newDatabaseName))

// Parse and update the Initial Catalog dynamically

var builder = new SqlConnectionStringBuilder(connStr)

InitialCatalog = newDatabaseName

};

return builder.ConnectionString;

return connStr; // Return the original if no override exists

3. Set the New Database Name in Azure App Service

1. Azure Portal → Your App Service → Configuration

2. Under Application settings, click New application setting

3. Key: NewDatabaseName

4. Value: NewDatabase

5. Click Save

Now, the application will automatically update Initial Catalog at runtime while keeping the rest of
the connection string unchanged.

Alternative: Transform Connection String Using Azure DevOps Pipeline

If you want to transform Initial Catalog during the build pipeline, modify it using PowerShell in an
Azure DevOps pipeline:

yaml

CopyEdit

- task: PowerShell@2
displayName: "Modify Initial Catalog in web.config"

inputs:

targetType: 'inline'

script: |

[xml]$xml = Get-Content "$(Build.SourcesDirectory)/Web.config"

$connStrNode = $xml.configuration.connectionStrings.add | Where-Object { $_.name -eq


"DefaultConnection" }

if ($connStrNode -ne $null) {

$connStrNode.connectionString = $connStrNode.connectionString -replace "Initial


Catalog=\w+", "Initial Catalog=$(NewDatabaseName)"

$xml.Save("$(Build.SourcesDirectory)/Web.config")

 Define NewDatabaseName as a pipeline variable or use an Azure DevOps variable group.

Which Method to Choose?

Method Use Case

Modify at runtime
If you need dynamic database switching without redeployment
(Recommended)

Transform in Azure DevOps If the database is fixed per deployment and doesn’t change at
pipeline runtime

Let me know if you need further adjustments!

4o

You said:

Keyword not supported: 'metadata'

ChatGPT said:

ChatGPT

The error "Keyword not supported: 'metadata'" typically occurs when Entity Framework (EF)
attempts to parse an incorrect connection string format. This usually happens when EF6 (or EF
Core) is expecting a standard SQL Server connection string but instead receives an Entity
Framework-specific metadata connection string.
Possible Causes and Fixes

1. Using the Wrong Connection String for Entity Framework

If you are using Entity Framework with a standard SQL Server connection, your connection string
should NOT contain metadata=....

Correct SQL Server Connection String (for EF6 & EF Core)

xml

CopyEdit

<connectionStrings>

<add name="DefaultConnection"

connectionString="Server=myserver.database.windows.net;Database=mydb;User
Id=myuser;Password=mypassword;"

providerName="System.Data.SqlClient" />

</connectionStrings>

If you accidentally used an Entity Framework Database-First connection string, it might look like
this:

xml

CopyEdit

<connectionStrings>

<add name="DefaultConnection"

connectionString="metadata=res://*/Models.MyModel.csdl|res://*/Models.MyModel.ssdl|res://*/M
odels.MyModel.msl;

provider=System.Data.SqlClient;

provider connection string='data source=myserver.database.windows.net;initial


catalog=mydb;user
id=myuser;password=mypassword;multipleactiveresultsets=True;App=EntityFramework'" />

</connectionStrings>

This connection string contains metadata=... which is only valid for EDMX-based models
(Database-First EF6).

Fix

 If you are using Code-First EF6 or EF Core, remove the metadata=... and keep only the
provider connection string.
 If you are using Database-First (EDMX) and you don’t need the metadata=, make sure your
DbContext is initialized with only the provider connection string.

2. Fix DbContext Constructor in Code

If you are dynamically modifying the connection string (like changing Initial Catalog), make sure you
are not mistakenly modifying a metadata-based connection string.

Correct Way to Modify a Connection String Dynamically

csharp

CopyEdit

using System;

using System.Configuration;

using System.Data.SqlClient;

using System.Data.Entity;

public class MyDbContext : DbContext

public MyDbContext() : base(GetUpdatedConnectionString()) { }

public DbSet<MyEntity> MyEntities { get; set; }

private static string GetUpdatedConnectionString()

// Get the base connection string from web.config

string connStr =
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

// Ensure it's a valid SQL connection string (not metadata-based)

if (connStr.Contains("metadata="))

{
throw new InvalidOperationException("The connection string contains 'metadata=', which is
not supported in Code-First.");

// Modify only the Initial Catalog dynamically

var builder = new SqlConnectionStringBuilder(connStr)

InitialCatalog = "NewDatabaseName" // Change this dynamically if needed

};

return builder.ConnectionString;

3. If You Are Using metadata= (EDMX Approach)

If you must use the metadata connection string (e.g., in Database-First EF6), ensure you pass the
entire metadata connection string to DbContext:

csharp

CopyEdit

public class MyDbContext : DbContext

public MyDbContext() : base("name=DefaultConnection") { }

 Do NOT modify metadata= connection strings dynamically.

 Ensure web.config contains the correct metadata path.

Final Thoughts

If you're getting the metadata error:

Use a correct connection string format based on whether you are using Code-First or
Database-First.
Ensure DbContext is initialized properly and not modifying an EDMX-based connection string.
If modifying Initial Catalog, ensure you start with a valid SQL Server connection string (not
metadata=).

Let me know if you need further clarification!

4o

You might also like