2013-03-12 38 views
3

我一直在研究相當長一段時間,爲文本框和多行文本框進行適當的拼寫檢查。我們可以通過使用asp.net web服務的badsyntax運行jquery spellchecker嗎?

我可以看到,這個功能是內置的Firefox,但它不存在鉻。

我正在查看拼寫檢查的所有演示,這是由 提供的jquery spellchecker - badsyntax,我覺得它非常好,很有用。

這裏是鏈接 http://jquery-spellchecker.badsyntax.co/

但在這裏我的問題是 - 拼寫檢查器利用PHP Web服務的,我想在我的ASP.net web應用中使用它。

是否有任何解決方法,以便我可以使用asp.net web服務運行它?

請給我一個解決方案。

回答

0

我已經找到了問題的解決方案及以下 是返回jQuery的拼寫檢查

JSON響應的WebService此代碼的代碼修改後的優化版本中

發現github.com/jackmyang/jQuery-Spell-Checker-for-ASP.NET

 /// <summary> 


    using System; 
    using System.Collections.Generic; 
    using System.Net; 
    using System.Text; 
    using System.Web; 
    using System.Xml; 

< %@ WebHandler Language="C#" Class="JQuerySpellCheckerHandler2" %> 



/// <summary> 
/// jQuery spell checker http handler class. Original server-side code was written by Richard Willis in PHP. 
/// This is a version derived from the original design and implemented for ASP.NET platform. 
/// 
/// It's very easy to use this handler with ASP.NET WebForm or MVC. Simply do the following steps: 
///  1. Include project jquery.spellchecker assembly in the website as a reference 
///  2. Include the httphandler node in the system.web node for local dev or IIS 6 or below 
/// <example> 
///  <![CDATA[ 
///   <system.web> 
///    <httpHandlers> 
///     <add verb="GET,HEAD,POST" type="jquery.spellchecker.JQuerySpellCheckerHandler" path="JQuerySpellCheckerHandler.ashx"/> 
///    </httpHandlers> 
///   </system.web> 
///  ]]> 
/// </example> 
///  3. If IIS7 is the target web server, also need to include the httphandler node in the system.webServer node 
/// <example> 
///  <![CDATA[ 
///   <system.webServer> 
///    <handlers> 
///     <add verb="GET,HEAD,POST" name="JQuerySpellCheckerHandler" type="jquery.spellchecker.JQuerySpellCheckerHandler" path="JQuerySpellCheckerHandler.ashx"/> 
///    </handlers> 
///   </system.webServer> 
///  ]]> 
/// </example> 
///  4. On the web page which included the spell checker, set the 'url' property to '~/JQuerySpellCheckerHandler.ashx' 
/// <example> 
///  <![CDATA[ 
///   $("#text-content") 
///    .spellchecker({ 
///     url: "~/JQuerySpellCheckerHandler.ashx", 
///     lang: "en", 
///     engine: "google", 
///     suggestBoxPosition: "above" 
///   }) 
///  ]]> 
/// </example> 
/// </summary> 
/// <remarks> 
/// Manipulations of XmlNodeList is used for compatibility concern with lower version of .NET framework, 
/// alternatively, they can be simplified using 'LINQ for XML' if .NET 3.5 or higher is available. 
/// </remarks> 
public class JQuerySpellCheckerHandler2 : IHttpHandler 
{ 
    #region fields 

    // in case google changes url, value of GoogleSpellCheckRpc can be stored in web.config instead to avoid code re-compilation 
    private const string GoogleSpellCheckRpc = "https://www.google.com/tbproxy/spell?"; 
    private const string GoogleFlagTextAlreadClipped = "textalreadyclipped"; 
    private const string GoogleFlagIgnoreDups = "ignoredups"; 
    private const string GoogleFlagIgnoreDigits = "ignoredigits"; 
    private const string GoogleFlagIgnoreAllCaps = "ignoreallcaps"; 

    #endregion 

    #region properties 

    /// <summary> 
    /// Gets or sets a value indicating whether [ignore duplicated words]. 
    /// </summary> 
    /// <value><c>true</c> if [ignore dups]; otherwise, <c>false</c>.</value> 
    private bool IgnoreDups { get; set; } 

    /// <summary> 
    /// Gets or sets a value indicating whether [ignore digits]. 
    /// </summary> 
    /// <value><c>true</c> if [ignore digits]; otherwise, <c>false</c>.</value> 
    private bool IgnoreDigits { get; set; } 

    /// <summary> 
    /// Gets or sets a value indicating whether [ignore all capitals]. 
    /// </summary> 
    /// <value><c>true</c> if [ignore all caps]; otherwise, <c>false</c>.</value> 
    private bool IgnoreAllCaps { get; set; } 

    /// <summary> 
    /// Gets or sets a value indicating whether [text alread clipped]. 
    /// </summary> 
    /// <value><c>true</c> if [text alread clipped]; otherwise, <c>false</c>.</value> 
    private bool TextAlreadClipped { get; set; } 

    #endregion 

    #region Implementation of IHttpHandler 

    /// <summary> 
    /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface. 
    /// </summary> 
    /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests. 
    /// </param> 
    public void ProcessRequest(HttpContext context) 
    { 
     string engine = context.Request.Form[1]; 
     string lang = context.Request.Form["lang"]; 
     string text = context.Request.Form[3]; 
     string suggest = context.Request.Form[2]; 
     SetSwitches(context);    
     string result = SpellCheck(text, lang, engine, suggest); 
     context.Response.ContentType = "application/js"; 
     string jsonStr = "{\"outcome\":\"success\",\"data\":[" + result + "]}"; 
     if (suggest == "get_incorrect_words") 
     { 
      context.Response.Write(jsonStr); 
     } 
     else 
     { 
      context.Response.Write(result); 
     } 
    } 

    /// <summary> 
    /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance. 
    /// </summary> 
    /// <returns> 
    /// true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false. 
    /// </returns> 
    public bool IsReusable 
    { 
     get { return false; } 
    } 

    #endregion 

    #region private methods 

    /// <summary> 
    /// Spells the check. 
    /// </summary> 
    /// <param name="text">The text.</param> 
    /// <param name="lang">The lang.</param> 
    /// <param name="engine">The engine.</param> 
    /// <param name="suggest">The suggest.</param> 
    /// <returns></returns> 
    private string SpellCheck(string text, string lang, string engine, string suggest) 
    { 
     if (0 == string.Compare(suggest, "undefined", StringComparison.OrdinalIgnoreCase)) 
     { 
      suggest = string.Empty; 
     } 
     if (0 != string.Compare(engine, "google", true)) 
     { 
      throw new NotImplementedException("Only google spell check engine is support at this moment."); 
     } 
     string xml; 
     List<string> result; 
     if (string.IsNullOrEmpty(suggest) || suggest == "get_incorrect_words") 
     { 
      xml = GetSpellCheckRequest(text, lang); 
      result = GetListOfMisspelledWords(xml, text); 
     } 
     else 
     { 
      xml = GetSpellCheckRequest(text, lang); 
      result = GetListOfSuggestWords(xml, text); 
     } 
     return ConvertStringListToJavascriptArrayString(result); 
    } 

    /// <summary> 
    /// Sets the boolean switch. 
    /// </summary> 
    /// <param name="context">The context.</param> 
    /// <param name="queryStringParameter">The query string parameter.</param> 
    /// <returns></returns> 
    private static bool SetBooleanSwitch(HttpContext context, string queryStringParameter) 
    { 
     byte tryParseZeroOne; 
     string queryStringValue = context.Request.QueryString[queryStringParameter]; 
     if (!string.IsNullOrEmpty(queryStringValue) && byte.TryParse(queryStringValue, out tryParseZeroOne)) 
     { 
      if (1 < tryParseZeroOne || 0 > tryParseZeroOne) 
      { 
       throw new InvalidOperationException(string.Format("Query string parameter '{0}' only supports values of 1 and 0.", queryStringParameter)); 
      } 
      return tryParseZeroOne == 1; 
     } 
     return false; 
    } 

    /// <summary> 
    /// Gets the list of suggest words. 
    /// </summary> 
    /// <param name="xml">The source XML.</param> 
    /// <param name="suggest">The word to be suggested.</param> 
    /// <returns></returns> 
    private static List<string> GetListOfSuggestWords(string xml, string suggest) 
    { 
     if (string.IsNullOrEmpty(xml) || string.IsNullOrEmpty(suggest)) 
     { 
      return null; 
     } 
     // 
     XmlDocument xdoc = new XmlDocument(); 
     xdoc.LoadXml(xml); 
     if (!xdoc.HasChildNodes) 
     { 
      return null; 
     } 
     XmlNodeList nodeList = xdoc.SelectNodes("//c"); 
     if (null == nodeList || 0 >= nodeList.Count) 
     { 
      return null; 
     } 
     List<string> list = new List<string>(); 
     foreach (XmlNode node in nodeList) 
     { 
      list.AddRange(node.InnerText.Split('\t')); 
      return list; 
     } 
     return list; 
    } 

    /// <summary> 
    /// Gets the list of misspelled words. 
    /// </summary> 
    /// <param name="xml">The source XML.</param> 
    /// <param name="text">The text.</param> 
    /// <returns></returns> 
    private static List<string> GetListOfMisspelledWords(string xml, string text) 
    { 
     if (string.IsNullOrEmpty(xml) || string.IsNullOrEmpty(text)) 
     { 
      return null; 
     } 
     XmlDocument xdoc = new XmlDocument(); 
     xdoc.LoadXml(xml); 
     if (!xdoc.HasChildNodes) 
     { 
      return null; 
     } 
     XmlNodeList nodeList = xdoc.SelectNodes("//c"); 
     if (null == nodeList || 0 >= nodeList.Count) 
     { 
      return null; 
     } 
     List<string> list = new List<string>(); 
     foreach (XmlNode node in nodeList) 
     { 
      int offset = Convert.ToInt32(node.Attributes["o"].Value); 
      int length = Convert.ToInt32(node.Attributes["l"].Value); 
      list.Add(text.Substring(offset, length)); 
     } 
     return list; 
    } 

    /// <summary> 
    /// Constructs the request URL. 
    /// </summary> 
    /// <param name="text">The text which may contain multiple words.</param> 
    /// <param name="lang">The language.</param> 
    /// <returns></returns> 
    private static string ConstructRequestUrl(string text, string lang) 
    { 
     if (string.IsNullOrEmpty(text)) 
     { 
      return string.Empty; 
     } 
     lang = string.IsNullOrEmpty(lang) ? "en" : lang; 
     return string.Format("{0}lang={1}&text={2}", GoogleSpellCheckRpc, lang, text); 
    } 

    /// <summary> 
    /// Converts the C# string list to Javascript array string. 
    /// </summary> 
    /// <param name="list">The list.</param> 
    /// <returns></returns> 
    private static string ConvertStringListToJavascriptArrayString(ICollection<string> list) 
    { 
     StringBuilder stringBuilder = new StringBuilder(); 
     stringBuilder.Append("["); 
     if (null != list && 0 < list.Count) 
     { 
      bool showSeperator = false; 
      foreach (string word in list) 
      { 
       if (showSeperator) 
       { 
        stringBuilder.Append(","); 
       } 
       stringBuilder.AppendFormat("\"{0}\"", word); 
       showSeperator = true; 
      } 
     } 
     stringBuilder.Append("]"); 
     return stringBuilder.ToString(); 
    } 

    /// <summary> 
    /// Sets the switches. 
    /// </summary> 
    /// <param name="context">The context.</param> 
    private void SetSwitches(HttpContext context) 
    { 
     IgnoreAllCaps = SetBooleanSwitch(context, GoogleFlagIgnoreAllCaps); 
     IgnoreDigits = SetBooleanSwitch(context, GoogleFlagIgnoreDigits); 
     IgnoreDups = SetBooleanSwitch(context, GoogleFlagIgnoreDups); 
     TextAlreadClipped = SetBooleanSwitch(context, GoogleFlagTextAlreadClipped); 
    } 

    /// <summary> 
    /// Requests the spell check and get the result back. 
    /// </summary> 
    /// <param name="text">The text.</param> 
    /// <param name="lang">The language.</param> 
    /// <returns></returns> 
    private string GetSpellCheckRequest(string text, string lang) 
    { 
     string requestUrl = ConstructRequestUrl(text, lang); 
     string requestContentXml = ConstructSpellRequestContentXml(text); 
     byte[] buffer = Encoding.UTF8.GetBytes(requestContentXml); 

     WebClient webClient = new WebClient(); 
     webClient.Headers.Add("Content-Type", "text/xml"); 
     try 
     { 
      byte[] response = webClient.UploadData(requestUrl, "POST", buffer); 
      return Encoding.UTF8.GetString(response); 
     } 
     catch (ArgumentException) 
     { 
      return string.Empty; 
     } 
    } 

    /// <summary> 
    /// Constructs the spell request content XML. 
    /// </summary> 
    /// <param name="text">The text which may contain multiple words.</param> 
    /// <returns></returns> 
    private string ConstructSpellRequestContentXml(string text) 
    { 
     XmlDocument doc = new XmlDocument(); // Create the XML Declaration, and append it to XML document 
     XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", null, null); 
     doc.AppendChild(declaration); 
     XmlElement root = doc.CreateElement("spellrequest"); 
     root.SetAttribute(GoogleFlagTextAlreadClipped, TextAlreadClipped ? "1" : "0"); 
     root.SetAttribute(GoogleFlagIgnoreDups, IgnoreDups ? "1" : "0"); 
     root.SetAttribute(GoogleFlagIgnoreDigits, IgnoreDigits ? "1" : "0"); 
     root.SetAttribute(GoogleFlagIgnoreAllCaps, IgnoreAllCaps ? "1" : "0"); 
     doc.AppendChild(root); 
     XmlElement textElement = doc.CreateElement("text"); 
     textElement.InnerText = text; 
     root.AppendChild(textElement); 
     return doc.InnerXml; 
    } 

    #endregion 
} 

您也可以使用此javascript:

 // Replace the Spellchecker.php path with Asp.net ashx path 

    spellchecker = new $.SpellChecker(body, { 
     lang: 'en', 
     parser: 'html', 
     webservice: { 
      path: "../Includes/JS/spellify/JQuerySpellCheckerHandler2.ashx", 
      driver: 'google' 
     }, 
     suggestBox: { 
      position: 'below' 
     } 
     }); 

     // Bind spellchecker handler functions 
     spellchecker.on('check.success', function() { 
     alert('There are no incorrectly spelt words.'); 
     }); 

     spellchecker.check(); 
1

我是該插件的作者,並且真的想要合併一些其他的web服務實現。

這在我的谷歌快訊最近突然出現了,我無法驗證它的工作原理,但:

+0

謝謝你回覆badsyntax。我非常感謝你在插件中所做的所有工作。這個插件已經塑造得非常好。如果我們以某種方式將它實現爲ASP.net Web服務,它將變得非常棒。我正在做。如果我突破,我肯定會分享代碼。另外請讓我知道什麼是PHP Web服務所採取的參數,以及我們從它得到的迴應是什麼。在此先感謝 – 2013-03-12 13:35:38

1

嗨,大家好:韋雷德拉帕布,badsyntax;我已經集成了Nhunspell和asp.net Web Service(.asmx),目前我正在嘗試將jquery spellchecker - badsyntax集成到項目中,我是jquery spellchecker現在與我的web服務合作,但是我仍然處理返回的數據我的web服務的類型,以允許jquery spellcheker做它的魔力,但我認爲它的東西。

我把想法來自:

deepinthecode.com

這裏有一些想法,我用:

我用NHusnpell,有助於獲得通過的文本中不正確的話,看看進入dictionary(作爲.oxt下載的開放式辦公室,但您必須通過zip來獲取en_US.aff和en_US.dic),這些文件需要位於bin目錄中。

在Glabal.asax文件中,我創建了一個完成所有工作的NHuspell靜態實例。

public class Global : System.Web.HttpApplication 
{ 
    static SpellEngine spellEngine; 
    static public SpellEngine SpellEngine { get { return spellEngine; } } 

    protected void Application_Start(object sender, EventArgs e) 
    { 
     try 
     { 
      string dictionaryPath = Server.MapPath("Bin") + "\\"; 
      Hunspell.NativeDllPath = dictionaryPath; 

      spellEngine = new SpellEngine(); 
      LanguageConfig enConfig = new LanguageConfig(); 
      enConfig.LanguageCode = "en"; 
      enConfig.HunspellAffFile = dictionaryPath + "en_us.aff"; 
      enConfig.HunspellDictFile = dictionaryPath + "en_us.dic"; 
      enConfig.HunspellKey = ""; 
      //enConfig.HyphenDictFile = dictionaryPath + "hyph_en_us.dic"; 
      spellEngine.AddLanguage(enConfig); 
     } 
     catch (Exception ex) 
     { 
      if (spellEngine != null) 
       spellEngine.Dispose(); 
     } 
    } 

    ... 

    protected void Application_End(object sender, EventArgs e) 
    { 
     if (spellEngine != null) 
      spellEngine.Dispose(); 
     spellEngine = null; 

    } 
} 

然後,我創建了Get_Incorrect_Words和Get_Suggestions方法

/// <summary> 
/// Summary description for SpellCheckerService 
/// </summary> 
[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
[ScriptService()] 
public class SpellCheckerService : System.Web.Services.WebService 
{  

    [WebMethod] 
    //[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public string get_incorrect_words(string words) 
    { 
     Dictionary<string, string> IncorrectWords = new Dictionary<string, string>(); 

     List<string> wrongWords = new List<string>(); 

     var palabras = words.Split(' '); 

     // Check spelling of each word that has been passed to the method 
     foreach (string word in palabras) 
     { 
      bool correct = Global.SpellEngine["en"].Spell(word); 

      if (!correct){ 

       wrongWords.Add(word); 
      } 
     } 

     IncorrectWords.Add("data", wrongWords[0]); 

     return wrongWords[0]; 
    } 

    [WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public List<string> get_suggestions(string word) 
    { 
     List<string> suggestions = new List<string>(); 
     suggestions = Global.SpellEngine["en"].Suggest(word); 
     suggestions.Sort(); 
     return suggestions; 
    } 

,最後我修改爲jquery.Spellchecker的get_incorrect_words和get_suggestions調用的ASMX Web服務。JS

/* Config 
    *************************/ 

    var defaultConfig = { 
    lang: 'en', 
    webservice: { 
     path: 'SpellCheckerService.asmx/get_incorrect_words' 
     //,driver: 'LabNET' 
    }, 
    local: { 
     requestError: 'There was an error processing the request.', 
     ignoreWord: 'Ignore word', 
     ignoreAll: 'Ignore all', 
     ignoreForever: 'Add to dictionary', 
     loading: 'Loading...', 
     noSuggestions: '(No suggestions)' 
    }, 
    suggestBox: { 
     numWords: 5, 
     position: 'above', 
     offset: 2, 
     appendTo: null 
    }, 
    incorrectWords: { 
     container: 'body', //selector 
     position: null //function 
    } 
    }; 

    var pluginName = 'spellchecker'; 

... 

    /* Spellchecker web service 
    *************************/ 

    var WebService = function(config) { 

    this.config = config; 

    this.defaultConfig = { 
     url: config.webservice.path, 
     //contentType: "application/json; charset=utf-8", 
     type: 'POST', 
     dataType: 'text', 
     cache: false, 
     data: JSON.stringify({ 
     lang: config.lang, 
     driver: config.webservice.driver 
     }, null,2) , 
     error: function() { 
     alert(config.local.requestError); 
     }.bind(this) 
    }; 
    }; 

    WebService.prototype.makeRequest = function(config) { 

    var defaultConfig = $.extend(true, {}, this.defaultConfig); 

    return $.ajax($.extend(true, defaultConfig, config)); 
    }; 

    WebService.prototype.checkWords = function (text, callback) { 
     //action: 'get_incorrect_words', 
     //JSON.stringify({ 

     // text: text 
     //}, null, 2) 

     return this.makeRequest(
      { 
       data: { words: text }, 
       success: callback 
    }); 
    }; 

    WebService.prototype.getSuggestions = function (word, callback) { 
     //action: 'get_suggestions', 
    return this.makeRequest({ 
     data: JSON.stringify({ 

     word: word 
     }, null, 2), 
     success: callback 
    }); 
    }; 
+0

嗨維克托..我會檢查你提供的代碼,看看它是如何工作的。謝謝 – 2013-03-13 05:40:55

+0

我發現jquery spellchecker期望從web服務返回的數據是一個json格式如下:「 {'outcome':'success','data':[「incorrectoWord01,incorrectoWord02」]}「用於返回拼寫單詞和數據作爲響應的方法,格式爲[」suggest01,suggest02「]該方法檢索部分 – 2013-03-13 23:28:22

+0

維克托感謝了很多..我檢查相同使用螢火蟲:) ..我已經通過https://github.com/jackmyang/jQuery-Spell-Checker-for-ASP修改代碼。 NET與jquery-spellchecker一起使用,它被認爲是badsyntax。我將很快分享代碼 – 2013-03-14 06:12:48

相關問題