SDK de archivos: procesar archivos de .msg de correo electrónico (C++)

El SDK de archivos admite operaciones de etiquetado para .msg archivos de una manera idéntica a cualquier otro tipo de archivo, excepto que el SDK necesita la aplicación para habilitar la marca de características msg. Aquí veremos cómo establecer este indicador.

Como se ha descrito anteriormente, la creación de instancias de mip::FileEngine requiere un objeto de configuración, mip::FileEngineSettings. FileEngineSettings se puede usar para pasar parámetros para la configuración personalizada que la aplicación debe establecer para una instancia determinada. La propiedad CustomSettings de mip::FileEngineSettings se utiliza para establecer el indicador de enable_msg_file_type para habilitar el procesamiento de archivos .msg.

Prerequisites

Si aún no lo ha hecho, asegúrese de completar los siguientes requisitos previos antes de continuar:

Pasos de implementación de requisitos previos

  1. Abra la solución de Visual Studio que creó en el artículo anterior "Inicio rápido: inicialización de aplicaciones cliente (C++)".

  2. Cree un script de PowerShell para generar tokens de acceso como se explica en Inicio rápido "Enumerar etiquetas de confidencialidad (C++)".

  3. Implemente la clase observer para supervisar mip::FileHandler como se explica en Inicio rápido "Establecer/obtener etiquetas de confidencialidad (C++)".

Configurar enable_msg_file_type y usar el SDK de archivos para etiquetar un archivo .msg

Agregue el código de construcción del motor de archivos siguiente para establecer enable_msg_file_type flag y usar el motor de archivos para etiquetar un archivo .msg.

  1. Con el Explorador de soluciones, abra el archivo .cpp en el proyecto que contiene la implementación del main() método . El valor predeterminado es el mismo nombre que el proyecto que lo contiene, que especificó durante la creación del proyecto.

  2. Agregue las siguientes directivas #include y using, debajo de las directivas existentes correspondientes, en la parte superior del archivo:

    #include "filehandler_observer.h" 
    #include "mip/file/file_handler.h" 
    #include <iostream>    
    using mip::FileHandler;   
    using std::endl;
    
  3. Eliminar la implementación de la función main() de la guía de inicio rápido anterior. Dentro del main() cuerpo, inserte el código siguiente. En el siguiente bloque de código, la marca enable_msg_file_type se establece durante la creación del motor de archivos; a continuación, un archivo .msg puede ser procesado por objetos mip::FileHandler creados mediante el motor de archivos.

int main()
{
    // Construct/initialize objects required by the application's profile object
    ApplicationInfo appInfo { "<application-id>",                    // ApplicationInfo object (App ID, name, version)
                              "<application-name>", 
                              "1.0" 
    };

    std::shared_ptr<mip::MipConfiguration> mipConfiguration = std::make_shared<mip::MipConfiguration>(mAppInfo,
				                                                                                       "mip_data",
                                                                                        			   mip::LogLevel::Trace,
                                                                                                       false);

    std::shared_ptr<mip::MipContext> mMipContext = mip::MipContext::Create(mipConfiguration);

    auto profileObserver = make_shared<ProfileObserver>();                      // Observer object
    auto authDelegateImpl = make_shared<AuthDelegateImpl>("<application-id>");  // Authentication delegate object (App ID)
    auto consentDelegateImpl = make_shared<ConsentDelegateImpl>();              // Consent delegate object

    // Construct/initialize profile object
    FileProfile::Settings profileSettings(mipContext,mip::CacheStorageType::OnDisk,authDelegateImpl,
        consentDelegateImpl,profileObserver);

    // Set up promise/future connection for async profile operations; load profile asynchronously
    auto profilePromise = make_shared<promise<shared_ptr<FileProfile>>>();
    auto profileFuture = profilePromise->get_future();
    try
    {
        mip::FileProfile::LoadAsync(profileSettings, profilePromise);
    }
    catch (const std::exception& e)
    {
        std::cout << "An exception occurred. Are the Settings and ApplicationInfo objects populated correctly?\n\n"<< e.what() << "'\n";
        system("pause");
        return 1;
    }

    auto profile = profileFuture.get();

    // Construct/initialize engine object
    FileEngine::Settings engineSettings(
                            mip::Identity("<engine-account>"),      // Engine identity (account used for authentication)
                            "<engine-state>",                       // User-defined engine state
                            "en-US");                               // Locale (default = en-US)

    //Set enable_msg_file_type flag as true
    std::vector<std::pair<string, string>> customSettings;
    customSettings.emplace_back(mip::GetCustomSettingEnableMsgFileType(), "true");
    engineSettings.SetCustomSettings(customSettings);

    // Set up promise/future connection for async engine operations; add engine to profile asynchronously
    auto enginePromise = make_shared<promise<shared_ptr<FileEngine>>>();
    auto engineFuture = enginePromise->get_future();
    profile->AddEngineAsync(engineSettings, enginePromise);
    std::shared_ptr<FileEngine> engine;

    try
    {
        engine = engineFuture.get();
    }
    catch (const std::exception& e)
    {
        cout << "An exception occurred... is the access token incorrect/expired?\n\n"<< e.what() << "'\n";
        system("pause");
        return 1;
    }

    //Set file paths
    string inputFilePath = "<input-file-path>"; //.msg file to be labeled
    string actualFilePath = inputFilePath;
    string outputFilePath = "<output-file-path>"; //labeled .msg file
    string actualOutputFilePath = outputFilePath;

    //Create a file handler for original file
    auto handlerPromise = std::make_shared<std::promise<std::shared_ptr<FileHandler>>>();
    auto handlerFuture = handlerPromise->get_future();

    engine->CreateFileHandlerAsync(inputFilePath,
                                    actualFilePath,
                                    true,
                                    std::make_shared<FileHandlerObserver>(),
                                    handlerPromise);

    auto fileHandler = handlerFuture.get();

    //List labels available to the user    

    // Use mip::FileEngine to list all labels
    labels = mEngine->ListSensitivityLabels();

    // Iterate through each label, first listing details
    for (const auto& label : labels) {
        cout << label->GetName() << " : " << label->GetId() << endl;

        // get all children for mip::Label and list details
        for (const auto& child : label->GetChildren()) {
            cout << "->  " << child->GetName() << " : " << child->GetId() << endl;
        }
    }

    string labelId = "<labelId-id>"; //set a label ID to use

    // Labeling requires a mip::LabelingOptions object. 
    // Review API ref for more details. The sample implies that the file was labeled manually by a user.
    mip::LabelingOptions labelingOptions(mip::AssignmentMethod::PRIVILEGED);

    fileHandler->SetLabel(labelId, labelingOptions, mip::ProtectionSettings());

    // Commit changes, save as outputFilePath
    auto commitPromise = std::make_shared<std::promise<bool>>();
    auto commitFuture = commitPromise->get_future();

    if(fileHandler->IsModified())
    {
        fileHandler->CommitAsync(outputFilePath, commitPromise);
    }
    
    if (commitFuture.get()) {
        cout << "\n Label applied to file: " << outputFilePath << endl;
    }
    else {
        cout << "Failed to label: " + outputFilePath << endl;
        return 1;
    }

    // Create a new handler to read the label
    auto msgHandlerPromise = std::make_shared<std::promise<std::shared_ptr<FileHandler>>>();
    auto msgHandlerFuture = handlerPromise->get_future();

    engine->CreateFileHandlerAsync(inputFilePath,
                                    actualFilePath,
                                    true,
                                    std::make_shared<FileHandlerObserver>(),
                                    msgHandlerPromise);

    auto msgFileHandler = msgHandlerFuture.get();

    cout << "Original file: " << inputFilePath << endl;
    cout << "Labeled file: " << outputFilePath << endl;
    cout << "Label applied to file : " 
            << msgFileHandler->GetName() 
            << endl;
    
    // Application shutdown. Null out profile, engine, handler.
    // Application may crash at shutdown if resources aren't properly released.
    msgFileHandler = nullptr;
    fileHandler = nullptr;
    engine = nullptr;
    profile = nullptr;
    mipContext = nullptr;

    return 0;
}

Para obtener más información sobre las operaciones de archivo, consulte los conceptos del controlador de archivos.

  1. Reemplace los valores de marcador de posición en el código fuente con los siguientes valores:

    Marcador de posición Value
    <application-id> El identificador de aplicación tal como está registrado con Microsoft Entra inquilino, por ejemplo: 00001111-aaaa-2222-bbbb-3333cccc4444.
    <cuenta del motor> La cuenta usada para la identidad del motor, por ejemplo: user@tenant.onmicrosoft.com.
    <estado del motor> Estado de aplicación definido por el usuario, por ejemplo: My engine state.
    <ruta-del-archivo-de-entrada> Ruta de acceso completa a un archivo de mensaje de entrada de prueba, por ejemplo: c:\\Test\\message.msg.
    <ruta del archivo de salida> Ruta de acceso completa al archivo de salida, que será una copia etiquetada del archivo de entrada, por ejemplo: c:\\Test\\message_labeled.msg.
    <etiqueta-id> El labelId obtenido mediante ListSensitivityLabels, por ejemplo: 667466bf-a01b-4b0a-8bbf-a79a3d96f720.

Crear y probar la aplicación

Use F6 (Compilar la solución) para compilar la aplicación cliente. Si no tiene errores de compilación, use F5 (Iniciar depuración) para ejecutar la aplicación.