Back to Devexpress

Restrictions and Protection

wpf-9111-controls-and-libraries-rich-text-editor-restrictions-and-protection.md

latest15.6 KB
Original Source

Restrictions and Protection

  • Feb 24, 2025
  • 9 minutes to read

This topic describes how to prevent end users from document modification. The Rich Text Editor provides three ways to solve this task: protect the entire document from editing, restrict certain operations and prevent users from inserting unnecessary elements.

Restrict Document Modification

You can restrict document modification using the Document.Protect method. This method sets the password, and specifies actions allowed for the protected document (the DevExpress.XtraRichEdit.API.Native.DocumentProtectionType enumeration values). The Document.IsDocumentProtected property indicates whether content modification protection is enabled.

If you want to protect only parts of the document, separate the document into sections and protect specific sections. To do this, use the ProtectedForForms property. For more information on sections, refer to the following topic: Sections.

Use the Document.Unprotect method to disable protection. Note that it unlocks the document without a password request. To prompt the user to enter a password, execute the UnprotectDocumentCommand command.

You can also restrict document modification with Document Protection and Unprotect Document dialogs. For more information, refer to the following topic: Document Protection Dialogs.

Note

The protection mechanism described above affects only the document modification.

Open and Save Password-Encrypted Files

The DXRichEdit allows you to load and save password-encrypted files.

Open an Encrypted File

Specify the DXRichEditDocumentImportOptions.EncryptionPassword property to decrypt a loaded file. The table below lists a chain of events raised if the EncryptionPassword property is not specified or returns an invalid password.

EventDescription
RichEditControl.EncryptedFilePasswordRequestedFires if the EncryptionPassword property is not specified or returns an invalid password. Use the EncryptedFilePasswordRequestedEventArgs.Password property to specify a new password.
RichEditControl.EncryptedFilePasswordCheckFailedOccurs if the EncryptedFilePasswordRequestedEventArgs.Password is set to an empty or invalid password. Handle this event to obtain the error that led to this event (Error) and determine whether to prompt a user for a password (TryAgain).
RichEditControl.DecryptionFailedRaised if the TryAgain property is not specified or set to false. This event also occurs if the RichEditControl fails to open an encrypted file. The Exception property indicates the exception that led to this event.

The code sample below shows how to handle the events mentioned above to prompt users to enter a password. If the user cancels the operation or exceeded the amount of attempts to enter the password, the RichEditControl loads an empty file.

View Example: Document Encryption (Simple Example)

csharp
int tryCount = 4;

private void RichEditControl1_EncryptedFilePasswordRequested(object sender, EncryptedFilePasswordRequestedEventArgs e)
{
    //Count the amount of attempts to enter the password
    if (tryCount > 0)
    {
        tryCount--;
    }
}

private void RichEditControl1_EncryptedFilePasswordCheckFailed(object sender, EncryptedFilePasswordCheckFailedEventArgs e)
{
    //Analyze the error led to this event
    switch (e.Error)
    {
        case RichEditDecryptionError.PasswordRequired:
            if (tryCount > 0)
            {
                e.TryAgain = true;
                e.Handled = true;
                System.Windows.Forms.MessageBox.Show("You did not enter the password!", String.Format("{0} attempts left", tryCount));
            }
            else
                e.TryAgain = false;

            break;

        case RichEditDecryptionError.WrongPassword:
            if (tryCount > 0)
            {
                if (System.Windows.Forms.MessageBox.Show("The password is incorrect. Try Again?", string.Format("{0} attempts left", tryCount),
                    MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                {
                    e.TryAgain = true;
                    e.Handled = true;
                }
            }
            break;
    }

}
vb
Private tryCount As Integer = 4

Private Sub RichEditControl1_EncryptedFilePasswordRequested(ByVal sender As Object, ByVal e As EncryptedFilePasswordRequestedEventArgs)
    'Count the amount of attempts to enter the password
    If tryCount > 0 Then
        tryCount -= 1
    End If
End Sub

Private Sub RichEditControl1_EncryptedFilePasswordCheckFailed(ByVal sender As Object, ByVal e As EncryptedFilePasswordCheckFailedEventArgs)
    'Analyze the error led to this event
    Select Case e.[Error]
        Case RichEditDecryptionError.PasswordRequired

            If tryCount > 0 Then
                e.TryAgain = True
                e.Handled = True
                System.Windows.Forms.MessageBox.Show("You did not enter the password!", String.Format("{0} attempts left", tryCount))
            Else
                e.TryAgain = False
            End If

        Case RichEditDecryptionError.WrongPassword

            If tryCount > 0 Then

                If System.Windows.Forms.MessageBox.Show("The password is incorrect. Try Again?", String.Format("{0} attempts left", tryCount), MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = System.Windows.Forms.DialogResult.Yes Then
                    e.TryAgain = True
                    e.Handled = True
                End If
            End If
    End Select
End Sub

The RichEditControl.EncryptedFileIntegrityCheckFailed event occurs if the document did not pass the code verification.

Important

If an encrypted file is loaded using the RichEditControl.DocumentSource property, its format cannot be detected. Use the RichEditDocumentSource instance to bind encrypted files.

Encrypt a Document with a Password

Use the Document.Encryption property to access the document encryption options.

csharp
richEditControl.Document.Encryption.Type = DevExpress.XtraRichEdit.API.Native.EncryptionType.Strong;
richEditControl.Document.Encryption.Password = "12345";
vb
richEditControl.Document.Encryption.Type = DevExpress.XtraRichEdit.API.Native.EncryptionType.Strong
richEditControl.Document.Encryption.Password = "12345"

Call the RichEditControl.SaveDocument(String, DocumentFormat, EncryptionSettings) method overload to password-protect the document on save. Use the DevExpress.XtraRichEdit.API.Native.EncryptionSettings object properties to specify password and protection type.

csharp
EncryptionOptions encryptionOptions = new EncryptionOptions();
encryptionOptions.Type = EncryptionType.Strong;
encryptionOptions.Password = "12345";

richEditControl.SaveDocument("EncryptedFile.docx", DocumentFormat.Docx, encryptionOptions);
vb
Dim encryptionOptions As EncryptionOptions = New EncryptionOptions()
encryptionOptions.Type = EncryptionType.Strong
encryptionOptions.Password = "12345"

richEditControl.SaveDocument("EncryptedFile.docx", DocumentFormat.Docx, encryptionOptions)

Grant Permission to Users

Create Range Permissions as described in the steps below to allow certain users to edit parts of a protected document.

  1. Set the users and user group lists. The default users list is empty and the user group list contains predefined entries ( Everyone , Administrators , Contributors , Owners , Editors and Current User ). To use a custom list of users or user groups, provide a custom service implementing the IUserListService or IUserGroupListService interface and register this service with the RichEditControl.ReplaceService<T> method. The RichEditControl does not associate users with groups, so user names and group names are independent.

  2. The edit permission is given depending on the authentication credentials. To define the identity of the current user, use the AuthenticationOptions class properties.

  3. Call the SubDocument.BeginUpdateRangePermissions method to access the document range permissions collection.

  4. Create a new RangePermission object using the RangePermissionCollection.CreateRangePermission method.

  5. Utilize the RangePermission.UserName and/or RangePermission.Group properties to specify the specific user and/or the group of users that are eligible to edit the document.

  6. Add the created object to the corresponding collection.

  7. Finalize the modification with the SubDocument.EndUpdateRangePermissions method.

  8. Enable document protection as described above

  9. Customize the appearance of the protected ranges in the document. At runtime, they are highlighted with a certain color and enclosed with bookmark brackets. By default, the highlighting color is selected from a predefined colors collection. This is done to specify different highlighting colors for ranges that belong to different user groups. There is no straightforward way to change these colors manually.

Restrict Performing Operations

Protect the document from editing, copying or printing by restricting the corresponding functions. To perform the restriction, access the desired operation using the RichEditControl.BehaviorOptions property and specify its behavior. Depending on the selected property value, the application menu buttons that correspond to restricted operations can be disabled or hidden. Additionally, you can prevent the showing of the context menu. To do that, use the DXRichEditBehaviorOptions.ShowPopupMenu property.

csharp
private void RestrictOperations()
   {
     richEditControl.BehaviorOptions.Drag = DocumentCapability.Disabled;
     richEditControl.BehaviorOptions.Printing = DocumentCapability.Disabled;
     richEditControl.BehaviorOptions.Copy = DocumentCapability.Hidden;
   }
vb
Private Sub RestrictOperations()
    richEditControl.BehaviorOptions.Drag = DocumentCapability.Disabled
    richEditControl.BehaviorOptions.Printing = DocumentCapability.Disabled
    richEditControl.BehaviorOptions.Copy = DocumentCapability.Hidden
End Sub
xaml
<dxre:RichEditControl.BehaviorOptions>
    <dxre:DXRichEditBehaviorOptions Drag="Disabled" Printing="Disabled" Copy="Hidden"/>
</dxre:RichEditControl.BehaviorOptions>

The code execution result is illustrated in the picture below. Print , Quick Print and Print Preview are disabled, the Copy item is hidden from the context menu.

Restrict Using Document Elements

You can also forbid the formatting of characters and paragraphs or the use of certain document elements, such as pictures, tables, fields, etc.

These restrictions can be specified by the RichEditControl.DocumentCapabilitiesOptions property, as illustrated in the following code sample.

csharp
private void RestrictFormatting()
{
  richEditControl.DocumentCapabilitiesOptions.CharacterFormatting = DocumentCapability.Hidden;
  richEditControl.DocumentCapabilitiesOptions.Comments = DocumentCapability.Disabled;
  richEditControl.DocumentCapabilitiesOptions.FloatingObjects = DocumentCapability.Hidden;
}
vb
Private Sub RestrictFormatting()
   richEditControl.DocumentCapabilitiesOptions.CharacterFormatting = DocumentCapability.Hidden          
   richEditControl.DocumentCapabilitiesOptions.FloatingObjects = DocumentCapability.Hidden 
   richEditControl.DocumentCapabilitiesOptions.Comments = DocumentCapability.Disabled
End Sub
xaml
<dxre:RichEditControl.DocumentCapabilitiesOptions>
    <dxre:DXRichEditDocumentCapabilitiesOptions CharacterFormatting="Hidden" Comments="Disabled" FloatingObjects="Hidden"/>
</dxre:RichEditControl.DocumentCapabilitiesOptions>

The application menu items that correlate with the forbidden actions can be hidden or disabled. If a document is loaded after certain restrictions are applied, the corresponding settings are set to default and the restricted objects are not created. The existing floating pictures are converted into inline pictures, the text boxes and their contents are hidden.

See Also

Range Permissions