Hızlı Başlangıç: İlke eylemlerini hesaplama - İlke SDK'sı (C#)

Bu hızlı başlangıçta, duyarlılık etiketlerini uygularken veya değiştirirken yapılması gereken eylemleri hesaplamak için MIP .NET İlkesi SDK'sını nasıl kullanacağınız gösterilir.

Prerequisites

Henüz yapmadıysanız devam etmeden önce aşağıdaki önkoşulları tamamladığınızdan emin olun:

ExecutionState'i Uygula

çağrısından ComputeActions()önce, geçerli ve istenen etiket durumunu sağlayan soyut ExecutionState sınıfın bir uygulamasına ihtiyacınız vardır.

  1. Önceki hızlı başlangıçta oluşturduğunuz Visual Studio çözümünü açın.

  2. Projenize, ExecutionState öğesinden türetilen yeni bir sınıf ekleyin:

    using Microsoft.InformationProtection;
    using Microsoft.InformationProtection.Policy;
    using Microsoft.InformationProtection.Policy.Actions;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    public class PolicyExecutionState : ExecutionState
    {
        private Label _newLabel;
        private AssignmentMethod _assignmentMethod;
        private List<MetadataEntry> _metadata;
        private bool _isDowngradeJustified;
        private string _downgradeJustification;
        private string _contentIdentifier;
    
        public PolicyExecutionState(
            Label newLabel,
            string contentIdentifier,
            AssignmentMethod assignmentMethod = AssignmentMethod.Standard,
            List<MetadataEntry> existingMetadata = null,
            bool isDowngradeJustified = false,
            string downgradeJustification = "")
        {
            _newLabel = newLabel;
            _contentIdentifier = contentIdentifier;
            _assignmentMethod = assignmentMethod;
            _metadata = existingMetadata ?? new List<MetadataEntry>();
            _isDowngradeJustified = isDowngradeJustified;
            _downgradeJustification = downgradeJustification;
        }
    
        public override Label GetNewLabel()
        {
            return _newLabel;
        }
    
        public override AssignmentMethod GetNewLabelAssignmentMethod()
        {
            return _assignmentMethod;
        }
    
        public override ProtectionDescriptor GetProtectionDescriptor()
        {
            return null;
        }
    
        public override string GetContentFormat()
        {
            return ContentFormat.File;
        }
    
        public override string GetContentIdentifier()
        {
            return _contentIdentifier;
        }
    
        public override ActionType GetSupportedActions()
        {
            return ActionType.Metadata
                | ActionType.ProtectByTemplate
                | ActionType.Justify
                | ActionType.AddContentFooter
                | ActionType.AddContentHeader
                | ActionType.AddWatermark;
        }
    
        public override bool IsDowngradeJustified(out string justification)
        {
            justification = _downgradeJustification;
            return _isDowngradeJustified;
        }
    
        public override List<MetadataEntry> GetContentMetadata(
            List<string> names, List<string> namePrefixes)
        {
            return _metadata.Where(entry =>
                (names.Count == 0 && namePrefixes.Count == 0)
                || names.Contains(entry.Key)
                || namePrefixes.Any(prefix => entry.Key.StartsWith(prefix, StringComparison.Ordinal)))
                .ToList();
        }
    }
    

Yeni etiket için eylemleri hesapla

Etiketlenmemiş içeriğe yeni bir etiket uygularken gereken eylemleri hesaplamak için mantık ekleyin.

Altyapı yüklendikten ve etiketler listelendikten sonra aşağıdaki kodu ekleyin. Microsoft.InformationProtection.Policy.Actions öğesini bu kodu içeren dosyaya içe aktarın:

// Replace with a valid label ID from your tenant.
string newLabelId = "<label-id>";

// Resolve the label by ID.
var label = engine.GetLabelById(newLabelId);

// Create the ExecutionState for applying a new label.
var state = new PolicyExecutionState(
    newLabel: label,
    contentIdentifier: "MyDocument.docx");

// Create a policy handler and compute actions.
var handler = engine.CreatePolicyHandler(false);
var actions = handler.ComputeActions(state);

Console.WriteLine("\nActions for applying label:");

foreach (var action in actions)
{
    if (action is MetadataAction metadataAction)
    {
        Console.WriteLine("MetadataAction:");
        foreach (var name in metadataAction.MetadataToRemove)
        {
            Console.WriteLine($"  Remove: {name}");
        }
        foreach (var prop in metadataAction.MetadataToAdd)
        {
            Console.WriteLine($"  Add: {prop.Key} : {prop.Value}");
        }
    }
    else if (action is ProtectByTemplateAction protectAction)
    {
        Console.WriteLine($"ProtectByTemplateAction: TemplateId = {protectAction.TemplateId}");
    }
    else if (action is AddContentFooterAction)
    {
        Console.WriteLine("AddContentFooterAction");
    }
    else if (action is AddContentHeaderAction)
    {
        Console.WriteLine("AddContentHeaderAction");
    }
    else if (action is AddWatermarkAction)
    {
        Console.WriteLine("AddWatermarkAction");
    }
    else if (action is JustifyAction)
    {
        Console.WriteLine("JustifyAction");
    }
    else
    {
        Console.WriteLine($"Other action: {action.GetType().Name}");
    }
}

Etiket düşürme senaryosunu işleme

Daha yüksek bir duyarlılık etiketinden daha düşük bir etikete geçtiğinizde, ilke gerekçe gerektirebilir. Her iki etiket kimliği yer tutucularını da kiracınızdaki birbirinden farklı etiketlerle değiştirin. Üretimde, içerikten mevcut meta verilerin tamamını okuyun ve kullanıcıdan gerekçe alın; Aşağıdaki kod, basitleştirilmiş meta verileri ve gösterim için sabit bir gerekçeyi kullanır.

// Resolve the lower sensitivity label.
var lowerLabel = engine.GetLabelById("<lower-sensitivity-label-id>");

// Build existing metadata from the previously applied label.
var existingMetadata = new List<MetadataEntry>
{
    new MetadataEntry("MSIP_Label_<previous-label-id>_Enabled", "true",
        new MetadataVersion(0, MetadataVersionFormat.DEFAULT)),
    new MetadataEntry("MSIP_Label_<previous-label-id>_Method", "Standard",
        new MetadataVersion(0, MetadataVersionFormat.DEFAULT))
};

// Create the ExecutionState with downgrade justification.
var downgradeState = new PolicyExecutionState(
    newLabel: lowerLabel,
    contentIdentifier: "MyDocument.docx",
    existingMetadata: existingMetadata,
    isDowngradeJustified: true,
    downgradeJustification: "Manager approved declassification");

var downgradeHandler = engine.CreatePolicyHandler(false);
var downgradeActions = downgradeHandler.ComputeActions(downgradeState);

Console.WriteLine("\nActions for label downgrade:");
foreach (var action in downgradeActions)
{
    Console.WriteLine($"  Action: {action.GetType().Name}");
}

Uygulamayı derleme ve test etme

İstemci uygulamanızı derleyin ve test edin.

  1. Uygulamayı derlemek için Ctrl+Shift+B (Derleme Çözümü) tuşlarını kullanın. Derleme hatanız yoksa, çalıştırmak için F5 (Hata ayıklamayı başlat) kullanın.

  2. İlk çalıştırmada uygulama kimlik doğrulaması ister. Kiracınızdaki bir kullanıcı hesabı için kimlik bilgilerini sağlayın.

  3. Çıkışta belirtilen etiket için hesaplanan eylemler görüntülenmelidir, örneğin:

    Actions for applying label:
    MetadataAction:
      Add: MSIP_Label_<label-id>_Enabled : true
      Add: MSIP_Label_<label-id>_SetDate : 2026-03-11T10:00:00-0800
      Add: MSIP_Label_<label-id>_Method : Standard
      Add: MSIP_Label_<label-id>_Name : Confidential
      Add: MSIP_Label_<label-id>_SiteId : <site-id>
      Add: MSIP_Label_<label-id>_ActionId : <action-id>
      Add: MSIP_Label_<label-id>_ContentBits : 3
    AddContentFooterAction
    AddContentHeaderAction
    

Sonraki Adımlar

Bu hızlı başlangıçta yalnızca eylemler görüntülenir; belgeyi etiketlemez, işaretlemez veya korumaz. Eksiksiz bir uygulama, GetSupportedActions() aracılığıyla tanıttığı her eylemi uygulamalıdır. Gerekçeyi değişiklikleri kaydetmeden önce işleyin ve yalnızca eylemler uygulandıktan ve içerik başarıyla kaydedildikten sonra NotifyCommittedActions(state) öğesini çağırın.