How to run Azure CLI command line application in C# web application

218 Views Asked by At

How to run Below azure cli command/Script using C# code in Web application

Below code is in featuremanager.cli file

endpoint=<<EndPoint>>
featurename=<<FeatureName>>
jsondata=$(az appconfig feature filter show --connection-string $endpoint  --feature $featurename --filter-name Microsoft.Targeting)
audiencesection=$(echo "$jsondata" | jq -r '.[].parameters.Audience')
echo $audiencesection
new_user='newuser'
file_content=$(echo "$audiencesection" | jq --arg new_user "$new_user" '.Users += [$new_user]')
echo "$file_content"
az appconfig feature filter update --connection-string $endpoint  --feature $featurename --filter-name Microsoft.Targeting --filter-parameters Audience="$file_content" --yes

Below code is in HomeController.cs file

public async Task<IActionResult> Index()
{
    ProcessStartInfo psi=new ProcessStartInfo("cmd");
    psi.UseShellExecute = false;
    psi.RedirectStandardOutput = true;
    psi.CreateNoWindow = true;
    psi.RedirectStandardInput = true;
    var proc=Process.Start(psi);

    proc.StandardInput.WriteLine(@".\featuremanager.cli");
    proc.StandardInput.WriteLine("exit");
    string s=proc.StandardOutput.ReadToEnd();
    return View();
}

When I try to run this code cli file is not executing and the code got directly exited.

1

There are 1 best solutions below

0
On

var proc=Process.Start(psi);

In a web application scenario, the execution of command-line scripts using Process.Start may not work as expected due to limitations or restrictions in the web hosting environment.

  • Instead, consider using the Azure SDK for .NET to interact with Azure services programmatically, including Azure App Configuration.

HomeController.cs:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.AzureAppConfiguration;
using System;
using System.Threading.Tasks;

public class HomeController : Controller
{
    private readonly IConfiguration _configuration;

    public HomeController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public async Task<IActionResult> Index()
    {
        try
        {
            string endpoint = _configuration["AppConfig:Endpoint"];
            string featureName = _configuration["AppConfig:FeatureName"];

            var configProvider = new AzureAppConfigurationProvider(new AzureAppConfigurationOptions
            {
                ConnectionString = endpoint
            });

            IConfigurationRoot configRoot = new ConfigurationBuilder()
                .Add(configProvider)
                .Build();

            var jsondata = configRoot.GetSection($"AppConfig:Features:{featureName}:Filters:Microsoft.Targeting").Get<string>();
            var audienceSection = jsondata?.Split(',')[0]; // Assuming Audience is a string in the JSON

            // Your logic to modify the audience section
            string new_user = "newuser";
            var updatedAudienceSection = $"{audienceSection}, {new_user}";

            // Update the configuration
            configProvider.Set($"AppConfig:Features:{featureName}:Filters:Microsoft.Targeting:Audience", updatedAudienceSection);
            await configProvider.LoadAsync();

            return View();
        }
        catch (Exception ex)
        {
            return Content($"Error: {ex.Message}");
        }
    }
}
  • The Azure App Configuration connection string and feature name are retrieved from the application's configuration (appsettings.json).

enter image description here Install NuGet package Microsoft.Extensions.Configuration.AzureAppConfiguration.

Below is the sample script taken to test.

# Define variables
resourceGroupName="MyResourceGroup"
location="eastus"
storageAccountName="mystorageaccount"
sku="Standard_LRS"

# Create a new resource group
az group create --name $resourceGroupName --location $location

# Create a storage account
az storage account create \
  --resource-group $resourceGroupName \
  --name $storageAccountName \
  --location $location \
  --sku $sku

echo "Azure CLI script execution completed."

enter image description here

I was already in log-in with my AZ account in my Azure CLI.

Result:

enter image description here