Spell Check in a Web Service
2012-03-23 by
I used this code to allow spell checking from a web page. Using Javascript or silverlight would be a great way to implement this. This worked for what I was doing on a small website.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
namespace Webservices.Word
{
///
/// Summary description for SpellChecker
///
[WebService(Namespace = "http://www.pinecrest-it.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class SpellChecker : System.Web.Services.WebService
{
[WebMethod]
public string CheckSpelling(string text)
{
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(text);
string origText = xmlDoc.SelectSingleNode("/*[local-name()='checkSpelling']/*[local-name()='text']").InnerText;
string componentID = xmlDoc.SelectSingleNode("/*[local-name()='checkSpelling']/*[local-name()='componentID']").InnerText;
SpellingErrorCollection errorList = null;
if (origText.Length > 0)
{
int errors = 0;
Microsoft.Office.Interop.Word._Application word = new Microsoft.Office.Interop.Word.ApplicationClass();
word.Visible = false;
object template = Type.Missing;
object newTemplate = Type.Missing;
object documentType = Type.Missing;
object visible = false;
Microsoft.Office.Interop.Word._Document doc = word.Documents.Add(ref template, ref newTemplate, ref documentType, ref documentType);
doc.Words.First.InsertBefore(origText);
Microsoft.Office.Interop.Word.ProofreadingErrors spellErrorsColl = doc.SpellingErrors;
errors = spellErrorsColl.Count;
object optional = Type.Missing;
object trueValue = false;
object falseValue = false;
foreach (Microsoft.Office.Interop.Word.Range mispelledRange in spellErrorsColl)
{
SpellCheckError currentError = new SpellCheckError();
Microsoft.Office.Interop.Word.SpellingSuggestions suggestions = word.GetSpellingSuggestions(mispelledRange.Text, ref optional, ref trueValue, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional);
currentError.StartIndex = mispelledRange.Start;
currentError.EndIndex = mispelledRange.End;
currentError.SelectedText = mispelledRange.Text;
foreach (Microsoft.Office.Interop.Word.SpellingSuggestion suggestion in suggestions)
{
currentError.Suggestions.Add(suggestion.Name);
}
if(errorList == null)
errorList = new SpellingErrorCollection(origText,componentID);
errorList.Add(currentError);
}
doc.Close(ref falseValue, ref optional, ref optional);
word.Quit(ref falseValue, ref optional, ref optional);
}
string xmlOut = "";
if (errorList != null)
{
xmlOut = errorList.GetXMLData();
}
return xmlOut;
}
}
[Serializable]
public class SpellCheckError
{
private string _selectedText = "";
public string SelectedText
{
get
{
return _selectedText;
}
set
{
_selectedText = value;
}
}
public int SelectedChange
{
get
{
return _selectedChange;
}
set
{
_selectedChange = value;
}
}
public string SelectedChangeValue
{
get
{
if (_selectedChangeValue == null)
{
if (_selectedChange >= 0)
return Suggestions[_selectedChange];
else
{
return null;
}
}
else
{
return _selectedChangeValue;
}
}
set
{
_selectedChangeValue = value;
_selectedChange = -1;
}
}
private string _selectedChangeValue = null;
private int _startIndex;
private int _endIndex;
private int _selectedChange = -1;
public int StartIndex
{
get
{
return _startIndex;
}
set
{
_startIndex = value;
}
}
public int EndIndex
{
get
{
return _endIndex;
}
set
{
_endIndex = value;
}
}
private List<string> _suggestions = new List<string>();
public List<string> Suggestions
{
get
{
return _suggestions;
}
set
{
_suggestions = value;
}
}
}
[Serializable]
public class SpellingErrorCollection : IList<SpellCheckError>, System.Xml.Serialization.IXmlSerializable
{
private List<SpellCheckError> _errors;
private List<string> _ignoreList;
public string GetUpdatedText()
{
string newText = OriginalText;
for (int i = this.Count - 1; i >= 0; i--)
{
SpellCheckError error = this[i];
if (error.SelectedChangeValue != null)
{
newText = newText.Remove(error.StartIndex, error.EndIndex - error.StartIndex);
newText = newText.Insert(error.StartIndex, error.SelectedChangeValue);
}
}
return newText;
}
public string GetXMLData()
{
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(SpellingErrorCollection));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ser.Serialize(ms, this);
ms.Flush();
ms.Seek(0, System.IO.SeekOrigin.Begin);
return System.Text.ASCIIEncoding.ASCII.GetString(ms.ToArray());
}
private string _originalText = "";
private string _controlID = "";
public void AddToIgnoreList(string newItem)
{
if (!_ignoreList.Contains(newItem))
_ignoreList.Add(newItem);
}
public List<string> GetIgnoreList()
{
return _ignoreList;
}
public SpellingErrorCollection():base()
{
_ignoreList =new List<string>();
_controlID = "";
_errors = new List<SpellCheckError>();
_originalText = "";
}
public SpellingErrorCollection(string originalText, string controlID)
{
_ignoreList = new List<string>();
_controlID = controlID;
_errors = new List<SpellCheckError>();
_originalText = originalText;
}
public string OriginalText
{
get
{ return _originalText; }
set
{ _originalText = value; }
}
public string ControlID
{
get
{ return _controlID; }
set
{ _controlID = value; }
}
#region IList
public int IndexOf(SpellCheckError item)
{
return _errors.IndexOf(item);
}
public void Insert(int index, SpellCheckError item)
{
_errors.Insert(index, item);
}
public void RemoveAt(int index)
{
_errors.RemoveAt(index);
}
public SpellCheckError this[int index]
{
get
{
return _errors[index];
}
set
{
_errors[index] = value;
}
}
#endregion
#region ICollection
public void Add(SpellCheckError item)
{
_errors.Add(item);
}
public void Clear()
{
_errors.Clear();
}
public bool Contains(SpellCheckError item)
{
return _errors.Contains(item);
}
public void CopyTo(SpellCheckError[] array, int arrayIndex)
{
_errors.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _errors.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(SpellCheckError item)
{
return _errors.Remove(item);
}
#endregion
#region IEnumerable
public IEnumerator<SpellCheckError> GetEnumerator()
{
return _errors.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _errors.GetEnumerator();
}
#endregion
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
throw new NotImplementedException();
}
public void ReadXml(System.Xml.XmlReader reader)
{
reader.ReadStartElement();
_originalText = reader.ReadElementString();
_controlID = reader.ReadElementString();
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(List<SpellCheckError>));
_errors = ser.Deserialize(reader) as List<SpellCheckError>;
}
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteStartElement("SpellingErrorCollection");
writer.WriteElementString("OriginalText", OriginalText);
writer.WriteElementString("ControlID", ControlID);
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(List<SpellCheckError>));
ser.Serialize(writer, _errors);
writer.WriteEndElement();
}
#endregion
}
}