Partager via


Démarrage rapide : Partager et recevoir des données avec le kit de développement logiciel (SDK) .NET Partage de données Microsoft Purview

Importante

Cette fonctionnalité est actuellement en préversion. Les conditions d’utilisation supplémentaires pour les préversions de Microsoft Azure incluent des conditions juridiques supplémentaires qui s’appliquent aux fonctionnalités Azure qui sont en version bêta, en préversion ou qui ne sont pas encore publiées en disponibilité générale.

Dans ce guide de démarrage rapide, vous allez utiliser le Kit de développement logiciel (SDK) .NET pour partager des données et recevoir des partages à partir de Azure Data Lake Storage (ADLS Gen2) ou de comptes de stockage Blob. L’article inclut des extraits de code qui vous permettent de créer, d’accepter et de gérer des partages à l’aide de Partage de données Microsoft Purview.

Pour une vue d’ensemble du fonctionnement du partage de données, watch cette courte démonstration.

Remarque

Cette fonctionnalité a été mise à jour en février 2023, et le SDK et les autorisations nécessaires pour afficher et gérer les partages de données dans Microsoft Purview ont changé.

  • Aucune autorisation n’est désormais requise dans Microsoft Purview pour utiliser le Kit de développement logiciel (SDK) pour créer et gérer des partages. (Des autorisations de lecteur sont nécessaires pour utiliser le portail de gouvernance Microsoft Purview pour partager des données.)
  • Les autorisations sont toujours requises sur les comptes de stockage.

Consultez le package NuGet mis à jour et les extraits de code mis à jour pour utiliser le Kit de développement logiciel (SDK) mis à jour.

Configuration requise

Conditions préalables à Microsoft Purview

  • Un compte Microsoft Purview. Vous pouvez également utiliser deux comptes Microsoft Purview, l’un pour le fournisseur de données et l’autre pour le consommateur de données afin de tester les deux scénarios.
  • Adresse e-mail de connexion Azure de votre destinataire à laquelle vous pouvez envoyer l’invitation. L’alias de messagerie du destinataire ne fonctionne pas.

Conditions préalables requises pour le compte de stockage Azure

  • Votre abonnement Azure doit être inscrit pour la fonctionnalité d’évaluation AllowDataSharing . Suivez les étapes ci-dessous à l’aide de Portail Azure ou de PowerShell.

    1. Dans Portail Azure, sélectionnez votre abonnement Azure que vous utiliserez pour créer le compte de stockage source et cible.
    2. Dans le menu de gauche, sélectionnez Fonctionnalités d’aperçu sous Paramètres.
    3. Sélectionnez AutoriserDataSharing et Inscrire.
    4. Actualisez l’écran Fonctionnalités en préversion pour vérifier que l’état est Inscrit. L’inscription peut prendre entre 15 minutes et 1 heure.
    5. En outre, pour utiliser le partage de données pour les comptes de stockage dans USA Est, USA Est2, Europe Nord, USA Centre Sud, USA Centre Ouest, Europe Ouest, USA Ouest, USA Ouest, USA Ouest2, USA Ouest 3 : Sélectionnez AutoriserDataSharingInHeroRegion et Inscrire

    Pour plus d’informations, consultez Inscrire la fonctionnalité en préversion.

    RegistrationState doit être Inscrit. L’inscription peut prendre entre 15 minutes et 1 heure. Pour plus d’informations, consultez Inscrire la fonctionnalité en préversion.

    Remarque

    Les configurations de compte de stockage prises en charge sont les suivantes :

    • Régions Azure : Canada Centre, Canada Est, Royaume-Uni Sud, Royaume-Uni Ouest, Australie Est, Japon Est, Corée Sud et Afrique du Sud Nord
    • Régions Azure supplémentaires : USA Est, USA Est2, Europe Nord, USA central Sud, USA Centre-Ouest, Europe Ouest, USA Ouest, USA Ouest2, USA Ouest3
    • Performances : Standard
    • Options de redondance : LRS
  • Comptes de stockage source et cible créés une fois l’étape d’inscription terminée. Les deux comptes de stockage doivent se trouver dans la même région Azure. Les deux comptes de stockage doivent être des comptes de stockage ADLS Gen2 ou Stockage Blob. Vos comptes de stockage peuvent se trouver dans une région Azure différente de celle de votre compte Microsoft Purview.

  • Dernière version du Kit de développement logiciel (SDK) de stockage, de PowerShell, de l’interface CLI et Explorateur Stockage Azure. La version de l’API REST de stockage doit être février 2020 ou ultérieure.

  • Les comptes de stockage doivent être inscrits dans les collections où vous allez envoyer ou recevoir le partage. Si vous utilisez un compte Microsoft Purview, il peut s’agir de deux collections différentes ou de la même collection. Pour obtenir des instructions sur l’inscription, consultez les pages sources de données du stockage d’objets blob ou ADLS Gen2.

  • Si les comptes de stockage source ou cible se trouvent dans un autre abonnement Azure que celui du compte Microsoft Purview, le fournisseur de ressources Microsoft.Purview est automatiquement inscrit dans l’abonnement Azure où se trouve le magasin de données au moment où le fournisseur de partage ajoute une ressource ou partage consommateur mappant une ressource et uniquement si l’utilisateur est autorisé à effectuer l’opération /register/action pour le fournisseur de ressources. L’autorisation est incluse dans les rôles Contributeur et Propriétaire.

    Remarque

    Cette inscription n’est nécessaire que la première fois lors du partage ou de la réception de données dans un compte de stockage dans l’abonnement Azure.

Rôles requis

Voici les rôles requis pour le partage de données et la réception de partages.

Rôles de compte de stockage Azure Rôles de collection Microsoft Purview
Fournisseur de données L’un des rôles suivants :
  • Propriétaire
  • Propriétaire des données blob du stockage
Lecteur de données
Consommateur de données L’un des rôles suivants :
  • Collaborateur
  • Propriétaire
  • Contributeur aux données Blob du stockage
  • Propriétaire des données blob du stockage
Lecteur de données

Remarque

Si vous avez créé le compte Microsoft Purview, tous les rôles vous sont automatiquement attribués à la collection racine. Reportez-vous aux autorisations Microsoft Purview pour en savoir plus sur la collection et les rôles Microsoft Purview.

Visual Studio

La procédure pas à pas de cet article utilise Visual Studio 2022. Les procédures pour Visual Studio 2013, 2015, 2017 ou 2019 peuvent différer légèrement.

Kit de développement logiciel (SDK) Azure .NET

Téléchargez et installez le Kit de développement logiciel (SDK) Azure .NET sur votre ordinateur.

Utiliser un principal de service

Dans les extraits de code de ce didacticiel, vous pouvez vous authentifier à l’aide de vos propres informations d’identification ou à l’aide d’un principal de service. Pour configurer un principal de service, suivez ces instructions :

  1. Dans Créer une application Azure Active Directory, créez une application qui représente l’application .NET que vous créez dans ce tutoriel. Pour l’URL de connexion, vous pouvez fournir une URL factice comme indiqué dans l’article (https://contoso.org/exampleapp).

  2. Dans Obtenir des valeurs pour la connexion, obtenez l’ID d’application, l’ID de locataire et l’ID d’objet, puis notez ces valeurs que vous utiliserez plus loin dans ce tutoriel.

  3. Dans Certificats et secrets, obtenez la clé d’authentification et notez cette valeur que vous utiliserez plus loin dans ce tutoriel.

  4. Attribuez à l’application les rôles suivants :

    Utilisateur Rôles de compte de stockage Azure Rôles de collection Microsoft Purview
    Fournisseur de données L’un des rôles suivants :
    • Propriétaire
    • Propriétaire des données du stockage Blob
    Contributeur Data Share
    Consommateur de données L’un des rôles suivants :
    • Collaborateur
    • Propriétaire
    • Contributeur aux données Blob du stockage
    • Propriétaire des données du stockage Blob
    Contributeur Data Share

Créer un projet Visual Studio

Ensuite, créez une application console C# .NET dans Visual Studio :

  1. Lancez Visual Studio.
  2. Dans la fenêtre Démarrer, sélectionnez Créer uneapplication consolede projet>. .NET version 6.0 ou ultérieure est obligatoire.
  3. Dans Nom du projet, entrez PurviewDataSharingQuickStart.
  4. Sélectionnez Créer pour créer le projet.

Installation de packages NuGet

  1. Sélectionnez Outils>NuGet Package ManagerConsole du gestionnaire >de package.

  2. Dans la console De gestion de package , exécutez la commande .NET cli add package affichée sur cette page pour ajouter le package NuGet : Microsoft.Azure.Analytics.Purview.Sharing Package NuGet.

  3. Dans le volet Console du Gestionnaire de package, exécutez les commandes suivantes pour installer les packages.

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

    Conseil

    Si vous obtenez une erreur indiquant « Impossible de trouver un projet dans... » lors de la tentative de ces commandes, vous devrez peut-être simplement déplacer un niveau de dossier vers le bas dans votre projet. Essayez la commande dir pour répertorier les dossiers dans votre répertoire, puis utilisez « cd <name of the project folder> » pour descendre d’un niveau vers le dossier de votre projet. Réessayez ensuite.

Créer un partage envoyé

Ce script crée un partage de données que vous pouvez envoyer à des utilisateurs internes ou externes. Pour l’utiliser, veillez à remplir les variables suivantes :

  • SenderTenantId : ID de locataire Azure pour l’identité de l’expéditeur.
  • SenderPurviewAccountName : nom du compte Microsoft Purview à partir duquel les données seront envoyées.
  • ShareName : nom d’affichage pour votre partage envoyé.
  • ShareDescription : (facultatif) Description de votre partage envoyé.
  • SenderStorageKind : BlobAccount ou AdlsGen2Account.
  • SenderStorageResourceId : ID de ressource du compte de stockage à partir duquel les données seront envoyées.
  • SenderStorageContainer : nom du conteneur dans lequel les données à partager sont stockées.
  • SenderPathToShare : chemin d’accès au fichier/dossier des données à partager.
  • UseServiceTokenCredentials : (facultatif) Si vous souhaitez utiliser un principal de service pour créer les partages, définissez-le sur true.
  • SenderClientId : (facultatif) Si vous utilisez un principal de service pour créer les partages, il s’agit de l’ID d’application (client) du principal de service.
  • SenderClientSecret : (facultatif) Si vous utilisez un principal de service pour créer les partages, ajoutez votre clé secrète client/clé d’authentification.
  • SentShareID : (facultatif) Cette option doit être un GUID et la valeur actuelle en génère un pour vous, mais vous pouvez la remplacer par une autre valeur si vous le souhaitez.
  • ReceiverVisiblePath : (facultatif) Nom du partage que le récepteur verra. Actuellement défini sur un GUID, mais guid n’est pas obligatoire.
  • SenderPurviewEndPoint : si vous utilisez Si vous utilisez l’expérience Microsoft purview classique, utilisez $"https://{SenderPurviewAccountName}.purview.azure.com"; Si vous utilisez la nouvelle expérience Microsoft Purview, utilisez 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;
    }
}

Envoyer une invitation à un utilisateur

Ce script envoie une invitation par e-mail pour un partage à un utilisateur. Si vous souhaitez envoyer une invitation à un principal de service, consultez l’exemple de code suivant. Pour l’utiliser, veillez à remplir les variables suivantes :

  • RecipientUserEmailId : adresse Email à laquelle l’utilisateur doit envoyer l’invitation.
  • SenderTenantId : ID de locataire Azure pour l’identité de l’expéditeur du partage.
  • SenderPurviewAccountName : nom du compte Microsoft Purview à partir duquel les données seront envoyées.
  • SenderStorageResourceId : ID de ressource du compte de stockage à partir duquel les données seront envoyées.
  • SentShareDisplayName : nom du partage envoyé pour lequel vous envoyez une invitation.
  • UseServiceTokenCredentials : (facultatif) Si vous souhaitez utiliser un principal de service pour créer les partages, définissez-le sur true.
  • SenderClientId : (facultatif) Si vous utilisez un principal de service pour créer les partages, il s’agit de l’ID d’application (client) du principal de service.
  • SenderClientSecret : (facultatif) Si vous utilisez un principal de service pour créer les partages, ajoutez votre clé secrète client/clé d’authentification.
  • InvitationId : (facultatif) Cette option doit être un GUID et la valeur actuelle en génère un pour vous, mais vous pouvez la remplacer par une autre valeur si vous le souhaitez.
  • SenderPurviewEndPoint : si vous utilisez Si vous utilisez l’expérience Microsoft purview classique, utilisez $"https://{SenderPurviewAccountName}.purview.azure.com"; Si vous utilisez la nouvelle expérience Microsoft Purview, utilisez 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;
    }
}

Envoyer une invitation à un service

Ce script envoie une invitation par e-mail pour un partage à un principal de service. Si vous souhaitez envoyer une invitation à un utilisateur, consultez l’exemple précédent. Pour l’utiliser, veillez à remplir les variables suivantes :

  • RecipientApplicationTenantId : ID de locataire Azure pour le principal de service de réception.
  • RecipientApplicationObjectId : ID d’objet du principal de service de réception.
  • SenderTenantId : ID de locataire Azure pour l’identité de l’expéditeur du partage.
  • SenderPurviewAccountName : nom du compte Microsoft Purview à partir duquel les données seront envoyées.
  • SenderStorageResourceId : ID de ressource du compte de stockage à partir duquel les données seront envoyées.
  • SentShareDisplayName : nom du partage envoyé pour lequel vous envoyez une invitation.
  • UseServiceTokenCredentials : (facultatif) Si vous souhaitez utiliser un principal de service pour créer les partages, définissez-le sur true.
  • SenderClientId : (facultatif) Si vous utilisez un principal de service pour créer les partages, il s’agit de l’ID d’application (client) du principal de service.
  • SenderClientSecret : (facultatif) Si vous utilisez un principal de service pour créer les partages, ajoutez votre clé secrète client/clé d’authentification.
  • InvitationId : (facultatif) Cette option doit être un GUID et la valeur actuelle en génère un pour vous, mais vous pouvez la remplacer par une autre valeur si vous le souhaitez.
  • SenderPurviewEndPoint : si vous utilisez Si vous utilisez l’expérience Microsoft purview classique, utilisez $"https://{SenderPurviewAccountName}.purview.azure.com"; Si vous utilisez la nouvelle expérience Microsoft Purview, utilisez 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;
    }

}

Répertorier les partages envoyés

Ce script répertorie tous les partages envoyés pour une ressource de stockage spécifique. Pour l’utiliser, veillez à remplir les variables suivantes :

  • SenderTenantId : ID de locataire Azure pour l’identité de l’expéditeur du partage.
  • SenderPurviewAccountName : nom du compte Microsoft Purview à partir duquel les données ont été envoyées.
  • SenderStorageResourceId : ID de ressource du compte de stockage à partir duquel des partages ont été envoyés.
  • UseServiceTokenCredentials : (facultatif) Si vous souhaitez utiliser un principal de service pour créer les partages, définissez-le sur true.
  • SenderClientId : (facultatif) Si vous utilisez un principal de service pour créer les partages, il s’agit de l’ID d’application (client) du principal de service.
  • SenderClientSecret : (facultatif) Si vous utilisez un principal de service pour créer les partages, ajoutez votre clé secrète client/clé d’authentification.
  • SenderPurviewEndPoint : si vous utilisez Si vous utilisez l’expérience Microsoft purview classique, utilisez $"https://{SenderPurviewAccountName}.purview.azure.com"; Si vous utilisez la nouvelle expérience Microsoft Purview, utilisez 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;
    }
}

Répertorier tous les destinataires de partage

Ce script répertorie tous les destinataires d’un partage spécifique. Pour l’utiliser, veillez à remplir les variables suivantes :

  • SenderTenantId : ID de locataire Azure pour l’identité de l’expéditeur du partage.
  • SenderPurviewAccountName : nom du compte Microsoft Purview à partir duquel les données ont été envoyées.
  • SentShareDisplayName : nom du partage envoyé pour lequel vous répertoriez les destinataires.
  • SenderStorageResourceId : ID de ressource du compte de stockage à partir duquel les données seront envoyées.
  • UseServiceTokenCredentials : (facultatif) Si vous souhaitez utiliser un principal de service pour créer les partages, définissez-le sur true.
  • SenderClientId : (facultatif) Si vous utilisez un principal de service pour créer les partages, il s’agit de l’ID d’application (client) du principal de service.
  • SenderClientSecret : (facultatif) Si vous utilisez un principal de service pour créer les partages, ajoutez votre clé secrète client/clé d’authentification.
  • SenderPurviewEndPoint : si vous utilisez Si vous utilisez l’expérience Microsoft purview classique, utilisez $"https://{SenderPurviewAccountName}.purview.azure.com"; Si vous utilisez la nouvelle expérience Microsoft Purview, utilisez 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;
    }
}

Supprimer le destinataire

Ce script supprime une invitation de partage, et donc le partage, pour un destinataire. Pour l’utiliser, veillez à remplir les variables suivantes :

  • SenderTenantId : ID de locataire Azure pour l’identité de l’expéditeur du partage.
  • SenderPurviewAccountName : nom du compte Microsoft Purview à partir duquel les données ont été envoyées.
  • SentShareDisplayName : nom du partage envoyé pour lequel vous supprimez un destinataire.
  • SenderStorageResourceId : ID de ressource du compte de stockage à partir duquel les données seront envoyées.
  • RecipientUserEmailId : adresse Email de l’utilisateur à supprimer.
  • UseServiceTokenCredentials : (facultatif) Si vous souhaitez utiliser un principal de service pour créer les partages, définissez-le sur true.
  • SenderClientId : (facultatif) Si vous utilisez un principal de service pour créer les partages, il s’agit de l’ID d’application (client) du principal de service.
  • SenderClientSecret : (facultatif) Si vous utilisez un principal de service pour créer les partages, ajoutez votre clé secrète client/clé d’authentification.
  • SenderPurviewEndPoint : si vous utilisez Si vous utilisez l’expérience Microsoft purview classique, utilisez $"https://{SenderPurviewAccountName}.purview.azure.com"; Si vous utilisez la nouvelle expérience Microsoft Purview, utilisez 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;
    }
}

Supprimer le partage envoyé

Ce script supprime un partage envoyé. Pour l’utiliser, veillez à remplir les variables suivantes :

  • SenderTenantId : ID de locataire Azure pour l’identité de l’expéditeur du partage.
  • SenderPurviewAccountName : nom du compte Microsoft Purview à partir duquel les données ont été envoyées.
  • SentShareDisplayName : nom du partage envoyé pour lequel vous répertoriez les destinataires.
  • SenderStorageResourceId : ID de ressource du compte de stockage à partir duquel les données seront envoyées.
  • UseServiceTokenCredentials : (facultatif) Si vous souhaitez utiliser un principal de service pour créer les partages, définissez-le sur true.
  • SenderClientId : (facultatif) Si vous utilisez un principal de service pour créer les partages, il s’agit de l’ID d’application (client) du principal de service.
  • SenderClientSecret : (facultatif) Si vous utilisez un principal de service pour créer les partages, ajoutez votre clé secrète client/clé d’authentification.
  • SenderPurviewEndPoint : si vous utilisez Si vous utilisez l’expérience Microsoft purview classique, utilisez $"https://{SenderPurviewAccountName}.purview.azure.com"; Si vous utilisez la nouvelle expérience Microsoft Purview, utilisez 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;
    }
}

Créer un partage reçu

Ce script vous permet de recevoir un partage de données. Pour l’utiliser, veillez à remplir les variables suivantes :

  • ReceiverTenantId : ID de locataire Azure pour l’utilisateur/service qui reçoit les données partagées.
  • ReceiverPurviewAccountName : nom du compte Microsoft Purview dans lequel les données seront reçues.
  • ReceiverStorageKind : BlobAccount ou AdlsGen2Account.
  • ReceiverStorageResourceId : ID de ressource du compte de stockage dans lequel les données seront reçues.
  • ReceiverStorageContainer : nom du conteneur dans lequel les données partagées seront stockées.
  • ReceiverTargetFolderName : chemin d’accès au dossier où les données partagées seront stockées.
  • ReceiverTargetMountPath : chemin de montage que vous souhaitez utiliser pour stocker vos données dans le dossier .
  • UseServiceTokenCredentials : (facultatif) Si vous souhaitez utiliser un principal de service pour recevoir les partages, définissez-le sur true.
  • ReceiverClientId : (facultatif) Si vous utilisez un principal de service pour recevoir les partages, il s’agit de l’ID d’application (client) du principal de service.
  • ReceiverClientSecret : (facultatif) Si vous utilisez un principal de service pour recevoir les partages, ajoutez votre clé secrète client/clé d’authentification.
  • ReceivedShareId : (facultatif) Cette option doit être un GUID et la valeur actuelle en générera un pour vous, mais vous pouvez la remplacer par une autre valeur si vous le souhaitez.
  • ReceiverVisiblePath : (facultatif) Nom que vous souhaitez utiliser pour le chemin d’accès de votre partage reçu.
  • ReceivedShareDisplayName : (facultatif) Nom d’affichage pour votre partage reçu.
  • ReceiverPurviewEndPoint : si vous utilisez Si vous utilisez l’expérience Microsoft purview classique, utilisez $"https://{ReceiverPurviewAccountName}.purview.azure.com"; Si vous utilisez la nouvelle expérience Microsoft Purview, utilisez 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;
    }
}

Répertorier tous les partages reçus

Ce script répertorie tous les partages reçus sur un compte de stockage. Pour l’utiliser, veillez à remplir les variables suivantes :

  • ReceiverTenantId : ID de locataire Azure pour l’utilisateur/service qui reçoit les données partagées.
  • ReceiverPurviewAccountName : nom du compte Microsoft Purview où les données ont été reçues.
  • ReceiverStorageResourceId : ID de ressource du compte de stockage dans lequel les données ont été partagées.
  • UseServiceTokenCredentials : (facultatif) Si vous souhaitez utiliser un principal de service pour recevoir les partages, définissez-le sur true.
  • ReceiverClientId : (facultatif) Si vous utilisez un principal de service pour recevoir les partages, il s’agit de l’ID d’application (client) du principal de service.
  • ReceiverClientSecret : (facultatif) Si vous utilisez un principal de service pour recevoir les partages, ajoutez votre clé secrète client/clé d’authentification.
  • ReceiverPurviewEndPoint : si vous utilisez Si vous utilisez l’expérience Microsoft purview classique, utilisez $"https://{ReceiverPurviewAccountName}.purview.azure.com"; Si vous utilisez la nouvelle expérience Microsoft Purview, utilisez 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;
    }
}

Mettre à jour le partage reçu

Ce script vous permet de mettre à jour l’emplacement de stockage d’un partage reçu. Tout comme pour créer un partage reçu, vous ajoutez les informations du compte de stockage dans lequel vous souhaitez que les données soient hébergées. Pour l’utiliser, veillez à remplir les variables suivantes :

  • ReceiverTenantId : ID de locataire Azure pour l’utilisateur/service qui reçoit les données partagées.
  • ReceiverPurviewAccountName : nom du compte Microsoft Purview dans lequel les données seront reçues.
  • ReceiverStorageKind : BlobAccount ou AdlsGen2Account.
  • ReceiverStorageResourceId : ID de ressource du compte de stockage dans lequel les données ont été partagées.
  • ReAttachStorageResourceId : ID de ressource du compte de stockage dans lequel les données seront reçues.
  • ReceiverStorageContainer : nom du conteneur dans lequel les données partagées seront stockées.
  • ReceiverTargetFolderName : chemin d’accès au dossier où les données partagées seront stockées.
  • ReceiverTargetMountPath : chemin de montage que vous souhaitez utiliser pour stocker vos données dans le dossier .
  • ReceivedShareDisplayName : nom d’affichage de votre partage reçu.
  • UseServiceTokenCredentials : (facultatif) Si vous souhaitez utiliser un principal de service pour recevoir les partages, définissez-le sur true.
  • ReceiverClientId : (facultatif) Si vous utilisez un principal de service pour recevoir les partages, il s’agit de l’ID d’application (client) du principal de service.
  • ReceiverClientSecret : (facultatif) Si vous utilisez un principal de service pour recevoir les partages, ajoutez votre clé secrète client/clé d’authentification.
  • ReceiverPurviewEndPoint : si vous utilisez Si vous utilisez l’expérience Microsoft purview classique, utilisez $"https://{ReceiverPurviewAccountName}.purview.azure.com"; Si vous utilisez la nouvelle expérience Microsoft Purview, utilisez 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;
    }
}

Supprimer le partage reçu

Ce script supprime un partage reçu. Pour l’utiliser, veillez à remplir les variables suivantes :

  • ReceiverTenantId : ID de locataire Azure pour l’utilisateur/service qui reçoit les données partagées.
  • ReceiverPurviewAccountName : nom du compte Microsoft Purview dans lequel les données seront reçues.
  • ReceivedShareDisplayName : nom d’affichage de votre partage reçu.
  • ReceiverStorageResourceId : ID de ressource du compte de stockage dans lequel les données ont été partagées.
  • UseServiceTokenCredentials : (facultatif) Si vous souhaitez utiliser un principal de service pour recevoir les partages, définissez-le sur true.
  • ReceiverClientId : (facultatif) Si vous utilisez un principal de service pour recevoir les partages, il s’agit de l’ID d’application (client) du principal de service.
  • ReceiverClientSecret : (facultatif) Si vous utilisez un principal de service pour recevoir les partages, ajoutez votre clé secrète client/clé d’authentification.
  • ReceiverPurviewEndPoint : si vous utilisez Si vous utilisez l’expérience Microsoft purview classique, utilisez $"https://{ReceiverPurviewAccountName}.purview.azure.com"; Si vous utilisez la nouvelle expérience Microsoft Purview, utilisez 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;
    }
}

Nettoyer les ressources

Pour propre les ressources créées pour le démarrage rapide, suivez les instructions suivantes :

  1. Dans le portail Microsoft Purview, supprimez le partage envoyé.
  2. Supprimez également votre partage reçu.
  3. Une fois les partages supprimés, supprimez le conteneur cible et le dossier Microsoft Purview créés dans votre compte de stockage cible lorsque vous avez reçu des données partagées.

Prochaines étapes