Search code examples
c#azureazure-sql-database

How to detect if my Azure SQL Database is in a "Pause" state using C#


How to detect if my Azure SQL Database is in a "Pause" state using C#? I am trying to find some sample code to detect if my SQL Database is "paused"

enter image description here


Solution

  • You can call the REST API through C# to know the status of an Azure SQL database. First, go to the REST API below and generate a Bearer token by running it with the required details:

    After that, use the Bearer token in the code below:

    using System;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Threading.Tasks;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            await CallAzureManagementAPI();
        }
    
        static async Task CallAzureManagementAPI()
        {
            string subscriptionId = "<subscriptionId>";
            string resourceGroupName = "<resourceGroupName>";
            string serverName = "<serverName>";
            string databaseName = "<databaseName>";
            string apiVersion = "2021-11-01";
    
            string url = $"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}?api-version={apiVersion}";
    
            using (var client = new HttpClient())
            {
                string bearerToken = "<bearerToken>"; // Replace this with your actual Bearer token
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
    
                HttpResponseMessage response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Failed to call Azure Management API. Status code: {response.StatusCode}");
                }
            }
        }
    }
    

    You will get the status of the database as shown below:

    enter image description here