Пакет SDK для файла — обработка MSG-файлов электронной почты (C#)

Пакет SDK для файлf поддерживает операции меток для MSG-файлов так же, как и любые другие типы файлов, за исключением того, что пакету SDK требуется приложение, чтобы включить флаг функций MSG. Здесь вы узнаете, как установить этот флаг.

Как уже было рассмотрено, для создания экземпляра IFileEngine требуется объект параметра FileEngineSettings. FileEngineSettings можно использовать для передачи параметров в пользовательские настройки, которые приложение должно установить для определенного экземпляра. Свойство CustomSettings элемента FileEngineSettings используется для установки флага enable_msg_file_type для включения обработки MSG-файлов.

Необходимые компоненты

Прежде чем продолжить, выполните следующие предварительные требования:

Настройка enable_msg_file_type и использование пакета SDK для меток MSG-файла

В продолжение краткого руководства по инициализации приложения для API файлов измените код конструкции обработчика файлов, чтобы установить enable_msg_file_type flag, а затем используйте обработчик файлов, чтобы пометить MSG-файл.

  1. Откройте решение Visual Studio, созданное при изучении предыдущей статьи "Краткое руководство. Инициализация приложения пакета SDK для файла (C#)".

  2. С помощью Обозревателя решений откройте в проекте CS-файл, содержащий реализацию метода Main(). По умолчанию он имеет то же имя, что и содержащий его проект, который вы указали при создании проекта.

  3. Удалите реализацию функции Main() из предыдущего краткого руководства. Вставьте указанный ниже код в Main(). Если в указанном ниже блоке кода установлен флаг enable_msg_file_type во время создания обработчика файлов, MGS-файл может обрабатываться объектами IFileHandler, созданными с помощью обработчика файлов.

    static void Main(string[] args)
    {
        // Initialize Wrapper for File SDK operations.
        MIP.Initialize(MipComponent.File);
    
        // Create ApplicationInfo, setting the clientID from Azure AD App Registration as the ApplicationId.
        ApplicationInfo appInfo = new ApplicationInfo()
        {
                ApplicationId = clientId,
                ApplicationName = appName,
                ApplicationVersion = "1.0.0"
        };
    
        // Instantiate the AuthDelegateImpl object, passing in AppInfo.
        AuthDelegateImplementation authDelegate = new AuthDelegateImplementation(appInfo);
    
        MipContext mipContext = MIP.CreateMipContext(appInfo,"mip_data",LogLevel.Trace,null,null);
    
        // Initialize and instantiate the File Profile.
        // Create the FileProfileSettings object.
        // Initialize file profile settings to create/use local state.
        var profileSettings = new FileProfileSettings(mipContext, 
                                    CacheStorageType.OnDiskEncrypted, 
                                    new ConsentDelegateImplementation());
    
        // Load the Profile async and wait for the result.
        var fileProfile = Task.Run(async () => await MIP.LoadFileProfileAsync(profileSettings)).Result;
    
        // Create a FileEngineSettings object, then use that to add an engine to the profile.
        var customSettings = new List<KeyValuePair<string, string>>();
        customSettings.Add(new KeyValuePair<string, string>("enable_msg_file_type", "true"));
    
        // Create a FileEngineSettings object, then use that to add an engine to the profile.
        var engineSettings = new FileEngineSettings("user1@tenant.com", authDelegate, "", "en-US");
        engineSettings.Identity = new Identity("user1@tenant.com");
        //set custom settings for the engine
        engineSettings.CustomSettings = customSettings;
    
        //Add fileEngine to profile
        var fileEngine = Task.Run(async () => await fileProfile.AddEngineAsync(engineSettings)).Result;
    
        //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
        var fileHandler = Task.Run(async () => await fileEngine.CreateFileHandlerAsync(inputFilePath, 
                                                                    actualFilePath, 
                                                                    true)).Result;
    
        // List labels available to the user and use one of them to label the MSG file.
    
        foreach (var label in fileEngine.SensitivityLabels)
        {
            Console.WriteLine(string.Format("{0} - {1}", label.Name, label.Id));
    
            if (label.Children.Count > 0)
            {
                foreach (Label child in label.Children)
                {
                    Console.WriteLine(string.Format("\t{0} - {1}", child.Name, child.Id));
                }
            }
        }
    
        string labelId = "<label-id>"; //label retrieved using file engine
    
        LabelingOptions labelingOptions = new LabelingOptions()
        {
            AssignmentMethod = options.AssignmentMethod
        };
    
        fileHandler.SetLabel(labelId, labelingOptions, new ProtectionSettings());
    
        // Commit changes, save as outputFilePath
        var result = Task.Run(async () => await fileHandler.CommitAsync(outputFilePath)).Result;
    
        // Create a new handler to read the labeled file metadata
        var handlerModified = Task.Run(async () => await fileEngine.CreateFileHandlerAsync(outputFilePath, 
                                                                        actualOutputFilePath, 
                                                                        true)).Result;
    
        Console.WriteLine(string.Format("Original file: {0}", inputFilePath));
        Console.WriteLine(string.Format("Labeled file: {0}", outputFilePath));
        Console.WriteLine(string.Format("Label applied to file: {0}", 
            handlerModified.Label.Name));
        Console.WriteLine("Press a key to continue.");
        Console.ReadKey();
    
        // Application Shutdown
        fileHandler = null;
        handlerModified = null;
        fileEngine = null;
        fileProfile = null;
        mipContext = null;
    }
    
    

    Дополнительные сведения об операциях с файлами см. на странице основных понятий обработчика файлов.

  4. Замените значения-заполнители в исходном коде следующими значениями:

    Заполнитель Значение
    <input-file-path> Полный путь к тестовому входному файлу сообщения, например: c:\\Test\\message.msg.
    <output-file-path> Полный путь к выходному файлу, который является помеченной копией входного файла, например: c:\\Test\\message_labeled.msg.
    <label-id> Идентификатор метки, извлеченный с помощью обработчика файлов, например: 667466bf-a01b-4b0a-8bbf-a79a3d96f720.

Создание и тестирование приложения

Для создания клиентского приложения нажмите клавишу F6 (Сборка решения). Если ошибок сборки нет, нажмите клавишу F5 (Начать отладку), чтобы запустить приложение.

    Original file: C:\Test.msg
    Labeled file: C:\Test_Labeled.msg
    Label applied to file: Confidential    
    Press a key to continue.