Skip to main content

How to: Grant Editing Permissions in Code

  • 2 minutes to read

This code snippet illustrates how to unlock specific document ranges in a protected document for authenticated users by doing the following:

  1. Access the document collection of ranges with permissions by calling the SubDocument.BeginUpdateRangePermissions method.
  2. Call the RangePermissionCollection.CreateRangePermission method to create a RangePermission instance to the target document range.
  3. Specify the user and/or the group of users that are eligible to edit the document using the RangePermission.Group and RangePermission.UserName properties.

    In this example, actions from step 2 and 3 are implemented in the CreateRangePermissions method.

  4. Finish the update by calling the SubDocument.EndUpdateRangePermissions method.
  5. Use the Document.Protect method to protect the document from modification. With document protection enabled, ranges without edit permission are read-only.
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.API.Native;
using DevExpress.XtraRichEdit.Services;

// Create document ranges.
DocumentRange rangeAdmin = AppendDocument("Documents\\administrator.docx");
DocumentRange rangeBody = AppendDocument("Documents\\body.docx");
DocumentRange rangeSignature = AppendDocument("Documents\\signature.docx");

// Protect document ranges.
RangePermissionCollection rangePermissions = richEditControl1.Document.BeginUpdateRangePermissions();
rangePermissions.AddRange(CreateRangePermissions(rangeAdmin, String.Empty, "Admin@somecompany.com", "Nancy Skywalker"));
rangePermissions.AddRange(CreateRangePermissions(rangeBody, "Everyone", String.Empty));
rangePermissions.AddRange(CreateRangePermissions(rangeSignature, "Skywalkers", String.Empty));            
richEditControl1.Document.EndUpdateRangePermissions(rangePermissions);
// Enforce protection and set password.
richEditControl1.Document.Protect("123");

private DocumentRange AppendDocument(string filename)
{
    richEditControl1.Document.Paragraphs.Insert(richEditControl1.Document.Range.End);
    DocumentPosition pos = richEditControl1.Document.CreatePosition(richEditControl1.Document.Range.End.ToInt() - 2);
    DocumentRange range = richEditControl1.Document.InsertDocumentContent(pos, filename, DocumentFormat.OpenXml);
    return range;
}

private static List<RangePermission> CreateRangePermissions(DocumentRange range, string userGroup, params string[] usernames)
{
    List<RangePermission> rangeList = new List<RangePermission>();
    foreach (string username in usernames)
    {
        RangePermission rp = new RangePermission(range);
        rp.Group = userGroup;
        rp.UserName = username;
        rangeList.Add(rp);
    }
    return rangeList;
}