简体   繁体   中英

Azure Management Libraries Sdk for .NET list() function not working for various interfaces

I'm using the Azure Management Libraries (specifically fluent) to create web request towards their api to get a list of my databases under my subscription. I'm able to get an instance of the sqlserver using fluent but am unable to get a list of all databases under a specific server. Define and delete work fine it is just the list() function.

I've tried using it for sqlserver.firewallrules and the list function doesn't work there as well.

Here is some code: The log at some point just pauses then writes "has exited with code 0"

    public async Task<List<String>> getSqlDatabaseList()
    {
        System.Diagnostics.Debug.WriteLine("Starting to get database list");
        List<string> dbNameList = new List<string>();

        //the var azure is defined earlier in the project and is authenticated.
        var sqlServer = await azure.SqlServers.GetByResourceGroupAsync("<resource group name>", "<server Name>");

        //The code below successfully writes the server name
        System.Diagnostics.Debug.WriteLine(sqlServer.Name);

        //The code below here is where everyting stop and "has exited with code 0" happens after a few seconds of delay
        var dbList = sqlServer.Databases.List();

        //Never reaches this line
        System.Diagnostics.Debug.WriteLine("This line never is written");

        foreach (ISqlDatabase db in dbList)
        {
            dbNameList.Add(db.Name);
        }
        return dbNameList;
    }

Clarification: I'm using ASP.NET MVC Here is how my controller method accesses the class method. Resource Manager is the name of the class that implements getSQlDatabaseList();

        // GET: Home
    public async Task<ActionResult> Index()
    {
        ResourceManager rm = new ResourceManager();
        List<string> test = await rm.getSqlDatabaseList();
        //Never Gets to this line of code and never calls the for each or anything after
        foreach (var item in test)
        {
            System.Diagnostics.Debug.WriteLine(item);
        }
        System.Diagnostics.Debug.WriteLine("Is past for each");
        //AzureManager azm = await AzureManager.createAzureManager();
        //await azm.getResourceGroupList();
        return View(new UserLogin());
    }

According to your code and description, I guess the reason why your code couldn't create the table is about your async getSqlDatabaseList.

I guess you call this method in console main method or something else.

If your main method is executed completely, your async method getSqlDatabaseList isn't execute the completely and return the list of the string. It will end all async method.

I suggest you could add await or result key keyword when calling the getSqlDatabaseList method to wait the thread execute the method completely.

More details, you could refer to below test demo.

  static void Main(string[] args)
        {
            //use result to wait the mehtod executed completely
            List<String> test =  getSqlDatabaseList().Result;

            foreach (var item in test)
            {
                Console.WriteLine(item);
            }

            Console.Read();

        }

        public static async Task<List<String>> getSqlDatabaseList()
        {
            //System.Diagnostics.Debug.WriteLine("Starting to get database list");
            List<string> dbNameList = new List<string>();

            var credentials = SdkContext.AzureCredentialsFactory.FromFile(@"D:\Auth.txt");

            var azure = Azure
                .Configure()
                .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                .Authenticate(credentials)
                .WithDefaultSubscription();

            var sqlServer = await azure.SqlServers.GetByResourceGroupAsync("groupname", "brandotest");


            var dbList = sqlServer.Databases.List();

            foreach (ISqlDatabase db in dbList)
            {
                dbNameList.Add(db.Name);
            }
            return dbNameList;
        }

Update:

According to your description, I have created a test MVC application. As you say I have reproduce your issue.

I think there are something wrong with the azure management fluent SDK.

Here is a workaround, I suggest you could directly send rest api to get the database.

More details, you could refer to below codes:

Send the request to below url:

https://management.azure.com/subscriptions/ {subscriptionsid}/resourceGroups/{resourceGroupsname}/providers/Microsoft.Sql/servers/{servername}/databases?api-version={apiversion}

 public static List<String> getSqlDatabaseList()
        {
            //System.Diagnostics.Debug.WriteLine("Starting to get database list");
            List<string> dbNameList = new List<string>();

            string tenantId = "yourtenantid";
            string clientId = "yourclientId";
            string clientSecret = "clientSecret";
            string subscriptionid = "subscriptionid";
            string resourcegroup = "resourcegroupname";

            string sqlservername = "brandotest";
            string version = "2014-04-01";

            string authContextURL = "https://login.windows.net/" + tenantId;
            var authenticationContext = new AuthenticationContext(authContextURL);
            var credential = new ClientCredential(clientId, clientSecret);
            var result = authenticationContext.AcquireToken(resource: "https://management.azure.com/", clientCredential: credential);

            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }

            string token = result.AccessToken;

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Sql/servers/{2}/databases?api-version={3}", subscriptionid, resourcegroup, sqlservername, version));

            request.Method = "GET";
            request.Headers["Authorization"] = "Bearer " + token;


            request.ContentType = "application/json";


            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                string jsonResponse = streamReader.ReadToEnd();

                dynamic json = JsonConvert.DeserializeObject(jsonResponse);

                dynamic resultList = json.value.Children();


                foreach (var item in resultList)
                {

                    dbNameList.Add(((Newtonsoft.Json.Linq.JValue)item.name).Value.ToString());
                }
            }


            return dbNameList;
        }

Result:

在此处输入图片说明


Another workaround.

I suggest you could use thread.join to wait the list method execute completely.

Code:

 public static async Task<List<String>> getSqlDatabaseList()
        {
            //System.Diagnostics.Debug.WriteLine("Starting to get database list");
            List<string> dbNameList = new List<string>();

            var credentials = SdkContext.AzureCredentialsFactory.FromFile(@"D:\Auth.txt");

            var azure = Azure
                .Configure()
                .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                .Authenticate(credentials)
                .WithDefaultSubscription();

            var sqlServer = await azure.SqlServers.GetByResourceGroupAsync("brandosecondtest", "brandotest");

            IReadOnlyList<ISqlDatabase> dbList = null;

            Thread thread = new Thread(() => { dbList = sqlServer.Databases.List(); });
            thread.Start();
            //wait the thread
            thread.Join();

            foreach (ISqlDatabase db in dbList)
            {
                dbNameList.Add(db.Name);
            }
            return dbNameList;
        }

Result:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM