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

iqih9akk  于 2023-02-16  发布在  其他
关注(0)|答案(1)|浏览(147)

作为一点背景知识,我希望将C#应用中的现有代码从现有的Microsoft.Azure.Management.Fluent(现已弃用)替换为较新的Azure.ResourceManager组件。
复制数据库的现有代码:

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);
}

较新的组件都使用资源,我一直在努力如何使用较新的Azure.ArmClient执行一些操作。我已经能够使用它进行查询,找到我的SQL服务器和数据库。我甚至可以删除一些数据库,但我无法解决如何像上面的代码那样重命名或复制数据库。我知道有其他方法可以直接在SQL中执行此操作,但我更想看看如何用代码来实现。
我已经看了一下MS文档,我只能找到对象定义的信息,但没有示例。
我已设法着手重新命名:

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);
}

我不确定如何定义SqlResourceMoveDefinition。我也完全无法像在旧版SDK中那样执行复制。
有谁有关于如何在C#中实现这些操作的指南吗?

tjvv9vkg

tjvv9vkg1#

最终从https://learn.microsoft.com/en-us/dotnet/azure/sdk/resource-management?tabs=PowerShell开始工作后,我设法解决了这个问题。可能有更好的方法来做到这一点,如果其他人到那时还没有找到答案,我会在找到答案后编辑答案!

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);
}

相关问题