Products Technologies Demo Docs Blog Support Company

Best Practices: Reliable Auto-Save in TX Text Control Using the WebSocketHandler and Background Services

When developing modern document processing applications with TX Text Control, data loss prevention is a critical requirement. This article explores the best practices for implementing a reliable autosave feature using WebSocketHandler and Background Services in ASP.NET Core.

Best Practices: Reliable Auto-Save in TX Text Control Using the WebSocketHandler and Background Services

When developing modern document processing applications with TX Text Control, data loss prevention is a critical requirement. A common scenario involves a temporary client-side network outage interrupting the WebSocket connection between the document editor and the server. If the document is only stored locally, this could result in data loss.

To address this challenge, we implemented a server-side autosave strategy that saves documents independently of the stability of the WebSocket connection. This is a best practice for mission-critical environments, such as healthcare and legal applications.

This article walks through the code of a reference implementation that uses a background service and the WebSocketHandler to continuously save document data on the server.

Why Auto-Save Server-Side?

TX Text Control provides access to the loaded document via the WebSocketHandler on the server. Periodically saving the document via this handler avoids:

  • Interfering with the active WebSocket communication to the client
  • Data loss when the WebSocket connection drops (e.g., due to an internet issue on the client side)

The document is stored in memory in an internal format and can be saved to a database, disk, or blob storage later.

Key Components of the Strategy

The implementation consists of the following key components:

  • DocumentStore: In-Memory Document Buffer
  • AutoSaveService: Background Document Saver
  • AutoSaveController: Document Session Management

DocumentStore

This static store maps a connection ID, which is associated with a client, to the current document in byte format. It is thread-safe and lightweight, making it ideal for temporarily caching document data.

public static class DocumentStore
{
    public static readonly ConcurrentDictionary<string, byte[]> Documents = new();

    public static void RegisterConnection(string connectionId) => 
        Documents.TryAdd(connectionId, Array.Empty<byte>());

    public static void UpdateDocument(string connectionId, byte[] newContent) => 
        Documents[connectionId] = newContent ?? Array.Empty<byte>();

    public static bool Remove(string connectionId) => 
        Documents.TryRemove(connectionId, out _);

    public static IEnumerable<KeyValuePair<string, byte[]>> GetAll() => 
        Documents.ToArray();
}

AutoSaveService

This service calls SaveText on each active WebSocketHandler every 5 seconds and updates the document in memory. Since these calls are made asynchronously and independently of the UI thread, they have no impact on the user's editing experience. The interval is hardcoded, but you're welcome to put this into an application config file and tweak this number as needed.

public class AutoSaveService : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await Task.Delay(_interval, stoppingToken);

            foreach (var kvp in DocumentStore.Documents)
            {
                SaveDocument(kvp.Key);
            }
        }
    }

    private void SaveDocument(string connectionId)
    {
        var handler = WebSocketHandler.GetInstance(connectionId);
        if (handler == null) return;

        handler.SaveText(out var data, BinaryStreamType.InternalUnicodeFormat);
        DocumentStore.UpdateDocument(connectionId, data);
    }
}

AutoSaveController

The controller provides endpoints for registering, unregistering, and querying document sessions. This allows clients to explicitly start or stop tracking a document's lifecycle.

[ApiController]
[Route("[controller]")]
public class AutoSaveController : ControllerBase
{
    [HttpPost("RegisterConnection")]
    public IActionResult RegisterConnection([FromQuery] string connectionId)
    {
        DocumentStore.RegisterConnection(connectionId);
        return Ok();
    }

    [HttpDelete("UnregisterConnection")]
    public IActionResult UnregisterConnection([FromQuery] string connectionId)
    {
        return DocumentStore.Remove(connectionId) ? Ok() : NotFound();
    }

    [HttpGet("GetDocument")]
    public IActionResult GetDocument([FromQuery] string connectionId)
    {
        if (!DocumentStore.Documents.TryGetValue(connectionId, out var doc))
            return NotFound();

        return Ok(doc);
    }
}

Resilience in Unstable Networks

In the event of a network outage, the WebSocket connection may drop, but the AutoSaveService continues to run in the background. This ensures that the document remains up-to-date on the server, even if the client cannot receive updates. Once the connection is restored, the client can retrieve the latest version of the document from the server.

The advantage of the TX Text Control editor is that the document lives on the server. Even if the internet connection is lost, the document can be securely saved. It is important to have a data loss strategy when handling sensitive data.

  • The last known state is saved server-side in memory.
  • Recovery logic can rehydrate the session or prompt the user to reload the last auto-saved version.

This provides a reliable backup option for scenarios with poor connectivity.

Conclusion

Implementing a server-side auto-save strategy with TX Text Control enhances data integrity and user experience in document processing applications. By leveraging the WebSocketHandler and a background service, developers can ensure that documents are continuously saved, minimizing the risk of data loss during network interruptions.

You can download the complete code for this implementation from our GitHub repository.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

GitHub

Download and Fork This Sample on GitHub

We proudly host our sample code on github.com/TextControl.

Please fork and contribute.

Download ZIP

Open on GitHub

Open in Visual Studio

Requirements for this sample

  • TX Text Control .NET Server
  • Visual Studio 2022

ASP.NET

Integrate document processing into your applications to create documents such as PDFs and MS Word documents, including client-side document editing, viewing, and electronic signatures.

ASP.NET Core
Angular
Blazor
JavaScript
React
  • Angular
  • Blazor
  • React
  • JavaScript
  • ASP.NET MVC, ASP.NET Core, and WebForms

Learn more Trial token Download trial

Related Posts

ASP.NETASP.NET Core

Celebrating a Remarkable 2025: A Year of Innovation and Growth

2025 is coming to an end. Now is a great time to pause and reflect. What a year it has been for us! We are reflecting on the milestones and achievements of 2025 and highlighting the innovation and…


ASP.NETASP.NET CoreForms

Designing the Perfect PDF Form with TX Text Control in .NET C#

Learn how to create and design interactive PDF forms using TX Text Control in .NET C#. This guide covers essential features and best practices for effective form design.


ASP.NETASP.NET CoreMIME

Why Defining MIME Types for PDF/A Attachments Is Essential

The PDF/A standard was created to ensure the long-term reliable archiving of digital documents. An important aspect of the standard involves properly handling embedded files and attachments within…


ASP.NETASP.NET CoreConference

We are Returning to CodeMash 2026 as a Sponsor and Exhibitor

We are excited to announce that we will be returning to CodeMash 2026 as a sponsor and exhibitor. Join us to learn about the latest in .NET development and how our products can help you build…


ASP.NETASP.NET Core

AI-Ready Documents in .NET C#: How Structured Content Unlocks Better…

Most organizations use AI on documents that were never designed for machines. PDFs without tags, inconsistent templates, undescribed images, and disorganized reading orders are still common. This…

Summarize this blog post with:

Share on this blog post on: