Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code to invoke MIP SDK for SharePoint files
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);
try
{
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("admin@tenant.com"); //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);
clientContext.ExecuteQuery();
var listItem = list.GetItemById(1);
clientContext.Load(listItem, l => l.File, l => l.File.ServerRelativeUrl);
var fileData = listItem.File.OpenBinaryStream();
clientContext.ExecuteQuery();
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"
};
handler.DeleteLabel(labelingOptions);
//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);
clientContext.Load(uploadedFile);
clientContext.ExecuteQuery();
}
}
}
}
catch(Exception ex)
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.