AutoCorrect Text C# Word - c#

I'm trying to use word to automatically correct some text that is not in English the problem is that when i use the SpellCheck function the "Spell and Grammar" dialog box pop-up and waits for users input and i want the text to be corrected automatically. So my question is how do i solve this ?
using System.Collections.Generic;
using Microsoft.Office.Interop.Word;
using Word = Microsoft.Office.Interop.Word;
using TobyCL.ro.toby.StringOperations;
namespace namespace.ro.toby
{
class WordProofing:IProof
{
private readonly Word.Application _wordApp;
private readonly Word.Document _wordDoc;
private static object _oEndOfDoc = "\\endofdoc";
public WordProofing()
{
_wordApp = new Word.Application {Visible = false};
_wordDoc = _wordApp.Documents.Add();
}
public void Close()
{
object obj = Word.WdSaveOptions.wdDoNotSaveChanges;
_wordDoc.Close(ref obj);
_wordApp.Quit(ref obj);
}
#region Implementation of IProof
public string Proof(string proofText)
{
Range wRng = _wordDoc.Bookmarks.get_Item(ref _oEndOfDoc).Range;
wRng.Text = proofText;
_wordDoc.CheckSpelling(IgnoreUppercase: true,AlwaysSuggest:false);
string str = wRng.Text;
wRng.Text = "";
return str;
}
#endregion
}
}
I wrote this code a few days ago and it worked. The problem is that i uninstall proofing tools to run some tests and now i keep getting that dialog so i'm thinking that may i have to set some Word settings or i've changed something in my code without knowing. Any help would be greatly appreciated.
I am using Microsoft Office Word 2010

For whoever might be interested this is the way i managed to solve it, but it really takes a lot of time so any improvements or new ideas are welcomed.
using Microsoft.Office.Interop.Word;
class WordProofing
{
private Application _wordApp;
private readonly Document _wordDoc;
private static object _oEndOfDoc = "\\endofdoc";
public WordProofing()
{
_wordApp = new Application { Visible = false };
_wordDoc = _wordApp.Documents.Add();
}
public void Close()
{
_wordDoc.Close(WdSaveOptions.wdDoNotSaveChanges);
_wordApp.Quit();
}
public string Proof(string proofText)
{
Range wRng = _wordDoc.Bookmarks.get_Item(ref _oEndOfDoc).Range;
wRng.Text = proofText;
ProofreadingErrors spellingErros = wRng.SpellingErrors;
foreach (Range spellingError in spellingErros)
{
SpellingSuggestions spellingSuggestions =
_wordApp.GetSpellingSuggestions(spellingError.Text,IgnoreUppercase:true);
foreach (SpellingSuggestion spellingSuggestion in spellingSuggestions)
{
spellingError.Text = spellingSuggestion.Name;
break;
}
}
string str = wRng.Text;
wRng.Text = "";
return str;
}
}

Which MS Word version are you using?
By default the spell checker will show you the dialog box. To disable the dialog box there are two ways that I know.
1) Using Code, automatically choose the first option from Auto Correct.
It is something like this
AutoCorrect.Entries.Add Name:="AdSAD", Value:="Assad"
2) Or use the menu option. Please refer to this link.
Topic: Automatically correct spelling with words from the main dictionary
Link: http://office.microsoft.com/en-us/word-help/automatically-correct-spelling-with-words-from-the-main-dictionary-HA010174790.aspx
Do let me know if this is not what you want?

Related

Visual studio C# VSTO: Refactoring

Coming from Visual basic, I kind of miss the With statement that is lacking in C#, I'm looking for ways to refactor the code so it's not so crowded.
I have the following code:
Globals.Ribbons.RibbonMain.chkCalculation.Checked = (Globals.ThisAddIn.Application.Calculation == Microsoft.Office.Interop.Excel.XlCalculation.xlCalculationAutomatic);
Globals.Ribbons.RibbonMain.chkScreenUpdating.Checked = Globals.ThisAddIn.Application.ScreenUpdating;
Globals.Ribbons.RibbonMain.chkEvents.Checked = Globals.ThisAddIn.Application.EnableEvents;
Globals.Ribbons.RibbonMain.chkDisplayAlerts.Checked = Globals.ThisAddIn.Application.DisplayAlerts;
How can I extract the common denominators to trim down the code to make it more legible?
What I thought is creating the 2 variables below, but i don't know the variable type I should use. Is there somewhere I could look for the variable type?
variableType R = Globals.Ribbons.RibbonMain
variableType A = Globals.ThisAddIn.Application
var should work fine, let the compiler figure out the type:
var R = Globals.Ribbons.RibbonMain;
var A = Globals.ThisAddIn.Application;
R.chkCalculation.Checked = (A.Calculation == Microsoft.Office.Interop.Excel.XlCalculation.xlCalculationAutomatic);
R.chkScreenUpdating.Checked = A.ScreenUpdating;
R.chkEvents.Checked = A.EnableEvents;
R.chkDisplayAlerts.Checked = A.DisplayAlerts;
Thank you #madreflection for sharing the knowledge.
As I'm using the 2 variables in multiple places, I extracted them as Static variables.
using EXCEL = Microsoft.Office.Interop.Excel;
internal class clsMacros
{
//GLOBAL VARIABLES
static RibbonMain RIBBON = Globals.Ribbons.RibbonMain;
static EXCEL.Application APPLICATION = Globals.ThisAddIn.Application;
public static void GetStatus()
{
RIBBON.chkCalculation.Checked = (APPLICATION.Calculation == EXCEL.XlCalculation.xlCalculationAutomatic);
RIBBON.chkScreenUpdating.Checked = APPLICATION.ScreenUpdating;
RIBBON.chkEvents.Checked = APPLICATION.EnableEvents;
RIBBON.chkDisplayAlerts.Checked = APPLICATION.DisplayAlerts;
}
}

Using RichEditDocumentServer to change from rtf to text

I am trying to convert RTF to plain text in a c# program. I figured out how to do it but it isn't very clean. It uses RichTextBox which I'm not a huge fan of:
using (System.Windows.Forms.RichTextBox rtfBox = new System.Windows.Forms.RichTextBox())
{
rtfBox.Rtf = cTrans.NoteDescription;
tItem.ProcedureShortDescription = rtfBox.Text;
}
I was wondering if there is a better way to go about accomplishing this. Perhaps using RichEditDocumentServer? I could not find a ton of info on it though and was wondering if I could get some help on it. My thought was:
var documentServer = new RichEditDocumentServer();
documentServer.Document.RtfText = cTrans.NoteDescription;
tItem.ProcedureShortDescription = documentServer.Document.Text;
I did some more digging and this works. I figured I'd just post this as I couldn't see it answered anywhere on the site. I'm not sure if that is proper protocol.
I ended up putting it in a helper class so it can be called if needed again:
namespace ABELSoft.Dental.Interface.Helper
{
public class RtfToText
{
public static string convert(string rtfText)
{
string _text;
var documentServer = new RichEditDocumentServer();
documentServer.Document.RtfText = rtfText;
_text = documentServer.Document.Text;
return _text;
}
}
}
This is how I called it:
tItem.ProcedureShortDescription = RtfToText.convert(cTrans.NoteDescription);

How to complete aspx connection string from text file

I must use a text file "db.txt" which inherits the names of the Server and Database to make my connection string complete.
db.txt looks like this:
<Anfang>
SERVER==dbServer\SQLEXPRESS
DATABASE==studentweb
<Ende>
The connection string:
string constr = ConfigurationManager.ConnectionStrings["DRIVER={SQL Server}; SERVER=SERVER DATABASE=DB UID=;PWD=;LANGUAGE=Deutsch;Trusted_Connection=YES"].ConnectionString;
Unfortunatly we are only allowed to use Classic ASPX.net (C# 2.0) and not the web.config.
I've searched a lot, but found nothing close to help me.
Somebody got an Idea how to make it work?
Here is something to get you going.
In a nutshell, I put the DBInfo file through a method that reads the file line by line. When I see the line <anfang> I know the next line will be important, and when I see the line <ende> I know it's the end, so I need to grab everything in between. Hence why I came up with the booleans areWeThereYet and isItDoneYet which I use to start and stop gathering data from the file.
In this snippet I use a Dictionary<string, string> to store and return the values but, you could use something different. At first I was going to create a custom class that would hold all the DB information but, since this is a school assignment, we'll go step by step and start by using what's already available.
using System;
using System.Collections.Generic;
namespace _41167195
{
class Program
{
static void Main(string[] args)
{
string pathToDBINfoFile = #"M:\StackOverflowQuestionsAndAnswers\41167195\41167195\sample\DBInfo.txt";//the path to the file holding the info
Dictionary<string, string> connStringValues = DoIt(pathToDBINfoFile);//Get the values from the file using a method that returns a dictionary
string serverValue = connStringValues["SERVER"];//just for you to see what the results are
string dbValue = connStringValues["DATABASE"];//just for you to see what the results are
//Now you can adjust the line below using the stuff you got from above.
//string constr = ConfigurationManager.ConnectionStrings["DRIVER={SQL Server}; SERVER=SERVER DATABASE=DB UID=;PWD=;LANGUAGE=Deutsch;Trusted_Connection=YES"].ConnectionString;
}
private static Dictionary<string, string> DoIt(string incomingDBInfoPath)
{
Dictionary<string, string> retVal = new Dictionary<string, string>();//initialize a dictionary, this will be our return value
using (System.IO.StreamReader sr = new System.IO.StreamReader(incomingDBInfoPath))
{
string currentLine = string.Empty;
bool areWeThereYet = false;
bool isItDoneYet = false;
while ((currentLine = sr.ReadLine()) != null)//while there is something to read
{
if (currentLine.ToLower() == "<anfang>")
{
areWeThereYet = true;
continue;//force the while to go into the next iteration
}
else if (currentLine.ToLower() == "<ende>")
{
isItDoneYet = true;
}
if (areWeThereYet && !isItDoneYet)
{
string[] bleh = currentLine.Split(new string[] { "==" }, StringSplitOptions.RemoveEmptyEntries);
retVal.Add(bleh[0], bleh[1]);//add the value to the dictionary
}
else if (isItDoneYet)
{
break;//we are done, get out of here
}
else
{
continue;//we don't need this line
}
}
}
return retVal;
}
}
}

C# - AddStore not working properly in Outlook

I have been attempting this all morning (VS2K10, OL2K7, .NET 3.5) and my PSTs never attach. I've modified the path to include escaped slashes, no dice. I occasionally see the PST get added then disappear when I hit the command bar button for which I am trying to program.
Here is a snip of my code:
void b_removedPSTs_Click(Office.CommandBarButton Ctrl, ref bool CancelDefault)
{
string PSTToAdd = dd_removed_PSTs.Text;
foreach (PSTWithPath p in removedPSTs)
{
if (PSTToAdd == p.name)
{
olApp.Session.AddStore(#p.path);
}
}
UpdateRemovedList();
}
PSTWithPath is a custom class I've created as follows:
public class PSTWithPath
{
public string name;
public string path;
public Outlook.MAPIFolder mapifolder;
public PSTWithPath(string PSTName, string PSTPath, Outlook.MAPIFolder PSTMAPIFolder)
{
name = PSTName;
path = PSTPath;
mapifolder = PSTMAPIFolder;
}
Advice would be greatly appreciated.
Thanks,
Larry
I solved the issue. It seems that the function was being case sensitive. Not sure if this was a MS or Novell thing, but it's working now.

Replace MergeFields in a Word 2003 document and keep style

I've been trying to create a library to replace the MergeFields on a Word 2003 document, everything works fine, except that I lose the style applied to the field when I replace it, is there a way to keep it?
This is the code I'm using to replace the fields:
private void FillFields2003(string template, Dictionary<string, string> values)
{
object missing = Missing.Value;
var application = new ApplicationClass();
var document = new Microsoft.Office.Interop.Word.Document();
try
{
// Open the file
foreach (Field mergeField in document.Fields)
{
if (mergeField.Type == WdFieldType.wdFieldMergeField)
{
string fieldText = mergeField.Code.Text;
string fieldName = Extensions.GetFieldName(fieldText);
if (values.ContainsKey(fieldName))
{
mergeField.Select();
application.Selection.TypeText(values[fieldName]);
}
}
}
document.Save();
}
finally
{
// Release resources
}
}
I tried using the CopyFormat and PasteFormat methods in the selection, also using the get_style and set_style but to no exent.
Instead of using TypeText over the top of your selection use the the Result property of the Field:
if (values.ContainsKey(fieldName))
{
mergeField.Result = (values[fieldName]);
}
This will ensure any formatting in the field is retained.

Categories