### Example Console Output Source: https://learn.microsoft.com/en-us/information-protection/develop/quick-protection-list-templates-csharp This is an example of the expected console output after successfully listing protection templates. The output shows the index, name, and ID of each available template. ```console 0: Confidential \ All Employees : a74f5027-f3e3-4c55-abcd-74c2ee41b607 1: Highly Confidential \ All Employees : bb7ed207-046a-4caf-9826-647cff56b990 2: Confidential : 174bc02a-6e22-4cf2-9309-cb3d47142b05 3: Contoso Employees Only : 667466bf-a01b-4b0a-8bbf-a79a3d96f720 Press a key to continue. ``` -------------------------------- ### Example Console Output for Sensitivity Labels Source: https://learn.microsoft.com/en-us/information-protection/develop/quick-file-list-labels-cpp This is an example of the console output you should see after successfully pasting an access token into your application prompt. It lists the available sensitivity labels with their corresponding IDs. ```console Non-Business : 87ba5c36-17cf-14793-bbc2-bd5b3a9f95cz Public : 83867195-f2b8-2ac2-b0b6-6bb73cb33afz General : f42a3342-8706-4288-bd31-ebb85995028z Confidential : 074e457c-5848-4542-9a6f-34a182080e7z Highly Confidential : f55c2dea-db0f-47cd-8520-a52e1590fb6z Press any key to continue . . . ``` -------------------------------- ### Install MIP SDK NuGet Packages Source: https://learn.microsoft.com/en-us/information-protection/develop/setup-configure-mip Use these commands in the Package Manager Console to install the MIP SDK components if you are developing with Visual Studio. ```powershell Install-Package Microsoft.InformationProtection.File Install-Package Microsoft.InformationProtection.Policy Install-Package Microsoft.InformationProtection.Protection ``` -------------------------------- ### Install MSAL for Python Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-authentication-acquire-token-py Install the MSAL for Python library using pip or pip3 before running the script. ```shell pip install msal pip3 install msal ``` -------------------------------- ### Console Output Example Source: https://learn.microsoft.com/en-us/information-protection/develop/quick-file-republishing-csharp This console output demonstrates the expected results after building and running the client application, including available labels, file protection status, and reprotection details. ```console Personal : 73c47c6a-eb00-4a6a-8e19-efaada66dee6 Public : 73254501-3d5b-4426-979a-657881dfcb1e General : da480625-e536-430a-9a9e-028d16a29c59 Confidential : 569af77e-61ea-4deb-b7e6-79dc73653959 Highly Confidential : 905845d6-b548-439c-9ce5-73b2e06be157 Press a key to continue. Getting the label committed to file: C:\Test\Test_protected.docx File Label: Confidential IsProtected: True Press a key to continue. Originally protected file: C:\Test\Test_protected.docx File LabelID: 569af77e-61ea-4deb-b7e6-79dc73653959 ProtectionOwner: User1@Contoso.OnMicrosoft.com IsProtected: True Reprotected file: C:\Test\Test_reprotected.docx File LabelID: 569af77e-61ea-4deb-b7e6-79dc73653959 ProtectionOwner: User1@Contoso.OnMicrosoft.com IsProtected: True Press a key to continue. ``` -------------------------------- ### Get File Status in C# Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-handler-file-status-cpp This C# example demonstrates how to check a file's protection and labeling status using `FileHandler.GetFileStatus()`. It's efficient as it avoids engine creation and authentication. ```csharp if (options.GetFileStatus) { var fileStatus = FileHandler.GetFileStatus(options.FilePath, mipContext); if (fileStatus.IsProtected()) { Console.WriteLine("The file is protected."); } if (fileStatus.IsLabeled()) { Console.WriteLine("The file is labeled."); } if (fileStatus.ContainsProtectedObjects()) { Console.WriteLine("The file contains protected objects."); } return true; } ``` -------------------------------- ### C++ Main Function with String Conversion Example Source: https://learn.microsoft.com/en-us/information-protection/develop/faqs-known-issues Demonstrates the usage of string conversion utility functions within a C++ application's main function. Shows how to handle command-line arguments and interact with MIP SDK string functions. ```cpp // An implementation of wmain(int argc, wchar_t *argv[]) in file\samples\file\main.cpp ``` -------------------------------- ### Install Microsoft Information Protection .NET Package Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-summary-csharp Install the Microsoft.InformationProtection.File NuGet package using the Package Manager Console in Visual Studio. No additional packages are required as all dependencies are included. ```powershell install-package Microsoft.InformationProtection.File ``` -------------------------------- ### Console Output Example Source: https://learn.microsoft.com/en-us/information-protection/develop/quick-protection-app-initialization-cpp This console output indicates that the application has successfully constructed the protection profile and engine. It is shown after a successful build but before the authentication module has been fired. ```console C:\MIP Sample Apps\ProtectionQS\Debug\ProtectionQS.exe (process 8252) exited with code 0. To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops. Press any key to close this window . . . ``` -------------------------------- ### Console Build Output Example Source: https://learn.microsoft.com/en-us/information-protection/develop/quick-email-msg-csharp This console output shows the result of a build process, including the original and labeled file paths, the applied label, and a prompt to continue. ```console Original file: C:\Test.msg Labeled file: C:\Test_Labeled.msg Label applied to file: Confidential Press a key to continue. ``` -------------------------------- ### Add MIP File SDK and MSAL NuGet Packages Source: https://learn.microsoft.com/en-us/information-protection/develop/quick-app-initialization-csharp Install the Microsoft.InformationProtection.File and Microsoft.Identity.Client NuGet packages into your C# project. ```csharp using Microsoft.InformationProtection; using Microsoft.Identity.Client; ``` -------------------------------- ### Example: Inspecting C++ Label Protection Types Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-label-protection-types Iterate through sensitivity labels and inspect their protection types using C++ methods. This example demonstrates how to identify different protection schemes like Do Not Forward, Encrypt Only, ad-hoc, or template-based protection. ```cpp for (const auto& label : engine->ListSensitivityLabels()) { std::cout << "Label: " << label->GetName() << std::endl; if (label->HasRightsManagementPolicy()) { if (label->HasDoNotForwardProtection()) { std::cout << " Protection type: Do Not Forward" << std::endl; } else if (label->HasEncryptOnlyProtection()) { std::cout << " Protection type: Encrypt Only" << std::endl; } else if (label->HasAdhocProtection()) { std::cout << " Protection type: Ad-hoc (user-defined permissions)" << std::endl; } else { std::cout << " Protection type: Template-based" << std::endl; } } else { std::cout << " No protection" << std::endl; } } ``` -------------------------------- ### Check License Expiration During Consumption (C++) Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-license-expiry This example demonstrates how to check if offline access is allowed, if the license expires, and then retrieve and display the license expiration time. It handles cases where the license does not expire or offline access is disallowed. ```cpp auto handler = protectionEngine->CreateProtectionHandlerForConsumption(consumptionSettings); auto descriptor = handler->GetProtectionDescriptor(); if (descriptor->DoesAllowOfflineAccess()) { if (descriptor->DoesLicenseExpire()) { auto expiry = descriptor->GetLicenseValidUntil(); auto timeT = std::chrono::system_clock::to_time_t(expiry); std::cout << "License expires: " << std::ctime(&timeT) << std::endl; } else { std::cout << "License does not expire." << std::endl; } } else { std::cout << "Offline access is not allowed. Online validation is always required." << std::endl; } ``` -------------------------------- ### Client Application Console Output Example Source: https://learn.microsoft.com/en-us/information-protection/develop/quick-file-justify-actions-cpp This console output illustrates the typical flow when running a client application integrated with the Information Protection SDK. It shows label IDs, file operations, token acquisition prompts, and justification for label downgrades. ```console Non-Business : 87ba5c36-17cf-14793-bbc2-bd5b3a9f95cz Public : 83867195-f2b8-2ac2-b0b6-6bb73cb33afz General : f42a3342-8706-4288-bd31-ebb85995028z Confidential : 074e457c-5848-4542-9a6f-34a182080e7z Highly Confidential : f55c2dea-db0f-47cd-8520-a52e1590fb6z Press any key to continue . . . Applying Label ID f55c2dea-db0f-47cd-8520-a52e1590fb6z to c:\Test\Test.docx Committing changes Label committed to file: c:\Test\Test.docx Press any key to continue . . . Run the PowerShell script to generate an access token using the following values, then copy/paste it below: Set $authority to: https://login.microsoftonline.com/37f4583d-9985-4e7f-a1ab-71afd8b55ba0 Set $resourceUrl to: https://aadrm.com Sign in with user account: user1@tenant.onmicrosoft.com Enter access token: Press any key to continue . . . Getting the label committed to file: c:\Test\Test_labeled.docx Name: Highly Confidential Id: f55c2dea-db0f-47cd-8520-a52e1590fb6z Press any key to continue . . . Applying new Label ID f42a3342-8706-4288-bd31-ebb85995028z to c:\Test\Test_labeled.docx Please provide justification for downgrading a label: Need for sharing with wider audience. Committing changes Label committed to file: c:\Test\Test_downgraded.docx Press any key to continue . . . Getting the label committed to file: c:\Test\Test_downgraded.docx Name: General Id: f42a3342-8706-4288-bd31-ebb85995028z Press any key to continue . . . ``` -------------------------------- ### Check rights before opening a file in C++ Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-rights-for-label This example demonstrates how to use the synchronous GetRightsForLabelId method to check if a user has edit rights before proceeding to open a file. ```cpp auto fileEngine = profile->AddEngine(engineSettings); std::string documentId = "document-unique-id"; std::string labelId = "d9f23ae3-1234-5678-abcd-1a2b3c4d5e6f"; std::string ownerEmail = "owner@contoso.com"; auto rights = fileEngine->GetRightsForLabelId( documentId, labelId, ownerEmail, nullptr); for (const auto& right : rights) { std::cout << "Right: " << right << std::endl; } // Check for a specific right before proceeding bool canEdit = std::find(rights.begin(), rights.end(), mip::rights::Edit()) != rights.end(); if (canEdit) { // Proceed with opening the file for editing } else { std::cout << "User does not have edit rights for this label." << std::endl; } ``` -------------------------------- ### MSAL Confidential Client Authentication Flow in C# Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-auth-scenario-csharp This example demonstrates how to build a `ConfidentialClientApplication` using either a certificate or a client secret for authentication. It then acquires an access token for client credentials. Pay attention to the scope format for `AcquireTokenForClient`. ```csharp public string AcquireToken(Identity identity, string authority, string resource, string claim) { AuthenticationResult result; var authorityUri = new Uri(authority); authority = string.Format("https://{0}/{1}", authorityUri.Host, ""); // Certification Based Auth if (doCertAuth) { // Build ConfidentialClientApplication using certificate. _app = ConfidentialClientApplicationBuilder.Create("") .WithCertificate(certificate) //Assumption here is Application passes a certificate created using certificate thumbprint .WithAuthority(new Uri(authority)) .Build(); } // Client secret based Auth else { // Build ConfidentialClientApplication using app secret _app = ConfidentialClientApplicationBuilder.Create("") .WithClientSecret(clientSecret) .WithAuthority(new Uri(authority)) .Build(); } // Append .default to the resource passed in to AcquireToken(). string[] scopes = new string[] { resource[resource.Length - 1].Equals('/') ? $"{resource}.default" : $"{resource}/.default" }; try{ result = _app.AcquireTokenForClient(scopes).ExecuteAsync().Result; } catch (MsalServiceException ex) when (ex.Message.Contains("AADSTS70011")) { // Invalid scope. The scope has to be of the form "https://resourceurl/.default" // Mitigation: change the scope to be as expected Console.WriteLine("Scope provided is not supported"); return null; } return result.AccessToken; } ``` -------------------------------- ### Client Application Output Source: https://learn.microsoft.com/en-us/information-protection/develop/quick-file-set-get-label-csharp This output shows the available sensitivity labels and their GUIDs, followed by the process of applying a label to a file and verifying its application. It also indicates if the file is protected. ```console Personal : 73c47c6a-eb00-4a6a-8e19-efaada66dee6 Public : 73254501-3d5b-4426-979a-657881dfcb1e General : da480625-e536-430a-9a9e-028d16a29c59 Confidential : 569af77e-61ea-4deb-b7e6-79dc73653959 Recipients Only (C) : d98c4267-727b-430e-a2d9-4181ca5265b0 All Employees (C) : 2096f6a2-d2f7-48be-b329-b73aaa526e5d Anyone (not protected) (C) : 63a945ec-1131-420d-80da-2fedd15d3bc0 Highly Confidential : 905845d6-b548-439c-9ce5-73b2e06be157 Recipients Only : 05ee72d9-1a75-441f-94e2-dca5cacfe012 All Employees : 922b06ef-044b-44a3-a8aa-df12509d1bfe Anyone (not protected) : c83fc820-961d-40d4-ba12-c63f72a970a3 Press a key to continue. Applying Label ID 074e457c-5848-4542-9a6f-34a182080e7z to c:\Test\Test.docx Committing changes Label committed to file: c:\Test\Test_labeled.docx Press any key to continue. Getting the label committed to file: c:\Test\Test_labeled.docx File Label: Confidential IsProtected: false Press any key to continue. ``` -------------------------------- ### Labeling a .msg file with C++ File SDK Source: https://learn.microsoft.com/en-us/information-protection/develop/quick-email-msg-cpp This snippet demonstrates the process of labeling a .msg file using the MIP File SDK. It includes creating a file handler, listing labels, applying a label, and committing changes. Ensure you have the necessary setup for the MIP SDK and replace placeholder values with your specific details. ```cpp //Create a file handler for original file auto handlerPromise = std::make_shared>>(); auto handlerFuture = handlerPromise->get_future(); engine->CreateFileHandlerAsync(inputFilePath, actualFilePath, true, std::make_shared(), 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 = ""; //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>(); 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>>(); auto msgHandlerFuture = handlerPromise->get_future(); engine->CreateFileHandlerAsync(inputFilePath, actualFilePath, true, std::make_shared(), 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; } ``` -------------------------------- ### Implement User Consent Logic in C++ Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-consent-cpp Provide a concrete implementation for the `GetUserConsent` method. This example displays a consent URL to the user, prompts for a choice (Accept Always, Accept, Reject), and returns the corresponding `mip::Consent` enum value. ```cpp #include "mip_sdk_consent.h" #include #include // Assuming Consent and string are in the mip namespace or globally available using mip::Consent; using std::string; Consent ConsentDelegateImpl::GetUserConsent(const string& url) { //Print the consent URL, ask user to choose std::cout << "SDK will connect to: " << url << std::endl; std::cout << "1) Accept Always" << std::endl; std::cout << "2) Accept" << std::endl; std::cout << "3) Reject" << std::endl; std::cout << "Select an option: "; char input; std::cin >> input; switch (input) { case '1': return Consent::AcceptAlways; break; case '2': return Consent::Accept; break; case '3': return Consent::Reject; break; default: return Consent::Reject; } } ``` -------------------------------- ### Create FileEngineSettings C++ Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-profile-engine-cpp Demonstrates how to create a `FileEngineSettings` object, specifying the engine ID, authentication delegate, locale, and other options. ```cpp // Create the FileEngineSettings object FileEngine::Settings engineSettings(mip::Identity(mUsername), // This will be the engine ID. UPN, email address, or other unique user identifiers are recommended. mAuthDelegate, // authDelegate implementation "", // ClientData "en-US", // Client Locale false); // Load Sensitive Information Types ``` -------------------------------- ### NoPermissionsError Source: https://learn.microsoft.com/en-us/information-protection/develop/reference/class_mip_filehandler The user could not get access to the content. For example, no permissions, content revoked. ```APIDOC ## NoPermissionsError ### Description The user could not get access to the content. For example, no permissions, content revoked. ### Error NoPermissionsError ``` -------------------------------- ### Custom Metadata Format Example Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-mip-metadata Custom metadata is stored with a specific prefix including the label GUID, followed by the custom attribute name. ```text MSIP_Label_f048e7b8-f3aa-4857-bf32-a317f4bc3f29_GeneratedBy = HRReportingSystem ``` -------------------------------- ### Configure ProtectionProfileSettings (C++) Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-offline-publishing Initialize ProtectionProfileSettings and enable offline publishing. Ensure MipContext is initialized. ```cpp // Initialize ProtectionProfileSettings using MipContext ProtectionProfile::Settings profileSettings(mMipContext, mip::CacheStorageType::OnDiskEncrypted, ::make_shared(), std::make_shared() ); // Enable Offline Publishing profileSettings.SetOfflinePublishing(true); ``` -------------------------------- ### Install MSAL.PS PowerShell Module Source: https://learn.microsoft.com/en-us/information-protection/develop/setup-configure-mip Install the MSAL.PS PowerShell module. Administrator rights are required. You may need to confirm installation from an untrusted repository. ```PowerShell PS C:\WINDOWS\system32> Install-Module -Name MSAL.PS Untrusted repository You are installing the modules from an untrusted repository. If you trust this repository, change its InstallationPolicy value by running the Set-PSRepository cmdlet. Are you sure you want to install the modules from 'PSGallery'? [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): A PS C:\WINDOWS\system32> ``` -------------------------------- ### Initialize MipContext, PolicyProfile, and PolicyEngine Source: https://learn.microsoft.com/en-us/information-protection/develop/quick-policy-app-initialization-cpp This C++ code snippet shows the main function for initializing the MIP SDK, loading a Policy Profile, and adding a Policy Engine. It includes setting up configuration, observers, and authentication delegates. ```cpp #include "mip/mip_context.h" #include "mip/upe/policy_profile.h" #include "auth_delegate.h" #include "profile_observer.h" #include #include using std::cout; using std::endl; using std::make_shared; using std::shared_ptr; int main() { // Construct/initialize objects required by the application's profile object auto mipConfiguration = make_shared( "your_app_id", // Application ID from Microsoft Entra app registration "MIP SDK Policy Quickstart", // Friendly name "1.0", // Version true // GUID for each machine ); auto mipContext = mip::MipContext::Create(mipConfiguration); auto profileObserver = make_shared(); auto authDelegateImpl = make_shared("your_app_id"); mip::PolicyProfile::Settings profileSettings(mipContext, mip::CacheStorageType::OnDiskEncrypted, authDelegateImpl ); // Load Policy Profile auto profilePromise = make_shared>>(); auto profileFuture = profilePromise->get_future(); mip::PolicyProfile::LoadAsync(profileSettings, profileObserver, profilePromise); auto profile = profileFuture.get(); // Add a Policy Engine mip::PolicyEngine::Settings engineSettings( mip::Identity("user@contoso.com"), authDelegateImpl, "", "en-US", false ); auto enginePromise = make_shared>>(); auto engineFuture = enginePromise->get_future(); profile->AddEngineAsync(engineSettings, profileObserver, enginePromise); auto engine = engineFuture.get(); // Application using Policy engine is ready. // Engine can be used to list labels, compute actions, etc. cout << "Policy engine loaded successfully." << endl; return 0; } ``` -------------------------------- ### Configure ProtectionProfileSettings (.NET) Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-offline-publishing Initialize ProtectionProfileSettings and enable offline publishing. Use CacheStorageType.OnDisk for local caching. ```csharp // Initialize ProtectionProfileSettings var profileSettings = new ProtectionProfileSettings(mipContext, CacheStorageType.OnDisk, new ConsentDelegateImplementation()); // Enable Offline Publishing profileSettings.OfflinePublishing = true; ``` -------------------------------- ### Initialize File Profile and Engine Source: https://learn.microsoft.com/en-us/information-protection/develop/quick-app-initialization-csharp This snippet shows the complete process of initializing the MIP SDK for file operations, including creating application info, authentication delegates, profile settings, and adding a file engine. Replace placeholder values for client ID and application name. ```csharp using System; using System.Threading.Tasks; using Microsoft.InformationProtection; using Microsoft.InformationProtection.File; namespace mip_sdk_dotnet_quickstart { class Program { private const string clientId = ""; private const string appName = ""; static void Main(string[] args) { // Initialize Wrapper for File SDK operations. MIP.Initialize(MipComponent.File); // Create ApplicationInfo, setting the clientID from Microsoft Entra 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); // Create MipConfiguration Object MipConfiguration mipConfiguration = new MipConfiguration(appInfo, "mip_data", LogLevel.Trace, false); // Create MipContext using Configuration MipContext mipContext = MIP.CreateMipContext(mipConfiguration); // 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. // This pattern sets the engine ID to user1@tenant.com, then sets the identity used to create the engine. var engineSettings = new FileEngineSettings("user1@tenant.com", authDelegate, "", "en-US"); engineSettings.Identity = new Identity("user1@tenant.com"); var fileEngine = Task.Run(async () => await fileProfile.AddEngineAsync(engineSettings)).Result; // Application Shutdown // handler = null; // This will be used in later quick starts. fileEngine = null; fileProfile = null; mipContext.ShutDown(); mipContext = null; } } } ``` -------------------------------- ### Initialize Policy Profile and Engine in C# Source: https://learn.microsoft.com/en-us/information-protection/develop/quick-policy-app-initialization-csharp This code snippet demonstrates how to initialize the MIP SDK by creating an application info object, MipContext, authentication and consent delegates, loading a PolicyProfile, and adding a PolicyEngine. Ensure you replace placeholder values like '' and '' with your actual application details. ```csharp using Microsoft.InformationProtection; using Microsoft.InformationProtection.Policy; // Application info for Microsoft Entra app registration ApplicationInfo appInfo = new ApplicationInfo() { ApplicationId = "", ApplicationName = "MIP SDK Policy Quickstart", ApplicationVersion = "1.0" }; // Create MipConfiguration and MipContext var mipConfiguration = new MipConfiguration(appInfo, "mip_data", LogLevel.Trace, false); var mipContext = MIP.CreateMipContext(mipConfiguration); // Create auth and consent delegates var authDelegate = new AuthDelegateImplementation(appInfo); var consentDelegate = new ConsentDelegateImplementation(); // Create PolicyProfile var profileSettings = new PolicyProfileSettings(mipContext, CacheStorageType.OnDiskEncrypted, consentDelegate); var profile = MIP.LoadPolicyProfileAsync(profileSettings).GetAwaiter().GetResult(); // Create PolicyEngine var engineSettings = new PolicyEngineSettings( identity: new Identity(""), authDelegate: authDelegate, clientData: "", locale: "en-US") { Identity = new Identity("") }; var engine = profile.AddEngineAsync(engineSettings).GetAwaiter().GetResult(); Console.WriteLine("Policy engine loaded successfully."); ``` -------------------------------- ### Example: Inspecting C# Label Protection Types Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-label-protection-types Iterate through sensitivity labels and inspect their protection types using C# properties. This example shows how to determine if a label applies Do Not Forward, Encrypt Only, ad-hoc, or template-based protection. ```csharp foreach (var label in engine.SensitivityLabels) { Console.WriteLine($"Label: {label.Name}"); if (label.HasRightsManagementPolicy) { if (label.HasDoNotForwardProtection) Console.WriteLine(" Protection type: Do Not Forward"); else if (label.HasEncryptOnlyProtection) Console.WriteLine(" Protection type: Encrypt Only"); else if (label.HasAdhocProtection) Console.WriteLine(" Protection type: Ad-hoc (user-defined permissions)"); else Console.WriteLine(" Protection type: Template-based"); } else { Console.WriteLine(" No protection"); } } ``` -------------------------------- ### Configure ProtectionProfileSettings (Java) Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-offline-publishing Initialize ProtectionProfileSettings in Java, setting the cache storage type and enabling offline publishing. ```java ProtectionProfileSettings profileSettings = new ProtectionProfileSettings(); profileSettings.setMipContext(mipContext); profileSettings.setCacheStorageType(CacheStorageType.ON_DISK); profileSettings.setConsentDelegate(new ConsentDelegateImplementation()); // Enable Offline Publishing profileSettings.setOfflinePublishing(true); ``` -------------------------------- ### Remove Protection - .NET Example Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-handler-file-cpp This .NET example demonstrates how to remove file protection. It checks if the file is protected and if the user has 'Export' or 'Owner' rights. If the user has the 'Extract' right, protection is removed and the change is committed; otherwise, an exception is thrown. ```csharp if(handler.Protection != null) { // Validate that user has rights to remove protection from the file. if(handler.Protection.AccessCheck(Rights.Export) || handler.Protection.AccessCheck(Rights.Owner)) { // If user has Extract right, remove protection and commit the change. Otherwise, throw exception. handler.RemoveProtection(); bool result = handler.CommitAsync(outputPath).GetAwaiter().GetResult(); return result; } else { throw new Microsoft.InformationProtection.Exceptions.AccessDeniedException("User lacks EXPORT right."); } } ``` -------------------------------- ### Load File Profile in C++ Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-profile-engine-file-profile-cpp This snippet shows the complete process of initializing MipConfiguration, creating a MipContext, defining profile settings with custom delegates, and asynchronously loading a FileProfile. Ensure all necessary headers are included before using this code. ```cpp int main() { const string userName = "MyTestUser@contoso.com"; const string password = "P@ssw0rd!"; const string clientId = "MyClientId"; mip::ApplicationInfo appInfo {clientId, "APP NAME", "1.2.3" }; std::shared_ptr mipConfiguration = std::make_shared(mAppInfo, ``` -------------------------------- ### Get Application Scenario ID from FileExecutionState Source: https://learn.microsoft.com/en-us/information-protection/develop/version-release-history Retrieve the application scenario ID from FileExecutionState. ```csharp string scenarioId = fileExecutionState.GetApplicationScenarioId(); ``` -------------------------------- ### NoAuthTokenError Source: https://learn.microsoft.com/en-us/information-protection/develop/reference/class_mip_filehandler The user could not get access to the content due to missing authentication token. ```APIDOC ## NoAuthTokenError ### Description The user could not get access to the content due to missing authentication token. ### Error NoAuthTokenError ``` -------------------------------- ### Get Serialized Publishing License Source: https://learn.microsoft.com/en-us/information-protection/develop/version-release-history Retrieve the serialized publishing license for a file using FileHandler::GetSerializedPublishingLicense(). ```csharp string license = fileHandler.GetSerializedPublishingLicense(); ``` -------------------------------- ### Create Protection Engine Settings Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-profile-engine-protection-engine-cpp Initializes a `ProtectionEngine::Settings` object with a unique ID and empty client data. Ensure to manually set the identity and cloud environment if using this constructor. ```cpp ProtectionEngine::Settings engineSettings("UniqueID", ""); ``` -------------------------------- ### NoPermissionsExtendedError Source: https://learn.microsoft.com/en-us/information-protection/develop/reference/class_mip_filehandler The user could not get access to the content due to extended Access checks like ABAC. ```APIDOC ## NoPermissionsExtendedError ### Description The user could not get access to the content due to extended Access checks like ABAC. ### Error NoPermissionsExtendedError ``` -------------------------------- ### Initialize MIP SDK Objects and Load Profile Source: https://learn.microsoft.com/en-us/information-protection/develop/quick-email-msg-cpp This code initializes the MIP SDK profile, including application info, configuration, context, and observers. It demonstrates asynchronous profile loading. ```cpp int main() { // Construct/initialize objects required by the application's profile object ApplicationInfo appInfo { "", // ApplicationInfo object (App ID, name, version) "", "1.0" }; std::shared_ptr mipConfiguration = std::make_shared(mAppInfo, * The code snippet below shows how to construct and initialize the MIP SDK profile and engine objects, including setting the `enable_msg_file_type` flag to true to enable processing of .msg files. This is a crucial step for applications that need to interact with .msg files using the File SDK. The code includes error handling for asynchronous operations. The `main()` function is the entry point of the application. It first constructs an `ApplicationInfo` object with placeholder values for application ID, name, and version. Then, it creates a `MipConfiguration` object, specifying the application information, a directory for MIP data, a log level, and whether to enable telemetry. A `MipContext` is created using this configuration. An observer object (`ProfileObserver`), an authentication delegate (`AuthDelegateImpl`), and a consent delegate (`ConsentDelegateImpl`) are instantiated. The `FileProfile::Settings` object is then constructed using the `MipContext` and the delegate objects. The profile is loaded asynchronously using `FileProfile::LoadAsync`, with a `promise` and `future` to handle the asynchronous operation. A `FileEngine::Settings` object is created, specifying the engine identity, state, and locale. A vector of custom settings is created, and the `enable_msg_file_type` flag is set to 'true' using `mip::GetCustomSettingEnableMsgFileType()`. This custom setting is then applied to the `engineSettings`. Finally, the engine is added to the profile asynchronously using `profile->AddEngineAsync`, again utilizing a `promise` and `future` for handling the asynchronous operation. Error handling is included for both profile loading and engine addition. The code also sets up placeholder file paths for input and output .msg files. The `enable_msg_file_type` flag is essential for the `mip::FileHandler` to correctly process .msg files. Ensure that the placeholder values like ``, ``, ``, ``, and file paths are replaced with actual values relevant to your application. The `system( ``` -------------------------------- ### Fetch templates to initialize cache (.NET) Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-offline-publishing Retrieve templates using GetTemplates() to populate the cache for offline publishing. ```csharp List templates = engine.GetTemplates(); ``` -------------------------------- ### Implement Consent Delegate in C# Source: https://learn.microsoft.com/en-us/information-protection/develop/quick-app-initialization-csharp Implement the IConsentDelegate interface to handle user consent for accessing services. This example hardcodes consent to 'Accept'. ```csharp class ConsentDelegateImplementation : IConsentDelegate { public Consent GetUserConsent(string url) { return Consent.Accept; } } ``` -------------------------------- ### Print Labels and IDs Source: https://learn.microsoft.com/en-us/information-protection/develop/concept-profile-engine-file-engine-cpp Iterates through the retrieved labels and their children, printing the name and GUID for each. The label identifier (ID) is required to apply labels to a file. ```cpp //Iterate through all labels in the vector for (const auto& label : labels) { //Print label name and GUID cout << label->GetName() << " : " << label->GetId() << endl; //Print child label name and GUID for (const auto& child : label->GetChildren()) { cout << "-> " << child->GetName() << " : " << child->GetId() << endl; } } ``` -------------------------------- ### Initialize MIP SDK File SDK in C++ Source: https://learn.microsoft.com/en-us/information-protection/develop/quick-app-initialization-cpp This code initializes the MIP SDK File SDK by constructing and configuring ApplicationInfo, MipConfiguration, MipContext, profile settings, and engine settings. It demonstrates asynchronous loading of the profile and adding of an engine to the profile. Ensure ApplicationInfo and delegate objects are correctly populated. ```cpp #include "mip/mip_context.h" #include "auth_delegate.h" #include "consent_delegate.h" #include "profile_observer.h" using std::promise; using std::future; using std::make_shared; using std::shared_ptr; using std::string; using std::cout; using mip::ApplicationInfo; using mip::FileProfile; using mip::FileEngine; int main() { // Construct/initialize objects required by the application's profile object // ApplicationInfo object (App ID, name, version) ApplicationInfo appInfo{"", "", ""}; // Create MipConfiguration object. std::shared_ptr mipConfiguration = std::make_shared(appInfo,
The code snippet provided is in C++ and demonstrates how to construct a File profile and engine using the MIP SDK. It includes necessary headers, namespace declarations, and the main function where the profile and engine objects are instantiated and configured. The code also shows how to handle asynchronous operations for loading the profile and adding the engine, along with basic error handling and application shutdown procedures. It's important to replace placeholder values like "" with actual application details. The `AuthDelegateImpl` requires an application ID, and the `FileEngine::Settings` requires an engine account identity and state. The `mMipContext->ShutDown()` call is crucial for proper resource release during application termination. The code also includes a `system( ``` -------------------------------- ### Encrypt and Decrypt Text Example Source: https://learn.microsoft.com/en-us/information-protection/develop/quick-protection-encrypt-decrypt-text-csharp This snippet shows the original, encrypted, and decrypted content of a text string. It's useful for verifying encryption and decryption processes. ```text Original content: My secure text Encrypted content: c?_hp???Q??+