Condividi tramite


Avvio rapido: Condividere e ricevere dati con Condivisione dei dati di Microsoft Purview .NET SDK

Importante

Al momento questa funzionalità è disponibile in anteprima. Le Condizioni aggiuntive per l'uso per le anteprime di Microsoft Azure includono termini legali aggiuntivi che si applicano alle funzionalità di Azure in versione beta, in anteprima o in altro modo non ancora rilasciate nella disponibilità generale.

In questa guida introduttiva si userà .NET SDK per condividere dati e ricevere condivisioni da account di archiviazione AZURE DATA LAKE STORAGE (ADLS Gen2) o BLOB. L'articolo include frammenti di codice che consentono di creare, accettare e gestire condivisioni usando Condivisione dei dati di Microsoft Purview.

Per una panoramica del funzionamento della condivisione dei dati, watch questa breve demo.

Nota

Questa funzionalità è stata aggiornata a febbraio 2023 e l'SDK e le autorizzazioni necessarie per visualizzare e gestire le condivisioni dati in Microsoft Purview sono state modificate.

  • In Microsoft Purview non sono ora necessarie autorizzazioni per usare l'SDK per creare e gestire condivisioni. Le autorizzazioni di lettura sono necessarie per usare il portale di governance di Microsoft Purview per la condivisione dei dati.
  • Le autorizzazioni sono ancora necessarie per gli account di archiviazione.

Vedere il pacchetto NuGet aggiornato e i frammenti di codice aggiornati per usare l'SDK aggiornato.

Prerequisiti

Prerequisiti di Microsoft Purview

  • Un account Microsoft Purview. È anche possibile usare due account Microsoft Purview, uno per il provider di dati e uno per il consumer di dati per testare entrambi gli scenari.
  • Indirizzo di posta elettronica di accesso di Azure del destinatario che è possibile usare per inviare l'invito. L'alias di posta elettronica del destinatario non funzionerà.

Prerequisiti dell'account di archiviazione di Azure

  • La sottoscrizione di Azure deve essere registrata per la funzionalità di anteprima AllowDataSharing . Seguire i passaggi seguenti usando portale di Azure o PowerShell.

    1. In portale di Azure selezionare la sottoscrizione di Azure che verrà usata per creare l'account di archiviazione di origine e di destinazione.
    2. Nel menu a sinistra selezionare Funzionalità di anteprima in Impostazioni.
    3. Selezionare AllowDataSharing e Register (Registra).
    4. Aggiornare la schermata Delle funzionalità di anteprima per verificare che lo stato sia Registrato. Il completamento della registrazione potrebbe richiedere da 15 minuti a 1 ora.
    5. Inoltre, per usare la condivisione dati per gli account di archiviazione in Stati Uniti orientali, Stati Uniti orientali2, Europa settentrionale, Stati Uniti centro-meridionali, Stati Uniti centro-occidentali, Europa occidentale, Stati Uniti occidentali, Stati Uniti occidentali2, Stati Uniti occidentali3: selezionare AllowDataSharingInHeroRegion and Register

    Per altre informazioni, vedere Registrare la funzionalità di anteprima.

    RegistrationState deve essere Registrato. Il completamento della registrazione potrebbe richiedere da 15 minuti a 1 ora. Per altre informazioni, vedere Registrare la funzionalità di anteprima.

    Nota

    Di seguito sono riportate le configurazioni degli account di archiviazione supportate:

    • Aree di Azure: Canada centrale, Canada orientale, Regno Unito meridionale, Regno Unito occidentale, Australia orientale, Giappone orientale, Corea del Sud e Sud Africa settentrionale
    • Aree di Azure aggiuntive: Stati Uniti orientali, Stati Uniti orientali2, Europa settentrionale, Stati Uniti centro-meridionali, Stati Uniti centro-occidentali, Europa occidentale, Stati Uniti occidentali, Stati Uniti occidentali2, Stati Uniti occidentali3
    • Prestazioni: Standard
    • Opzioni di ridondanza: LRS
  • Account di archiviazione di origine e di destinazione creati dopo il completamento del passaggio di registrazione. Entrambi gli account di archiviazione devono trovarsi nella stessa area di Azure. Entrambi gli account di archiviazione devono essere account di archiviazione ADLS Gen2 o BLOB. Gli account di archiviazione possono trovarsi in un'area di Azure diversa dall'account Microsoft Purview.

  • Versione più recente dell'SDK di archiviazione, PowerShell, interfaccia della riga di comando e Azure Storage Explorer. La versione dell'API REST di archiviazione deve essere febbraio 2020 o successiva.

  • Gli account di archiviazione devono essere registrati nelle raccolte in cui si invierà o si riceverà la condivisione. Se si usa un account Microsoft Purview, possono essere due raccolte diverse o la stessa raccolta. Per istruzioni sulla registrazione, vedere le pagine dell'origine dati dell'archiviazione BLOB o ADLS Gen2.

  • Se gli account di archiviazione di origine o di destinazione si trovano in una sottoscrizione di Azure diversa da quella per l'account Microsoft Purview, il provider di risorse Microsoft.Purview viene registrato automaticamente nella sottoscrizione di Azure in cui si trova l'archivio dati al momento dell'aggiunta di un asset o condivisione del mapping dei consumer da parte del provider di risorse e SOLO se l'utente dispone dell'autorizzazione per eseguire l'operazione /register/action per il provider di risorse. L'autorizzazione è inclusa nei ruoli Collaboratore e Proprietario.

    Nota

    Questa registrazione è necessaria solo la prima volta quando si condividono o si ricevono dati in un account di archiviazione nella sottoscrizione di Azure.

Ruoli obbligatori

Di seguito sono riportati i ruoli obbligatori per la condivisione dei dati e la ricezione di condivisioni.

Ruoli dell'account di archiviazione di Azure Ruoli della raccolta di Microsoft Purview
Provider di dati Uno dei ruoli seguenti:
  • Proprietario
  • Proprietario dei dati dei BLOB di archiviazione
Lettore dati
Consumer di dati Uno dei ruoli seguenti:
  • Collaboratore
  • Proprietario
  • Collaboratore ai dati dei BLOB di archiviazione
  • Proprietario dei dati dei BLOB di archiviazione
Lettore dati

Nota

Se è stato creato l'account Microsoft Purview, tutti i ruoli vengono assegnati automaticamente alla raccolta radice. Per altre informazioni sulla raccolta e sui ruoli di Microsoft Purview, vedere Autorizzazioni di Microsoft Purview .

Visual Studio

La procedura dettagliata in questo articolo usa Visual Studio 2022. Le procedure per Visual Studio 2013, 2015, 2017 o 2019 potrebbero differire leggermente.

Azure .NET SDK

Scaricare e installare Azure .NET SDK nel computer.

Usare un'entità servizio

Nei frammenti di codice di questa esercitazione è possibile eseguire l'autenticazione usando credenziali personalizzate o un'entità servizio. Per configurare un'entità servizio, seguire queste istruzioni:

  1. In Creare un'applicazione Azure Active Directory creare un'applicazione che rappresenta l'applicazione .NET che si sta creando in questa esercitazione. Per l'URL di accesso, è possibile specificare un URL fittizio, come illustrato nell'articolo (https://contoso.org/exampleapp).

  2. In Recupera valori per l'accesso ottenere l'ID applicazione, l'IDtenant e l'ID oggetto e annotare questi valori usati più avanti in questa esercitazione.

  3. In Certificati e segreti ottenere la chiave di autenticazione e prendere nota di questo valore usato più avanti in questa esercitazione.

  4. assegnare l'applicazione a questi ruoli:

    Utente Ruoli dell'account di archiviazione di Azure Ruoli della raccolta di Microsoft Purview
    Provider di dati Uno dei ruoli seguenti:
    • Proprietario
    • Proprietario dei dati dell'archiviazione BLOB
    Collaboratore Condivisione dati
    Consumer di dati Uno dei ruoli seguenti:
    • Collaboratore
    • Proprietario
    • Collaboratore ai dati dei BLOB di archiviazione
    • Proprietario dei dati dell'archiviazione BLOB
    Collaboratore Condivisione dati

Creare un progetto di Visual Studio

Creare quindi un'applicazione console .NET C# in Visual Studio:

  1. Avviare Visual Studio.
  2. Nella finestra Start selezionare Crea una nuovaapp console di progetto>. È necessaria la versione 6.0 o successiva di .NET.
  3. In Nome progetto immettere PurviewDataSharingQuickStart.
  4. Selezionare Crea per creare il progetto.

Installare pacchetti NuGet

  1. Selezionare Strumenti>Console di Gestione pacchetti Di Gestione>pacchetti NuGet.

  2. Nella console di gestione pacchetti eseguire il comando aggiungi pacchetto dell'interfaccia della riga di comando di .NET visualizzato in questa pagina per aggiungere il pacchetto NuGet: Microsoft.Azure.Analytics.Purview.Sharing NuGet.

  3. Nel riquadro Console di Gestione pacchetti eseguire i comandi seguenti per installare i pacchetti.

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

    Consiglio

    Se viene visualizzato un errore che indica che non è stato possibile trovare alcun progetto in ..." quando si provano questi comandi, potrebbe essere sufficiente spostare un livello di cartella verso il basso nel progetto. Provare il comando dir per elencare le cartelle nella directory, quindi usare "nome cd <della cartella> del progetto" per spostarsi verso il basso di un livello nella cartella del progetto. Riprovare.

Creare una condivisione inviata

Questo script crea una condivisione dati che è possibile inviare agli utenti interni o esterni. Per usarlo, assicurarsi di compilare queste variabili:

  • SenderTenantId : ID tenant di Azure per l'identità del mittente.
  • SenderPurviewAccountName : nome dell'account Microsoft Purview da cui verranno inviati i dati.
  • ShareName : nome visualizzato per la condivisione inviata.
  • ShareDescription - (facoltativo) Descrizione per la condivisione inviata.
  • SenderStorageKind : BLOBAccount o AdlsGen2Account.
  • SenderStorageResourceId : ID risorsa per l'account di archiviazione da cui verranno inviati i dati.
  • SenderStorageContainer : nome del contenitore in cui vengono archiviati i dati da condividere.
  • SenderPathToShare : percorso file/cartella dei dati da condividere.
  • UseServiceTokenCredentials : (facoltativo) Se si vuole usare un'entità servizio per creare le condivisioni, impostare su true.
  • SenderClientId : (facoltativo) Se si usa un'entità servizio per creare le condivisioni, si tratta dell'ID applicazione (client) per l'entità servizio.
  • SenderClientSecret : (facoltativo) Se si usa un'entità servizio per creare le condivisioni, aggiungere la chiave di autenticazione/segreto client.
  • SentShareID - (facoltativo) Questa opzione deve essere un GUID e il valore corrente ne genera uno, ma è possibile sostituirlo con un valore diverso, se si desidera.
  • ReceiverVisiblePath : (facoltativo) Nome della condivisione visualizzata dal ricevitore. Attualmente impostato su un GUID, ma il GUID non è obbligatorio.
  • SenderPurviewEndPoint : se si usa Se si usa l'esperienza classica di Microsoft Purview, usare $"https://{SenderPurviewAccountName}.purview.azure.com"; Se si usa la nuova esperienza di Microsoft Purview, usare 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;
    }
}

Inviare un invito a un utente

Questo script invia un invito tramite posta elettronica per una condivisione a un utente. Se si vuole inviare un invito a un'entità servizio, vedere l'esempio di codice successivo. Per usarlo, assicurarsi di compilare queste variabili:

  • RecipientUserEmailId: Email indirizzo a cui l'utente può inviare l'invito.
  • SenderTenantId : ID tenant di Azure per l'identità del mittente della condivisione.
  • SenderPurviewAccountName : nome dell'account Microsoft Purview da cui verranno inviati i dati.
  • SenderStorageResourceId : ID risorsa per l'account di archiviazione da cui verranno inviati i dati.
  • SentShareDisplayName : nome della condivisione inviata per cui si sta inviando un invito.
  • UseServiceTokenCredentials : (facoltativo) Se si vuole usare un'entità servizio per creare le condivisioni, impostare su true.
  • SenderClientId : (facoltativo) Se si usa un'entità servizio per creare le condivisioni, si tratta dell'ID applicazione (client) per l'entità servizio.
  • SenderClientSecret : (facoltativo) Se si usa un'entità servizio per creare le condivisioni, aggiungere la chiave di autenticazione/segreto client.
  • InvitationId : (facoltativo) Questa opzione deve essere un GUID e il valore corrente ne genera uno, ma è possibile sostituirlo con un valore diverso, se si vuole.
  • SenderPurviewEndPoint : se si usa Se si usa l'esperienza classica di Microsoft Purview, usare $"https://{SenderPurviewAccountName}.purview.azure.com"; Se si usa la nuova esperienza di Microsoft Purview, usare 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;
    }
}

Inviare un invito a un servizio

Questo script invia un invito tramite posta elettronica per una condivisione a un'entità servizio. Se si vuole inviare un invito a un utente, vedere l'esempio precedente. Per usarlo, assicurarsi di compilare queste variabili:

  • RecipientApplicationTenantId : ID tenant di Azure per l'entità servizio ricevente.
  • RecipientApplicationObjectId : ID oggetto per l'entità servizio ricevente.
  • SenderTenantId : ID tenant di Azure per l'identità del mittente della condivisione.
  • SenderPurviewAccountName : nome dell'account Microsoft Purview da cui verranno inviati i dati.
  • SenderStorageResourceId : ID risorsa per l'account di archiviazione da cui verranno inviati i dati.
  • SentShareDisplayName : nome della condivisione inviata per cui si sta inviando un invito.
  • UseServiceTokenCredentials : (facoltativo) Se si vuole usare un'entità servizio per creare le condivisioni, impostare su true.
  • SenderClientId : (facoltativo) Se si usa un'entità servizio per creare le condivisioni, si tratta dell'ID applicazione (client) per l'entità servizio.
  • SenderClientSecret : (facoltativo) Se si usa un'entità servizio per creare le condivisioni, aggiungere la chiave di autenticazione/segreto client.
  • InvitationId : (facoltativo) Questa opzione deve essere un GUID e il valore corrente ne genera uno, ma è possibile sostituirlo con un valore diverso, se si vuole.
  • SenderPurviewEndPoint : se si usa Se si usa l'esperienza classica di Microsoft Purview, usare $"https://{SenderPurviewAccountName}.purview.azure.com"; Se si usa la nuova esperienza di Microsoft Purview, usare 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;
    }

}

Elencare le condivisioni inviate

Questo script elenca tutte le condivisioni inviate per una risorsa di archiviazione specifica. Per usarlo, assicurarsi di compilare queste variabili:

  • SenderTenantId : ID tenant di Azure per l'identità del mittente della condivisione.
  • SenderPurviewAccountName : nome dell'account Microsoft Purview da cui sono stati inviati i dati.
  • SenderStorageResourceId : ID risorsa per l'account di archiviazione da cui sono state inviate le condivisioni.
  • UseServiceTokenCredentials : (facoltativo) Se si vuole usare un'entità servizio per creare le condivisioni, impostare su true.
  • SenderClientId : (facoltativo) Se si usa un'entità servizio per creare le condivisioni, si tratta dell'ID applicazione (client) per l'entità servizio.
  • SenderClientSecret : (facoltativo) Se si usa un'entità servizio per creare le condivisioni, aggiungere la chiave di autenticazione/segreto client.
  • SenderPurviewEndPoint : se si usa Se si usa l'esperienza classica di Microsoft Purview, usare $"https://{SenderPurviewAccountName}.purview.azure.com"; Se si usa la nuova esperienza di Microsoft Purview, usare 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;
    }
}

Elencare tutti i destinatari delle condivisioni

Questo script elenca tutti i destinatari per una condivisione specifica. Per usarlo, assicurarsi di compilare queste variabili:

  • SenderTenantId : ID tenant di Azure per l'identità del mittente della condivisione.
  • SenderPurviewAccountName : nome dell'account Microsoft Purview da cui sono stati inviati i dati.
  • SentShareDisplayName : nome della condivisione inviata per cui si stanno elencando i destinatari.
  • SenderStorageResourceId : ID risorsa per l'account di archiviazione da cui verranno inviati i dati.
  • UseServiceTokenCredentials : (facoltativo) Se si vuole usare un'entità servizio per creare le condivisioni, impostare su true.
  • SenderClientId : (facoltativo) Se si usa un'entità servizio per creare le condivisioni, si tratta dell'ID applicazione (client) per l'entità servizio.
  • SenderClientSecret : (facoltativo) Se si usa un'entità servizio per creare le condivisioni, aggiungere la chiave di autenticazione/segreto client.
  • SenderPurviewEndPoint : se si usa Se si usa l'esperienza classica di Microsoft Purview, usare $"https://{SenderPurviewAccountName}.purview.azure.com"; Se si usa la nuova esperienza di Microsoft Purview, usare 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;
    }
}

Eliminare il destinatario

Questo script rimuove un invito alla condivisione, e quindi la condivisione, per un destinatario. Per usarlo, assicurarsi di compilare queste variabili:

  • SenderTenantId : ID tenant di Azure per l'identità del mittente della condivisione.
  • SenderPurviewAccountName : nome dell'account Microsoft Purview da cui sono stati inviati i dati.
  • SentShareDisplayName : nome della condivisione inviata per cui si sta rimuovendo un destinatario.
  • SenderStorageResourceId : ID risorsa per l'account di archiviazione da cui verranno inviati i dati.
  • RecipientUserEmailId: Email indirizzo per l'utente da eliminare.
  • UseServiceTokenCredentials : (facoltativo) Se si vuole usare un'entità servizio per creare le condivisioni, impostare su true.
  • SenderClientId : (facoltativo) Se si usa un'entità servizio per creare le condivisioni, si tratta dell'ID applicazione (client) per l'entità servizio.
  • SenderClientSecret : (facoltativo) Se si usa un'entità servizio per creare le condivisioni, aggiungere la chiave di autenticazione/segreto client.
  • SenderPurviewEndPoint : se si usa Se si usa l'esperienza classica di Microsoft Purview, usare $"https://{SenderPurviewAccountName}.purview.azure.com"; Se si usa la nuova esperienza di Microsoft Purview, usare 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;
    }
}

Eliminare la condivisione inviata

Questo script elimina una condivisione inviata. Per usarlo, assicurarsi di compilare queste variabili:

  • SenderTenantId : ID tenant di Azure per l'identità del mittente della condivisione.
  • SenderPurviewAccountName : nome dell'account Microsoft Purview da cui sono stati inviati i dati.
  • SentShareDisplayName : nome della condivisione inviata per cui si stanno elencando i destinatari.
  • SenderStorageResourceId : ID risorsa per l'account di archiviazione da cui verranno inviati i dati.
  • UseServiceTokenCredentials : (facoltativo) Se si vuole usare un'entità servizio per creare le condivisioni, impostare su true.
  • SenderClientId : (facoltativo) Se si usa un'entità servizio per creare le condivisioni, si tratta dell'ID applicazione (client) per l'entità servizio.
  • SenderClientSecret : (facoltativo) Se si usa un'entità servizio per creare le condivisioni, aggiungere la chiave di autenticazione/segreto client.
  • SenderPurviewEndPoint : se si usa Se si usa l'esperienza classica di Microsoft Purview, usare $"https://{SenderPurviewAccountName}.purview.azure.com"; Se si usa la nuova esperienza di Microsoft Purview, usare 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;
    }
}

Creare una condivisione ricevuta

Questo script consente di ricevere una condivisione dati. Per usarlo, assicurarsi di compilare queste variabili:

  • ReceiverTenantId : ID tenant di Azure per l'utente/servizio che riceve i dati condivisi.
  • ReceiverPurviewAccountName : nome dell'account Microsoft Purview in cui verranno ricevuti i dati.
  • ReceiverStorageKind : BLOBAccount o AdlsGen2Account.
  • ReceiverStorageResourceId : ID risorsa per l'account di archiviazione in cui verranno ricevuti i dati.
  • ReceiverStorageContainer : nome del contenitore in cui verranno archiviati i dati condivisi.
  • ReceiverTargetFolderName : percorso della cartella in cui verranno archiviati i dati condivisi.
  • ReceiverTargetMountPath : percorso di montaggio che si vuole usare per archiviare i dati nella cartella.
  • UseServiceTokenCredentials : (facoltativo) Se si vuole usare un'entità servizio per ricevere le condivisioni, impostare su true.
  • ReceiverClientId : (facoltativo) Se si usa un'entità servizio per ricevere le condivisioni, si tratta dell'ID applicazione (client) per l'entità servizio.
  • ReceiverClientSecret : (facoltativo) Se si usa un'entità servizio per ricevere le condivisioni, aggiungere la chiave di autenticazione/segreto client.
  • ReceivedShareId - (facoltativo) Questa opzione deve essere un GUID e il valore corrente ne genererà uno automaticamente, ma è possibile sostituirlo con un valore diverso, se si desidera.
  • ReceiverVisiblePath : (facoltativo) Nome da usare per il percorso della condivisione ricevuta.
  • ReceivedShareDisplayName : (facoltativo) Nome visualizzato per la condivisione ricevuta.
  • ReceiverPurviewEndPoint : se si usa Se si usa l'esperienza classica di Microsoft Purview, usare $"https://{ReceiverPurviewAccountName}.purview.azure.com"; Se si usa la nuova esperienza di Microsoft Purview, usare 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;
    }
}

Elencare tutte le condivisioni ricevute

Questo script elenca tutte le condivisioni ricevute in un account di archiviazione. Per usarlo, assicurarsi di compilare queste variabili:

  • ReceiverTenantId : ID tenant di Azure per l'utente/servizio che riceve i dati condivisi.
  • ReceiverPurviewAccountName : nome dell'account Microsoft Purview in cui sono stati ricevuti i dati.
  • ReceiverStorageResourceId : ID risorsa per l'account di archiviazione in cui sono stati condivisi i dati.
  • UseServiceTokenCredentials : (facoltativo) Se si vuole usare un'entità servizio per ricevere le condivisioni, impostare su true.
  • ReceiverClientId : (facoltativo) Se si usa un'entità servizio per ricevere le condivisioni, si tratta dell'ID applicazione (client) per l'entità servizio.
  • ReceiverClientSecret : (facoltativo) Se si usa un'entità servizio per ricevere le condivisioni, aggiungere la chiave di autenticazione/segreto client.
  • ReceiverPurviewEndPoint : se si usa Se si usa l'esperienza classica di Microsoft Purview, usare $"https://{ReceiverPurviewAccountName}.purview.azure.com"; Se si usa la nuova esperienza di Microsoft Purview, usare 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;
    }
}

Aggiornare la condivisione ricevuta

Questo script consente di aggiornare il percorso di archiviazione per una condivisione ricevuta. Proprio come la creazione di una condivisione ricevuta, si aggiungono le informazioni per l'account di archiviazione in cui si desidera che i dati vengano ospitati. Per usarlo, assicurarsi di compilare queste variabili:

  • ReceiverTenantId : ID tenant di Azure per l'utente/servizio che riceve i dati condivisi.
  • ReceiverPurviewAccountName : nome dell'account Microsoft Purview in cui verranno ricevuti i dati.
  • ReceiverStorageKind : BLOBAccount o AdlsGen2Account.
  • ReceiverStorageResourceId : ID risorsa per l'account di archiviazione in cui sono stati condivisi i dati.
  • ReAttachStorageResourceId : ID risorsa per l'account di archiviazione in cui verranno ricevuti i dati.
  • ReceiverStorageContainer : nome del contenitore in cui verranno archiviati i dati condivisi.
  • ReceiverTargetFolderName : percorso della cartella in cui verranno archiviati i dati condivisi.
  • ReceiverTargetMountPath : percorso di montaggio che si vuole usare per archiviare i dati nella cartella.
  • ReceivedShareDisplayName : nome visualizzato per la condivisione ricevuta.
  • UseServiceTokenCredentials : (facoltativo) Se si vuole usare un'entità servizio per ricevere le condivisioni, impostare su true.
  • ReceiverClientId : (facoltativo) Se si usa un'entità servizio per ricevere le condivisioni, si tratta dell'ID applicazione (client) per l'entità servizio.
  • ReceiverClientSecret : (facoltativo) Se si usa un'entità servizio per ricevere le condivisioni, aggiungere la chiave di autenticazione/segreto client.
  • ReceiverPurviewEndPoint : se si usa Se si usa l'esperienza classica di Microsoft Purview, usare $"https://{ReceiverPurviewAccountName}.purview.azure.com"; Se si usa la nuova esperienza di Microsoft Purview, usare 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;
    }
}

Eliminare la condivisione ricevuta

Questo script elimina una condivisione ricevuta. Per usarlo, assicurarsi di compilare queste variabili:

  • ReceiverTenantId : ID tenant di Azure per l'utente/servizio che riceve i dati condivisi.
  • ReceiverPurviewAccountName : nome dell'account Microsoft Purview in cui verranno ricevuti i dati.
  • ReceivedShareDisplayName : nome visualizzato per la condivisione ricevuta.
  • ReceiverStorageResourceId : ID risorsa per l'account di archiviazione in cui sono stati condivisi i dati.
  • UseServiceTokenCredentials : (facoltativo) Se si vuole usare un'entità servizio per ricevere le condivisioni, impostare su true.
  • ReceiverClientId : (facoltativo) Se si usa un'entità servizio per ricevere le condivisioni, si tratta dell'ID applicazione (client) per l'entità servizio.
  • ReceiverClientSecret : (facoltativo) Se si usa un'entità servizio per ricevere le condivisioni, aggiungere la chiave di autenticazione/segreto client.
  • ReceiverPurviewEndPoint : se si usa Se si usa l'esperienza classica di Microsoft Purview, usare $"https://{ReceiverPurviewAccountName}.purview.azure.com"; Se si usa la nuova esperienza di Microsoft Purview, usare 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;
    }
}

Pulire le risorse

Per pulire le risorse create per la guida introduttiva, usare le linee guida seguenti:

  1. Nel portale di Microsoft Purview eliminare la condivisione inviata.
  2. Eliminare anche la condivisione ricevuta.
  3. Dopo aver eliminato correttamente le condivisioni, eliminare il contenitore e la cartella di destinazione Creati da Microsoft Purview nell'account di archiviazione di destinazione quando sono stati ricevuti i dati condivisi.

Passaggi successivi