Using MIP SDK in SharePoint – II

This post is in continuation with how to use MIP SDK in C#. Please go through it first to cover some basic concepts like, setting up your system, nuget required for MIP and registering Azure AD app which will be used in the code below too.

My case scenario was to analyze a protected file present in SharePoint Document Library and set/remove protection on it depending on the contents of the document. In case you are not aware, we can use Azure Information Protection or Unified Labeling in SharePoint too. It’s pretty straight-forward and more details can be found here.

In comparison to the code I uploaded on git, there are few basic changes for using MIP SDK in Provider Hosted add-ins. Instead of relying on file path, we will use file stream from SharePoint and similarly, upload that stream back to SharePoint. I am assuming that you all are aware of provider hosted add-ins and have gone through the part one of this post. I am listing the changes below while rest of the stuff remains the same.

  1. Create a provider hosted add-in using Visual Studio. I have used SharePoint Online and MVC template for my work
  2. In AppManifest.xml give proper permission to access libraries of your target site collection
  3. Now coming to HomeController, InvokeMIP method, the first difference is how will we get tenant id of our host web. Instead of finding it in Claims, we will get it using TokenHelper’s method GetRealmFromTargetUrl
  4. Apart from this, we will create SharePoint context to get file stream of the uploaded file where we need to perform MIP operations
  5. Using this stream, MIP file handler will be created
  6. The output will be collected in memory stream
  7. Output Stream will be used to upload the changed document back to SharePoint (For more details on how to upload large files in provider hosted add-in, check this post here)

The complete code will look like below:

private void InvokeMIP()
//this client id is for Azure AD app and NOT of SharePoint app
private static readonly string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static readonly string appName = ConfigurationManager.AppSettings["app:Name"];
private static readonly string appVersion = ConfigurationManager.AppSettings["app:Version"];
private static readonly string mipData = ConfigurationManager.AppSettings["MipData"];
private readonly string mipPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, mipData);
SharePointContext spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
Uri sharepointUrl = new Uri(spContext.SPHostUrl.AbsoluteUri.ToString());
//fetch tenant id to be used in getting access token
string tenantId = TokenHelper.GetRealmFromTargetUrl(sharepointUrl).ToString();
// Set path to bins folder.
var path = Path.Combine(
Directory.GetParent(Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath)).FullName,
Environment.Is64BitProcess ? "bin\\x64" : "bin\\x86");
MIP.Initialize(MipComponent.File, path);
ApplicationInfo appInfo = new ApplicationInfo()
ApplicationId = clientId,
ApplicationName = appName,
ApplicationVersion = appVersion
AuthDelegateImplementation authDelegate = new AuthDelegateImplementation(appInfo, tenantId);
var profileSettings = new FileProfileSettings(mipPath, false, authDelegate, new ConsentDelegateImplementation(), appInfo, LogLevel.Trace);
//create MIP File Profile
var fileProfile = Task.Run(async () => await MIP.LoadFileProfileAsync(profileSettings)).Result;
//create MIP Engine and add it to the file profile
var engineSettings = new FileEngineSettings("", "", "en-US");
engineSettings.Identity = new Identity(""); //important to paas a valid admin account here
var fileEngine = Task.Run(async () => await fileProfile.AddEngineAsync(engineSettings)).Result;
//client context to get file stream
using (var clientContext = spContext.CreateUserClientContextForSPHost())
if (clientContext != null)
var list = clientContext.Web.Lists.GetByTitle("Documents");
clientContext.Load(list, i => i.RootFolder);
var listItem = list.GetItemById(1);
clientContext.Load(listItem, l => l.File, l => l.File.ServerRelativeUrl);
var fileData = listItem.File.OpenBinaryStream();
if (fileData.Value != null)
var fileStream = fileData.Value;
//create file handler with the stream from SharePoint
var handler = Task.Run(async () => await fileEngine.CreateFileHandlerAsync(fileStream, listItem.File.ServerRelativeUrl, true)).Result;
//if needed, can check the existing labels and protection details using below two lines
var labelDetails = handler.Label;
var protectionDetails = handler.Protection;
LabelingOptions labelingOptions = new LabelingOptions()
AssignmentMethod = AssignmentMethod.Privileged, //because I am removing a high priority label
IsDowngradeJustified = true,
JustificationMessage = "Lowering label"
//output stream where new file will be stored
Stream outputStream = new MemoryStream();
var result = Task.Run(async () => await handler.CommitAsync(outputStream)).Result;
//This is neccessary else you will get following error
//Specified argument was out of the range of valid values.\r\nParameter name: bytesToCopy
outputStream.Position = 0;
//You can create a new file handler using output stream here
//and use it to apply different label using newhandler.SetLabel() method
//and then upload it to SharePoint too
FileCreationInformation decryptedFile = new FileCreationInformation();
decryptedFile.ContentStream = outputStream;
decryptedFile.Url = "decrypted.docx"; //change this according to your need
decryptedFile.Overwrite = true;
var uploadedFile = list.RootFolder.Files.Add(decryptedFile);
catch(Exception ex)

view raw
hosted with ❤ by GitHub

Make sure you have registered Azure AD app with proper permissions and your SharePoint App has correct permissions too.

P.S. Please note that MIP SDK does not support content marking (watermark, header, footer). You can apply a label with watermark but it wont be reflected until you open the document and save it in office again. More details here

Happy Coding!

Update November 9, 2019:

Now you can enable sensitivity labels for file present in OneDrive and SharePoint. The feature comes with some new capabilities and some limitations and is currently in public preview. Click here to learn more about this.

14 thoughts on “Using MIP SDK in SharePoint – II

  1. Pingback: Working with C# MIP SDK – I | My SharePoint Learnings

  2. Hi, Thanks for ur article…I tried the same but I couldnt get it working which is weird because it doesnt throw any error…just doesnt apply the label. Tried applying to a file in a file share and that worked perfectly fine. Any thoughts.

    • Hi Tulika,

      Could you check few things for me:
      1. Are you trying this for files uploaded in SharePoint ?
      2. If yes, have you tried applying label manually to them? Does it work?
      3. Can you debug code and see if file stream has valid value in it (line 60)?
      4. Can you debug and check if you get back sensitivity labels in file engine object (line 42)?
      Since it is working in file share it is tough to understand why it does not work in SharePoint unless you are NOT using unified labeling. I hope you can see the labels in O365 Security and Compliance Center too.

      • Hi Garima,
        I am trying this for files uploaded in SharePoint.
        2. I do not know how to apply sensitivity labels to documents in a SharePoint Document library.
        3. The file stream has valid value in it (line 60)
        4. I can get back sensitivity labels in file engine object (line 42)
        I am using unified labeling and can see the labels in O365 Security and Compliance Center too.
        Really appreciate your time and help.

      • That’s weird. As you are doing it for SharePoint documents, how do you know the label is not applied? Also on which file format are you trying?

  3. Stream outputStream = new MemoryStream();
    var result = Task.Run(async () => await handler.CommitAsync(outputStream)).Result;

    while debugging i found that result variable is false which means the handler is not applying the label.
    I am using word documents.

  4. As you suggested I delete the file and it works fine now. However it doesnt seem to apply the footer associated to the label. Have you had any luck with footers being applied to the documents as well.

  5. This is superb article, thanks for sharing.. just one question have you found any file size issue while uploading or downloading?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s