Search code examples
c#azure.net-coreazure-management-api

How to get all snapshot by using of Azure Mgmt SDK fluent


I am using Fluent for getting resources in Azure programmatically(C# .NET-Core Web app) and tried to get resources information by providing service principals as below:

string subscriptionId="XXX"; 
AzureCredentials cred = new AzureCredentialsFactory()
                      .FromServicePrincipal(UIConstants.ClientID, 
                       UIConstants.Secret, UIConstants.Tenant,AzureEnvironment
                      .AzureGlobalCloud);                      
            
var azure = Azure.Configure()
            .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) 
            .Authenticate(cred) 
            .WithSubscription(subscriptionId);

When I tried to get all snapshot like this

foreach (var s in azure.Snapshots.List())
{
//get snapshot
}

But there is no error and loop is also not executing. Is there any code sample in C# which get all all snapshot info.


Solution

  • As mentioned in the comment, this is due to no snapshots are there.

    Actually, before the loop, you can determine that if there're snapshots returned or not. The code like below:

    using System.Linq;
    
    //your other code
    
     //convert to list
     var mysanpshots = azure.Snapshots.List().ToList();            
    
     //if there are snapshots existing
     if (mysanpshots.Count > 0)
     {
          foreach (var s in mysanpshots)
          {
              //code
          }
     }
     //if no snapshots
     else
     {
        //code
     }