Azure ArmClient 重命名和复制数据库操作

huangapple go评论105阅读模式
英文:

Azure ArmClient Rename & Copy DB Operations

问题

A bit of background, I am looking to replace existing code in a C# App from the existing Microsoft.Azure.Management.Fluent (now deprecated) to the newer Azure.ResourceManager components.

Existing code to copy a database:

  1. public async Task<bool> CopyDb(string? server, string? fromName, string? toName)
  2. {
  3. _log.LogInformation("Connecting to Azure");
  4. var azure = GetAzureObject();
  5. var servers = await azure.SqlServers.ListAsync();
  6. var fromServer = servers.FirstOrDefault(f => server != null && server.Contains(f.Name));
  7. if (fromServer == null)
  8. {
  9. throw new InvalidOperationException("Unable to find original database server");
  10. }
  11. var toNameBackup = $"{toName}-Old";
  12. var existingDbs = await fromServer.Databases.ListAsync();
  13. var fromDB = existingDbs.FirstOrDefault(f => f.Name.Equals(fromName));
  14. if (fromDB == null)
  15. {
  16. throw new InvalidOperationException("Unable to find original database");
  17. }
  18. if (existingDbs.Any(a => a.Name.Equals(toNameBackup, StringComparison.OrdinalIgnoreCase))
  19. && existingDbs.Any(a => a Name.Equals(toName, StringComparison.OrdinalIgnoreCase)))
  20. {
  21. _log.LogInformation("Deleting any existing backup called {0}", toNameBackup);
  22. await fromServer.Databases.DeleteAsync(toNameBackup);
  23. }
  24. if (existingDbs.Any(a => a.Name.Equals(toName, StringComparison.OrdinalIgnoreCase))
  25. {
  26. _log.LogInformation("Renaming target database from {0} to {1} (if exists)", toName, toNameBackup);
  27. await (await fromServer.Databases.GetAsync(toName)).RenameAsync(toNameBackup);
  28. }
  29. _log.LogInformation("Copying database from from {0} to {1}", fromName, toName);
  30. var result = await fromServer.Databases.
  31. Define(toName).
  32. WithSourceDatabase(fromDB).
  33. WithMode(Microsoft.Azure.Management.Sql.Fluent.Models.CreateMode.Copy).CreateAsync();
  34. return result != null;
  35. }
  36. private Microsoft.Azure.Management.Fluent.IAzure GetAzureObject()
  37. {
  38. var clientId = _configuration["AzureClientId"];
  39. var clientSecret = _configuration["AzureClientSecret"];
  40. var tenantId = _configuration["AzureTenantId"];
  41. var subscriptionId = _configuration["AzureSubscriptionId"];
  42. var credentials = Microsoft.Azure.Management.ResourceManager.Fluent.SdkContext.AzureCredentialsFactory.FromServicePrincipal(
  43. clientId: clientId,
  44. clientSecret: clientSecret,
  45. tenantId: tenantId,
  46. environment: Microsoft.Azure.Management.ResourceManager.Fluent.AzureEnvironment.AzureGlobalCloud);
  47. return Microsoft.Azure.Management.Fluent.Azure.Configure().Authenticate(credentials).WithSubscription(subscriptionId);
  48. }

The newer components all work with resources and I've been struggling how to do a couple operations with the newer Azure.ArmClient. I've been able to query with it finding my SQL server and databases. I can even delete some DBs, but I'm unable to work out how to rename or copy databases like the above code. I know there are alternative ways to do this directly in SQL, but I'd prefer to see how to do it in code.

I have had a look around MS docs, I can only find information on the object definitions but no examples.

I have managed to get down to the point of renaming:-

  1. var backupDb = fromServer.GetSqlDatabase(toName);
  2. if (backupDb != null && backupDb.Value != null)
  3. {
  4. // What do I pass in to the definition?
  5. var moveDefinition = new SqlResourceMoveDefinition()
  6. {
  7. // What to set here?
  8. };
  9. await (await backupDb.Value.GetAsync()).Value.RenameAsync(moveDefinition);
  10. }

I'm not sure on how to define the SqlResourceMoveDefinition. I also can't work out at all how to perform the copy like in the older SDK.

Anyone have any guides on how to achieve these operations in C#?

英文:

A bit of background, I am looking to replace existing code in a C# App from the existing Microsoft.Azure.Management.Fluent (now deprecated) to the newer Azure.ResourceManager components.

Existing code to copy a database:

  1. public async Task&lt;bool&gt; CopyDb(string? server, string? fromName, string? toName)
  2. {
  3. _log.LogInformation(&quot;Connecting to Azure&quot;);
  4. var azure = GetAzureObject();
  5. var servers = await azure.SqlServers.ListAsync();
  6. var fromServer = servers.FirstOrDefault(f =&gt; server != null &amp;&amp; server.Contains(f.Name));
  7. if (fromServer == null)
  8. {
  9. throw new InvalidOperationException(&quot;Unable to find original database server&quot;);
  10. }
  11. var toNameBackup = $&quot;{toName}-Old&quot;;
  12. var existingDbs = await fromServer.Databases.ListAsync();
  13. var fromDB = existingDbs.FirstOrDefault(f =&gt; f.Name.Equals(fromName));
  14. if (fromDB == null)
  15. {
  16. throw new InvalidOperationException(&quot;Unable to find original database&quot;);
  17. }
  18. if (existingDbs.Any(a =&gt; a.Name.Equals(toNameBackup, StringComparison.OrdinalIgnoreCase))
  19. &amp;&amp; existingDbs.Any(a =&gt; a.Name.Equals(toName, StringComparison.OrdinalIgnoreCase)))
  20. {
  21. _log.LogInformation(&quot;Deleting any existing backup called {0}&quot;, toNameBackup);
  22. await fromServer.Databases.DeleteAsync(toNameBackup);
  23. }
  24. if (existingDbs.Any(a =&gt; a.Name.Equals(toName, StringComparison.OrdinalIgnoreCase)))
  25. {
  26. _log.LogInformation(&quot;Renaming target database from {0} to {1} (if exists)&quot;, toName, toNameBackup);
  27. await (await fromServer.Databases.GetAsync(toName)).RenameAsync(toNameBackup);
  28. }
  29. _log.LogInformation(&quot;Copying database from from {0} to {1}&quot;, fromName, toName);
  30. var result = await fromServer.Databases.
  31. Define(toName).
  32. WithSourceDatabase(fromDB).
  33. WithMode(Microsoft.Azure.Management.Sql.Fluent.Models.CreateMode.Copy).CreateAsync();
  34. return result != null;
  35. }
  36. private Microsoft.Azure.Management.Fluent.IAzure GetAzureObject()
  37. {
  38. var clientId = _configuration[&quot;AzureClientId&quot;];
  39. var clientSecret = _configuration[&quot;AzureClientSecret&quot;];
  40. var tenantId = _configuration[&quot;AzureTenantId&quot;];
  41. var subscriptionId = _configuration[&quot;AzureSubscriptionId&quot;];
  42. var credentials = Microsoft.Azure.Management.ResourceManager.Fluent.SdkContext.AzureCredentialsFactory.FromServicePrincipal(
  43. clientId: clientId,
  44. clientSecret: clientSecret,
  45. tenantId: tenantId,
  46. environment: Microsoft.Azure.Management.ResourceManager.Fluent.AzureEnvironment.AzureGlobalCloud);
  47. return Microsoft.Azure.Management.Fluent.Azure.Configure().Authenticate(credentials).WithSubscription(subscriptionId);
  48. }

The newer components all work with resources and I've been struggling how to do a couple operations with the newer Azure.ArmClient. I've been able to query with it finding my SQL server and databases. I can even delete some DBs, but I'm unable to work out how to rename or copy databases like the above code. I know there are alternative ways to do this directly in SQL, but I'd prefer to see how to do it in code.

I have had a look around MS docs, I can only find information on the object definitions but no examples.

I have managed to get down to the point of renaming:-

  1. var backupDb = fromServer.GetSqlDatabase(toName);
  2. if (backupDb != null &amp;&amp; backupDb.Value != null)
  3. {
  4. // What do I pass in to the definition?
  5. var moveDefinition = new SqlResourceMoveDefinition()
  6. {
  7. // What to set here?
  8. };
  9. await (await backupDb.Value.GetAsync()).Value.RenameAsync(moveDefinition);
  10. }

I'm not sure on how to define the SqlResourceMoveDefinition. I also can't work out at all how to perform the copy like in the older SDK.

Anyone have any guides on how to achieve these operations in C#?

答案1

得分: 1

以下是您要翻译的代码部分:

  1. Managed to work it out after eventually working from https://learn.microsoft.com/en-us/dotnet/azure/sdk/resource-management?tabs=PowerShell. There may be better ways to do this, and I'll edit the answer when I find them if others don't by then!
  2. public async Task<bool> CopyDb(string? server, string? fromName, string? toName)
  3. {
  4. _log.LogInformation("Connecting to Azure");
  5. var azure = GetAzureSubscription();
  6. var servers = azure.GetSqlServers().ToList();
  7. var fromServer = servers.SingleOrDefault(f => server != null && f.Data != null && server.Contains(f.Data.Name));
  8. if (fromServer == null)
  9. {
  10. throw new InvalidOperationException("Unable to find original database server");
  11. }
  12. var oldName = $"{toName}-Old";
  13. var databases = fromServer.GetSqlDatabases();
  14. _log.LogInformation("Check for any existing backup called {0}", oldName);
  15. if (await databases.ExistsAsync(oldName))
  16. {
  17. _log.LogInformation("Deleting for any existing backup called {0}", oldName);
  18. var oldBackup = await databases.GetAsync(oldName);
  19. await oldBackup.Value.DeleteAsync(WaitUntil.Completed);
  20. }
  21. _log.LogInformation("Check target database {0} exists", toName, oldName);
  22. if (await databases.ExistsAsync(toName))
  23. {
  24. _log.LogInformation("Renaming target database from {0} to {1}", toName, oldName);
  25. var toDbBackup = await databases.GetAsync(toName);
  26. var resourceIdString = toDbBackup.Value.Data.Id.Parent?.ToString();
  27. var newResourceId = new ResourceIdentifier($"{resourceIdString}/databases/{oldName}");
  28. var moveDefinition = new SqlResourceMoveDefinition(newResourceId);
  29. var toDb = await toDbBackup.Value.GetAsync();
  30. await toDb.Value.RenameAsync(moveDefinition);
  31. }
  32. _log.LogInformation("Copying database from from {0} to {1}", fromName, toName);
  33. var fromDb = await databases.GetAsync(fromName);
  34. var result = await databases.CreateOrUpdateAsync(WaitUntil.Completed, toName, fromDb.Value.Data);
  35. _log.LogInformation("Operation completed!");
  36. return result.HasValue;
  37. }
  38. private SubscriptionResource GetAzureSubscription()
  39. {
  40. var configValue = _configuration["AzureSubscriptionId"];
  41. var subscriptionId = new ResourceIdentifier($"/subscriptions/{configValue}");
  42. return GetAzureArmClient().GetSubscriptionResource(subscriptionId);
  43. }
  44. private ArmClient GetAzureArmClient()
  45. {
  46. var clientId = _configuration["AzureClientId"];
  47. var clientSecret = _configuration["AzureClientSecret"];
  48. var tenantId = _configuration["AzureTenantId"];
  49. var credentials = new ClientSecretCredential(
  50. clientId: clientId,
  51. clientSecret: clientSecret,
  52. tenantId: tenantId);
  53. return new ArmClient(credentials);
  54. }
英文:

Managed to work it out after eventually working from https://learn.microsoft.com/en-us/dotnet/azure/sdk/resource-management?tabs=PowerShell. There may be better ways to do this, and I'll edit the answer when I find them if others don't by then!

  1. public async Task&lt;bool&gt; CopyDb(string? server, string? fromName, string? toName)
  2. {
  3. _log.LogInformation(&quot;Connecting to Azure&quot;);
  4. var azure = GetAzureSubscription();
  5. var servers = azure.GetSqlServers().ToList();
  6. var fromServer = servers.SingleOrDefault(f =&gt; server != null &amp;&amp; f.Data != null &amp;&amp; server.Contains(f.Data.Name));
  7. if (fromServer == null)
  8. {
  9. throw new InvalidOperationException(&quot;Unable to find original database server&quot;);
  10. }
  11. var oldName = $&quot;{toName}-Old&quot;;
  12. var databases = fromServer.GetSqlDatabases();
  13. _log.LogInformation(&quot;Check for any existing backup called {0}&quot;, oldName);
  14. if (await databases.ExistsAsync(oldName))
  15. {
  16. _log.LogInformation(&quot;Deleting for any existing backup called {0}&quot;, oldName);
  17. var oldBackup = await databases.GetAsync(oldName);
  18. await oldBackup.Value.DeleteAsync(WaitUntil.Completed);
  19. }
  20. _log.LogInformation(&quot;Check target database {0} exists&quot;, toName, oldName);
  21. if (await databases.ExistsAsync(toName))
  22. {
  23. _log.LogInformation(&quot;Renaming target database from {0} to {1}&quot;, toName, oldName);
  24. var toDbBackup = await databases.GetAsync(toName);
  25. var resourceIdString = toDbBackup.Value.Data.Id.Parent?.ToString();
  26. var newResourceId = new ResourceIdentifier($&quot;{resourceIdString}/databases/{oldName}&quot;);
  27. var moveDefinition = new SqlResourceMoveDefinition(newResourceId);
  28. var toDb = await toDbBackup.Value.GetAsync();
  29. await toDb.Value.RenameAsync(moveDefinition);
  30. }
  31. _log.LogInformation(&quot;Copying database from from {0} to {1}&quot;, fromName, toName);
  32. var fromDb = await databases.GetAsync(fromName);
  33. var result = await databases.CreateOrUpdateAsync(WaitUntil.Completed, toName, fromDb.Value.Data);
  34. _log.LogInformation(&quot;Operation completed!&quot;);
  35. return result.HasValue;
  36. }
  37. private SubscriptionResource GetAzureSubscription()
  38. {
  39. var configValue = _configuration[&quot;AzureSubscriptionId&quot;];
  40. var subscriptionId = new ResourceIdentifier($&quot;/subscriptions/{configValue}&quot;);
  41. return GetAzureArmClient().GetSubscriptionResource(subscriptionId);
  42. }
  43. private ArmClient GetAzureArmClient()
  44. {
  45. var clientId = _configuration[&quot;AzureClientId&quot;];
  46. var clientSecret = _configuration[&quot;AzureClientSecret&quot;];
  47. var tenantId = _configuration[&quot;AzureTenantId&quot;];
  48. var credentials = new ClientSecretCredential(
  49. clientId: clientId,
  50. clientSecret: clientSecret,
  51. tenantId: tenantId);
  52. return new ArmClient(credentials);
  53. }

huangapple
  • 本文由 发表于 2023年2月14日 20:54:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75448136.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定