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

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

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:

public async Task<bool> CopyDb(string? server, string? fromName, string? toName)
{
    _log.LogInformation("Connecting to Azure");
    var azure = GetAzureObject();

    var servers = await azure.SqlServers.ListAsync();
    var fromServer = servers.FirstOrDefault(f => server != null && server.Contains(f.Name));
    if (fromServer == null)
    {
        throw new InvalidOperationException("Unable to find original database server");
    }

    var toNameBackup = $"{toName}-Old";

    var existingDbs = await fromServer.Databases.ListAsync();

    var fromDB = existingDbs.FirstOrDefault(f => f.Name.Equals(fromName));
    if (fromDB == null)
    {
        throw new InvalidOperationException("Unable to find original database");
    }

    if (existingDbs.Any(a => a.Name.Equals(toNameBackup, StringComparison.OrdinalIgnoreCase)) 
        && existingDbs.Any(a => a Name.Equals(toName, StringComparison.OrdinalIgnoreCase)))
    {
        _log.LogInformation("Deleting any existing backup called {0}", toNameBackup);
        await fromServer.Databases.DeleteAsync(toNameBackup);
    }

    if (existingDbs.Any(a => a.Name.Equals(toName, StringComparison.OrdinalIgnoreCase))
    {
        _log.LogInformation("Renaming target database from {0} to {1} (if exists)", toName, toNameBackup);
        await (await fromServer.Databases.GetAsync(toName)).RenameAsync(toNameBackup);
    }

    _log.LogInformation("Copying database from from {0} to {1}", fromName, toName);
    var result = await fromServer.Databases.
        Define(toName).
        WithSourceDatabase(fromDB).
        WithMode(Microsoft.Azure.Management.Sql.Fluent.Models.CreateMode.Copy).CreateAsync();

    return result != null;
}

private Microsoft.Azure.Management.Fluent.IAzure GetAzureObject()
{
    var clientId = _configuration["AzureClientId"];
    var clientSecret = _configuration["AzureClientSecret"];
    var tenantId = _configuration["AzureTenantId"];
    var subscriptionId = _configuration["AzureSubscriptionId"];

    var credentials = Microsoft.Azure.Management.ResourceManager.Fluent.SdkContext.AzureCredentialsFactory.FromServicePrincipal(
        clientId: clientId,
        clientSecret: clientSecret,
        tenantId: tenantId,
        environment: Microsoft.Azure.Management.ResourceManager.Fluent.AzureEnvironment.AzureGlobalCloud);

    return Microsoft.Azure.Management.Fluent.Azure.Configure().Authenticate(credentials).WithSubscription(subscriptionId);
}

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:-

var backupDb = fromServer.GetSqlDatabase(toName);
if (backupDb != null && backupDb.Value != null)
{
    // What do I pass in to the definition?
    var moveDefinition = new SqlResourceMoveDefinition()
    {
        // What to set here?
    };

    await (await backupDb.Value.GetAsync()).Value.RenameAsync(moveDefinition);
}

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:

public async Task&lt;bool&gt; CopyDb(string? server, string? fromName, string? toName)
{
    _log.LogInformation(&quot;Connecting to Azure&quot;);
    var azure = GetAzureObject();

    var servers = await azure.SqlServers.ListAsync();
    var fromServer = servers.FirstOrDefault(f =&gt; server != null &amp;&amp; server.Contains(f.Name));
    if (fromServer == null)
    {
        throw new InvalidOperationException(&quot;Unable to find original database server&quot;);
    }

    var toNameBackup = $&quot;{toName}-Old&quot;;

    var existingDbs = await fromServer.Databases.ListAsync();

    var fromDB = existingDbs.FirstOrDefault(f =&gt; f.Name.Equals(fromName));
    if (fromDB == null)
    {
        throw new InvalidOperationException(&quot;Unable to find original database&quot;);
    }

    if (existingDbs.Any(a =&gt; a.Name.Equals(toNameBackup, StringComparison.OrdinalIgnoreCase)) 
        &amp;&amp; existingDbs.Any(a =&gt; a.Name.Equals(toName, StringComparison.OrdinalIgnoreCase)))
    {
        _log.LogInformation(&quot;Deleting any existing backup called {0}&quot;, toNameBackup);
        await fromServer.Databases.DeleteAsync(toNameBackup);
    }

    if (existingDbs.Any(a =&gt; a.Name.Equals(toName, StringComparison.OrdinalIgnoreCase)))
    {
        _log.LogInformation(&quot;Renaming target database from {0} to {1} (if exists)&quot;, toName, toNameBackup);
        await (await fromServer.Databases.GetAsync(toName)).RenameAsync(toNameBackup);
    }

    _log.LogInformation(&quot;Copying database from from {0} to {1}&quot;, fromName, toName);
    var result = await fromServer.Databases.
        Define(toName).
        WithSourceDatabase(fromDB).
        WithMode(Microsoft.Azure.Management.Sql.Fluent.Models.CreateMode.Copy).CreateAsync();

    return result != null;
}

private Microsoft.Azure.Management.Fluent.IAzure GetAzureObject()
{
    var clientId = _configuration[&quot;AzureClientId&quot;];
    var clientSecret = _configuration[&quot;AzureClientSecret&quot;];
    var tenantId = _configuration[&quot;AzureTenantId&quot;];
    var subscriptionId = _configuration[&quot;AzureSubscriptionId&quot;];

    var credentials = Microsoft.Azure.Management.ResourceManager.Fluent.SdkContext.AzureCredentialsFactory.FromServicePrincipal(
        clientId: clientId,
        clientSecret: clientSecret,
        tenantId: tenantId,
        environment: Microsoft.Azure.Management.ResourceManager.Fluent.AzureEnvironment.AzureGlobalCloud);

    return Microsoft.Azure.Management.Fluent.Azure.Configure().Authenticate(credentials).WithSubscription(subscriptionId);
}

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:-

var backupDb = fromServer.GetSqlDatabase(toName);
if (backupDb != null &amp;&amp; backupDb.Value != null)
{
    // What do I pass in to the definition?
    var moveDefinition = new SqlResourceMoveDefinition()
    {
        // What to set here?
    };

    await (await backupDb.Value.GetAsync()).Value.RenameAsync(moveDefinition);
}

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

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

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!

public async Task<bool> CopyDb(string? server, string? fromName, string? toName)
{
    _log.LogInformation("Connecting to Azure");

    var azure = GetAzureSubscription();

    var servers = azure.GetSqlServers().ToList();

    var fromServer = servers.SingleOrDefault(f => server != null && f.Data != null && server.Contains(f.Data.Name));
    if (fromServer == null)
    {
        throw new InvalidOperationException("Unable to find original database server");
    }

    var oldName = $"{toName}-Old";
    var databases = fromServer.GetSqlDatabases();

    _log.LogInformation("Check for any existing backup called {0}", oldName);
    if (await databases.ExistsAsync(oldName))
    {
        _log.LogInformation("Deleting for any existing backup called {0}", oldName);
        var oldBackup = await databases.GetAsync(oldName);
        await oldBackup.Value.DeleteAsync(WaitUntil.Completed);
    }

    _log.LogInformation("Check target database {0} exists", toName, oldName);
    if (await databases.ExistsAsync(toName))
    {
        _log.LogInformation("Renaming target database from {0} to {1}", toName, oldName);
        var toDbBackup = await databases.GetAsync(toName);
        var resourceIdString = toDbBackup.Value.Data.Id.Parent?.ToString();
        var newResourceId = new ResourceIdentifier($"{resourceIdString}/databases/{oldName}");
        var moveDefinition = new SqlResourceMoveDefinition(newResourceId);
        var toDb = await toDbBackup.Value.GetAsync();
        await toDb.Value.RenameAsync(moveDefinition);
    }

    _log.LogInformation("Copying database from from {0} to {1}", fromName, toName);
    var fromDb = await databases.GetAsync(fromName);
    var result = await databases.CreateOrUpdateAsync(WaitUntil.Completed, toName, fromDb.Value.Data);
    _log.LogInformation("Operation completed!");

    return result.HasValue;
}

private SubscriptionResource GetAzureSubscription()
{
    var configValue = _configuration["AzureSubscriptionId"];
    var subscriptionId = new ResourceIdentifier($"/subscriptions/{configValue}");
    return GetAzureArmClient().GetSubscriptionResource(subscriptionId);
}

private ArmClient GetAzureArmClient()
{
    var clientId = _configuration["AzureClientId"];
    var clientSecret = _configuration["AzureClientSecret"];
    var tenantId = _configuration["AzureTenantId"];

    var credentials = new ClientSecretCredential(
        clientId: clientId,
        clientSecret: clientSecret,
        tenantId: tenantId);

    return new ArmClient(credentials);
}
英文:

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!

public async Task&lt;bool&gt; CopyDb(string? server, string? fromName, string? toName)
{
_log.LogInformation(&quot;Connecting to Azure&quot;);
var azure = GetAzureSubscription();
var servers = azure.GetSqlServers().ToList();
var fromServer = servers.SingleOrDefault(f =&gt; server != null &amp;&amp; f.Data != null &amp;&amp; server.Contains(f.Data.Name));
if (fromServer == null)
{
throw new InvalidOperationException(&quot;Unable to find original database server&quot;);
}
var oldName = $&quot;{toName}-Old&quot;;
var databases = fromServer.GetSqlDatabases();
_log.LogInformation(&quot;Check for any existing backup called {0}&quot;, oldName);
if (await databases.ExistsAsync(oldName))
{
_log.LogInformation(&quot;Deleting for any existing backup called {0}&quot;, oldName);
var oldBackup = await databases.GetAsync(oldName);
await oldBackup.Value.DeleteAsync(WaitUntil.Completed);
}
_log.LogInformation(&quot;Check target database {0} exists&quot;, toName, oldName);
if (await databases.ExistsAsync(toName))
{
_log.LogInformation(&quot;Renaming target database from {0} to {1}&quot;, toName, oldName);
var toDbBackup = await databases.GetAsync(toName);
var resourceIdString = toDbBackup.Value.Data.Id.Parent?.ToString();
var newResourceId = new ResourceIdentifier($&quot;{resourceIdString}/databases/{oldName}&quot;);
var moveDefinition = new SqlResourceMoveDefinition(newResourceId);
var toDb = await toDbBackup.Value.GetAsync();
await toDb.Value.RenameAsync(moveDefinition);
}
_log.LogInformation(&quot;Copying database from from {0} to {1}&quot;, fromName, toName);
var fromDb = await databases.GetAsync(fromName);
var result = await databases.CreateOrUpdateAsync(WaitUntil.Completed, toName, fromDb.Value.Data);
_log.LogInformation(&quot;Operation completed!&quot;);
return result.HasValue;
}
private SubscriptionResource GetAzureSubscription()
{
var configValue = _configuration[&quot;AzureSubscriptionId&quot;];
var subscriptionId = new ResourceIdentifier($&quot;/subscriptions/{configValue}&quot;);
return GetAzureArmClient().GetSubscriptionResource(subscriptionId);
}
private ArmClient GetAzureArmClient()
{
var clientId = _configuration[&quot;AzureClientId&quot;];
var clientSecret = _configuration[&quot;AzureClientSecret&quot;];
var tenantId = _configuration[&quot;AzureTenantId&quot;];
var credentials = new ClientSecretCredential(
clientId: clientId,
clientSecret: clientSecret,
tenantId: tenantId);
return new ArmClient(credentials);
}

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:

确定