Search code examples
c#azure-cliazure-app-configurationazure-feature-manager

Unable to execute Azure CLI commands in C# Console Application


When attempting to run Azure CLI commands through a C# Console Application, an exception is encountered. While there are no build errors, the execution of the project results in an error. Here is a snapshot of the error I encountered: enter image description here

Here is the C# code I am attempting to run.

using System;
using System.Diagnostics;
using System.IO;


public class AzureCliCommandRunner
{
    public static string RunAzureCliCommand(string command)
    {
        var processStartInfo = new ProcessStartInfo
        {
            FileName = "az",
            Arguments = command,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };

        using (var process = new Process { StartInfo = processStartInfo })
        {
            process.Start();

            // Read the output and error streams
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();

            process.WaitForExit();

            if (process.ExitCode == 0)
            {
                return output;
            }
            else
            {
                // Handle the error
                throw new InvalidOperationException($"Command execution failed. Error: {error}");
            }
        }
    }
    public static void UpdateAppConfigFilter(string endpoint, string featureName)
    {
        // Run Azure CLI commands to update AppConfig filter
        string command1 = $"appconfig feature filter show --connection-string {endpoint} --feature {featureName} --filter-name Microsoft.Targeting";
        string jsondata = RunAzureCliCommand(command1);

        string command2 = $"echo '{jsondata}' | jq -r '.[].parameters.Audience'";
        string audienceSection = RunAzureCliCommand(command2).Trim();

        string new_user = "newuser";
        string command3 = $"echo '{audienceSection}' | jq --arg new_user '{new_user}' '.Users += [\"$new_user\"]'";
        string file_content = RunAzureCliCommand(command3).Trim();

        string command4 = $"appconfig feature filter update --connection-string {endpoint} --feature {featureName} --filter-name Microsoft.Targeting --filter-parameters Audience='{file_content}' --yes";
        RunAzureCliCommand(command4);
    }

    public static void Main()
    {
        // Replace <<EndPoint>> and <<FeatureName>> with your actual values
        string endpoint = <<EndPoint>>;
        string featureName = <<FeatureName>>";

        UpdateAppConfigFilter(endpoint, featureName);
    }
}

Solution

  • Firstly, i too got similar error, Here Filename should be changed to a place where az.cmd is located in your system.

    I modified your code a bit as below:

    using System.Diagnostics;
    
    
    public class AzureCliCommandRunner
    {
        public static string RunAzureCliCommand(string command)
        {
            var processStartInfo = new ProcessStartInfo
            {
                FileName = @"C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd",
                Arguments = command,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true
    
            };
            using (var process = new Process { StartInfo = processStartInfo })
            {
                process.Start();
                string output = process.StandardOutput.ReadToEnd();
                string error = process.StandardError.ReadToEnd();
    
                process.WaitForExit();
    
                if (process.ExitCode == 0)
                {
                    return output;
                }
                else
                {
                    throw new InvalidOperationException($"Command execution failed. Error: {error}");
                }
            }
        }
        public static void UpdateAppConfigFilter(string name)
        {
            string rith_command = $"group show --name  {name}";
            string rithdata = RunAzureCliCommand(rith_command);
            Console.WriteLine(rithdata);     
        }
    
        public static void Main()
        {
            string name = "rbojja";  
            UpdateAppConfigFilter(name);
        }
    }
    

    Output:

    enter image description here