public NetSpellDictWrapper()
        {
            WordDictionary oDict = new NetSpell.SpellChecker.Dictionary.WordDictionary();

            oDict.DictionaryFile = "en-US.dic";
            //load and initialize the dictionary
            oDict.Initialize();
            Spelling = new Spelling();
            Spelling.Dictionary = oDict;
        }
    protected void Page_Init(object sender, EventArgs e)
    {
        string cacheName = "WordDictionary|" + CMSContext.PreferredCultureCode;
        // Get dictionary from cache
        WordDictionary = (WordDictionary)HttpContext.Current.Cache[cacheName];
        if (WordDictionary == null)
        {
            // If not in cache, create new
            WordDictionary = new WordDictionary();
            WordDictionary.EnableUserFile = false;

            // Getting folder for dictionaries
            string folderName = "~/App_Data/Dictionaries";
            folderName = MapPath(folderName);

            string culture = CMSContext.PreferredCultureCode;
            string dictFile = culture + ".dic";
            string dictPath = Path.Combine(folderName, dictFile);
            if (!File.Exists(dictPath))
            {
                // Get default culture
                string defaultCulture = ValidationHelper.GetString(SettingsHelper.AppSettings["CMSDefaultSpellCheckerCulture"], "");
                if (defaultCulture != "")
                {
                    culture = defaultCulture;
                    dictFile = defaultCulture + ".dic";
                    dictPath = Path.Combine(folderName, dictFile);
                }
            }

            if (!File.Exists(dictPath))
            {
                lblError.Text = string.Format(GetString("SpellCheck.DictionaryNotExists"), culture);
                lblError.Visible = true;
                return;
            }

            mDictExists = true;
            WordDictionary.DictionaryFolder = folderName;
            WordDictionary.DictionaryFile = dictFile;

            // Load and initialize the dictionary
            WordDictionary.Initialize();

            // Store the Dictionary in cache
            HttpContext.Current.Cache.Insert(cacheName, WordDictionary, new CacheDependency(Path.Combine(folderName, WordDictionary.DictionaryFile)));
        }
        else
        {
            mDictExists = true;
        }

        // Create spell checker
        SpellChecker = new Spelling();
        SpellChecker.ShowDialog = false;
        SpellChecker.Dictionary = WordDictionary;
        SpellChecker.IgnoreAllCapsWords = false;

        // Adding events
        SpellChecker.MisspelledWord += SpellChecker_MisspelledWord;
        SpellChecker.EndOfText += SpellChecker_EndOfText;
        SpellChecker.DoubledWord += SpellChecker_DoubledWord;
    }
    /// <summary>
    /// Did you mean suggestion.
    /// </summary>
    private static string DidYouMean(string dictionaryFile, string searchQuery, List<string> searchTerms)
    {
        if (searchTerms != null)
        {
            Spelling SpellChecker = null;
            WordDictionary WordDictionary = null;

            #region "Word dictionary"

            // If not in cache, create new
            WordDictionary = new WordDictionary();
            WordDictionary.EnableUserFile = false;

            // Getting folder for dictionaries
            string folderName = HttpContext.Current.Request.MapPath("~/App_Data/Dictionaries/");

            // Check if dictionary file exists
            string fileName = Path.Combine(folderName, dictionaryFile);
            if (!File.Exists(fileName))
            {
                EventLogProvider eventLog = new EventLogProvider();
                eventLog.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "DidYouMean webpart", "Dictionary file not found!");

                return String.Empty;
            }

            WordDictionary.DictionaryFolder = folderName;
            WordDictionary.DictionaryFile = dictionaryFile;

            // Load and initialize the dictionary
            WordDictionary.Initialize();

            #endregion

            #region "SpellCheck"

            // Prepare spellchecker
            SpellChecker = new Spelling();
            SpellChecker.Dictionary = WordDictionary;
            SpellChecker.SuggestionMode = Spelling.SuggestionEnum.NearMiss;

            bool suggest = false;

            // Check all searched terms
            foreach (string term in searchTerms)
            {
                if (term.Length > 2)
                {
                    SpellChecker.Suggest(term);
                    ArrayList al = SpellChecker.Suggestions;

                    // If there are some suggestions
                    if ((al != null) && (al.Count > 0))
                    {
                        suggest = true;

                        // Expression to find term
                        Regex regex = RegexHelper.GetRegex("([\\+\\-\\s\\(]|^)" + term + "([\\s\\)]|$)");

                        // Change term in original search query
                        string suggestion = "$1" + startTag + al[0] + endTag + "$2";
                        searchQuery = regex.Replace(searchQuery, suggestion);
                    }
                }
            }

            #endregion

            if (suggest)
            {
                return searchQuery;
            }
        }

        return String.Empty;
    }
Beispiel #4
0
    public static String decode(String cipher)
    {
        //decodes with the Caesar cipher
        List <object> retList = establishVariables();

        cipher = cipher.ToLower();
        String alphabet = Convert.ToString(retList[0]);
        Dictionary <char, int> characterToInteger = retList[1] as Dictionary <char, int>;
        Dictionary <int, char> integerToCharacter = retList[2] as Dictionary <int, char>;

        char[] cipherText = cipher.ToCharArray(); //so we have a permanent copy
        char[] guessText  = cipher.ToCharArray(); //this will be manipulated
        int    iter       = 0;
        bool   found      = false;                // when to break out of the while loop

        while (iter <= 25)
        {
            // constructs the shift "guess"
            var textList = new List <char>();
            foreach (char elem in guessText)
            {
                if (alphabet.Contains(elem.ToString()))
                {
                    int val = characterToInteger[elem];
                    val = (val + iter) % 26;     //performs shift
                    textList.Add(integerToCharacter[val]);
                }
                else
                {
                    textList.Add(elem);
                }
            }

            String   result = MakeString(textList);
            string[] strRes = result.Split(' ');

            // checks to see if NetSpell is working correctly
            NetSpell.SpellChecker.Dictionary.WordDictionary oDict = new NetSpell.SpellChecker.Dictionary.WordDictionary();
            String path = "..//..//en-US.dic";
            oDict.DictionaryFile = path;
            oDict.Initialize();
            NetSpell.SpellChecker.Spelling oSpell = new NetSpell.SpellChecker.Spelling();
            oSpell.Dictionary = oDict;

            // checks to see if the guess is proper English by at least 50%
            double englishThreshold   = 0.5;
            int    sizeOfGuess        = strRes.Length;
            int    properEnglishCount = 0;
            foreach (String current in strRes)
            {
                if (oSpell.TestWord(current))
                {
                    properEnglishCount++;
                }
                double thresholdCheck = (double)properEnglishCount / (double)sizeOfGuess;
                if (thresholdCheck >= englishThreshold)
                {
                    int shiftValue = 26 - iter;
                    found = true;
                }
            }
            if (found == true)
            {
                return(result);
            }
            //iterates the while
            iter++;
        }

        return("I'm sorry, indecipherable with a shift cipher.");
    }
Beispiel #5
0
        /// <summary>
        /// Loads a language into memory.
        /// </summary>
        private void LoadLanguage(string name)
        {
            try
            {
                // Load the dictionary into memory
                dictionary = new WordDictionary();
                dictionary.DictionaryFolder = DictionaryDirectory;
                dictionary.DictionaryFile = name + ".dic";
                dictionary.Initialize();

                // Load the frequencies and scores into memory
                FileInfo file =
                    new FileInfo(Path.Combine(DictionaryDirectory, name + ".xml"));

                if (!file.Exists)
                {
                    throw new WordplayException("Cannot find freq file: " + file);
                }

                TextReader tr = file.OpenText();
                XmlTextReader xtr = new XmlTextReader(tr);

                while (xtr.Read())
                {
                    if (xtr.LocalName == "letter")
                    {
                        char value = xtr["value"][0];
                        int freq = Int32.Parse(xtr["freq"]);
                        int score = Int32.Parse(xtr["score"]);
                        Register(value, freq, score);
                    }
                }

                xtr.Close();
                tr.Close();
            }
            catch (Exception e)
            {
                // Make an error message
                LogManager.Report(
                    this,
                    new LogEvent(
                        "Language", Severity.Error, null, "Cannot load language: {0}", name));

                // Try to load it
                if (name != "en-US")
                {
                    LoadLanguage("en-US");
                }
                else
                {
                    throw e;
                }
            }
        }
Beispiel #6
0
 public void Setup()
 {
     _dictionary = new WordDictionary();
     _dictionary.DictionaryFolder = @"..\..\..\..\dic";
     _dictionary.Initialize();
 }
        private void btnLookup_Click(object sender, System.EventArgs e)
        {
            // if saved and words > 0
            if (_Words.Count == 0)
            {
                MessageBox.Show(this, "Dictionary contains no words!", "No Words", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (this.Changed)
            {
                if (MessageBox.Show(this, "Dictionary should be saved before phonetic cache is added. \r\n \r\n Save Dictonary Now?",
                    "Save Dictonary", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    this.SaveDictionary();
                }
                else
                {
                    return;
                }
            }

            this.Cursor = Cursors.WaitCursor;

            WordDictionary dict = new WordDictionary();
            dict.DictionaryFile = this.FileName;
            dict.Initialize();

            string[] parts = _Words[(int)numUpDownWord.Value].ToString().Split('/');

            Word word = new Word();
            word.Text = parts[0];
            if (parts.Length > 1) word.AffixKeys = parts[1];
            if (parts.Length > 2) word.PhoneticCode = parts[2];

            ArrayList words = dict.ExpandWord(word);

            this.listAffixWords.Items.Clear();
            foreach (string tempWord in words)
            {
                this.listAffixWords.Items.Add(tempWord);
            }

            this.Cursor = Cursors.Default;
        }
        public void GenerateCache()
        {
            // if saved and words > 0
            if (_Words.Count == 0)
            {
                MessageBox.Show(this, "Dictionary contains no words!", "No Words", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (this.Changed)
            {
                if (MessageBox.Show(this, "Dictionary should be saved before phonetic cache is added. \r\n \r\n Save Dictonary Now?",
                    "Save Dictonary", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    this.SaveDictionary();
                }
                else
                {
                    return;
                }
            }

            this.Cursor = Cursors.WaitCursor;
            // load dictionary
            WordDictionary dict = new WordDictionary();
            dict.DictionaryFile = this.FileName;
            dict.Initialize();
            this.Cursor = Cursors.Default;

            if (dict.PhoneticRules.Count == 0)
            {
                MessageBox.Show(this, "Dictionary does not contain phonetic rules!", "No Phonetic Rules", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            MainForm main = (MainForm)this.MdiParent;

            this.Cursor = Cursors.WaitCursor;
            for (int i = 0; i < _Words.Count; i++)
            {
                if (i % 1000 == 0)
                {
                    main.statusBar.Text = string.Format("Word {0} of {1}", i, _Words.Count);
                    Application.DoEvents();
                }

                string[] parts = _Words[i].ToString().Split('/');
                // part 1 = base word
                string tempWord = parts[0];

                // part 2 = affix keys
                string tempKeys = "";
                if (parts.Length >= 2)
                {
                    tempKeys = parts[1];
                }
                // part 3 = phonetic code
                string tempCode = dict.PhoneticCode(tempWord);

                if (tempCode.Length > 0)
                {
                    _Words[i] = string.Format("{0}/{1}/{2}", tempWord, tempKeys, tempCode);
                }

            }
            main.statusBar.Text = "";

            this.Changed = true;
            this.Cursor = Cursors.Default;
            MessageBox.Show(this, "Cache created successfully", "Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Beispiel #9
0
    public static String decode(String cipherText)
    {
        List <object> retList = establishVariables();

        cipherText = cipherText.ToLower();
        String alphabet = Convert.ToString(retList[0]);
        Dictionary <char, int> characterToInteger = retList[1] as Dictionary <char, int>;
        Dictionary <int, char> integerToCharacter = retList[2] as Dictionary <int, char>;

        for (int i = 1; i <= 26; i++)
        {
            //Iterate through all possible "a" values
            int inverse = calculateInverse(i);
            if (inverse == 0 || i == 13)
            {
                // This value of a has no inverse, skip
            }
            else
            {
                for (int b = 0; b <= 26; b++)
                {
                    //iterate through all possible "b" values
                    var cipherTextGuess = new List <char>();
                    foreach (char letter in cipherText)
                    {
                        if (alphabet.Contains(letter.ToString()))
                        {
                            int value       = characterToInteger[letter];
                            int affineValue = (inverse * (value - b)) % 26; //perform affine calculation
                            if (affineValue < 0)
                            {
                                affineValue = affineValue + 26;
                            }
                            char charValue = integerToCharacter[affineValue];
                            cipherTextGuess.Add(charValue);
                        }
                        else
                        {
                            cipherTextGuess.Add(letter);
                        }
                    }
                    String   guess  = MakeString(cipherTextGuess);
                    string[] strRes = guess.Split(' ');

                    NetSpell.SpellChecker.Dictionary.WordDictionary oDict = new NetSpell.SpellChecker.Dictionary.WordDictionary();
                    String path = "..//..//en-US.dic";
                    oDict.DictionaryFile = path;
                    oDict.Initialize();
                    NetSpell.SpellChecker.Spelling oSpell = new NetSpell.SpellChecker.Spelling();
                    oSpell.Dictionary = oDict;

                    // checks to see if the guess is proper English by at least 60%
                    double englishThreshold   = 0.6;
                    int    sizeOfGuess        = strRes.Length;
                    int    properEnglishCount = 0;

                    foreach (String current in strRes)
                    {
                        if (oSpell.TestWord(current))
                        {
                            properEnglishCount++;
                        }
                        double thresholdCheck = (double)properEnglishCount / (double)sizeOfGuess;
                        if (thresholdCheck >= englishThreshold)
                        {
                            //if threshold met, return guess
                            return(guess);
                        }
                    }
                }
            }
        }
        return("I'm sorry, indecipherable cipher.");
    }