Usually, Azure SDK for .NET should provide the APIs to register an Azure AD application programmatically in C#. But as of February 2019, the facility is only available using PowerShell and not using C#. The C# APIs are under consideration or development. Hence, we will follow an approach of running a PowerShell script in the C# application to achieve our goal.

Prerequisites
We can check the PowerShell version by running the below command on PowerShell.
$PSVersionTable.PSVersion
There are 3 steps in this solution.
  • Create a C# application
  • Add NuGet packages to our project
  • Code to run PowerShell script in C#
Step 1 - Create a C# Application
  1. Open Visual Studio as Administrator.
  2. Create a console app (.NET Framework).
  3. Enter AppRegistration in the name section and click OK.
Register An Azure AD Application Programmatically Using C#
Step 2 - Add NuGet packages to our project
Add a NuGet package called System.Management.Automation.dll created by the Microsoft Corporation. This package will allow us to run the PowerShell scripts from C# applications.
Register An Azure AD Application Programmatically Using C#
We also need to add the Newtonsoft.Json package created by James Newton-King which will allow us to convert PowerShell Objects into JSON Objects. We can not directly convert a PowerShell Object to C# Object; so we need to first convert it into JSON and then, we can convert it into C# Object.
Register An Azure AD Application Programmatically Using C#
Step 3 - C# code to run PowerShell commands
Add the reference namespaces in the import section of your Program.cs file.
  1. using System.Management.Automation.Runspaces;
  2. using System.Management.Automation;
  3. using Newtonsoft.Json;
In Main method, write the below code.
  1. string Username = “<User name of Azure account>”;
  2. string Password = “<Password of Azure account>”;
  3. string Appname = “<Name using which we want to register an Azure Application>”;
  4. PowerShell powershell = PowerShell.Create();
  5. Runspace runspace = RunspaceFactory.CreateRunspace();
  6. runspace.Open();
  7. powershell.Runspace = runspace;
  8. powershell.AddScript("Install-Module -Name AzureADPreview -Force; \n");
  9. powershell.AddScript("Import-Module -Name AzureADPreview -Verbose \n");
  10. powershell.AddScript("$username = \""+Username +"\"; \n" +
  11. "$password = convertTo-securestring '"+ Password + "' -AsPlainText -Force; \n" +
  12. "$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password; \n" +
  13. "Connect-AzureAD -Credential $cred; \n" +
  14. "New-AzureADApplication -DisplayName '"+Appname+"' -ReplyUrls 'https://AppRegisterationDemo.contoso.com' -PublicClient $true");
  15. try
  16. {
  17. var result = powershell.Invoke();
  18. if (powershell.Streams.Error.Count > 0)
  19. {
  20. foreach (var err in powershell.Streams.Error.ToString())
  21. {
  22. Console.WriteLine(err);
  23. }
  24. return "0";
  25. }
  26. else
  27. {
  28. Console.WriteLine(result);
  29. int i = 0;
  30. foreach (var outputItem in result)
  31. {
  32. if (outputItem != null)
  33. {
  34. Console.WriteLine(outputItem.BaseObject.GetType());
  35. var jsonData =
  36. JsonConvert.SerializeObject(outputItem.Properties.ToDictionary(k => k.Name, v => v.Value), new JsonSerializerSettings()
  37. {
  38. PreserveReferencesHandling =
  39. PreserveReferencesHandling.Objects,
  40. Formatting = Formatting.Indented
  41. });
  42. if (i == 1)
  43. {
  44. var deseialized = JsonConvert.DeserializeObject<MyInfo>(jsonData);
  45. appID = deseialized.AppId;
  46. ObjectId = deseialized.ObjectId;
  47. Console.WriteLine(appID);
  48. }
  49. i++;
  50. }
  51. }
  52. }
  53. runspace.Close();
  54. Console.WriteLine("App Created Successfully");
  55. return "1";
  56. }
  57. catch (Exception ex)
  58. {
  59. return "0";
  60. }

We also need to add one class named MyInfo in which we will save the Object Id and Application Id.

  1. public class MyInfo
  2. {
  3. public string AppId { get; set; }
  4. public string ObjectId { get; set; }
  5. }
After all these changes, our file will look like following.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Collections.ObjectModel;
  6. using Newtonsoft.Json;
  7. using System.Management.Automation.Runspaces;
  8. namespace AppRegistraion
  9. {
  10. public class MyInfo
  11. {
  12. public string AppId { get; set; }
  13. public string ObjectId { get; set; }
  14. }
  15. class Program
  16. {
  17. public string appID = "";
  18. public string ObjectId = "";
  19. static void Main(string[] args)
  20. {
  21. string Username = “<User name of Azure account>”;
  22. string Password = “<Password of Azure account>”;
  23. string Appname = “<Name using which we want to register an Azure Application>”;
  24. PowerShell powershell = PowerShell.Create();
  25. Runspace runspace = RunspaceFactory.CreateRunspace();
  26. runspace.Open();
  27. powershell.Runspace = runspace;
  28. powershell.AddScript("Install-Module -Name AzureADPreview -Force; \n");
  29. powershell.AddScript("Import-Module -Name AzureADPreview -Verbose \n");
  30. powershell.AddScript("$username = \""+Username +"\"; \n" +
  31. "$password = convertTo-securestring '"+ Password + "' -AsPlainText -Force; \n" +
  32. "$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password; \n" +
  33. "Connect-AzureAD -Credential $cred; \n" +
  34. "New-AzureADApplication -DisplayName '"+Appname+"' -ReplyUrls 'https://AppRegisterationDemo.contoso.com' -PublicClient $true");
  35. try
  36. {
  37. var result = powershell.Invoke();
  38. if (powershell.Streams.Error.Count > 0)
  39. {
  40. foreach (var err in powershell.Streams.Error.ToString())
  41. {
  42. Console.WriteLine(err);
  43. }
  44. return "0";
  45. }
  46. else
  47. {
  48. Console.WriteLine(result);
  49. int i = 0;
  50. foreach (var outputItem in result)
  51. {
  52. if (outputItem != null)
  53. {
  54. Console.WriteLine(outputItem.BaseObject.GetType());
  55. var jsonData = JsonConvert.SerializeObject(outputItem.Properties.ToDictionary(k => k.Name, v => v.Value), new JsonSerializerSettings()
  56. {
  57. PreserveReferencesHandling = PreserveReferencesHandling.Objects,
  58. Formatting = Formatting.Indented
  59. });
  60. if (i == 1)
  61. {
  62. var deseialized = JsonConvert.DeserializeObject<MyInfo>(jsonData);
  63. appID = deseialized.AppId;
  64. ObjectId = deseialized.ObjectId;
  65. Console.WriteLine(appID);
  66. }
  67. i++;
  68. }
  69. }
  70. }
  71. runspace.Close();
  72. Console.WriteLine("App Created Successfully");
  73. return "1";
  74. }
  75. catch (Exception ex)
  76. {
  77. return "0";
  78. }
  79. }
  80. }
Code Explanation
  • In the above code, first, we are creating PowerShell object and a runspace in which the PowerShell script will run.
  • In this runspace, we are adding scripts using the Addscript() method.
  • In PowerShell scripts, we are first installing AzureADPreview module and importing it to our runspace. Then, we are connecting to Azure AD using Connect-AzureAD command.
  • Using New-AzureADApplication command, we are creating an Azure AD application.
  • Now, we have invoked the commands to run using the Invoke() method of PowerShell object.
  • We need to check for errors if any using powershell.Streams.Error.
  • We want an Object ID and Application ID for the application we have created in Azure AD. To get both of these IDs, we have converted the PowerShell object into a JSON object and JSON object into a C# object using JsonConvert.SerializeObject method and JsonConvert.DeserializeObject() method respectively.
After this code, we can go to the Azure portal and in the Azure Active Directory - App Registrations, we can see the app we have registered using the C# code.
Summary
Thus, we can automate the application registration using C# code and PowerShell. In the next blog, we will see how to add and grant permissions programatically.