Unable to execute Azure CLI commands in C# Console Application

151 Views Asked by At

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);
    }
}
2

There are 2 best solutions below

0
On BEST ANSWER

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

0
On

This code is working for my Question:

using System;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text.Json.Nodes;

public class AzureCliCommandRunner
{
    public static string RunAzureCliCommand(string command)
    {
        var processStartInfo = new ProcessStartInfo
        {
            FileName = "C:\\Program Files\\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();

            // 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);
        JArray jsonArray = JArray.Parse(jsondata);

        JObject audience = (JObject)jsonArray[0]["parameters"]["Audience"];
        var name = "user6";
        // Add a new user to the "Users" array
        ((JArray)audience["Users"]).Add(name);

        // Convert the modified JArray back to a JSON string
        string modifiedJson = jsonArray.ToString();

        JArray jsonArray1 = JArray.Parse(modifiedJson);
        JObject firstObject = (JObject)jsonArray1.First;

        // Access the "Audience" part
        JObject audienceObject = (JObject)firstObject["parameters"]["Audience"];

        // Serialize the audienceObject to a JSON string and escape it
        string escapedAudienceJsonString = JsonConvert.SerializeObject(audienceObject).Replace("\"", "\\\"");

        // Wrap the escaped JSON string with double quotes
        escapedAudienceJsonString = $"\"{escapedAudienceJsonString}\"";

        string command4 = $"appconfig feature filter update --connection-string {endpoint} --feature {featureName} --filter-name Microsoft.Targeting --filter-parameters Audience={escapedAudienceJsonString} --yes";
        RunAzureCliCommand(command4);
    }
    public static void Main()
    {
        // Replace <<EndPoint>> and <<FeatureName>> with your actual values
        string endpoint = "<<EndPoint>>";
        string featureName = "<<FeatureName>>";

        UpdateAppConfigFilter(endpoint, featureName);
    }
}