[Sample of Apr 27th] Customized Intelligent TextBox via ASP.NET

 

Homepage image
Sample of the Day RSS Feed

Sample Downloads: https://code.msdn.microsoft.com/CSASPNETIntelligentTextBox-08258112  

Today’s sample demonstrates how to create a customized intelligent TextBox control via Asp.net, just like MSDN library's search TextBox. This sample code can check the user's input words with word dictionary, and provides some similar words for select, customers can also add their own words in dictionary, this is a very useful function, for example, in your website, you can record the most popular search words or sentences in your dictionary, and these hot words and sentences appears when customers try to search them.

The sample was written by our star sample writer: Arwind Gao.

imageYou can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage https://1code.codeplex.com/.

Introduction

The project illustrates how to create a customized intelligent TextBox control via Asp.net, just like MSDN library's search TextBox. This sample code can check the user's input words with word dictionary, and provides some similar words for select, customers can also add their own words in dictionary, this is a very useful function, for example, in your website, you can record the most popular search words or sentences in your dictionary, and these hot words and sentences appears when customers try to search them.

 

Running the Sample

Please follow these demonstration steps below.

Step 1: Open the CSASPNETIntelligentTextBox.sln. Expand the CSASPNETIntelligentTextBox web application and press Ctrl + F5 to show the Default.aspx.

Step 3: We will see a TextBox control on the page. Please input a character or a word in it.

Step 4: When you input a word in TextBox, you can find a word list below the TextBox. The sample compares your word and put the similar words in word list.

image

Step 5: If everything is fine, you can edit your word with prompt or you can directly click words in list to update TextBox's value.

image

Step 6. You can Click the "Click here to add new word" button for adding more custom words in word dictionary. Then you can find them when you try to input the correct word.

image

Using the Code

Step 1. Create a C# "ASP.NET Empty Web Application" in Visual Studio 2010 or Visual Web Developer 2010. Name it as "CSASPNETIntelligentTextBox". Add one folder, "Dictionary". In order to execute this web application, please create a dictionary file. You can create a new dictionary file you like, or use the sample's WordList.txt file.

Step 2. Add one web form page in the root directory, "Default.aspx". Create a TextBox control, a div element and a label on page. Add some JavaScript functions on Default.aspx page and assigned to TextBox's onkeyup event.

The following code is use to call web method in code behind file via Ajax and attach the result in unordered list.

 function CallPageMethod() { 
    PageMethods.ReturnHtmlString(document.getElementById("tbInput").value, success, failed); 
} 
function success(result) { 
    var info = document.getElementById("recommandWordList"); 
    info.innerHTML = "" + result + ""; 
} 
function failed(error) { 
    var info = document.getElementById("recommandWordList"); 
    info.innerHTML = ""; 
} 

Step 3. After adding JavaScript function to TextBox, note this function is invoke a page method, it will call a public static method(ReturnHtmlString(string key)) in Default.aspx.cs file. This method provides a Dictionary instance to store the high similar level words with user's input, and the dictionary sorted by similar level.

The following code is use to compare dictionary with search key word, find and show them to customers.

 /// <summary> 
/// This method is used to call check user's input word and returns some recommended words. 
/// A JavsScript function will invoke this method to execute server-side code, 
/// This will bring many benefits, such as when user input words and the application will 
/// update recommended word list without page refresh, it can provide more responsive. 
/// </summary> 
/// <param name="key"></param> 
/// <returns></returns> 
[System.Web.Services.WebMethod] 
public static string ReturnHtmlString(string key) 
{ 
    #region ////Match Method//// 
 
 
    // Define an ArrayList to retrieve word list, 
    // the Dictionary use to record similar words. 
    ArrayList list = (ArrayList)LineList; 
    Dictionary<int, string[]> matchEntity = new Dictionary<int, string[]>(); 
    int sortID = 0; 
    int highLevel = 0; 
    // Loop the word dictionary, compare with source word. 
    for (int i = 0; i < list.Count; i++) 
    { 
        // Confirm the word length, calculate word's similar level and 
        // move the cursor to next character. 
        string source = list[i].ToString(); 
        int sourceLength = list[i].ToString().Length; 
        int keyLength = key.Length; 
        int matchLength = ((sourceLength > keyLength) ? keyLength : sourceLength); 
        int matchLevel = 0; 
        int cursor = 0; 
        while (cursor < matchLength) 
        { 
            if (source[cursor] == key[cursor]) 
            { 
                matchLevel++; 
                cursor++; 
            } 
            else if (matchLevel >= 1) 
            { 
                cursor++; 
            } 
            else 
            { 
                matchLevel = 0; 
                break; 
            } 
        } 
        if (matchLevel >= 1) 
        { 
            string[] entity = new string[4]; 
            entity[0] = matchLevel.ToString(); 
            entity[1] = source; 
            entity[2] = sourceLength.ToString(); 
            matchEntity.Add(sortID,entity); 
            if (matchLevel > highLevel) 
                highLevel = matchLevel; 
            sortID++;  
        } 
    } 
    var highLevelList = from d in matchEntity 
                        where d.Value[0] == highLevel.ToString() 
                        select d; 
    #endregion 
 
 
    #region ////Sort Method//// 
 
 
    // Sort the result with the highest similar level and characters' length. 
    // And we must make sure the recommended word list must include 10 words. 
    if (highLevelList.ToList().Count <= 10) 
    { 
        int listNumber = highLevelList.ToList().Count; 
        string returnHtml = string.Empty; 
        var sortMatchList = from d in highLevelList 
                            orderby Convert.ToInt32(d.Value[2]) 
                            select d; 
        foreach (var s in sortMatchList) 
        { 
            returnHtml += "" + s.Value[1] + ""; 
            matchEntity.Remove(s.Key); 
            listNumber++; 
        } 
        var lowLevelList = matchEntity.OrderByDescending(d => d.Value[0]); 
        int number = 0; 
        foreach (var s in lowLevelList) 
        { 
            if (number < (10 - listNumber)) 
            { 
                returnHtml += "" + s.Value[1] + ""; 
                number++; 
            } 
            else 
            { 
                break; 
            } 
        } 
        return returnHtml; 
    } 
    else 
    { 
        int listNumber = 0; 
        string returnHtml = string.Empty; 
        var sortMatchList = from d in highLevelList 
                            orderby Convert.ToInt32(d.Value[2]) 
                            select d; 
        for (int i = 0; i < sortMatchList.ToList().Count; i++) 
        { 
            if (listNumber < 10) 
            { 
                returnHtml += "" + sortMatchList.ToList()[i].Value[1] + ""; 
                listNumber++; 
            } 
            else 
            { 
                break; 
            } 
        } 
        return returnHtml; 
    } 
 
 
    #endregion 
} 

Step 4. Create a JavaScript function to get the value from word list. The function will help customers that copy the word from recommended word list to TextBox, customers can choose what they want.

 function getValue(li) { 
    var textBox = document.getElementById("tbInput"); 
    var value = li.innerText; 
    textBox.value = value; 
} 

Step 5. Add a web form page for adding new custom words in word dictionary file, name it as "WordAddPage.aspx". This page use to add new words in word dictionary, if you like, you can create a more convenient and intelligent methods that add most popular words timely  for keeping your words prompt function more efficient.

The following code shows how to add new words in txt file.

 /// <summary> 
/// Add new words 
/// </summary> 
/// <param name="sender"></param> 
/// <param name="e"></param> 
protected void btnSubmit_Click(object sender, EventArgs e) 
{ 
    string validateResult = StringValidate(tbNewWords.Text); 
    if (String.IsNullOrEmpty(validateResult)) 
    { 
        string[] words = tbNewWords.Text.Trim().Split(','); 
        using (StreamWriter writer = new StreamWriter(Server.MapPath("~/Dictionary/WordList.txt"), true)) 
        { 
            foreach (string str in words) 
            { 
                writer.WriteLine(str); 
            } 
            lbMessage.Text = "Congratulations, the new word has been added in Word dictionary."; 
        } 
    } 
    else 
    { 
        lbMessage.Text = validateResult; 
    } 
} 
 
 
/// <summary> 
/// String variables validation. 
/// </summary> 
/// <param name="strWords"></param> 
/// <returns></returns> 
protected static string StringValidate(string strWords) 
{ 
    string words = strWords.Trim(); 
    if (string.IsNullOrEmpty(words)) 
    { 
        return "Words can not be null."; 
    } 
    else if (StringIncludeNumberic(words)) 
    { 
        return "Words can not include numeral and special characters."; 
    } 
    else 
    { 
        return string.Empty; 
    }        
} 
 
 
protected static bool StringIncludeNumberic(string strWords) 
{ 
    string strRegex = @"[^a-zA-z,']"; 
    return Regex.IsMatch(strWords, strRegex); 
} 
 

 

More Information

MSDN:  PageMethods