Share via


Inicio rápido: Uso compartido y recepción de datos con el SDK de .NET de Uso compartido de datos de Microsoft Purview

Importante

Esta característica está actualmente en versión preliminar. Los Términos de uso complementarios para las versiones preliminares de Microsoft Azure incluyen términos legales adicionales que se aplican a las características de Azure que están en versión beta, en versión preliminar o que aún no se han publicado en disponibilidad general.

En este inicio rápido, usará el SDK de .NET para compartir datos y recibir recursos compartidos de Azure Data Lake Storage (ADLS Gen2) o cuentas de Blob Storage. El artículo incluye fragmentos de código que permiten crear, aceptar y administrar recursos compartidos mediante Uso compartido de datos de Microsoft Purview.

Para obtener información general sobre cómo funciona el uso compartido de datos, watch esta breve demostración.

Nota:

Esta característica se actualizó en febrero de 2023 y el SDK y los permisos necesarios para ver y administrar recursos compartidos de datos en Microsoft Purview han cambiado.

  • Ahora no se requieren permisos en Microsoft Purview para usar el SDK para crear y administrar recursos compartidos. (Se necesitan permisos de lector para usar el Portal de gobernanza de Microsoft Purview para compartir datos).
  • Los permisos siguen siendo necesarios en las cuentas de almacenamiento.

Consulte el paquete NuGet actualizado y los fragmentos de código actualizados para usar el SDK actualizado.

Requisitos previos

Requisitos previos de Microsoft Purview

  • Una cuenta de Microsoft Purview. También puede usar dos cuentas de Microsoft Purview, una para el proveedor de datos y otra para el consumidor de datos para probar ambos escenarios.
  • La dirección de correo electrónico de inicio de sesión de Azure del destinatario a la que puede usar para enviar la invitación. El alias de correo electrónico del destinatario no funcionará.

Requisitos previos de la cuenta de Azure Storage

  • La suscripción de Azure debe estar registrada para la característica de versión preliminar AllowDataSharing . Siga los pasos siguientes mediante Azure Portal o PowerShell.

    1. En Azure Portal, seleccione la suscripción de Azure que usará para crear la cuenta de almacenamiento de origen y de destino.
    2. En el menú de la izquierda, seleccione Características de vista previa en Configuración.
    3. Seleccione AllowDataSharing y Register (Registrar).
    4. Actualice la pantalla Características de vista previa para comprobar que el estado está registrado. El registro puede tardar entre 15 minutos y 1 hora en completarse.
    5. Además, para usar el recurso compartido de datos para cuentas de almacenamiento en Este de EE. UU., Este de EE. UU. 2, Norte de Europa, Centro-sur de EE. UU., Centro-oeste de EE. UU., Oeste de Europa, Oeste de EE. UU., Oeste de EE. UU. 2, Oeste de EE. UU. 3: Seleccione AllowDataSharingInHeroRegion y Registrar.

    Para obtener más información, vea Registrar la característica de vista previa.

    RegistrationState debe ser Registrado. El registro puede tardar entre 15 minutos y 1 hora en completarse. Para obtener más información, vea Registrar la característica de vista previa.

    Nota:

    Las siguientes son configuraciones de cuenta de almacenamiento admitidas:

    • Regiones de Azure: Centro de Canadá, Este de Canadá, Sur de Reino Unido, Oeste de Reino Unido, Este de Australia, Este de Japón, Sur de Corea del Sur y Norte de Sudáfrica
    • Regiones adicionales de Azure: Este de EE. UU., Este de EE. UU. 2, Norte de Europa, Centro-sur de EE. UU., Centro-oeste de EE. UU., Oeste de Europa, Oeste de EE. UU., Oeste de EE. UU. 2, Oeste de EE. UU. 3
    • Rendimiento: estándar
    • Opciones de redundancia: LRS
  • Cuentas de almacenamiento de origen y de destino creadas después de completar el paso de registro. Ambas cuentas de almacenamiento deben estar en la misma región de Azure entre sí. Ambas cuentas de almacenamiento deben ser cuentas de ADLS Gen2 o Blob Storage. Las cuentas de almacenamiento pueden estar en una región de Azure diferente de la cuenta de Microsoft Purview.

  • Versión más reciente del SDK de almacenamiento, PowerShell, cli y Explorador de Azure Storage. La versión de la API REST de Almacenamiento debe ser febrero de 2020 o posterior.

  • Las cuentas de almacenamiento deben registrarse en las colecciones donde enviará o recibirá el recurso compartido. Si usa una cuenta de Microsoft Purview, puede ser dos colecciones diferentes o la misma colección. Para obtener instrucciones para registrarse, consulte las páginas de origen de datos de ADLS Gen2 o Blob Storage .

  • Si las cuentas de almacenamiento de origen o de destino están en una suscripción de Azure diferente a la de la cuenta de Microsoft Purview, el proveedor de recursos Microsoft.Purview se registra automáticamente en la suscripción de Azure donde se encuentra el almacén de datos en el momento de agregar un recurso o asignación de consumidor de recursos compartidos a un recurso y SOLO si el usuario tiene permiso para realizar la operación /register/action para el proveedor de recursos. El permiso se incluye en los roles Colaborador y Propietario.

    Nota:

    Este registro solo es necesario la primera vez que se comparten o reciben datos en una cuenta de almacenamiento de la suscripción de Azure.

Roles necesarios

Estos son los roles necesarios para compartir datos y recibir recursos compartidos.

Roles de cuenta de Azure Storage Roles de colección de Microsoft Purview
Proveedor de datos Uno de los siguientes roles:
  • Owner
  • Propietario de datos de Storage Blob
Lector de datos
Consumidor de datos Uno de los siguientes roles:
  • Colaborador
  • Owner
  • Colaborador de datos de Storage Blob
  • Propietario de datos de Storage Blob
Lector de datos

Nota:

Si creó la cuenta de Microsoft Purview, se le asignarán automáticamente todos los roles a la colección raíz. Consulte Permisos de Microsoft Purview para obtener más información sobre la colección y los roles de Microsoft Purview.

Visual Studio

En el tutorial de este artículo se usa Visual Studio 2022. Los procedimientos para Visual Studio 2013, 2015, 2017 o 2019 pueden diferir ligeramente.

Azure .NET SDK

Descargue e instale el SDK de Azure .NET en el equipo.

Uso de una entidad de servicio

En los fragmentos de código de este tutorial, puede autenticarse mediante sus propias credenciales o mediante una entidad de servicio. Para configurar una entidad de servicio, siga estas instrucciones:

  1. En Creación de una aplicación de Azure Active Directory, cree una aplicación que represente la aplicación .NET que va a crear en este tutorial. Para la dirección URL de inicio de sesión, puede proporcionar una dirección URL ficticia como se muestra en el artículo (https://contoso.org/exampleapp).

  2. En Obtener valores para iniciar sesión, obtenga el identificador de aplicación, el identificador de inquilino y el identificador de objeto, y anote estos valores que usará más adelante en este tutorial.

  3. En Certificados y secretos, obtenga la clave de autenticación y anote este valor que usará más adelante en este tutorial.

  4. asignar la aplicación a estos roles:

    User Roles de cuenta de Azure Storage Roles de colección de Microsoft Purview
    Proveedor de datos Uno de los siguientes roles:
    • Owner
    • Propietario de datos de Blob Storage
    Colaborador de Data Share
    Consumidor de datos Uno de los siguientes roles:
    • Colaborador
    • Owner
    • Colaborador de datos de Storage Blob
    • Propietario de datos de Blob Storage
    Colaborador de Data Share

Creación de un proyecto de Visual Studio

A continuación, cree una aplicación de consola .NET de C# en Visual Studio:

  1. Inicie Visual Studio.
  2. En la ventana Inicio, seleccione Crear un nuevo proyecto>Aplicación de consola. Se requiere la versión 6.0 o posterior de .NET.
  3. En Nombre del proyecto, escriba PurviewDataSharingQuickStart.
  4. Seleccione Crear para crear el proyecto.

Instalar paquetes NuGet

  1. Seleccione Herramientas>NuGet Package ManagerPackage Manager Console (Consola del Administrador> de paquetes de NuGet).

  2. En la consola de administración de paquetes, ejecute el comando add package de la cli de .NET que se muestra en esta página para agregar el paquete NuGet: Microsoft.Azure.Analytics.Purview.Sharing NuGet.

  3. En el panel Consola del Administrador de paquetes, ejecute los siguientes comandos para instalar paquetes.

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

    Sugerencia

    Si recibe un error que indica "No se encontró ningún proyecto en..." al intentar estos comandos, es posible que solo tenga que bajar un nivel de carpeta en el proyecto. Pruebe el comando dir para enumerar las carpetas del directorio y, a continuación, use "cd <name of the project folder" (Nombre cd de la carpeta> del proyecto) para bajar un nivel a la carpeta del proyecto. A continuación, inténtelo de nuevo.

Creación de un recurso compartido enviado

Este script crea un recurso compartido de datos que puede enviar a usuarios internos o externos. Para usarlo, asegúrese de rellenar estas variables:

  • SenderTenantId : el identificador de inquilino de Azure para la identidad del remitente.
  • SenderPurviewAccountName : nombre de la cuenta de Microsoft Purview desde la que se enviarán los datos.
  • ShareName : nombre para mostrar del recurso compartido enviado.
  • ShareDescription : (opcional) Descripción del recurso compartido enviado.
  • SenderStorageKind : BlobAccount o AdlsGen2Account.
  • SenderStorageResourceId : el identificador de recurso de la cuenta de almacenamiento desde la que se enviarán los datos.
  • SenderStorageContainer : el nombre del contenedor donde se almacenan los datos que se van a compartir.
  • SenderPathToShare : la ruta de acceso de archivo o carpeta a los datos que se van a compartir.
  • UseServiceTokenCredentials : (opcional) Si desea usar una entidad de servicio para crear los recursos compartidos, establézcalo en true.
  • SenderClientId : (opcional) Si usa una entidad de servicio para crear los recursos compartidos, este es el identificador de aplicación (cliente) de la entidad de servicio.
  • SenderClientSecret : (opcional) Si usa una entidad de servicio para crear los recursos compartidos, agregue el secreto de cliente o la clave de autenticación.
  • SentShareID : (opcional) Esta opción debe ser un GUID y el valor actual genera uno automáticamente, pero puede reemplazarlo por un valor diferente si lo desea.
  • ReceiverVisiblePath : (opcional) El nombre del recurso compartido que verá el receptor. Actualmente se establece en un GUID, pero no es necesario.
  • SenderPurviewEndPoint : si usa si usa la experiencia clásica de Purview de Microsoft, use $"https://{SenderPurviewAccountName}.purview.azure.com"; Si usa la nueva experiencia de Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;
using System.ComponentModel;

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

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

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

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

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

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

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

    private static async Task<BinaryData> Sender_CreateSentShare()
    {

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

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

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

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

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

Enviar invitación a un usuario

Este script envía una invitación por correo electrónico para un recurso compartido a un usuario. Si desea enviar una invitación a una entidad de servicio, consulte el siguiente ejemplo de código. Para usarlo, asegúrese de rellenar estas variables:

  • RecipientUserEmailId: Email dirección a la que el usuario va a enviar la invitación.
  • SenderTenantId : el identificador de inquilino de Azure para la identidad del remitente del recurso compartido.
  • SenderPurviewAccountName : nombre de la cuenta de Microsoft Purview desde la que se enviarán los datos.
  • SenderStorageResourceId : el identificador de recurso de la cuenta de almacenamiento desde la que se enviarán los datos.
  • SentShareDisplayName : el nombre del recurso compartido enviado para el que va a enviar una invitación.
  • UseServiceTokenCredentials : (opcional) Si desea usar una entidad de servicio para crear los recursos compartidos, establézcalo en true.
  • SenderClientId : (opcional) Si usa una entidad de servicio para crear los recursos compartidos, este es el identificador de aplicación (cliente) de la entidad de servicio.
  • SenderClientSecret : (opcional) Si usa una entidad de servicio para crear los recursos compartidos, agregue el secreto de cliente o la clave de autenticación.
  • InvitationId : (opcional) Esta opción debe ser un GUID y el valor actual genera uno automáticamente, pero puede reemplazarlo por un valor diferente si lo desea.
  • SenderPurviewEndPoint : si usa si usa la experiencia clásica de Purview de Microsoft, use $"https://{SenderPurviewAccountName}.purview.azure.com"; Si usa la nueva experiencia de Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;
using System.ComponentModel;
using System.Text.Json;

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

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

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

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

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

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

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

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

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

        return list;
    }

    private static async Task<BinaryData> Sender_CreateUserRecipient()
    {

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

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

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

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

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

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

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

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

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

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

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

        return sentInvitation.Content;
    }
}

Enviar invitación a un servicio

Este script envía una invitación por correo electrónico para un recurso compartido a una entidad de servicio. Si desea enviar una invitación a un usuario, consulte el ejemplo anterior. Para usarlo, asegúrese de rellenar estas variables:

  • RecipientApplicationTenantId : el identificador de inquilino de Azure para la entidad de servicio receptora.
  • RecipientApplicationObjectId : el identificador de objeto de la entidad de servicio receptora.
  • SenderTenantId : el identificador de inquilino de Azure para la identidad del remitente del recurso compartido.
  • SenderPurviewAccountName : nombre de la cuenta de Microsoft Purview desde la que se enviarán los datos.
  • SenderStorageResourceId : el identificador de recurso de la cuenta de almacenamiento desde la que se enviarán los datos.
  • SentShareDisplayName : el nombre del recurso compartido enviado para el que va a enviar una invitación.
  • UseServiceTokenCredentials : (opcional) Si desea usar una entidad de servicio para crear los recursos compartidos, establézcalo en true.
  • SenderClientId : (opcional) Si usa una entidad de servicio para crear los recursos compartidos, este es el identificador de aplicación (cliente) de la entidad de servicio.
  • SenderClientSecret : (opcional) Si usa una entidad de servicio para crear los recursos compartidos, agregue el secreto de cliente o la clave de autenticación.
  • InvitationId : (opcional) Esta opción debe ser un GUID y el valor actual genera uno automáticamente, pero puede reemplazarlo por un valor diferente si lo desea.
  • SenderPurviewEndPoint : si usa si usa la experiencia clásica de Purview de Microsoft, use $"https://{SenderPurviewAccountName}.purview.azure.com"; Si usa la nueva experiencia de Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;
using System.ComponentModel;
using System.Text.Json;

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

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

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

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

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

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

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

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

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

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

        return list;
    }

    private static async Task<BinaryData> Sender_CreateServiceRecipient()
    {

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

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

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

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

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


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

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

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

}

Lista de recursos compartidos enviados

Este script enumera todos los recursos compartidos enviados para un recurso de almacenamiento específico. Para usarlo, asegúrese de rellenar estas variables:

  • SenderTenantId : el identificador de inquilino de Azure para la identidad del remitente del recurso compartido.
  • SenderPurviewAccountName : el nombre de la cuenta de Microsoft Purview desde la que se enviaron los datos.
  • SenderStorageResourceId : el identificador de recurso de la cuenta de almacenamiento desde la que se han enviado recursos compartidos.
  • UseServiceTokenCredentials : (opcional) Si desea usar una entidad de servicio para crear los recursos compartidos, establézcalo en true.
  • SenderClientId : (opcional) Si usa una entidad de servicio para crear los recursos compartidos, este es el identificador de aplicación (cliente) de la entidad de servicio.
  • SenderClientSecret : (opcional) Si usa una entidad de servicio para crear los recursos compartidos, agregue el secreto de cliente o la clave de autenticación.
  • SenderPurviewEndPoint : si usa si usa la experiencia clásica de Purview de Microsoft, use $"https://{SenderPurviewAccountName}.purview.azure.com"; Si usa la nueva experiencia de Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;

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

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

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

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


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

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

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

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

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

        return list;
    }
}

Enumerar todos los destinatarios del recurso compartido

En este script se enumeran todos los destinatarios de un recurso compartido específico. Para usarlo, asegúrese de rellenar estas variables:

  • SenderTenantId : el identificador de inquilino de Azure para la identidad del remitente del recurso compartido.
  • SenderPurviewAccountName : el nombre de la cuenta de Microsoft Purview desde la que se enviaron los datos.
  • SentShareDisplayName : el nombre del recurso compartido enviado para el que se enumeran los destinatarios.
  • SenderStorageResourceId : el identificador de recurso de la cuenta de almacenamiento desde la que se enviarán los datos.
  • UseServiceTokenCredentials : (opcional) Si desea usar una entidad de servicio para crear los recursos compartidos, establézcalo en true.
  • SenderClientId : (opcional) Si usa una entidad de servicio para crear los recursos compartidos, este es el identificador de aplicación (cliente) de la entidad de servicio.
  • SenderClientSecret : (opcional) Si usa una entidad de servicio para crear los recursos compartidos, agregue el secreto de cliente o la clave de autenticación.
  • SenderPurviewEndPoint : si usa si usa la experiencia clásica de Purview de Microsoft, use $"https://{SenderPurviewAccountName}.purview.azure.com"; Si usa la nueva experiencia de Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;
using System.Text.Json;

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

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

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

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

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

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

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

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

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

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

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

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

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

        return list;
    }
}

Eliminar destinatario

Este script quita una invitación de recurso compartido y, por tanto, el recurso compartido para un destinatario. Para usarlo, asegúrese de rellenar estas variables:

  • SenderTenantId : el identificador de inquilino de Azure para la identidad del remitente del recurso compartido.
  • SenderPurviewAccountName : el nombre de la cuenta de Microsoft Purview desde la que se enviaron los datos.
  • SentShareDisplayName : el nombre del recurso compartido enviado para el que se va a quitar un destinatario.
  • SenderStorageResourceId : el identificador de recurso de la cuenta de almacenamiento desde la que se enviarán los datos.
  • RecipientUserEmailId: Email dirección del usuario que desea eliminar.
  • UseServiceTokenCredentials : (opcional) Si desea usar una entidad de servicio para crear los recursos compartidos, establézcalo en true.
  • SenderClientId : (opcional) Si usa una entidad de servicio para crear los recursos compartidos, este es el identificador de aplicación (cliente) de la entidad de servicio.
  • SenderClientSecret : (opcional) Si usa una entidad de servicio para crear los recursos compartidos, agregue el secreto de cliente o la clave de autenticación.
  • SenderPurviewEndPoint : si usa si usa la experiencia clásica de Purview de Microsoft, use $"https://{SenderPurviewAccountName}.purview.azure.com"; Si usa la nueva experiencia de Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;
using System.Text.Json;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        }

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

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

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

        return list;
    }
}

Eliminar recurso compartido enviado

Este script elimina un recurso compartido enviado. Para usarlo, asegúrese de rellenar estas variables:

  • SenderTenantId : el identificador de inquilino de Azure para la identidad del remitente del recurso compartido.
  • SenderPurviewAccountName : el nombre de la cuenta de Microsoft Purview desde la que se enviaron los datos.
  • SentShareDisplayName : el nombre del recurso compartido enviado para el que se enumeran los destinatarios.
  • SenderStorageResourceId : el identificador de recurso de la cuenta de almacenamiento desde la que se enviarán los datos.
  • UseServiceTokenCredentials : (opcional) Si desea usar una entidad de servicio para crear los recursos compartidos, establézcalo en true.
  • SenderClientId : (opcional) Si usa una entidad de servicio para crear los recursos compartidos, este es el identificador de aplicación (cliente) de la entidad de servicio.
  • SenderClientSecret : (opcional) Si usa una entidad de servicio para crear los recursos compartidos, agregue el secreto de cliente o la clave de autenticación.
  • SenderPurviewEndPoint : si usa si usa la experiencia clásica de Purview de Microsoft, use $"https://{SenderPurviewAccountName}.purview.azure.com"; Si usa la nueva experiencia de Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;
using System.Text.Json;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return list;
    }
}

Creación de un recurso compartido recibido

Este script le permite recibir un recurso compartido de datos. Para usarlo, asegúrese de rellenar estas variables:

  • ReceiverTenantId : el identificador de inquilino de Azure para el usuario o servicio que recibe los datos compartidos.
  • ReceiverPurviewAccountName : nombre de la cuenta de Microsoft Purview donde se recibirán los datos.
  • ReceiverStorageKind : BlobAccount o AdlsGen2Account.
  • ReceiverStorageResourceId : el identificador de recurso de la cuenta de almacenamiento donde se recibirán los datos.
  • ReceiverStorageContainer : el nombre del contenedor donde se almacenarán los datos compartidos.
  • ReceiverTargetFolderName : la ruta de acceso de la carpeta a la que se almacenarán los datos compartidos.
  • ReceiverTargetMountPath : la ruta de montaje que desea usar para almacenar los datos en la carpeta.
  • UseServiceTokenCredentials : (opcional) Si desea usar una entidad de servicio para recibir los recursos compartidos, establézcalo en true.
  • ReceiverClientId : (opcional) Si se usa una entidad de servicio para recibir los recursos compartidos, se trata del identificador de aplicación (cliente) de la entidad de servicio.
  • ReceiverClientSecret : (opcional) Si usa una entidad de servicio para recibir los recursos compartidos, agregue el secreto de cliente o la clave de autenticación.
  • ReceivedShareId : (opcional) Esta opción debe ser un GUID y el valor actual generará uno automáticamente, pero puede reemplazarlo por un valor diferente si lo desea.
  • ReceiverVisiblePath : (opcional) Nombre que desea usar para la ruta de acceso del recurso compartido recibido.
  • ReceivedShareDisplayName : (opcional) Nombre para mostrar del recurso compartido recibido.
  • ReceiverPurviewEndPoint : si usa si usa la experiencia clásica de Purview de Microsoft, use $"https://{ReceiverPurviewAccountName}.purview.azure.com"; Si usa la nueva experiencia de Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;
using System.ComponentModel;
using System.Text.Json;

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

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

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

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

    private static string ReceivedShareDisplayName = "ReceivedShare";

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

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


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

    private static async Task<BinaryData> Receiver_CreateReceivedShare()
    {

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

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

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

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

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



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

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


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

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

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

        return receivedShare.Value;
    }

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

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

        return list;
    }
}

Enumerar todos los recursos compartidos recibidos

Este script enumera todos los recursos compartidos recibidos en una cuenta de almacenamiento. Para usarlo, asegúrese de rellenar estas variables:

  • ReceiverTenantId : el identificador de inquilino de Azure para el usuario o servicio que recibe los datos compartidos.
  • ReceiverPurviewAccountName : nombre de la cuenta de Microsoft Purview donde se recibieron los datos.
  • ReceiverStorageResourceId : el identificador de recurso de la cuenta de almacenamiento donde se han compartido los datos.
  • UseServiceTokenCredentials : (opcional) Si desea usar una entidad de servicio para recibir los recursos compartidos, establézcalo en true.
  • ReceiverClientId : (opcional) Si se usa una entidad de servicio para recibir los recursos compartidos, se trata del identificador de aplicación (cliente) de la entidad de servicio.
  • ReceiverClientSecret : (opcional) Si usa una entidad de servicio para recibir los recursos compartidos, agregue el secreto de cliente o la clave de autenticación.
  • ReceiverPurviewEndPoint : si usa si usa la experiencia clásica de Purview de Microsoft, use $"https://{ReceiverPurviewAccountName}.purview.azure.com"; Si usa la nueva experiencia de Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;

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

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

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

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

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

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

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

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

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

        return list;
    }
}

Actualización del recurso compartido recibido

Este script le permite actualizar la ubicación de almacenamiento de un recurso compartido recibido. Al igual que al crear un recurso compartido recibido, agrega la información de la cuenta de almacenamiento donde desea que se almacenen los datos. Para usarlo, asegúrese de rellenar estas variables:

  • ReceiverTenantId : el identificador de inquilino de Azure para el usuario o servicio que recibe los datos compartidos.
  • ReceiverPurviewAccountName : nombre de la cuenta de Microsoft Purview donde se recibirán los datos.
  • ReceiverStorageKind : BlobAccount o AdlsGen2Account.
  • ReceiverStorageResourceId : el identificador de recurso de la cuenta de almacenamiento donde se han compartido los datos.
  • ReAttachStorageResourceId : el identificador de recurso de la cuenta de almacenamiento donde se recibirán los datos.
  • ReceiverStorageContainer : el nombre del contenedor donde se almacenarán los datos compartidos.
  • ReceiverTargetFolderName : la ruta de acceso de la carpeta a la que se almacenarán los datos compartidos.
  • ReceiverTargetMountPath : la ruta de montaje que desea usar para almacenar los datos en la carpeta.
  • ReceivedShareDisplayName : el nombre para mostrar del recurso compartido recibido.
  • UseServiceTokenCredentials : (opcional) Si desea usar una entidad de servicio para recibir los recursos compartidos, establézcalo en true.
  • ReceiverClientId : (opcional) Si se usa una entidad de servicio para recibir los recursos compartidos, se trata del identificador de aplicación (cliente) de la entidad de servicio.
  • ReceiverClientSecret : (opcional) Si usa una entidad de servicio para recibir los recursos compartidos, agregue el secreto de cliente o la clave de autenticación.
  • ReceiverPurviewEndPoint : si usa si usa la experiencia clásica de Purview de Microsoft, use $"https://{ReceiverPurviewAccountName}.purview.azure.com"; Si usa la nueva experiencia de Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;
using System.ComponentModel;
using System.Text.Json;

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

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

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

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

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

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

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

    private static async Task<BinaryData> Receiver_UpdateReceivedShare()
    {

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

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

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

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

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

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

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


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

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

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

        return receivedShare.Value;
    }

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

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

        return list;
    }
}

Eliminar recurso compartido recibido

Este script elimina un recurso compartido recibido. Para usarlo, asegúrese de rellenar estas variables:

  • ReceiverTenantId : el identificador de inquilino de Azure para el usuario o servicio que recibe los datos compartidos.
  • ReceiverPurviewAccountName : nombre de la cuenta de Microsoft Purview donde se recibirán los datos.
  • ReceivedShareDisplayName : el nombre para mostrar del recurso compartido recibido.
  • ReceiverStorageResourceId : el identificador de recurso de la cuenta de almacenamiento donde se han compartido los datos.
  • UseServiceTokenCredentials : (opcional) Si desea usar una entidad de servicio para recibir los recursos compartidos, establézcalo en true.
  • ReceiverClientId : (opcional) Si se usa una entidad de servicio para recibir los recursos compartidos, se trata del identificador de aplicación (cliente) de la entidad de servicio.
  • ReceiverClientSecret : (opcional) Si usa una entidad de servicio para recibir los recursos compartidos, agregue el secreto de cliente o la clave de autenticación.
  • ReceiverPurviewEndPoint : si usa si usa la experiencia clásica de Purview de Microsoft, use $"https://{ReceiverPurviewAccountName}.purview.azure.com"; Si usa la nueva experiencia de Microsoft Purview, use https://api.purview-service.microsoft.com/
using Azure;
using Azure.Analytics.Purview.Sharing;
using Azure.Core;
using Azure.Identity;
using System.Text.Json;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return list;
    }
}

Limpie los recursos

Para limpiar los recursos creados para el inicio rápido, use las siguientes directrices:

  1. En el portal de Microsoft Purview, elimine el recurso compartido enviado.
  2. Elimine también el recurso compartido recibido.
  3. Una vez que los recursos compartidos se eliminen correctamente, elimine el contenedor de destino y la carpeta que Microsoft Purview creó en la cuenta de almacenamiento de destino cuando recibió datos compartidos.

Pasos siguientes