Compartilhar via


Início Rápido: Compartilhar e receber dados com o SDK do .NET Compartilhamento de Dados do Microsoft Purview

Importante

Este recurso está atualmente no modo de visualização. Os Termos de Uso Suplementares para Visualizações do Microsoft Azure incluem termos legais adicionais que se aplicam aos recursos do Azure que estão em versão beta, em versão prévia ou ainda não lançados em disponibilidade geral.

Neste início rápido, você usará o SDK do .NET para compartilhar dados e receber compartilhamentos de Azure Data Lake Storage (ADLS Gen2) ou contas de armazenamento de blobs. O artigo inclui snippets de código que permitem criar, aceitar e gerenciar compartilhamentos usando Compartilhamento de Dados do Microsoft Purview.

Para obter uma visão geral de como o compartilhamento de dados funciona, watch essa demonstração curta.

Observação

Esse recurso foi atualizado em fevereiro de 2023 e o SDK e as permissões necessárias para exibir e gerenciar compartilhamentos de dados no Microsoft Purview foram alterados.

  • Agora não são necessárias permissões no Microsoft Purview para usar o SDK para criar e gerenciar compartilhamentos. (Permissões de leitor são necessárias para usar o Portal de Governança do Microsoft Purview para compartilhamento de dados.)
  • As permissões ainda são necessárias em contas de armazenamento.

Consulte o pacote NuGet atualizado e os snippets de código atualizados para usar o SDK atualizado.

Pré-requisitos

Pré-requisitos do Microsoft Purview

  • Uma conta do Microsoft Purview. Você também pode usar duas contas do Microsoft Purview, uma para provedor de dados e outra para consumidor de dados para testar ambos os cenários.
  • O endereço de email de entrada do Azure do destinatário que você pode usar para enviar o convite. O alias de email do destinatário não funcionará.

Pré-requisitos da conta de armazenamento do Azure

  • Sua assinatura do Azure deve ser registrada para o recurso de visualização AllowDataSharing . Siga as etapas abaixo usando portal do Azure ou PowerShell.

    1. Em portal do Azure, selecione sua assinatura do Azure que você usará para criar a conta de armazenamento de origem e de destino.
    2. No menu à esquerda, selecione Visualizar recursos em Configurações.
    3. Selecione PermitirDataSharing e Registrar.
    4. Atualize a tela Recursos de visualização para verificar se o Estado está registrado. Pode levar de 15 minutos a 1 hora para o registro ser concluído.
    5. Além disso, para usar o compartilhamento de dados para contas de armazenamento no Leste dos EUA, Leste dos EUA2, Norte da Europa, Centro-Sul dos EUA, Centro-Oeste dos EUA, Oeste dos EUA, Oeste dos EUA2, Oeste dos EUA3: Selecione AllowDataSharingInHeroRegion and Register

    Para obter mais informações, confira Registrar recurso de visualização.

    O RegistrationState deve ser Registrado. Pode levar de 15 minutos a 1 hora para o registro ser concluído. Para obter mais informações, confira Registrar recurso de visualização.

    Observação

    A seguir estão configurações de conta de armazenamento com suporte:

    • Regiões do Azure: Canadá Central, Leste do Canadá, Sul do Reino Unido, Oeste do Reino Unido, Leste da Austrália, Leste do Japão, Sul da Coreia do Sul e Norte da África do Sul
    • Regiões adicionais do Azure: Leste dos EUA, Leste dos EUA2, Norte da Europa, Sulcentral dos EUA, Centro-Oeste dos EUA, Oeste dos EUA, Oeste dos EUA2, Oeste dos EUA3
    • Desempenho: Standard
    • Opções de redundância: LRS
  • Contas de armazenamento de origem e de destino criadas após a conclusão da etapa de registro. Ambas as contas de armazenamento devem estar na mesma região do Azure que as outras. Ambas as contas de armazenamento precisam ser contas do ADLS Gen2 ou do Armazenamento de Blobs. Suas contas de armazenamento podem estar em uma região do Azure diferente da sua conta do Microsoft Purview.

  • Versão mais recente do SDK de armazenamento, PowerShell, CLI e Gerenciador de Armazenamento do Azure. A versão da API REST de armazenamento deve ser fevereiro de 2020 ou posterior.

  • As contas de armazenamento precisam ser registradas nas coleções para onde você enviará ou receberá o compartilhamento. Se você estiver usando uma conta do Microsoft Purview, isso pode ser duas coleções diferentes ou a mesma coleção. Para obter instruções para registrar, consulte as páginas de fonte de dados do Armazenamento de Blobs ou do ADLS Gen2.

  • Se as contas de armazenamento de origem ou destino estiverem em uma assinatura do Azure diferente da da conta do Microsoft Purview, o provedor de recursos Microsoft.Purview será registrado automaticamente na assinatura do Azure em que o repositório de dados está localizado no momento do provedor de compartilhamento adicionando um ativo ou compartilhamento do consumidor mapeando um ativo e SOMENTE se o usuário tiver permissão para fazer a operação /register/action para o provedor de recursos. A permissão está incluída nas funções Colaborador e Proprietário.

    Observação

    Esse registro só é necessário na primeira vez ao compartilhar ou receber dados em uma conta de armazenamento na assinatura do Azure.

Funções necessárias

Aqui estão funções necessárias para compartilhar dados e receber compartilhamentos.

Funções da conta de armazenamento do Azure Funções de coleção do Microsoft Purview
Provedor de dados Uma das seguintes funções:
  • Proprietário
  • Proprietário de dados de blob de armazenamento
Leitor de Dados
Consumidor de dados Uma das seguintes funções:
  • Colaborador
  • Proprietário
  • Colaborador de dados de blob de armazenamento
  • Proprietário de dados de blob de armazenamento
Leitor de Dados

Observação

Se você criou a conta do Microsoft Purview, você recebe automaticamente todas as funções para a coleção raiz. Consulte as permissões do Microsoft Purview para saber mais sobre a coleção e funções do Microsoft Purview.

Visual Studio

O passo a passo neste artigo usa o Visual Studio 2022. Os procedimentos para Visual Studio 2013, 2015, 2017 ou 2019 podem ser ligeiramente diferentes.

Azure .NET SDK

Baixe e instale o SDK do .NET do Azure em seu computador.

Usar uma entidade de serviço

Nos snippets de código neste tutorial, você pode autenticar usando suas próprias credenciais ou usando uma entidade de serviço. Para configurar uma entidade de serviço, siga estas instruções:

  1. Em Criar um aplicativo do Azure Active Directory, crie um aplicativo que represente o aplicativo .NET que você está criando neste tutorial. Para a URL de logon, você pode fornecer uma URL fictícia, conforme mostrado no artigo (https://contoso.org/exampleapp).

  2. Em Obter valores para entrar, obtenha a ID do aplicativo, a ID do locatário e a ID do objeto e observe esses valores usados posteriormente neste tutorial.

  3. Em Certificados e segredos, obtenha a chave de autenticação e anote esse valor que você usa mais tarde neste tutorial.

  4. atribuir o aplicativo a essas funções:

    User Funções da conta de armazenamento do Azure Funções de coleção do Microsoft Purview
    Provedor de dados Uma das seguintes funções:
    • Proprietário
    • Proprietário de dados de armazenamento de blobs
    colaborador Data Share
    Consumidor de dados Uma das seguintes funções:
    • Colaborador
    • Proprietário
    • Colaborador de dados de blob de armazenamento
    • Proprietário de dados de armazenamento de blobs
    colaborador Data Share

Criar um projeto do Visual Studio

Em seguida, crie um aplicativo de console .NET em C# no Visual Studio:

  1. Inicie o Visual Studio.
  2. Na janela Iniciar, selecione Criar um aplicativo de console de projeto>. A versão 6.0 ou superior do .NET é necessária.
  3. No nome do projeto, insira PurviewDataSharingQuickStart.
  4. Selecione Criar para criar o projeto.

Instalar pacotes NuGet

  1. Selecione FerramentasDo Console do Gerenciador de Pacotes> doGerenciador de Pacotes> do NuGet.

  2. No Console de Gerenciamento de Pacotes , execute o comando de pacote de adição da cli do .NET mostrado nesta página para adicionar o pacote NuGet: Pacote NuGet: Microsoft.Azure.Analytics.Purview.Sharing NuGet.

  3. No painel Console do Gerenciador de Pacotes , execute os seguintes comandos para instalar pacotes.

    Install-Package Azure.Analytics.Purview.Sharing -IncludePrerelease
    Install-Package Azure.Identity
    

    Dica

    Se você receber um erro que diz "Não foi possível localizar nenhum projeto em..." Ao tentar esses comandos, talvez seja necessário apenas mover um nível de pasta para baixo em seu projeto. Experimente o comando dir para listar pastas em seu diretório e, em seguida, use "nome do cd <da pasta> do projeto" para baixar um nível para sua pasta de projeto. Então tente novamente.

Criar um compartilhamento enviado

Esse script cria um compartilhamento de dados que você pode enviar para usuários internos ou externos. Para usá-lo, certifique-se de preencher estas variáveis:

  • SenderTenantId - a ID do Locatário do Azure para a identidade do remetente.
  • SenderPurviewAccountName - o nome da conta do Microsoft Purview de onde os dados serão enviados.
  • ShareName – Um nome de exibição para o compartilhamento enviado.
  • ShareDescription – (opcional) Uma descrição para o compartilhamento enviado.
  • SenderStorageKind – BlobAccount ou AdlsGen2Account.
  • SenderStorageResourceId - a ID do recurso da conta de armazenamento da qual os dados serão enviados.
  • SenderStorageContainer – o nome do contêiner em que os dados a serem compartilhados são armazenados.
  • SenderPathToShare – o caminho arquivo/pasta para os dados a serem compartilhados.
  • UseServiceTokenCredentials – (opcional) Se você quiser usar uma entidade de serviço para criar os compartilhamentos, defina isso como true.
  • SenderClientId – (opcional) Se usar uma entidade de serviço para criar os compartilhamentos, esta será a ID do aplicativo (cliente) da entidade de serviço.
  • SenderClientSecret – (opcional) Se usar uma entidade de serviço para criar os compartilhamentos, adicione a chave segredo/autenticação do cliente.
  • SentShareID - (opcional) Essa opção deve ser um GUID e o valor atual gera um para você, mas você pode substituí-lo por um valor diferente, se desejar.
  • ReceiverVisiblePath – (opcional) O nome para o compartilhamento que o receptor verá. Atualmente definido como guid, mas GUID não é necessário.
  • SenderPurviewEndPoint – Se você estiver usando a experiência clássica do Microsoft Purview, use $"https://{SenderPurviewAccountName}.purview.azure.com"; Se você estiver usando a nova experiência do Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;
using System.ComponentModel;

public static class PurviewDataSharingQuickStart
{
    // [REQUIRED INPUTS] Set To Actual Values.
    private static string SenderTenantId = "<Sender Identity's Tenant ID>";
    private static string SenderPurviewAccountName = "<Sender Purview Account Name>";

    private static string ShareName = "<Share Display Name>";
    private static string ShareDescription = "Share created using the SDK.";
    private static string SenderStorageKind = "<Sender Storage Account Kind (BlobAccount / AdlsGen2Account)>";
    private static string SenderStorageResourceId = "<Sender Storage Account Resource Id>";
    private static string SenderStorageContainer = "<Share Data Container Name>";
    private static string SenderPathToShare = "<File/Folder Path To Share>";

    // Set if using Service principal to create shares
    private static bool UseServiceTokenCredentials = false;
    private static string SenderClientId = "<Sender Application (Client) Id>";
    private static string SenderClientSecret = "<Sender Application (Client) Secret>";

    // [OPTIONAL INPUTS] Override Value If Desired.
    private static string SentShareId = Guid.NewGuid().ToString();
    private static string ReceiverVisiblePath = Guid.NewGuid().ToString();

    // General Configs
    private static string SenderPurviewEndPoint = $"https://{SenderPurviewAccountName}.purview.azure.com";
    private static string SenderShareEndPoint = $"{SenderPurviewEndPoint}/share";

    private static async Task Main(string[] args)
    {
        try
        {
            /// Replace all placeholder inputs above with actual values before running this program.
            /// This updated Share experience API will create Shares based on callers RBAC role on the storage account.
            /// To view/manage Shares via UX in Purview Studio. Storage accounts need to be registered (one time action) in Purview account with DSA permissions.

            Console.WriteLine($"{DateTime.Now.ToShortTimeString()}: CreateShare - START");
            await Sender_CreateSentShare();
            Console.WriteLine($"{DateTime.Now.ToShortTimeString()}: CreateShare - FINISH");
        }
        catch (Exception ex)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(ex);
            Console.ForegroundColor = Console.ForegroundColor;
        }
    }

    private static async Task<BinaryData> Sender_CreateSentShare()
    {

        TokenCredential senderCredentials = UseServiceTokenCredentials
                ? new ClientSecretCredential(SenderTenantId, SenderClientId, SenderClientSecret)
                : new DefaultAzureCredential(new DefaultAzureCredentialOptions { AuthorityHost = new Uri("https://login.windows.net"), TenantId = SenderTenantId });

        SentSharesClient? sentSharesClient = new SentSharesClient(SenderShareEndPoint, senderCredentials);

        if (sentSharesClient == null)
        {
            throw new InvalidEnumArgumentException("Invalid Sent Shares Client.");
        }

        // Create sent share
        var inPlaceSentShareDto = new
        {
            shareKind = "InPlace",
            properties = new
            {
                displayName = ShareName,
                description = ShareDescription,
                artifact = new
                {
                    storeKind = SenderStorageKind,
                    storeReference = new
                    {
                        referenceName = SenderStorageResourceId,
                        type = "ArmResourceReference"
                    },
                    properties = new
                    {
                        paths = new[]
                        {
                            new
                            {
                                receiverPath = ReceiverVisiblePath,
                                containerName = SenderStorageContainer,
                                senderPath = SenderPathToShare
                            }
                        }
                    }
                }
            },
        };

        Operation<BinaryData> sentShare = await sentSharesClient.CreateOrReplaceSentShareAsync(WaitUntil.Completed, SentShareId, RequestContent.Create(inPlaceSentShareDto));
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine(sentShare.Value);
        Console.ForegroundColor = Console.ForegroundColor;
        return sentShare.Value;
    }
}

Enviar convite para um usuário

Este script envia um convite por email para um compartilhamento para um usuário. Se você quiser enviar um convite para uma entidade de serviço, consulte o próximo exemplo de código. Para usá-lo, certifique-se de preencher estas variáveis:

  • RecipientUserEmailId – Email endereço para o qual o usuário enviará o convite.
  • SenderTenantId - a ID do Locatário do Azure para a identidade do remetente de compartilhamento.
  • SenderPurviewAccountName - o nome da conta do Microsoft Purview de onde os dados serão enviados.
  • SenderStorageResourceId - a ID do recurso da conta de armazenamento da qual os dados serão enviados.
  • SentShareDisplayName - o nome do compartilhamento enviado para o qual você está enviando um convite.
  • UseServiceTokenCredentials – (opcional) Se você quiser usar uma entidade de serviço para criar os compartilhamentos, defina isso como true.
  • SenderClientId – (opcional) Se usar uma entidade de serviço para criar os compartilhamentos, esta será a ID do aplicativo (cliente) da entidade de serviço.
  • SenderClientSecret – (opcional) Se usar uma entidade de serviço para criar os compartilhamentos, adicione a chave segredo/autenticação do cliente.
  • InvitationId – (opcional) Essa opção deve ser um GUID e o valor atual gera um para você, mas você pode substituí-lo por um valor diferente, se desejar.
  • SenderPurviewEndPoint – Se você estiver usando a experiência clássica do Microsoft Purview, use $"https://{SenderPurviewAccountName}.purview.azure.com"; Se você estiver usando a nova experiência do Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;
using System.ComponentModel;
using System.Text.Json;

public static class PurviewDataSharingQuickStart
{
    // [REQUIRED INPUTS] Set To Actual Values.
    private static string RecipientUserEmailId = "<Target User's Email Id>";

    private static string SenderTenantId = "<Sender Indentity's Tenant ID>";
    private static string SenderPurviewAccountName = "<Sender Purview Account Name>";
    private static string SenderStorageResourceId = "<Sender Storage Account Resource Id>";

    // Set if using Service principal to send invitation
    private static bool UseServiceTokenCredentials = false;
    private static string SenderClientId = "<Sender Application (Client) Id>";
    private static string SenderClientSecret = "<Sender Application (Client) Secret>";

    private static string SentShareDisplayName = "<Name of share you're sending an invite for.>";
    private static string InvitationId = Guid.NewGuid().ToString();

    // General Configs
    private static string SenderPurviewEndPoint = $"https://{SenderPurviewAccountName}.purview.azure.com";
    private static string SenderShareEndPoint = $"{SenderPurviewEndPoint}/share";
    private static int StepCounter = 0;

    private static async Task Main(string[] args)
    {
        try
        {

            Console.WriteLine($"{DateTime.Now.ToShortTimeString()}: SendtoUser - START");
            await Sender_CreateUserRecipient();
            Console.WriteLine($"{DateTime.Now.ToShortTimeString()}: SendtoUser - FINISH");
        }
        catch (Exception ex)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(ex);
            Console.ForegroundColor = Console.ForegroundColor;
        }
    }

    public static async Task<List<T>> ToResultList<T>(this AsyncPageable<T> asyncPageable)
    {
        List<T> list = new List<T>();

        await foreach (T item in asyncPageable)
        {
            list.Add(item);
        }

        return list;
    }

    private static async Task<BinaryData> Sender_CreateUserRecipient()
    {

        TokenCredential senderCredentials = UseServiceTokenCredentials
                ? new ClientSecretCredential(SenderTenantId, SenderClientId, SenderClientSecret)
                : new DefaultAzureCredential(new DefaultAzureCredentialOptions { AuthorityHost = new Uri("https://login.windows.net"), TenantId = SenderTenantId });

        SentSharesClient? sentSharesClient = new SentSharesClient(SenderShareEndPoint, senderCredentials);

        if (string.IsNullOrEmpty(RecipientUserEmailId))
        {
            throw new InvalidEnumArgumentException("Invalid Recipient User Email Id.");
        }

        // Create user recipient and invite
        var invitationData = new
        {
            invitationKind = "User",
            properties = new
            {
                expirationDate = DateTime.Now.AddDays(7).ToString(),
                notify = true, // Send invitation email
                targetEmail = RecipientUserEmailId
            }
        };

        var allSentShares = await sentSharesClient.GetAllSentSharesAsync(SenderStorageResourceId).ToResultList();

        Console.ForegroundColor = ConsoleColor.Yellow;
        Console.WriteLine("{0}. {1}...", ++StepCounter, "Get a Specific Sent Share");
        Console.ForegroundColor = Console.ForegroundColor;

        var mySentShare = allSentShares.First(sentShareDoc =>
        {
            var doc = JsonDocument.Parse(sentShareDoc).RootElement;
            var props = doc.GetProperty("properties");
            return props.GetProperty("displayName").ToString() == SentShareDisplayName;
        });

        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine("My Sent Share Id: " + JsonDocument.Parse(mySentShare).RootElement.GetProperty("id").ToString());
        Console.ForegroundColor = Console.ForegroundColor;

        var SentShareId = JsonDocument.Parse(mySentShare).RootElement.GetProperty("id").ToString();

        var sentInvitation = await sentSharesClient.CreateSentShareInvitationAsync(SentShareId, InvitationId, RequestContent.Create(invitationData));

        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine(sentInvitation.Content);
        Console.ForegroundColor = Console.ForegroundColor;

        return sentInvitation.Content;
    }
}

Enviar convite para um serviço

Este script envia um convite por email para um compartilhamento para uma entidade de serviço. Se você quiser enviar um convite a um usuário, consulte o exemplo anterior. Para usá-lo, certifique-se de preencher estas variáveis:

  • RecipientApplicationTenantId – a ID do Locatário do Azure para a entidade de serviço receptora.
  • RecipientApplicationObjectId - a ID do objeto para a entidade de serviço receptora.
  • SenderTenantId - a ID do Locatário do Azure para a identidade do remetente de compartilhamento.
  • SenderPurviewAccountName - o nome da conta do Microsoft Purview de onde os dados serão enviados.
  • SenderStorageResourceId - a ID do recurso da conta de armazenamento da qual os dados serão enviados.
  • SentShareDisplayName - o nome do compartilhamento enviado para o qual você está enviando um convite.
  • UseServiceTokenCredentials – (opcional) Se você quiser usar uma entidade de serviço para criar os compartilhamentos, defina isso como true.
  • SenderClientId – (opcional) Se usar uma entidade de serviço para criar os compartilhamentos, esta será a ID do aplicativo (cliente) da entidade de serviço.
  • SenderClientSecret – (opcional) Se usar uma entidade de serviço para criar os compartilhamentos, adicione a chave segredo/autenticação do cliente.
  • InvitationId – (opcional) Essa opção deve ser um GUID e o valor atual gera um para você, mas você pode substituí-lo por um valor diferente, se desejar.
  • SenderPurviewEndPoint – Se você estiver usando a experiência clássica do Microsoft Purview, use $"https://{SenderPurviewAccountName}.purview.azure.com"; Se você estiver usando a nova experiência do Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;
using System.ComponentModel;
using System.Text.Json;

public static class PurviewDataSharingQuickStart
{
    // [REQUIRED INPUTS] Set To Actual Values.
    private static string RecipientApplicationTenantId = "<Target Application's Tenant Id>";
    private static string RecipientApplicationObjectId = "<Target Application's Object Id>";

    private static string SentShareDisplayName = "<Name of share you're sending an invite for.>";
    private static string InvitationId = Guid.NewGuid().ToString();

    private static string SenderTenantId = "<Sender Indentity's Tenant ID>";
    private static string SenderPurviewAccountName = "<Sender Purview Account Name>";

    private static string SenderStorageResourceId = "<Resource ID for storage account that has been shared>";

    // Set if using Service principal to send invitation
    private static bool UseServiceTokenCredentials = false;
    private static string SenderClientId = "<Sender Application (Client) Id>";
    private static string SenderClientSecret = "<Sender Application (Client) Secret>";

    // General Configs
    private static string SenderPurviewEndPoint = $"https://{SenderPurviewAccountName}.purview.azure.com";
    private static string SenderShareEndPoint = $"{SenderPurviewEndPoint}/share";

    private static async Task Main(string[] args)
    {
        try
        {

            Console.WriteLine($"{DateTime.Now.ToShortTimeString()}: SendtoService - START");
            await Sender_CreateServiceRecipient();
            Console.WriteLine($"{DateTime.Now.ToShortTimeString()}: SendtoService - FINISH");
        }
        catch (Exception ex)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(ex);
            Console.ForegroundColor = Console.ForegroundColor;
        }
    }

    public static async Task<List<T>> ToResultList<T>(this AsyncPageable<T> asyncPageable)
    {
        List<T> list = new List<T>();

        await foreach (T item in asyncPageable)
        {
            list.Add(item);
        }

        return list;
    }

    private static async Task<BinaryData> Sender_CreateServiceRecipient()
    {

        TokenCredential senderCredentials = UseServiceTokenCredentials
                ? new ClientSecretCredential(SenderTenantId, SenderClientId, SenderClientSecret)
                : new DefaultAzureCredential(new DefaultAzureCredentialOptions { AuthorityHost = new Uri("https://login.windows.net"), TenantId = SenderTenantId });

        SentSharesClient? sentSharesClient = new SentSharesClient(SenderShareEndPoint, senderCredentials);

        if (!Guid.TryParse(RecipientApplicationTenantId, out Guid _))
        {
            throw new InvalidEnumArgumentException("Invalid Recipient Service Tenant Id.");
        }

        if (!Guid.TryParse(RecipientApplicationObjectId, out Guid _))
        {
            throw new InvalidEnumArgumentException("Invalid Recipient Service Object Id.");
        }

        // Create service recipient
        var invitationData = new
        {
            invitationKind = "Service",
            properties = new
            {
                expirationDate = DateTime.Now.AddDays(5).ToString(),
                targetActiveDirectoryId = RecipientApplicationTenantId,
                targetObjectId = RecipientApplicationObjectId
            }
        };


        var allSentShares = await sentSharesClient.GetAllSentSharesAsync(SenderStorageResourceId).ToResultList();
        var mySentShare = allSentShares.First(sentShareDoc =>
        {
            var doc = JsonDocument.Parse(sentShareDoc).RootElement;
            var props = doc.GetProperty("properties");
            return props.GetProperty("displayName").ToString() == SentShareDisplayName;
        });

        var SentShareId = JsonDocument.Parse(mySentShare).RootElement.GetProperty("id").ToString();

        var sentInvitation = await sentSharesClient.CreateSentShareInvitationAsync(SentShareId, InvitationId, RequestContent.Create(invitationData));
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine(sentInvitation.Content);
        Console.ForegroundColor = Console.ForegroundColor;
        return sentInvitation.Content;
    }

}

Listar compartilhamentos enviados

Este script lista todos os compartilhamentos enviados para um recurso de armazenamento específico. Para usá-lo, certifique-se de preencher estas variáveis:

  • SenderTenantId - a ID do Locatário do Azure para a identidade do remetente de compartilhamento.
  • SenderPurviewAccountName - o nome da conta do Microsoft Purview de onde os dados foram enviados.
  • SenderStorageResourceId - a ID do recurso da conta de armazenamento da qual os compartilhamentos foram enviados.
  • UseServiceTokenCredentials – (opcional) Se você quiser usar uma entidade de serviço para criar os compartilhamentos, defina isso como true.
  • SenderClientId – (opcional) Se usar uma entidade de serviço para criar os compartilhamentos, esta será a ID do aplicativo (cliente) da entidade de serviço.
  • SenderClientSecret – (opcional) Se usar uma entidade de serviço para criar os compartilhamentos, adicione a chave segredo/autenticação do cliente.
  • SenderPurviewEndPoint – Se você estiver usando a experiência clássica do Microsoft Purview, use $"https://{SenderPurviewAccountName}.purview.azure.com"; Se você estiver usando a nova experiência do Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;

public static class PurviewDataSharingQuickStart
{
    // [REQUIRED INPUTS] Set To Actual Values.
    private static string SenderTenantId = "<Sender Tenant ID>";
    private static string SenderPurviewAccountName = "<Name of the Microsoft Purview account>";
    private static string SenderStorageResourceId = "<Sender Storage Account Resource Id>";

    // Set if using Service principal to list shares
    private static bool UseServiceTokenCredentials = false;
    private static string SenderClientId = "<Sender Application (Client) Id>";
    private static string SenderClientSecret = "<Sender Application (Client) Secret>";

    // General Configs
    private static string SenderPurviewEndPoint = $"https://{SenderPurviewAccountName}.purview.azure.com";
    private static string SenderShareEndPoint = $"{SenderPurviewEndPoint}/share";

    private static async Task Main(string[] args)
    {


        try
        {
            TokenCredential senderCredentials = UseServiceTokenCredentials
                ? new ClientSecretCredential(SenderTenantId, SenderClientId, SenderClientSecret)
                : new DefaultAzureCredential(new DefaultAzureCredentialOptions { AuthorityHost = new Uri("https://login.windows.net"), TenantId = SenderTenantId });

            SentSharesClient? sentSharesClient = new SentSharesClient(SenderShareEndPoint, senderCredentials);

            var allSentShares = await sentSharesClient.GetAllSentSharesAsync(SenderStorageResourceId).ToResultList();
            Console.WriteLine(allSentShares);
        }
        catch (Exception ex)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(ex);
            Console.ForegroundColor = Console.ForegroundColor;
        }
    }

    public static async Task<List<T>> ToResultList<T>(this AsyncPageable<T> asyncPageable)
    {
        List<T> list = new List<T>();

        await foreach (T item in asyncPageable)
        {
            list.Add(item);
        }

        return list;
    }
}

Listar todos os destinatários de compartilhamento

Este script lista todos os destinatários para um compartilhamento específico. Para usá-lo, certifique-se de preencher estas variáveis:

  • SenderTenantId - a ID do Locatário do Azure para a identidade do remetente de compartilhamento.
  • SenderPurviewAccountName - o nome da conta do Microsoft Purview de onde os dados foram enviados.
  • SentShareDisplayName - o nome do compartilhamento enviado para o qual você está listando destinatários.
  • SenderStorageResourceId - a ID do recurso da conta de armazenamento da qual os dados serão enviados.
  • UseServiceTokenCredentials – (opcional) Se você quiser usar uma entidade de serviço para criar os compartilhamentos, defina isso como true.
  • SenderClientId – (opcional) Se usar uma entidade de serviço para criar os compartilhamentos, esta será a ID do aplicativo (cliente) da entidade de serviço.
  • SenderClientSecret – (opcional) Se usar uma entidade de serviço para criar os compartilhamentos, adicione a chave segredo/autenticação do cliente.
  • SenderPurviewEndPoint – Se você estiver usando a experiência clássica do Microsoft Purview, use $"https://{SenderPurviewAccountName}.purview.azure.com"; Se você estiver usando a nova experiência do Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;
using System.Text.Json;

public static class PurviewDataSharingQuickStart
{
    // [REQUIRED INPUTS] Set To Actual Values.
    private static string SentShareDisplayName = "<Name of share you're listing recipients for.>";
    private static string SenderTenantId = "<Sender Tenant ID>";
    private static string SenderPurviewAccountName = "<Name of the Microsoft Purview account>";

    private static string SenderStorageResourceId = "<Sender Storage Account Resource Id>";

    // Set if using Service principal to list recipients
    private static bool UseServiceTokenCredentials = false;
    private static string SenderClientId = "<Sender Application (Client) Id>";
    private static string SenderClientSecret = "<Sender Application (Client) Secret>";

    // General Configs
    private static string SenderPurviewEndPoint = $"https://{SenderPurviewAccountName}.purview.azure.com";
    private static string SenderShareEndPoint = $"{SenderPurviewEndPoint}/share";

    private static async Task Main(string[] args)
    {
        try
        {
            TokenCredential senderCredentials = UseServiceTokenCredentials
                ? new ClientSecretCredential(SenderTenantId, SenderClientId, SenderClientSecret)
                : new DefaultAzureCredential(new DefaultAzureCredentialOptions { AuthorityHost = new Uri("https://login.windows.net"), TenantId = SenderTenantId });

            SentSharesClient? sentSharesClient = new SentSharesClient(SenderShareEndPoint, senderCredentials);

            var allSentShares = await sentSharesClient.GetAllSentSharesAsync(SenderStorageResourceId).ToResultList();
            var mySentShare = allSentShares.First(sentShareDoc =>
            {
                var doc = JsonDocument.Parse(sentShareDoc).RootElement;
                var props = doc.GetProperty("properties");
                return props.GetProperty("displayName").ToString() == SentShareDisplayName;
            });

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("My Sent Share Id: " + JsonDocument.Parse(mySentShare).RootElement.GetProperty("id").ToString());
            Console.ForegroundColor = Console.ForegroundColor;

            var SentShareId = JsonDocument.Parse(mySentShare).RootElement.GetProperty("id").ToString();

            var allRecipients = await sentSharesClient.GetAllSentShareInvitationsAsync(SentShareId).ToResultList();
            Console.WriteLine(allRecipients);

        }
        catch (Exception ex)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(ex);
            Console.ForegroundColor = Console.ForegroundColor;
        }
    }

    public static async Task<List<T>> ToResultList<T>(this AsyncPageable<T> asyncPageable)
    {
        List<T> list = new List<T>();

        await foreach (T item in asyncPageable)
        {
            list.Add(item);
        }

        return list;
    }
}

Excluir destinatário

Esse script remove um convite de compartilhamento e, portanto, o compartilhamento, para um destinatário. Para usá-lo, certifique-se de preencher estas variáveis:

  • SenderTenantId - a ID do Locatário do Azure para a identidade do remetente de compartilhamento.
  • SenderPurviewAccountName - o nome da conta do Microsoft Purview de onde os dados foram enviados.
  • SentShareDisplayName - o nome do compartilhamento enviado para o qual você está removendo um destinatário.
  • SenderStorageResourceId - a ID do recurso da conta de armazenamento da qual os dados serão enviados.
  • RecipientUserEmailId – Email endereço para o usuário que você deseja excluir.
  • UseServiceTokenCredentials – (opcional) Se você quiser usar uma entidade de serviço para criar os compartilhamentos, defina isso como true.
  • SenderClientId – (opcional) Se usar uma entidade de serviço para criar os compartilhamentos, esta será a ID do aplicativo (cliente) da entidade de serviço.
  • SenderClientSecret – (opcional) Se usar uma entidade de serviço para criar os compartilhamentos, adicione a chave segredo/autenticação do cliente.
  • SenderPurviewEndPoint – Se você estiver usando a experiência clássica do Microsoft Purview, use $"https://{SenderPurviewAccountName}.purview.azure.com"; Se você estiver usando a nova experiência do Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;
using System.Text.Json;

public static class PurviewDataSharingQuickStart
{
    // [REQUIRED INPUTS] Set To Actual Values.
    private static string SentShareDisplayName = "<Name of share you're removing a recipient for.>";
    private static string SenderTenantId = "<Sender Tenant ID>";
    private static string SenderPurviewAccountName = "<Name of the Microsoft Purview account>";
    private static string RecipientUserEmailId = "<Target User's Email Id>";

    private static string SenderStorageResourceId = "<Sender Storage Account Resource Id>";

    // Set if using Service principal to delete recipients
    private static bool UseServiceTokenCredentials = false;
    private static string SenderClientId = "<Sender Application (Client) Id>";
    private static string SenderClientSecret = "<Sender Application (Client) Secret>";

    // General Configs
    private static string SenderPurviewEndPoint = $"https://{SenderPurviewAccountName}.purview.azure.com";
    private static string SenderShareEndPoint = $"{SenderPurviewEndPoint}/share";

    private static async Task Main(string[] args)
    {
        try
        {
            TokenCredential senderCredentials = UseServiceTokenCredentials
                ? new ClientSecretCredential(SenderTenantId, SenderClientId, SenderClientSecret)
                : new DefaultAzureCredential(new DefaultAzureCredentialOptions { AuthorityHost = new Uri("https://login.windows.net"), TenantId = SenderTenantId });

            SentSharesClient? sentSharesClient = new SentSharesClient(SenderShareEndPoint, senderCredentials);

            var allSentShares = await sentSharesClient.GetAllSentSharesAsync(SenderStorageResourceId).ToResultList();

            var mySentShare = allSentShares.First(sentShareDoc =>
            {
                var doc = JsonDocument.Parse(sentShareDoc).RootElement;
                var props = doc.GetProperty("properties");
                return props.GetProperty("displayName").ToString() == SentShareDisplayName;
            });

            var SentShareId = JsonDocument.Parse(mySentShare).RootElement.GetProperty("id").ToString();

            var allRecipients = await sentSharesClient.GetAllSentShareInvitationsAsync(SentShareId).ToResultList();

            var recipient = allRecipients.First(recipient =>
            {
                var doc = JsonDocument.Parse(recipient).RootElement;
                var props = doc.GetProperty("properties");
                return props.TryGetProperty("targetEmail", out JsonElement rcpt) && rcpt.ToString() == RecipientUserEmailId;
            });

            var recipientId = JsonDocument.Parse(recipient).RootElement.GetProperty("id").ToString();

            await sentSharesClient.DeleteSentShareInvitationAsync(WaitUntil.Completed, SentShareId, recipientId);

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Remove Id: " + JsonDocument.Parse(recipient).RootElement.GetProperty("id").ToString());
            Console.WriteLine("Complete");
            Console.ForegroundColor = Console.ForegroundColor;

        }

        catch (Exception ex)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(ex);
            Console.ForegroundColor = Console.ForegroundColor;
        }
    }

    public static async Task<List<T>> ToResultList<T>(this AsyncPageable<T> asyncPageable)
    {
        List<T> list = new List<T>();

        await foreach (T item in asyncPageable)
        {
            list.Add(item);
        }

        return list;
    }
}

Excluir compartilhamento enviado

Este script exclui um compartilhamento enviado. Para usá-lo, certifique-se de preencher estas variáveis:

  • SenderTenantId - a ID do Locatário do Azure para a identidade do remetente de compartilhamento.
  • SenderPurviewAccountName - o nome da conta do Microsoft Purview de onde os dados foram enviados.
  • SentShareDisplayName - o nome do compartilhamento enviado para o qual você está listando destinatários.
  • SenderStorageResourceId - a ID do recurso da conta de armazenamento da qual os dados serão enviados.
  • UseServiceTokenCredentials – (opcional) Se você quiser usar uma entidade de serviço para criar os compartilhamentos, defina isso como true.
  • SenderClientId – (opcional) Se usar uma entidade de serviço para criar os compartilhamentos, esta será a ID do aplicativo (cliente) da entidade de serviço.
  • SenderClientSecret – (opcional) Se usar uma entidade de serviço para criar os compartilhamentos, adicione a chave segredo/autenticação do cliente.
  • SenderPurviewEndPoint – Se você estiver usando a experiência clássica do Microsoft Purview, use $"https://{SenderPurviewAccountName}.purview.azure.com"; Se você estiver usando a nova experiência do Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;
using System.Text.Json;

public static class PurviewDataSharingQuickStart
{
    // [REQUIRED INPUTS] Set To Actual Values.
    private static string SenderTenantId = "<Sender Tenant ID>";
    private static string SenderPurviewAccountName = "<Name of the Microsoft Purview account>";
    private static string SentShareDisplayName = "<Name of share you're removing.>";

    private static string SenderStorageResourceId = "<Sender Storage Account Resource Id>";

    // Set if using Service principal to delete share
    private static bool UseServiceTokenCredentials = false;
    private static string SenderClientId = "<Sender Application (Client) Id>";
    private static string SenderClientSecret = "<Sender Application (Client) Secret>";

    // General Configs
    private static string SenderPurviewEndPoint = $"https://{SenderPurviewAccountName}.purview.azure.com";
    private static string SenderShareEndPoint = $"{SenderPurviewEndPoint}/share";

    private static async Task Main(string[] args)
    {
        try
        {
            TokenCredential senderCredentials = UseServiceTokenCredentials
                ? new ClientSecretCredential(SenderTenantId, SenderClientId, SenderClientSecret)
                : new DefaultAzureCredential(new DefaultAzureCredentialOptions { AuthorityHost = new Uri("https://login.windows.net"), TenantId = SenderTenantId });

            SentSharesClient? sentSharesClient = new SentSharesClient(SenderShareEndPoint, senderCredentials);

            var allSentShares = await sentSharesClient.GetAllSentSharesAsync(SenderStorageResourceId).ToResultList();

            var mySentShare = allSentShares.First(sentShareDoc =>
            {
                var doc = JsonDocument.Parse(sentShareDoc).RootElement;
                var props = doc.GetProperty("properties");
                return props.GetProperty("displayName").ToString() == SentShareDisplayName;
            });

            var SentShareId = JsonDocument.Parse(mySentShare).RootElement.GetProperty("id").ToString();

            await sentSharesClient.DeleteSentShareAsync(WaitUntil.Completed, SentShareId);

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Remove Id: " + SentShareId);
            Console.WriteLine("Complete");
            Console.ForegroundColor = Console.ForegroundColor;

        }
        catch (Exception ex)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(ex);
            Console.ForegroundColor = Console.ForegroundColor;
        }
    }

    public static async Task<List<T>> ToResultList<T>(this AsyncPageable<T> asyncPageable)
    {
        List<T> list = new List<T>();

        await foreach (T item in asyncPageable)
        {
            list.Add(item);
        }

        return list;
    }
}

Criar um compartilhamento recebido

Esse script permite que você receba um compartilhamento de dados. Para usá-lo, certifique-se de preencher estas variáveis:

  • ReceiverTenantId - a ID do Locatário do Azure para o usuário/serviço que está recebendo os dados compartilhados.
  • ReceiverPurviewAccountName - o nome da conta do Microsoft Purview em que os dados serão recebidos.
  • ReceiverStorageKind – BlobAccount ou AdlsGen2Account.
  • ReceiverStorageResourceId - a ID do recurso da conta de armazenamento em que os dados serão recebidos.
  • ReceiverStorageContainer - o nome do contêiner em que os dados compartilhados serão armazenados.
  • ReceiverTargetFolderName – o caminho da pasta para onde os dados compartilhados serão armazenados.
  • ReceiverTargetMountPath – o caminho de montagem que você gostaria de usar para armazenar seus dados na pasta.
  • UseServiceTokenCredentials – (opcional) Se você quiser usar uma entidade de serviço para receber os compartilhamentos, defina isso como true.
  • ReceiverClientId – (opcional) Se usar uma entidade de serviço para receber os compartilhamentos, esta será a ID do aplicativo (cliente) da entidade de serviço.
  • ReceiverClientSecret – (opcional) Se usar uma entidade de serviço para receber os compartilhamentos, adicione a chave segredo/autenticação do cliente.
  • ReceivedShareId - (opcional) Essa opção deve ser um GUID e o valor atual gerará um para você, mas você pode substituí-lo por um valor diferente, se desejar.
  • ReceiverVisiblePath – (opcional) Nome que você deseja usar para o caminho do compartilhamento recebido.
  • ReceivedShareDisplayName – (opcional) Um nome de exibição para o compartilhamento recebido.
  • ReceiverPurviewEndPoint - Se você estiver usando Se estiver usando a experiência clássica do Microsoft Purview, use $"https://{ReceiverPurviewAccountName}.purview.azure.com"; Se você estiver usando a nova experiência do Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;
using System.ComponentModel;
using System.Text.Json;

public static class PurviewDataSharingQuickStart
{
    // [REQUIRED INPUTS] Set To Actual Values.
    private static string ReceiverTenantId = "<Receiver Indentity's Tenant ID>";
    private static string ReceiverPurviewAccountName = "<Receiver Purview Account Name>";

    private static string ReceiverStorageKind = "<Receiver Storage Account Kind (BlobAccount / AdlsGen2Account)>";
    private static string ReceiverStorageResourceId = "<Receiver Storage Account Resource Id>";
    private static string ReceiverStorageContainer = "<Container Name To Receive Data Under>";
    private static string ReceiverTargetFolderName = "<Folder Name to Received Data Under>";
    private static string ReceiverTargetMountPath = "<Mount Path to store Received Data Under>";

    //Use if using a service principal to receive a share
    private static bool UseServiceTokenCredentials = false;
    private static string ReceiverClientId = "<Receiver Caller Application (Client) Id>";
    private static string ReceiverClientSecret = "<Receiver Caller Application (Client) Secret>";

    // [OPTIONAL INPUTS] Override Values If Desired.
    private static string ReceivedShareId = Guid.NewGuid().ToString();
    private static string ReceiverVisiblePath = "ReceivedSharePath";

    private static string ReceivedShareDisplayName = "ReceivedShare";

    // General Configs
    private static string ReceiverPurviewEndPoint = $"https://{ReceiverPurviewAccountName}.purview.azure.com";
    private static string ReceiverShareEndPoint = $"{ReceiverPurviewEndPoint}/share";

    private static async Task Main(string[] args)
    {
        try
        {


            Console.WriteLine($"{DateTime.Now.ToShortTimeString()}: CreateReceivedShare - START");
            await Receiver_CreateReceivedShare();
            Console.WriteLine($"{DateTime.Now.ToShortTimeString()}: CreateReceivedShare - FINISH");
        }
        catch (Exception ex)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(ex);
            Console.ForegroundColor = Console.ForegroundColor;
        }
    }

    private static async Task<BinaryData> Receiver_CreateReceivedShare()
    {

        TokenCredential receiverCredentials = UseServiceTokenCredentials
            ? new ClientSecretCredential(ReceiverTenantId, ReceiverClientId, ReceiverClientSecret)
            : new DefaultAzureCredential(new DefaultAzureCredentialOptions { AuthorityHost = new Uri("https://login.windows.net"), TenantId = ReceiverTenantId });

        ReceivedSharesClient? receivedSharesClient = new ReceivedSharesClient(ReceiverShareEndPoint, receiverCredentials);

        if (receivedSharesClient == null)
        {
            throw new InvalidEnumArgumentException("Invalid Received Shares Client.");
        }

        var results = await receivedSharesClient.GetAllDetachedReceivedSharesAsync().ToResultList();
        var detachedReceivedShare = results;

        if (detachedReceivedShare == null)
        {
            throw new InvalidOperationException("No received shares found.");
        }



        var myReceivedShare = detachedReceivedShare.First(recShareDoc =>
        {
            var doc = JsonDocument.Parse(recShareDoc).RootElement;
            var props = doc.GetProperty("properties");
            return props.GetProperty("displayName").ToString() == ReceivedShareDisplayName;
        });

        var ReceivedShareId = JsonDocument.Parse(myReceivedShare).RootElement.GetProperty("id").ToString();


        var attachedReceivedShareData = new
        {
            shareKind = "InPlace",
            properties = new
            {
                displayName = ReceivedShareDisplayName,
                sink = new
                {
                    storeKind = ReceiverStorageKind,
                    properties = new
                    {
                        containerName = ReceiverStorageContainer,
                        folder = ReceiverTargetFolderName,
                        mountPath = ReceiverTargetMountPath
                    },
                    storeReference = new
                    {
                        referenceName = ReceiverStorageResourceId,
                        type = "ArmResourceReference"
                    }
                }
            }
        };

        var receivedShare = await receivedSharesClient.CreateOrReplaceReceivedShareAsync(WaitUntil.Completed, ReceivedShareId, RequestContent.Create(attachedReceivedShareData));

        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine(receivedShare.Value);
        Console.ForegroundColor = Console.ForegroundColor;

        return receivedShare.Value;
    }

    public static async Task<List<T>> ToResultList<T>(this AsyncPageable<T> asyncPageable)
    {
        List<T> list = new List<T>();

        await foreach (T item in asyncPageable)
        {
            list.Add(item);
        }

        return list;
    }
}

Listar todos os compartilhamentos recebidos

Este script lista todos os compartilhamentos recebidos em uma conta de armazenamento. Para usá-lo, certifique-se de preencher estas variáveis:

  • ReceiverTenantId - a ID do Locatário do Azure para o usuário/serviço que está recebendo os dados compartilhados.
  • ReceiverPurviewAccountName - o nome da conta do Microsoft Purview em que os dados foram recebidos.
  • ReceiverStorageResourceId - a ID do recurso da conta de armazenamento em que os dados foram compartilhados.
  • UseServiceTokenCredentials – (opcional) Se você quiser usar uma entidade de serviço para receber os compartilhamentos, defina isso como true.
  • ReceiverClientId – (opcional) Se usar uma entidade de serviço para receber os compartilhamentos, esta será a ID do aplicativo (cliente) da entidade de serviço.
  • ReceiverClientSecret – (opcional) Se usar uma entidade de serviço para receber os compartilhamentos, adicione a chave segredo/autenticação do cliente.
  • ReceiverPurviewEndPoint - Se você estiver usando Se estiver usando a experiência clássica do Microsoft Purview, use $"https://{ReceiverPurviewAccountName}.purview.azure.com"; Se você estiver usando a nova experiência do Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;

public static class PurviewDataSharingQuickStart
{
    // [REQUIRED INPUTS] Set To Actual Values.
    private static string ReceiverTenantId = "<Receiver Indentity's Tenant ID>";
    private static string ReceiverPurviewAccountName = "<Receiver Purview Account Name>";

    private static string ReceiverStorageResourceId = "<Storage Account Resource Id that is housing shares>";

    //Use if using a service principal to list shares
    private static bool UseServiceTokenCredentials = false;
    private static string ReceiverClientId = "<Receiver Caller Application (Client) Id>";
    private static string ReceiverClientSecret = "<Receiver Caller Application (Client) Secret>";

    // General Configs
    private static string ReceiverPurviewEndPoint = $"https://{ReceiverPurviewAccountName}.purview.azure.com";
    private static string ReceiverShareEndPoint = $"{ReceiverPurviewEndPoint}/share";

    private static async Task Main(string[] args)
    {
        try
        {
            TokenCredential receiverCredentials = UseServiceTokenCredentials
            ? new ClientSecretCredential(ReceiverTenantId, ReceiverClientId, ReceiverClientSecret)
            : new DefaultAzureCredential(new DefaultAzureCredentialOptions { AuthorityHost = new Uri("https://login.windows.net"), TenantId = ReceiverTenantId });

            ReceivedSharesClient? receivedSharesClient = new ReceivedSharesClient(ReceiverShareEndPoint, receiverCredentials);

            var allReceivedShares = await receivedSharesClient.GetAllAttachedReceivedSharesAsync(ReceiverStorageResourceId).ToResultList();
            Console.WriteLine(allReceivedShares);
        }
        catch (Exception ex)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(ex);
            Console.ForegroundColor = Console.ForegroundColor;
        }
    }

    public static async Task<List<T>> ToResultList<T>(this AsyncPageable<T> asyncPageable)
    {
        List<T> list = new List<T>();

        await foreach (T item in asyncPageable)
        {
            list.Add(item);
        }

        return list;
    }
}

Atualizar o compartilhamento recebido

Esse script permite que você atualize o local de armazenamento para um compartilhamento recebido. Assim como criar um compartilhamento recebido, você adiciona as informações para a conta de armazenamento em que deseja que os dados sejam alojados. Para usá-lo, certifique-se de preencher estas variáveis:

  • ReceiverTenantId - a ID do Locatário do Azure para o usuário/serviço que está recebendo os dados compartilhados.
  • ReceiverPurviewAccountName - o nome da conta do Microsoft Purview em que os dados serão recebidos.
  • ReceiverStorageKind – BlobAccount ou AdlsGen2Account.
  • ReceiverStorageResourceId - a ID do recurso da conta de armazenamento em que os dados foram compartilhados.
  • ReAttachStorageResourceId - a ID do recurso da conta de armazenamento em que os dados serão recebidos.
  • ReceiverStorageContainer - o nome do contêiner em que os dados compartilhados serão armazenados.
  • ReceiverTargetFolderName – o caminho da pasta para onde os dados compartilhados serão armazenados.
  • ReceiverTargetMountPath – o caminho de montagem que você gostaria de usar para armazenar seus dados na pasta.
  • ReceivedShareDisplayName – O nome de exibição do compartilhamento recebido.
  • UseServiceTokenCredentials – (opcional) Se você quiser usar uma entidade de serviço para receber os compartilhamentos, defina isso como true.
  • ReceiverClientId – (opcional) Se usar uma entidade de serviço para receber os compartilhamentos, esta será a ID do aplicativo (cliente) da entidade de serviço.
  • ReceiverClientSecret – (opcional) Se usar uma entidade de serviço para receber os compartilhamentos, adicione a chave segredo/autenticação do cliente.
  • ReceiverPurviewEndPoint - Se você estiver usando Se estiver usando a experiência clássica do Microsoft Purview, use $"https://{ReceiverPurviewAccountName}.purview.azure.com"; Se você estiver usando a nova experiência do Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;
using System.ComponentModel;
using System.Text.Json;

public static class PurviewDataSharingQuickStart
{
    // [REQUIRED INPUTS] Set To Actual Values.
    private static string ReceiverTenantId = "<Receiver Indentity's Tenant ID>";
    private static string ReceiverPurviewAccountName = "<Receiver Purview Account Name>";

    private static string ReceiverStorageKind = "<Receiver Storage Account Kind (BlobAccount / AdlsGen2Account)>";
    private static string ReceiverStorageResourceId = "<Storage Account Resource Id for the account where the share is currently attached.>";
    private static string ReAttachStorageResourceId = "<Storage Account Resource Id For Reattaching Received Share>";
    private static string ReceiverStorageContainer = "<Container Name To Receive Data Under>";
    private static string ReceiverTargetFolderName = "<Folder Name to Received Data Under>";
    private static string ReceiverTargetMountPath = "<Mount Path to Received Data Under>";

    private static string ReceivedShareDisplayName = "<Display name of your received share>";

    //Use if using a service principal to update the share
    private static bool UseServiceTokenCredentials = false;
    private static string ReceiverClientId = "<Receiver Caller Application (Client) Id>";
    private static string ReceiverClientSecret = "<Receiver Caller Application (Client) Secret>";

    // General Configs
    private static string ReceiverPurviewEndPoint = $"https://{ReceiverPurviewAccountName}.purview.azure.com";
    private static string ReceiverShareEndPoint = $"{ReceiverPurviewEndPoint}/share";

    private static async Task Main(string[] args)
    {
        try
        {

            Console.WriteLine($"{DateTime.Now.ToShortTimeString()}: UpdateReceivedShare - START");
            await Receiver_UpdateReceivedShare();
            Console.WriteLine($"{DateTime.Now.ToShortTimeString()}: UpdateReceivedShare - FINISH");
        }
        catch (Exception ex)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(ex);
            Console.ForegroundColor = Console.ForegroundColor;
        }
    }

    private static async Task<BinaryData> Receiver_UpdateReceivedShare()
    {

        TokenCredential receiverCredentials = UseServiceTokenCredentials
            ? new ClientSecretCredential(ReceiverTenantId, ReceiverClientId, ReceiverClientSecret)
            : new DefaultAzureCredential(new DefaultAzureCredentialOptions { AuthorityHost = new Uri("https://login.windows.net"), TenantId = ReceiverTenantId });

        ReceivedSharesClient? receivedSharesClient = new ReceivedSharesClient(ReceiverShareEndPoint, receiverCredentials);

        if (receivedSharesClient == null)
        {
            throw new InvalidEnumArgumentException("Invalid Received Shares Client.");
        }

        var attachedReceivedShareData = new
        {
            shareKind = "InPlace",
            properties = new
            {
                displayName = ReceivedShareDisplayName,
                sink = new
                {
                    storeKind = ReceiverStorageKind,
                    properties = new
                    {
                        containerName = ReceiverStorageContainer,
                        folder = ReceiverTargetFolderName,
                        mountPath = ReceiverTargetMountPath
                    },
                    storeReference = new
                    {
                        referenceName = ReAttachStorageResourceId,
                        type = "ArmResourceReference"
                    }
                }
            }
        };

        var allReceivedShares = await receivedSharesClient.GetAllAttachedReceivedSharesAsync(ReceiverStorageResourceId).ToResultList();

        var myReceivedShare = allReceivedShares.First(recShareDoc =>
        {
            var doc = JsonDocument.Parse(recShareDoc).RootElement;
            var props = doc.GetProperty("properties");
            return props.GetProperty("displayName").ToString() == ReceivedShareDisplayName;
        });

        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine("My Received Share Id: " + JsonDocument.Parse(myReceivedShare).RootElement.GetProperty("id").ToString());
        Console.ForegroundColor = Console.ForegroundColor;


        var ReceivedShareId = JsonDocument.Parse(myReceivedShare).RootElement.GetProperty("id").ToString();

        var receivedShare = await receivedSharesClient.CreateOrReplaceReceivedShareAsync(WaitUntil.Completed, ReceivedShareId, RequestContent.Create(attachedReceivedShareData));

        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine(receivedShare.Value);
        Console.ForegroundColor = Console.ForegroundColor;

        return receivedShare.Value;
    }

    public static async Task<List<T>> ToResultList<T>(this AsyncPageable<T> asyncPageable)
    {
        List<T> list = new List<T>();

        await foreach (T item in asyncPageable)
        {
            list.Add(item);
        }

        return list;
    }
}

Excluir compartilhamento recebido

Esse script exclui um compartilhamento recebido. Para usá-lo, certifique-se de preencher estas variáveis:

  • ReceiverTenantId - a ID do Locatário do Azure para o usuário/serviço que está recebendo os dados compartilhados.
  • ReceiverPurviewAccountName - o nome da conta do Microsoft Purview em que os dados serão recebidos.
  • ReceivedShareDisplayName – O nome de exibição do compartilhamento recebido.
  • ReceiverStorageResourceId - a ID do recurso da conta de armazenamento em que os dados foram compartilhados.
  • UseServiceTokenCredentials – (opcional) Se você quiser usar uma entidade de serviço para receber os compartilhamentos, defina isso como true.
  • ReceiverClientId – (opcional) Se usar uma entidade de serviço para receber os compartilhamentos, esta será a ID do aplicativo (cliente) da entidade de serviço.
  • ReceiverClientSecret – (opcional) Se usar uma entidade de serviço para receber os compartilhamentos, adicione a chave segredo/autenticação do cliente.
  • ReceiverPurviewEndPoint - Se você estiver usando Se estiver usando a experiência clássica do Microsoft Purview, use $"https://{ReceiverPurviewAccountName}.purview.azure.com"; Se você estiver usando a nova experiência do Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;
using System.Text.Json;

public static class PurviewDataSharingQuickStart
{
    // [REQUIRED INPUTS] Set To Actual Values.
    private static string ReceiverTenantId = "<Receiver Indentity's Tenant ID>";
    private static string ReceiverPurviewAccountName = "<Receiver Purview Account Name>";

    private static string ReceivedShareDisplayName = "<Display name of your received share>";

    private static string ReceiverStorageResourceId = "<Storage Account Resource Id for the account where the share is currently attached.>";

    //Use if using a service principal to delete share.
    private static bool UseServiceTokenCredentials = false;
    private static string ReceiverClientId = "<Receiver Caller Application (Client) Id>";
    private static string ReceiverClientSecret = "<Receiver Caller Application (Client) Secret>";

    // General Configs
    private static string ReceiverPurviewEndPoint = $"https://{ReceiverPurviewAccountName}.purview.azure.com";
    private static string ReceiverShareEndPoint = $"{ReceiverPurviewEndPoint}/share";

    private static async Task Main(string[] args)
    {
        try
        {
            TokenCredential receiverCredentials = UseServiceTokenCredentials
            ? new ClientSecretCredential(ReceiverTenantId, ReceiverClientId, ReceiverClientSecret)
            : new DefaultAzureCredential(new DefaultAzureCredentialOptions { AuthorityHost = new Uri("https://login.windows.net"), TenantId = ReceiverTenantId });

            ReceivedSharesClient? receivedSharesClient = new ReceivedSharesClient(ReceiverShareEndPoint, receiverCredentials);

            var allReceivedShares = await receivedSharesClient.GetAllAttachedReceivedSharesAsync(ReceiverStorageResourceId).ToResultList();

            var myReceivedShare = allReceivedShares.First(recShareDoc =>
            {
                var doc = JsonDocument.Parse(recShareDoc).RootElement;
                var props = doc.GetProperty("properties");
                return props.GetProperty("displayName").ToString() == ReceivedShareDisplayName;
            });

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("My Received Share Id: " + JsonDocument.Parse(myReceivedShare).RootElement.GetProperty("id").ToString());
            Console.ForegroundColor = Console.ForegroundColor;

            var ReceivedShareId = JsonDocument.Parse(myReceivedShare).RootElement.GetProperty("id").ToString();

            await receivedSharesClient.DeleteReceivedShareAsync(WaitUntil.Completed, ReceivedShareId);

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Delete Complete");
            Console.ForegroundColor = Console.ForegroundColor;
        }
        catch (Exception ex)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(ex);
            Console.ForegroundColor = Console.ForegroundColor;
        }
    }
    public static async Task<List<T>> ToResultList<T>(this AsyncPageable<T> asyncPageable)
    {
        List<T> list = new List<T>();

        await foreach (T item in asyncPageable)
        {
            list.Add(item);
        }

        return list;
    }
}

Limpe os recursos

Para limpo os recursos criados para o início rápido, use as seguintes diretrizes:

  1. No portal do Microsoft Purview, exclua o compartilhamento enviado.
  2. Exclua também o compartilhamento recebido.
  3. Depois que os compartilhamentos forem excluídos com êxito, exclua o contêiner de destino e a pasta Microsoft Purview criada em sua conta de armazenamento de destino quando você receber dados compartilhados.

Próximas etapas