Forum Discussion

rozeboosje's avatar
rozeboosje
Copper Contributor
May 11, 2023

Creating a Server with current nuget packages?

I want to programmatically create an Azure SQL Server and I found an example piece of code online

static void CreateServer()
{
    // Create a SQL Database management client
    SqlManagementClient sqlClient = new SqlManagementClient(new TokenCloudCredentials(subscriptionId, token.AccessToken));

    // Create a server
    ServerCreateOrUpdateParameters serverParameters = new ServerCreateOrUpdateParameters()
    {
        Location = location,
        Properties = new ServerCreateOrUpdateProperties()
        {
            AdministratorLogin = administratorLogin,
            AdministratorLoginPassword = administratorPassword,
            Version = serverVersion
        }
    };
        var serverResult = sqlClient.Servers.CreateOrUpdate(resourceGroupName, serverName, serverParameters);
}

... but I have since found that the packages I need for this are deprecated. Instead of Microsoft.Azure.Management.Sql.Fluent I should be using Azure.ResourceManager.Sql

But I can't find any example as clear as the above to create a new Azure SQL server using the new packages. This is an area I'm very unfamiliar with so I can't see the wood for the trees and I get lost in the definitions. Can someone please provide a code snippet as minimalistic as the above to achieve the same thing using new packages?

Many thanks.

1 Reply

  • How about this:

     

    using Azure.Identity;
    using Azure.ResourceManager;
    using Azure.ResourceManager.Resources;
    using Azure.ResourceManager.Sql;
    using Azure.ResourceManager.Sql.Models;
    
    async Task CreateSqlServerAsync()
    {
        string subscriptionId = "<your-subscription-id>";
        string resourceGroupName = "<your-resource-group>";
        string location = "eastus";
        string serverName = "<your-server-name>";
        string adminLogin = "sqladmin";
        string adminPassword = "<your-password>";
    
        // Authenticate
        var credential = new DefaultAzureCredential();
        var armClient = new ArmClient(credential, subscriptionId);
    
        // Get the resource group
        ResourceGroupResource resourceGroup = await armClient.GetDefaultSubscriptionAsync()
            .Result.GetResourceGroups().GetAsync(resourceGroupName);
    
        // Define server data
        var serverData = new SqlServerData(location)
        {
            AdministratorLogin = adminLogin,
            AdministratorLoginPassword = adminPassword
        };
    
        // Create the SQL Server
        var sqlServerLro = await resourceGroup.GetSqlServers().CreateOrUpdateAsync(
            WaitUntil.Completed,
            serverName,
            serverData);
    
        SqlServerResource sqlServer = sqlServerLro.Value;
        Console.WriteLine($"SQL Server created: {sqlServer.Data.Name}");
    }

     

Resources