Search code examples
azureazure-sdk

Creating an Azure SQL Server without Microsoft.Azure.Management.Sql.Fluent


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.


Solution

  • I have created SQL server in azure using the below C# code without Microsoft.Azure.Management.Sql.Fluent

    static async Task Main(string[] args)
       {
          string tenant_Id = "TenantId";
          string clnt_Id = "ClientId";
          string clnt_Secrt = "Secret";
          string subscrip_Id = "SubscriptionID";
    
           string resource_GrpName = "Resource Group";
           string server_Name = "myservertest4411";
           string admin_Login = "Rajesh";
           string admin_Pwd = "Password";
    
           string authenticationUrl = $"https://login.microsoftonline.com/{tenant_Id}/oauth2/token";
           string requestBody = $"grant_type=client_credentials&client_id={clnt_Id}&client_secret={clnt_Secrt}&resource=https://management.azure.com/";
           var content = new StringContent(requestBody, Encoding.UTF8, "application/x-www-form-urlencoded");
    
           using (var httpClient = new HttpClient())
                {
                    var res = await httpClient.PostAsync(authenticationUrl, content);
                    string res_Content = await res.Content.ReadAsStringAsync();
                    string access_Token = JsonConvert.DeserializeObject<dynamic>(res_Content).access_token;
    
                    string create_ServerUrl = $"https://management.azure.com/subscriptions/{subscrip_Id}/resourceGroups/{resource_GrpName}/providers/Microsoft.Sql/servers/{server_Name}?api-version=2021-02-01-preview";
                    string server_RequestBody = $"{{ \"location\": \"eastus\", \"properties\": {{ \"administratorLogin\": \"{admin_Login}\", \"administratorLoginPassword\": \"{admin_Pwd}\", \"version\": \"12.0\" }} }}";
                    var server_Req = new HttpRequestMessage(HttpMethod.Put, create_ServerUrl);
                    server_Req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", access_Token);
                    server_Req.Content = new StringContent(server_RequestBody, Encoding.UTF8, "application/json");
    
                    var server_Resp = await httpClient.SendAsync(server_Req);
                    if (server_Resp.IsSuccessStatusCode)
                    {
                        Console.WriteLine("SQL Server created successfully!");
                    }
                    else
                    {
                        string errorResponseContent = await server_Resp.Content.ReadAsStringAsync();
                        Console.WriteLine($"Failed to create SQL Server. Error: {errorResponseContent}");
                    }
                }
         }
    

    enter image description here

    In azure you can see the SQL server created.

    enter image description here

    • You need a create an app in the App registrations of Azure. enter image description here

    • I have given the owner permissions to the app, depending on your requirement you can choose the permissions.

    enter image description here