Products Technologies Demo Docs Blog Support Company

Loading and Saving User Dictionaries in TextControl.Web

This article shows how to load and save user dictionaries using a Web API and JavaScript.

Loading and Saving User Dictionaries in TextControl.Web

When using spell checking in our online editor, dictionaries that are located in the Dictionaries folder of the synchronization service are loaded automatically. That includes all OpenOffice dictionaries and user dictionaries.

This article explains how to enable spell checking for the HTML5-based online editor:

Web.TextControl and Spell Checking

A very common task is to load user specific user dictionaries for each individual user. Therefore, the JavaScript API provides methods to load and save user dictionaries locally. In order to load dictionaries from the server, you will need to retrieve the dictionary from the server and load it into the editor.

In this sample, we created a Web API to handle user dictionaries:

public class DictionaryController : ApiController
{
    // returns all user dictionaries in the specific folder
    [System.Web.Http.HttpGet]
    public HttpResponseMessage UserDictionaryFilenames()
    {
        var sFilenames = System.IO.Directory
            .EnumerateFiles(System.Web.Hosting.HostingEnvironment.MapPath("~/Dictionaries/"),
              "*.txd", System.IO.SearchOption.TopDirectoryOnly)
            .Select(System.IO.Path.GetFileName); 

        return new HttpResponseMessage()
        {
            StatusCode = HttpStatusCode.OK,
            Content = new ObjectContent<string[]>(sFilenames.ToArray(),
                new JsonMediaTypeFormatter())
        };
    }

    // loads a specific dictionary by filename
    [System.Web.Http.HttpGet]
    public HttpResponseMessage LoadUserDictionary(string filename)
    {
        UserDictionary userDictionary = new UserDictionary() {
            language = "en-US",
            name = filename
        };

        // read all lines from the dictionary
        string[] sDictionaryLines = System.IO.File.ReadAllLines(
          System.Web.Hosting.HostingEnvironment.MapPath("~/Dictionaries/" + filename));

        // skip the first entry (encoding)
        userDictionary.words = sDictionaryLines.Skip(1).ToArray();

        // return the object
        return new HttpResponseMessage()
        {
            StatusCode = HttpStatusCode.OK,
            Content = new ObjectContent<UserDictionary>(userDictionary,
                new JsonMediaTypeFormatter())
        };
    }

    // saves a specific dictionary
    [System.Web.Http.HttpPost]
    public HttpResponseMessage SaveUserDictionary([FromBody] UserDictionary dictionary)
    {
        // get all words and save the dictionary
        List<string> dictionaryLines = new List<string>();
        dictionaryLines.Add("SET iso-8859-1");
        dictionaryLines.AddRange(dictionary.words);

        System.IO.File.WriteAllLines(System.Web.Hosting.HostingEnvironment.MapPath(
          "~/Dictionaries/" + dictionary.name), dictionaryLines);

        return new HttpResponseMessage()
        {
            StatusCode = HttpStatusCode.OK,
            Content = new ObjectContent<string>("UserDictionary " + 
              dictionary.name + " successfully saved.", new JsonMediaTypeFormatter())
        };
    }
}

The Web API contains 3 endpoints:

  • UserDictionaryFilenames
    This endpoint returns all user dictionary filenames in the created folder Dictionaries.
  • LoadUserDictionary
    This endpoint loads a specific dictionary by filename.
  • SaveUserDictionary
    This endpoint saves a specific dictionary.

On loading the page, all available dictionaries are listed in a drop-down box:

// get available dictionary names and add them to select element
function getUserDictionaryFilenames() {
    var serviceURL = "/api/Dictionary/UserDictionaryFilenames/";

    $.ajax({
        type: "GET",
        url: serviceURL,
        contentType: 'application/json',
        success: successFunc,
        error: errorFunc
    });

    function successFunc(data, status) {
        data.forEach(function (item) {
            // append the options
            $("#availableDictionaries").append("<option>" + item + "</option>");
        });
    }

    function errorFunc() {
        console.log("error");
    }
}

If a dictionary is selected and the button Load UserDictionary is clicked, the selected dictionary is loaded asynchronously using JavaScript:

// load a specific user dictionary
function loadUserDictionary() {

    // call Web API endpoint to retrieve the dictionary
    var serviceURL = "/api/Dictionary/LoadUserDictionary?filename="
        + $("#availableDictionaries").val();

    $.ajax({
        type: "GET",
        url: serviceURL,
        contentType: 'application/json',
        success: successFunc,
        error: errorFunc
    });

    function successFunc(data, status) {
        // enable spell checking
        TXTextControl.isSpellCheckingEnabled = true;

        // load user dictionary
        TXTextControl.Proofing.loadUserDictionary(data.name, data.words, data.language);
        alert("Dictionary " + data.name + " successfully loaded.");
    }

    function errorFunc() {
        console.log("error");
    }
}

If the button Save UserDictionaries is clicked, all dictionaries are saved back on the server:

function saveUserDictionary() {
    // get information about all user dictionaries
    TXTextControl.Proofing.getUserDictionaryInfo(function (e) {

        // loop through all dictionaries
        e.forEach(function (item) {

            // save the dictionary
            TXTextControl.Proofing.saveUserDictionary(item.name, function (name, words) {
                // create a new dictionary JSON object
                var userDict = { language : item.language, name : name, words : words };

                // call the Web API and pass the dictionary object
                var serviceURL = "/api/Dictionary/SaveUserDictionary/";

                $.ajax({
                    type: "POST",
                    url: serviceURL,
                    contentType: 'application/json',
                    dataType: "json",
                    data: JSON.stringify(userDict),
                    success: successFunc,
                    error: errorFunc
                });

                function successFunc(data, status) {
                    alert(data);
                }

                function errorFunc() {
                    console.log("error");
                }
            });
        });
    })
}

The following animation shows this sample in action:

Loading user dictionaries

This this on your own and download the sample 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

  • Visual Studio 2017 or better
  • TX Text Control .NET Server (trial sufficient)

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.NETMailMergeMVC

Getting Started: ServerTextControl and MailMerge with ASP.NET MVC (.NET…

This article shows how to use the TX Text Control ASP.NET ServerTextControl and MailMerge classes within an ASP.NET web application in Visual Studio 2022.


ASP.NETGetting StartedMVC

Getting Started: Document Viewer with ASP.NET MVC (.NET Framework)

This article shows how to use the TX Text Control ASP.NET document viewer within a .NET Framework web application in Visual Studio 2022.


ASP.NETGetting StartedMVC

Getting Started: Document Editor with ASP.NET MVC (.NET Framework)

This article shows how to use the TX Text Control ASP.NET document editor within a .NET Framework web application in Visual Studio 2022.


ASP.NETJavaScriptDocument Editor

Detect Toggle Button Changes Using a MutationObserver

This article shows how to detect changes of toggle buttons in the ribbon of the web editor using a MutationObserver. The state of a toggle button in the ribbon visualizes the state of a certain…


ASP.NETJavaScriptDocumentViewer

Using the MVC DocumentViewer in ASP.NET Web Forms

The ASP.NET MVC DocumentViewer for ASP.NET provides more features including document signing capabilities than the DocumentViewer for Web Forms. This article shows how to use the MVC…