Observação
O acesso a essa página exige autorização. Você pode tentar entrar ou alterar diretórios.
O acesso a essa página exige autorização. Você pode tentar alterar os diretórios.
O SDK de Arquivo dá suporte a operações de rotulagem para arquivos .msg da mesma maneira que qualquer outro tipo de arquivo, exceto que o SDK precisa do aplicativo para habilitar o sinalizador de recurso MSG. Este início rápido mostra como definir esse sinalizador.
Conforme discutido anteriormente, a instanciação mip::FileEngine requer o mip::FileEngineSettings objeto de configurações. O aplicativo usa FileEngineSettings para passar configurações personalizadas para uma instância específica. A propriedade CustomSettings de mip::FileEngineSettings define o sinalizador enable_msg_file_type para habilitar o processamento de arquivos .msg.
Pré-requisitos
Caso ainda não tenha feito isso, certifique-se de concluir os seguintes pré-requisitos antes de continuar:
- Conclua primeiro o Guia de início rápido: inicialização de aplicativo SDK (C++), que compila uma solução inicial do Visual Studio. Este guia de início rápido "Como processar arquivos de mensagens de email .msg (C++)" foi construído com base no anterior.
- Revise Início rápido: listar rótulos de confidencialidade (C++).
- Revise Guia de início rápido: Definir/obter etiquetas de sensibilidade (C++).
- Examine Os conceitos de SDK da PIM de arquivos de email.
- Opcionalmente: examine os conceitos de mecanismos de arquivos no SDK do MIP.
- Opcionalmente: examine os conceitos de manipuladores de arquivos no SDK da PIM.
Etapas para a implementação de pré-requisitos
Abra a solução do Visual Studio que você criou no artigo "Início Rápido: Inicialização do aplicativo cliente (C++)" anterior.
Crie um script do PowerShell para gerar tokens de acesso, conforme explicado no Início Rápido: Listar rótulos de confidencialidade (C++).
Implemente uma classe de observador para monitorar
mip::FileHandler, conforme explicado no Início Rápido: Definir/obter rótulos de confidencialidade (C++).
Defina enable_msg_file_type e use o SDK de Arquivo para rotular arquivos .msg
Adicione o código de configuração do mecanismo de arquivo a seguir para definir o sinalizador enable_msg_file_type e usar o mecanismo de arquivo para rotular um arquivo .msg.
Em Gerenciador de Soluções, abra o arquivo .cpp em seu projeto que contém a implementação do
main()método. Ele usa como padrão o mesmo nome do projeto que o contém, que você especificou durante a criação do projeto.Adicione as seguintes diretivas #include e using após as diretivas correspondentes existentes, no início do arquivo:
#include "filehandler_observer.h" #include "mip/file/file_handler.h" #include <iostream> using mip::FileHandler; using std::endl;Remova a implementação da
main()função do início rápido anterior. Dentro domain()corpo, insira o código a seguir. No bloco de código a seguir, a criação do mecanismo de arquivo define o sinalizadorenable_msg_file_type.mip::FileHandleros objetos criados usando o mecanismo de arquivos podem processar um arquivo .msg.
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>(appInfo,
"mip_data",
mip::LogLevel::Trace,
false,
mip::CacheStorageType::OnDisk);
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(mMipContext, mip::CacheStorageType::OnDisk,
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)
authDelegateImpl, // Token acquisition implementation
"<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
auto labels = engine->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);
// Resolve the label ID to a mip::Label, then apply it.
auto label = engine->GetLabelById(labelId);
fileHandler->SetLabel(label, 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 = msgHandlerPromise->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->GetLabel()->GetLabel()->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;
mMipContext->ShutDown();
mMipContext = nullptr;
return 0;
}
Para obter mais informações sobre operações de arquivo, consulte os conceitos do Manipulador de Arquivos.
Substitua os valores dos marcadores no código-fonte pelos seguintes valores:
Espaço reservado Valor <application-id> O ID do aplicativo conforme registrado no locatário do Microsoft Entra, por exemplo: 00001111-aaaa-2222-bbbb-3333cccc4444.<engine-account> A conta usada para a identidade do mecanismo, por exemplo: user@tenant.onmicrosoft.com.<estado do mecanismo> Estado do aplicativo definido pelo usuário, por exemplo: My engine state.<caminho-do-arquivo-de-entrada> O caminho completo para um arquivo de mensagem de entrada de teste, por exemplo: c:\\Test\\message.msg.<output-file-path> O caminho completo para o arquivo de saída, que é uma cópia rotulada do arquivo de entrada, por exemplo: c:\\Test\\message_labeled.msg.<label-id> A ID do rótulo recuperada usando ListSensitivityLabels, por exemplo:667466bf-a01b-4b0a-8bbf-a79a3d96f720.
Criar e testar o aplicativo
Use F6 (Compilar Solução) para criar seu aplicativo cliente. Se você não tiver erros de compilação, use F5 (Iniciar depuração) para executar seu aplicativo.