C# read from a Word document - ms-word

I'm trying to read from a Word document and I want the computer to tell me what is written in document not to write itself in other place. So when I say the keyword "word" my program should open a dialog menu and let me to select a word file and tell me what is inside. The other keywords work. So here's my code and also my error.
case "word":
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
object readFromPath = null;
Document doc = app.Documents.Open(ref readFromPath);
foreach (Paragraph objParagraph in doc.Paragraphs)
ss.SpeakAsync(objParagraph.Range.Text.Trim());
((_Document)doc).Close();
((_Application)app).Quit();
}
And my error is enter image description here

Application.Documents.Open takes the full path and filename.
The path must end with \ and prefix the string with # (or leave out the # and double the backslashes \ as one backslash is considered to be an escape character)
object readFromPath = #"C:\Users\N.Horatiu\Desktop\s.docx"
Document doc = app.Documents.Open(ref readFromPath);

Related

unnamed/slim snippets in vscode

I'm using vscode to edit latex (with the latex workshop plugin), and
I recently started creating my own snippets and really like the feature. However, I find the syntax a bit heavy for creating "small" snippets that just abbreviate frequent sequences of words. In particular, I find it cumbersome to have to give a 'name' to each snippet.
Is there a mechanism for "slim" snippets/aliases, that would e.g. take as input a file where each snippet is one line -- the first word being the abbreviation and the rest what is abbreviated?
You have a couple of options. One is to write an extension that could do this - I'll show code that works like an extension that'll work - it looks complicated but use is pretty simple.
Second, you can come close using the Hyper Snips extension where your snippet file (say latex.hsnips) could like like this:
snippet dategreeting "Gives you the current date!"
Hello from your hsnip on ``rv = new Date().toDateString()``!
endsnippet
snippet // "Fraction simple" A
\frac{$1}{$2}$0
endsnippet
snippet stte A
some text to expand
endsnippet
The descriptions in "" are not necessary and I eliminated it in the last snippet. The A flag will immediately insert your replacement text, without it you would Tab to insert the replacement text. As the examples here show you can use javascript within a snippet if you want.
The gif doesn't show it well bit here is a demo of auto-expansion with Hyper Snips:
Alternatively, download the extension macro-commander. It allows you to use vscode extension commands in a macro within your settings. This macro would go into your settings.json file:
"macros": {
"slimSnippetsInsertion" : [
{
"javascript": [
"const editor = vscode.window.activeTextEditor;",
"const document = editor.document;",
"const we = new vscode.WorkspaceEdit();",
"const cursorPosition = editor.selection.active;", // use whether an actual selection or not, returns a Position
"let keyWordRange = document.getWordRangeAtPosition(cursorPosition);", // returns a Range of start/end Positions or undefined
"if (keyWordRange === undefined) {",
"await window.showInformationMessage(`cursor must be in or immediately after word to be replaced`);",
"return;",
"}",
"let wordAtCursor = document.getText(keyWordRange);", // this is the key word to find in slimSnippets.txt
"const thisWorkspace = vscode.workspace.workspaceFolders[0].uri.toString();",
// file:///c:/Users/Mark/OneDrive/Test Bed
"const snippetFileContent = await vscode.workspace.fs.readFile(vscode.Uri.parse(`${thisWorkspace}/.vscode/slimSnippets.txt`));",
"const snippets = snippetFileContent.toString();",
// ignore leading spaces/tabs before keys
// using a named capturing group for the replacement text
"const regex = new RegExp(`\\r?(?<=\\n|^)[\\t ]*(?<key>${wordAtCursor})[\\t ]+?(?<replacementText>.*?)(?=\\r?\\n|$)`);",
"let found = snippets.match(regex);", // returns null if no matches
// matched a key but only spaces as replacement text, so do nothing and exit
"if (found && found.groups.replacementText.trimStart().length === 0) {",
"await window.showInformationMessage(`replacement text is only spaces, not replacing`);",
"return;",
"}",
"if (found) {", // found at least a matching key
"if (found.groups.replacementText) {", // found non-space replacement text
// replace `\n` and `\t` with unicode values for newline and tab
"let replace = found.groups.replacementText.replace(/\\\\n/g, '\\u000A').replace(/\\\\t/g, '\\u0009');",
"let snippet = new vscode.SnippetString(replace)",
"if (editor.selections.length === 1) editor.insertSnippet(snippet, keyWordRange);", // if zero or one selection"
// if multiple selections, uses first key and replacement text"
"else editor.insertSnippet(snippet);",
"}",
"else await window.showInformationMessage(`matching key found but with no replacement text in slimSnippets.txt`);",
"}",
"else await window.showInformationMessage(`no matching key found in slimSnippets.txt`);",
]
}
You can see where I made it to read a simpleSnippets.txt file located in the .vscode folder in the workspace - but you can change the location as long as you alter the path info in the command: vscode.workspace.fs.readFile above.
The slimSnippets.txt file is just a simple text file where the first word in each line is the key and the rest of the line is the replacement.
howdy1 $1 first $2 sentence with tabstops
howdy1 this won't be used, duplicate key above
howdy2 second sentence with variable $TM_FILENAME
key3 videos 111111 // one space necessary between key and replacement text
// it will be removed, others retained
key1 222222
stte some text to expand
mt2e more text to expand
[replacement text can have placeholders, tabstops and choices just like regular snippets]
[join multiple-lines snippets into one string with newlines as below]
[some text\nsome more text] [\t can be used for tabs]
key5 line 1\n\tline 2\n\t\tline 3
Keys are single words and if there is no replacement text (or there are only spaces in the file after a key) nothing will happen - the key will not be replaced.
The text actually inserted can be plain text or use vscode's snippet format - see the sample text file above.
The cursor must be immediately after the word or in the word and the word can be selected or not. It must be a word in the regex sense - not continuous text adjoining the word before or after it - just a standalone word, it can be anywhere on the line.
If you have duplicate keys, the first will be used. There can be empty line spaces between key/replacement lines or not.
You will not get intellisense for the keys. I may work on that.
Finally, you will need a keybinding to trigger this macro (in keybindings.json):
{
"key": "ctrl+;", // whatever keybinding you wish
"command": "macros.slimSnippetsInsertion"
},

How to cut a string from the end in UIPATH

I have this string: "C:\Procesos\rrhh\CorteDocumentos\Cortados\10001662-1_20060301_29_1_20190301.pdf" and im trying to get this part : "20190301". The problem is the lenght is not always the same. It would be:
"9001662-1_20060301_4_1_20190301".
I've tried this: item.ToString.Substring(66,8), but it doesn't work sometimes.
What can I do?.
This is a code example of what I said in my comment.
Sub Main()
Dim strFileName As String = ""
Dim di As New DirectoryInfo("C:\Users\Maniac\Desktop\test")
Dim aryFi As FileInfo() = di.GetFiles("*.pdf")
Dim fi As FileInfo
For Each fi In aryFi
Dim arrname() As String
arrname = Split(Path.GetFileNameWithoutExtension(fi.Name), "_")
strFileName = arrname(arrname.Count - 1)
Console.WriteLine(strFileName)
Next
End Sub
You could achieve this using a simple regular expressions, which has the added benefit of including pattern validation.
If you need to get exactly eight numbers from the end of file name (and after an underscore), you can use this pattern:
_(\d{8})\.pdf
And then this VB.NET line:
Regex.Match(fileName, "_(\d{8})\.pdf").Groups(1).Value
It's important to mention that Regex is by default case sensitive, so to prevent from being in a situations where "pdf" is matched and "PDF" is not, the patter can be adjusted like this:
(?i)_(\d{8})\.pdf
You can than use it directly in any expression window:
PS: You should also ensure that System.Text.RegularExpressions reference is in the Imports:
You can achieve it by this way as well :)
Path.GetFileNameWithoutExtension(Str1).Split("_"c).Last
Path.GetFileNameWithoutExtension
Returns the file name of the specified path string without the extension.
so with your String it will return to you - 10001662-1_20060301_29_1_20190301
then Split above String i.e. 10001662-1_20060301_29_1_20190301 based on _ and will return an array of string.
Last
It will return you the last element of an array returned by Split..
Regards..!!
AKsh

Matlab: check if string has a correct file path syntax

I want to check if a string represents a full path of a file, like this:
p = 'C:\my\custom\path.txt'
The file does not exist, so commands like isdir and exist return false to me, but still the format of the string represents a valid path for my operating system, while the following one does not because it has an invalid character for the file name:
p = 'C:\my\custom\:path.txt'
So I'd like to know how to check if a string represents a valid file path without needing that the file actually exists.
You might want to use the regexp function with a regular expression to match Windows paths.
if isempty(regexp(p, '^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$', 'once'))
// This is not a path
end
You can also let Matlab try for you:
if ~isdir(p)
[status, msg] = mkdir(p);
if status
isdir(p)
rmdir(p)
else
error(msg)
end
end
First, you check if the folder exists, if not you try to create it. If you succeed then you delete it, and if not you throw an error.
This is not recommended for checking many strings but has the advantage of being cross-platform.
function bool = isLegalPath(str)
bool = true;
try
java.io.File(str).toPath;
catch
bool = false;
end
end

Search removing comma using Entity Framework

I want to search a text that contains comma in database, but, there is not comma in the reference.
For example. In database I have the following value:
"Development of computer programs, including electronic games"
So, I try to search the data using the following string as reference:
"development of computer programs including electronic games"
NOTE that the only difference is that in database I have a comma in the text, but, in my reference for search, I have not.
Here is my code:
public async Task<ActionResult>Index(string nomeServico)
{
using (MyDB db = new MyDB())
{
// 1st We receive the following string:"development-of-computer-programs-including-electronic-games"
// but we remove all "-" characters
string serNome = nomeServico.RemoveCaractere("-", " ");
// we search the service that contains (in the SerName field) the value equal to the parameter of the Action.
Servicos servico = db.Servicos.FirstOrDefault(c => c.SerNome.ToLower().Equals(serNome, StringComparison.OrdinalIgnoreCase));
}
}
The problem is that, in the database, the data contains comma, and in the search value, don't.
In you code you are replacing "-" with "" and that too in your search string. But as per your requirement you need to change "," with "" for your DB entry.
Try doing something like this:
string serNome = nomeServico.ToLower();
Servicos servico = db.Servicos.FirstOrDefault(c => c.SerNome.Replace(",","").ToLower() == serNome);

How to retrieve the value of an Input field and use it to modify a placeholder in a LibreOffice Basic macro?

I've spent two days on this and I'm still not able to figure it out 8-)
I have a LibreOffice Writer document with some Placeholders (Insert -> Fields -> More Fields -> Functions -> Placeholder -> Image) and Input fields (Insert -> Fields -> More Fieds -> Functions -> Input field) and I need to retrieve the value of an Input field and use it to replace a specified Placeholder in the same document.
To be more precise. I have an Input field where I enter for example 123
and somewhere in the document is a button, which triggers a macro, and this macro should:
retrieve the current value of the specified (named?) Input field ("123"),
"replace" a specified (named?) Placeholder with an image loaded from http://domain.tld/image/123.png
Is this somehow possible? Would be great, because I'm trying to to insert externally generated barcodes into my document...
These are both "Text fields", and some information and macro examples are in Andrew Pitonyak's book OpenOffice Macros Explained (available as a free pdf download from http://www.pitonyak.org/oo.php). The wiki page also has some good background.
Form controls (from the toolbar "Form controls") are named, so they have an advantage when working with macros. Text fields, however - the kind you have in your document - are not named, so you have to cycle through all the fields in a document, or highlight a particular run of text and cycle through the field within the highlighted area to find the one you are after. The Pitonyak document has examples of both methods.
Assuming the document has only one input field, this StarBasic code will print its current value:
Sub DisplayFields
Dim oEnum As Object
Dim oField As Object
oEnum = ThisComponent.getTextFields().createEnumeration()
Do While oEnum.hasMoreElements()
oField = oEnum.nextElement()
If oField.getPresentation(True) = "Input field" Then
Print "Input field contents: " & oField.getPresentation(False)
Exit Do
End If
Loop
End Sub
As far as I can tell, there is no API to replace a placeholder with its designated content. There might be a way with the dispatcher - the list of dispatch commands tantalizingly includes "FieldDialog" - but I wasn't able to find any documentation or examples.
I think what you'd have to do is find the field, put your cursor there, insert the image, then delete the placeholder field. Some more StarBasic code (again, assuming there's only a single placeholder field in the document):
Sub InsertImage
Dim oEnum As Object
Dim oField As Object
Dim oAnchor As Object
Dim oText As Object
Dim oCursor As Object
Dim FileName As String
Dim FileURL As String
Dim objTextGraphicObject As Object
oEnum = ThisComponent.getTextFields().createEnumeration()
Do While oEnum.hasMoreElements()
oField = oEnum.nextElement()
If oField.getPresentation(True) = "Placeholder" Then
oAnchor = oField.Anchor
oText = oAnchor.getText()
oCursor = oText.createTextCursorByRange(oAnchor.getEnd)
FileName = "C:\after zoo.JPG"
FileURL = convertToURL(FileName)
objTextGraphicObject = ThisComponent.createInstance("com.sun.star.text.TextGraphicObject")
REM Optional to set the size
' Dim objSize as New com.sun.star.awt.Size
' objSize.Width = 3530
' objSize.Height = 1550
' objTextGraphicObject.setSize(objSize)
objTextGraphicObject.GraphicURL = FileURL
oText.insertTextContent(oCursor.Start, objTextGraphicObject, false)
oField.dispose()
Exit Do
End If
Loop
End Sub