# How to Manipulate the Document using the WebSocketHandler

> The WebSocketHandler acts as a proxy between the client-side JavaScript and the TCP synchronization service. However, the WebSocketHandler can be used directly on the server side to do document manipulation.

- **Author:** Bjoern Meyer
- **Published:** 2023-11-22
- **Modified:** 2025-11-16
- **Description:** The WebSocketHandler acts as a proxy between the client-side JavaScript and the TCP synchronization service. However, the WebSocketHandler can be used directly on the server side to do document manipulation.
- **4 min read** (609 words)
- **Tags:**
  - ASP.NET
  - ASP.NET Core
  - WebSocketHandler
- **Web URL:** https://www.textcontrol.com/blog/2023/11/22/how-to-manipulate-the-document-using-the-websockethandler/
- **LLMs URL:** https://www.textcontrol.com/blog/2023/11/22/how-to-manipulate-the-document-using-the-websockethandler/llms.txt
- **LLMs-Full URL:** https://www.textcontrol.com/blog/2023/11/22/how-to-manipulate-the-document-using-the-websockethandler/llms-full.txt

---

As of [32.0 SP1](https://www.textcontrol.com/blog/2023/11/22/service-pack-1-for-tx-text-control-32-released/llms-full.txt), the Document Editor has the new JavaScript property *connectionID* that returns the unique ID of the WebSocket connection. The WebSocketHandler acts as a proxy between the client-side JavaScript and the TCP synchronization service. This id is used for communication between the editor and the server-side WebSocketHandler for document rendering synchronization.

Now that this ID is publicly available, you can use it to connect to the document instance on the server side and manipulate the document directly in the WebSocketHandler in server-side C# code.

The following JavaScript code shows how to retrieve the connection ID and store it globally.

```
var connectionID;

 TXTextControl.addEventListener("textControlLoaded", function () {
     connectionID = TXTextControl.connectionID;
 });
```

### Loading Documents

In the first example, a document is loaded directly from the server using the WebSocketHandler. The example consists of a button that calls the *loadDocument* function.

```
@using TXTextControl.Web.MVC

@Html.TXTextControl().TextControl().Render()

<input type="button" onclick="loadDocument()" value="Load Document" />

<script>

    var connectionID;

    TXTextControl.addEventListener("textControlLoaded", function () {
        connectionID = TXTextControl.connectionID;
    });

    function loadDocument() {
      $.ajax({
              url: '@Url.Action("LoadDocument")',
              type: 'POST',
              data: { connectionID: connectionID },
      });
    }
    
</script>
```

The method posts the connection ID to the *LoadDocument* endpoint. The *GetInstance* method of the WebSocketHandler returns the instance specified by the connection id. The *LoadText* method is then used to load the document directly into the instance.

```
[HttpPost]
public HttpResponseMessage LoadDocument(string ConnectionID)
{
	// connect the WebSocketHandler with the ConnectionID
	WebSocketHandler wsHandler = WebSocketHandler.GetInstance(ConnectionID);

	// the document directly server-side
	wsHandler.LoadText("App_Data/demo.tx", StreamType.InternalUnicodeFormat);

	return new HttpResponseMessage()
	{
		StatusCode = HttpStatusCode.OK
	};
}
```

Direct loading of a document is shown in the following screen video.

![Loading using WebSocketHandler](https://s1-www.textcontrol.com/assets/dist/blog/2023/11/22/b/assets/loading.gif "Loading using WebSocketHandler")

### Complex Formatting

For complex formatting tasks, the JavaScript API may be too slow (callbacks). In the following example, we want to highlight the keyword *TextControl* in a selected area of text.

![Formatting using WebSocketHandler](https://s1-www.textcontrol.com/assets/dist/blog/2023/11/22/b/assets/formatting.gif "Formatting using WebSocketHandler")

The *doComplexFormatting* function calls the *DoComplexFormatting* server-side method. Before the Http POST method is called, the editor is set to read-only, and upon successful execution, the editor is set back to edit mode.

```
@using TXTextControl.Web.MVC

@Html.TXTextControl().TextControl().Render()

input type="button" onclick="doComplexFormatting()" value="Complex Formatting" />

<script>

    var connectionID;

    TXTextControl.addEventListener("textControlLoaded", function () {
        connectionID = TXTextControl.connectionID;
    });

    function doComplexFormatting() {

        TXTextControl.editMode = TXTextControl.EditMode.ReadOnly;

        $.ajax({
            url: '@Url.Action("DoComplexFormatting")',
            type: 'POST',
            data: { connectionID: connectionID },
            success: function (data) {
                TXTextControl.editMode = TXTextControl.EditMode.Edit;
            }
        });
    }
</script>
```

The selection is loaded into a temporary ServerTextControl for manipulation. Found keywords are highlighted in a loop before the selection is saved and loaded back into the editor.

```
[HttpPost]
public HttpResponseMessage DoComplexFormatting(string ConnectionID)
{
    // connect the WebSocketHandler with the ConnectionID
    WebSocketHandler wsHandler = WebSocketHandler.GetInstance(ConnectionID);

    byte[] data;

    // save the current selection to a byte array
    wsHandler.Selection.Save(out data, BinaryStreamType.InternalUnicodeFormat);

    // load the byte array into a ServerTextControl
    using (TXTextControl.ServerTextControl tx = new TXTextControl.ServerTextControl())
    {
        tx.Create();
        tx.Load(data, TXTextControl.BinaryStreamType.InternalUnicodeFormat);

        // loop through all words and format the word "TextControl"
        for (int i = 0; i < tx.Text.Length; i++)
        {
            tx.Select(i, 1);
            tx.SelectWord();

            if (tx.Selection.Text == "TextControl")
            {
                tx.Selection.Bold = true;
                tx.Selection.Italic = true;
                tx.Selection.ForeColor = Color.Red;

                i += tx.Selection.Text.Length;
            }
        }

        // save the document to a byte array and load it into the WebSocketHandler
        tx.Save(out data, TXTextControl.BinaryStreamType.InternalUnicodeFormat);
        wsHandler.Selection.Load(data, BinaryStreamType.InternalUnicodeFormat);
    }

    return new HttpResponseMessage()
    {
        StatusCode = HttpStatusCode.OK
    };
}
```

### Conclusion

The WebSocketHandler can be used to directly manipulate the document on the server side using C# code. This is a very sufficient way to edit documents, especially for complex formatting tasks.

---

## About Bjoern Meyer

As CEO, Bjoern is the visionary behind our strategic direction and business development, bridging the gap between our customers and engineering teams. His deep passion for coding and web technologies drives the creation of innovative products. If you're at a tech conference, be sure to stop by our booth - you'll most likely meet Bjoern in person. With an advanced graduate degree (Dipl. Inf.) in Computer Science, specializing in AI, from the University of Bremen, Bjoern brings significant expertise to his role. In his spare time, Bjoern enjoys running, paragliding, mountain biking, and playing the piano.

- [LinkedIn](https://www.linkedin.com/in/bjoernmeyer/)
- [X](https://x.com/txbjoern)
- [GitHub](https://github.com/bjoerntx)

---

## Related Posts

- [WeAreDevelopers World Congress Europe 2026 Wrap Up: Record Breaking Days in Berlin](https://www.textcontrol.com/blog/2026/07/13/wearedevelopers-world-congress-europe-2026-wrap-up-record-breaking-days-in-berlin/llms.txt)
- [C# Document Generation: A Developer's Guide for .NET](https://www.textcontrol.com/blog/2026/07/08/csharp-document-generation-developer-guide-for-dotnet/llms.txt)
- [Validating PDF/UA Documents in .NET C#: A Practical Guide](https://www.textcontrol.com/blog/2026/07/06/validating-pdf-ua-documents-in-dotnet-csharp/llms.txt)
- [See Text Control at WeAreDevelopers World Congress Europe 2026 in Berlin](https://www.textcontrol.com/blog/2026/07/06/see-text-control-at-wearedevelopers-world-congress-europe-2026-in-berlin/llms.txt)
- [DWX 2026 Wrap-Up: Four Days of Innovation, Conversations, and Enterprise Document Solutions](https://www.textcontrol.com/blog/2026/07/03/dwx-2026-wrap-up-four-days-of-innovation-conversations-and-enterprise-document-solutions/llms.txt)
- [Create SignFabric Envelopes from Mail Merge Templates in .NET C#](https://www.textcontrol.com/blog/2026/06/23/create-signfabric-envelopes-from-mail-merge-templates-using-dotnet-csharp/llms.txt)
- [Convert SSRS RDL Reports to DOCX and TX Text Control Templates in .NET C#](https://www.textcontrol.com/blog/2026/06/22/convert-ssrs-rdl-reports-to-docx-and-tx-text-control-templates-in-dotnet-csharp/llms.txt)
- [Export Document Tables to CSV in .NET C#](https://www.textcontrol.com/blog/2026/06/19/export-document-tables-to-csv-in-dotnet-csharp/llms.txt)
- [Major SignFabric Updates: Stronger Audit Trails, Validation, and Recipient Workflows](https://www.textcontrol.com/blog/2026/06/17/major-signfabric-updates-stronger-audit-trails-validation-and-recipient-workflows/llms.txt)
- [Text Control Expands North American Conference Presence with WeAreDevelopers World Congress North America](https://www.textcontrol.com/blog/2026/06/12/text-control-expands-north-american-conference-presence-with-wearedevelopers-world-congress-north-america/llms.txt)
- [Converting HTML to Markdown in C# .NET](https://www.textcontrol.com/blog/2026/06/11/converting-html-to-markdown-in-csharp-dot-net/llms.txt)
- [Beyond WebSockets: A Glimpse into the Future of Document Editing with WebAssembly](https://www.textcontrol.com/blog/2026/06/10/beyond-websockets-glimpse-future-document-editing-webassembly/llms.txt)
- [Showcasing the Future of Document Processing at Developer World DWX 2026](https://www.textcontrol.com/blog/2026/06/08/showcasing-the-future-of-document-processing-at-dwx-developer-week-2026/llms.txt)
- [PDF Security Explained: Passwords, Permissions, Encryption and Digital Signatures in C# .NET](https://www.textcontrol.com/blog/2026/06/08/pdf-security-explained-passwords-permissions-encryption-and-digital-signatures-in-csharp-dotnet/llms.txt)
- [NDC Copenhagen 2026: Great Days in the Heart of Copenhagen's Developer Community](https://www.textcontrol.com/blog/2026/06/05/ndc-copenhagen-2026-great-days-in-the-heart-of-copenhagens-developer-community/llms.txt)
- [Automatically Mapping TX Text Control Form Fields to JSON Data in .NET C#](https://www.textcontrol.com/blog/2026/06/03/automatically-mapping-tx-text-control-form-fields-to-json-data-in-dotnet-csharp/llms.txt)
- [Getting Started with SignFabric: From Clone to Your First Signature Envelope](https://www.textcontrol.com/blog/2026/06/02/getting-started-with-signfabric-from-clone-to-your-first-signature-envelope/llms.txt)
- [We Never Pause - Join Us at NDC Copenhagen 2026](https://www.textcontrol.com/blog/2026/05/27/we-never-pause-join-us-at-ndc-copenhagen-2026/llms.txt)
- [MD DevDays 2026: Record Attendance, Packed Expo Hall, and Three Great Days in Magdeburg](https://www.textcontrol.com/blog/2026/05/21/md-devdays-2026-record-attendance-packed-expo-hall-and-three-great-days-in-magdeburg/llms.txt)
- [TX Text Control 34.0 SP4 is Now Available: What's New in the Latest Version](https://www.textcontrol.com/blog/2026/05/20/tx-text-control-34-0-sp4-is-now-available/llms.txt)
- [Techorama 2026: Welcome to The Document Forge](https://www.textcontrol.com/blog/2026/05/15/techorama-2026-welcome-to-the-document-forge/llms.txt)
- [Signed CycloneDX SBOMs for CRA Compliance Available for Text Control Products](https://www.textcontrol.com/blog/2026/05/08/signed-cyclonedx-sboms-for-cra-compliance-available-for-text-control-products/llms.txt)
- [Introducing SignFabric: An Open Source, Enterprise-Ready E-Sign Platform Built with TX Text Control](https://www.textcontrol.com/blog/2026/05/06/introducing-signfabric-an-open-source-enterprise-ready-esign-platform-built-with-tx-text-control/llms.txt)
- [TX Text Control vs IronPDF for Enterprise PDF Workflows: Complete Comparison Guide](https://www.textcontrol.com/blog/2026/04/28/tx-text-control-vs-ironpdf-for-enterprise-pdf-workflows-complete-comparison-guide/llms.txt)
- [Building a Modern Track Changes Review Workflow in ASP.NET Core C#](https://www.textcontrol.com/blog/2026/04/28/building-a-modern-track-changes-review-workflow-in-aspnet-core-csharp/llms.txt)
