How get paragraph FontName with Docx dll? - docx

I am using Docx dll to get paragraph information but not able to get paragraph format(font size-fontName-FontColor)
Here is my code for that:
using (DocX document = DocX.Load("Test.docx"))
{
if (document.Paragraphs.Count() > 0)
{
for (int i = 0; i < document.Paragraphs.Count; i++)
{
Novacode.Paragraph pg = document.Paragraphs[i];
Console.WriteLine("Text:" + pg.Text +" Alignment:" + pg.Alignment + " Direction:" + pg.Direction);
//how get FontName
}
}
}

You can do this:
pg.magictext[i].formatting.fontfamily.name.tostring()

Related

CSS style quotes and their content [duplicate]

This is a follow up question to my question about Setting the CSS of code if it contains a reserved word.
What I am trying to do: If some code has quotes or double quotes, I want to set the color of the font to red and bold. Ex. System.out.println( "Hello world" ); should set "Hello world" to red.
What's wrong: Despite my best efforts, I can't seem to get my control statements to work properly (at least I think that's the issue). It sets the first double quote and beyond to red, but when I tell it to stop when a word equals anyword" or anyword' it sets the rest of the code in the block to red.
HTML
<html>
<body>
<code id="java">
public static void main(String[] args)<br>
{
<pre> int i = 120; </pre><br>
<pre> // Displays a message in the console </pre>
<pre> // This is a test </pre>
<pre> System.out.println( "Hello Big World!" );</pre>
}
</code>
</body>
</html>
CSS
.quotes
{
font-weight: bold;
color: #E01B1B;
}
jQuery
$(document).ready(function() {
var code = $("#java").html(); // Get the code
var split = code.split(' '); // Split up each element
var chkQ = 0; // Check for quotes
var chkC = 0; // Check until end of comment line
// Set the CSS of reserved words, digits, strings, and comments
for (var j = 0; j < split.length; j++) {
// Check to see if chkQ is set to true
if (chkQ == 1) {
// If the element matches (anyword") or (anyword'), then set
// flag to false and continue checking the rest of the code.
// Else, continue setting the CSS to .quotes
if (split[j].match(/."/) || split[j].match(/.'/)) {
split[j] = '<span class="quotes">' + split[j] + '</span>';
chkQ = 0;
} else {
split[j] = '<span class="quotes">' + split[j] + '</span>';
}
}
...
} else if (chkQ == 0 && chkC == 0) {
...
// If the element matches a ("anyword) or ('anyword)...
} else if (split[j].match(/"./) || split[j].match(/'./)) {
split[j] = '<span class="quotes">' + split[j] + '</span>';
chkQ = 1;
} ...
}
}
// Join all the split up elements back together!
$("#java").html(split.join(' '));
});
Question: Is this just simply an issue with my regex, control blocks or something completely different?
Why split the string up when you can perform a simple global regex find and replace:
<script type="text/javascript">
$(document).ready(function(){
//cache the element
el = $('#java');
//get the HTML contained within the cached element
code = el.html();
//return the code having executed the replace method, regex explained:
/*
([^\w]{1}) -> look for a single character that is not an alpha character
(["']) -> then look for either a single quote or double quote
(.*?) -> then look any character, but don't be greedy
(\2) -> then look for what was found in the second group - " or '
([^\w]{1}) -> and finally look for a single character that is not an alpha character
*/
code = code.replace(/([^\w]{1})(["'])(.*?)(\2)([^\w]{1})/gm,
//execute an anonymous callback, passing in the result for every match found
function(match, $1, $2, $3, $4, $5, offset, original) {
//construct the replacement
str = $1 + '<span class="quotes">' + $2 + $3 + $4 + '</span>' + $5;
//return the replacement
return str;
});
//replace the existing HTML within the cached element
el.html(code);
});
</script>
Edit: Just updated it to accommodate nested quotes.
I don't know all your requirements, but it seems that your single quote could get a bit complicated.
I've set up a demonstration that works (updated link to include nested quotes).
I do not guarantee it is bug free. It does the replacement in two stages, first for double quotes, then for single, trying to weed out potential apostrophes (note in the code below the filters for apostrophes are based off common following letters--not sure how many you might practically need, if any).
Javascript
$(document).ready(function() {
var code = $("#java").html(); // Get the code
var split = code.split('\"'); // Split up each element at the "
// Set the CSS of reserved words, digits, strings, and comments
for (var j = 0; j < split.length - 1; j++) {
if (j%2 == 0) { //if first, add beginning
split[j] = split[j] + '<span class="quotes">"';
} else {//if second, add ending
split[j] = split[j] + '"</span>';
}
}
// Join all the split up elements back together!
$("#java").html(split.join(""));
code = $("#java").html(); // Get the code
split = code.split('\''); // Split up each element at the '
var openQ = 1;
var sub1;
var sub2;
for (var j = 0; j < split.length - 1; j++) {
sub1 = split[j+1].substr(0,2); //checking for a contraction of 's
sub2 = split[j+1].substr(0,3); //checking for a contraction of 'll
if(sub1 != "s " && sub2 != "ll ") {
if (openQ) { //if first, add beginning
split[j] = split[j] + '<span class="quotes">\'';
openQ = 0;
} else {//if second, add ending
split[j] = split[j] + '\'</span>';
openQ = 1;
}
}
else {//add apostrophe back
split[j] = split[j] + '\'';
}
}
$("#java").html(split.join(""));
});
Here's a pure JavaScript version:
id= id of element with quotes
classid= class to add to the quotes
function quotes(id,classid) {
var code = document.getElementById(id).innerHTML;
var split = code.split('\"');
for (var j = 0; j < split.length - 1; j++) {
if (j%2 == 0) {
split[j] = split[j] + '<span class='+classid+'>"';
} else {
split[j] = split[j] + '"</span>';
}
}
document.getElementById(id).innerHTML = split.join("");
code = document.getElementById(id).innerHTML;
split = code.split('\'');
var openQ = 1;
var sub1;
var sub2;
for (var j = 0; j < split.length - 1; j++) {
sub1 = split[j+1].substr(0,2);
sub2 = split[j+1].substr(0,3);
if(sub1 != "s " && sub2 != "ll ") {
if (openQ) {
split[j] = split[j] + '<span class='+classid+'>\'';
openQ = 0;
} else {
split[j] = split[j] + '\'</span>';
openQ = 1;
}
}
else {
split[j] = split[j] + '\'';
}
}
document.getElementById(id).innerHTML = split.join("");
}
String.prototype.Text2Html = function (){
var div = document.createElement('div');
div.appendChild(document.createTextNode(this))
encoded=div.innerHTML;
div.remove();
return encoded
}
String.prototype.colorTheQuotes = function(){
var re = /(?:<span style=|)(?:(?:"[^"]*")|(?:'[^']*'))/gm,
text = this.Text2Html(),
output = text,
tour = 0,
slen = 27;
while ((match = re.exec(text)) != null) {
if(match[0].startsWith("<span")) continue
output=output.slice(0,match.index+tour*slen)+'<span class="quote">'+output.slice(match.index+tour*slen,match.index+match[0].length+tour*slen)+"</span>"+output.slice(match.index+match[0].length+tour*slen);tour++
}
return output
}
element=document.getElementById("color")
document.addEventListener("readystatechange",(e)=>{
element.innerHTML=element.innerText.colorTheQuotes();
})
.quote{
color: red;
}
<span>System.out.println( "Hello world" );</span><br>
<span id="color">System.out.println( "Hello world" );</span>

TypeError: window.tinyMCE.execInstanceCommand is not a function

I can't add any shortcode in my wordpress editor. it shows - Uncaught TypeError: Object [object Object] has no method 'execInstanceCommand' . plesase help me to solve this.
the code(tinymce.js)
function init() {
tinyMCEPopup.resizeToInnerSize();
}
function getCheckedValue(radioObj) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
}
function tjshortcodesubmit() {
var tagtext;
var tj_shortcode = document.getElementById('tjshortcode_panel');
// who is active ?
if (tj_shortcode.className.indexOf('current') != -1) {
var tj_shortcodeid = document.getElementById('tjshortcode_tag').value;
switch(tj_shortcodeid)
{
case 0:
tinyMCEPopup.close();
break;
case "button":
tagtext = "["+ tj_shortcodeid + " url=\"#\" style=\"white\" size=\"small\"] Button text [/" + tj_shortcodeid + "]";
break;
case "alert":
tagtext = "["+ tj_shortcodeid + " style=\"white\"] Alert text [/" + tj_shortcodeid + "]";
break;
case "toggle":
tagtext = "["+ tj_shortcodeid + " title=\"Title goes here\"] Content here [/" + tj_shortcodeid + "]";
break;
case "tabs":
tagtext="["+tj_shortcodeid + " tab1=\"Tab 1 Title\" tab2=\"Tab 2 Title\" tab3=\"Tab 3 Title\"] [tab]Insert tab 1 content here[/tab] [tab]Insert tab 2 content here[/tab] [tab]Insert tab 3 content here[/tab] [/" + tj_shortcodeid + "]";
break;
default:
tagtext="["+tj_shortcodeid + "] Insert you content here [/" + tj_shortcodeid + "]";
}
}
if(window.tinyMCE) {
//TODO: For QTranslate we should use here 'qtrans_textarea_content' instead 'content'
window.tinyMCE.execInstanceCommand('content', 'mceInsertContent', false, tagtext);
//Peforms a clean up of the current editor HTML.
//tinyMCEPopup.editor.execCommand('mceCleanup');
//Repaints the editor. Sometimes the browser has graphic glitches.
tinyMCEPopup.editor.execCommand('mceRepaint');
tinyMCEPopup.close();
}
return;
}
I had the same problem. Change your code to this and it should work:
if(window.tinyMCE) {
/* get the TinyMCE version to account for API diffs */
var tmce_ver=window.tinyMCE.majorVersion;
if (tmce_ver>="4") {
window.tinyMCE.execCommand('mceInsertContent', false, tagtext);
} else {
window.tinyMCE.execInstanceCommand('content', 'mceInsertContent', false, tagtext);
}
tinyMCEPopup.editor.execCommand('mceRepaint');
tinyMCEPopup.close();
}
return;
}
Note: since .js files are cached, you'll need to do a hard refresh to get this to work. If you are still seeing the same console errors, that would likely be the cause.
Scott B's answer is partially innacurate.
The point of execInstanceCommand in TinyMCE version 3 was to execute a command on a specific instance of TinyMCE in the document. Calling execCommand without specifying an instance will either use the focused instance or the first instance in the document, if none is currently focused.
To specify the instance you would like to execute your command on in TinyMCE version 4, call execCommand on the desired editor instance like so:
tinyMCE.get(editorId).execCommand(...);

calender control in asp.net opening in another form

I am using calender control in asp.net 2.0, and after clicking on button its opening in another form. I am using the following JS code to open the window:
function openwindow(txtvalueID) {
leftVal = (3500 - screen.width) / 2;
topVal = (800 - screen.height) / 2;
if (txtvalueID == 'ctl00$CPH1$txtHireDate') {
var txtid = '<%=txtHireDate.ClientID %>';
}
else {
var txtid = '<%=txtTermDate.ClientID %>';
}
var frmid = '<%=Page.Form.ClientID %>';
var qs = "formname=" + frmid + "." + txtid;
window.open('/Calender.aspx?' + qs, 'calendar_window', 'fullscreen=no,toolbar=no,status=no,menubar=no,scrollbars=no,resizable=no,directories=no,location=no,width=230,height=240,left=' + leftVal + ',top=' + topVal + ',screenX=400,screenY=400')
}
function isNumeric(keyCode) {
return ((keyCode >= 48 && keyCode <= 57) || keyCode == 8)
}
In this line txtvalueID == 'ctl00$CPH1$txtHireDate' is wrong. I am referring to the control id, but the control id keeps changing.. Why?
You shouldn't explicitly refer to the ID directly, but instead do:
if (txtvalueID == '<%=txtHireDate.ClientID %>') {
In the first if line, that will help with the ID changing issue.
HTH.

webdriver: get element's xpath?

Is it possible to return a WebElement's xpath?
Not directly from WebDriver, but you can fake it if you really need to:
public String getElementXPath(WebDriver driver, WebElement element) {
return (String)((JavascriptExecutor)driver).executeScript("gPt=function(c){if(c.id!==''){return'id(\"'+c.id+'\")'}if(c===document.body){return c.tagName}var a=0;var e=c.parentNode.childNodes;for(var b=0;b<e.length;b++){var d=e[b];if(d===c){return gPt(c.parentNode)+'/'+c.tagName+'['+(a+1)+']'}if(d.nodeType===1&&d.tagName===c.tagName){a++}}};return gPt(arguments[0]).toLowerCase();", element);
}
The Javascript is from this post, minified to fit on one line. It may not be perfect, but could give you an idea of where to go. Most drivers implement the JavascriptExecutor interface and have the capability of executing Javascript in the browser. executeScript can return any primitive JavaScript type, an HTML element, or non-nested list of any of the preceding.
Not all browsers support xpath the same way, so be careful if using these xpaths to select elements. Also, not all browsers have native xpath support (cough IE cough), so it was faked in that case.
If WebElement was found by By.xpath:
on Java:
public static String GetWebElementXpath(WebElement El) throws AssertionError{
if ((El instanceof WebElement)){
Object o = El;
String text = o.toString();
/* text is smth like this
[[FirefoxDriver: firefox on WINDOWS (9170d4a5-1554-4018-adac-f3f6385370c0)] -> xpath: //div[contains(#class,'forum-topic-preview')]//div[contains(#class,'small-human')]]
*/
text = text.substring( text.indexOf("xpath: ")+7,text.length()-1);
return text;
}else { Assert.fail("Argument is not an WebElement, his actual class is:"+El.getClass()); }
return "";
}
Both of the above answers suffer from the same problem. By returning the completed XPath with the .toLowerCase() function called, any XPath containing an id with a capital letter will not work.
Example: //div[#id="deviceblock-1111"] will not work on tag <div id="deviceBlock-1111">
You could however just remove the .toLowerCase() call off the return but you'll end up with XPath's looking like this: //DIV[#id="deviceBlock-1111"]/DIV[2]/SELECT[1]/OPTION[5]
To solve this use the function below.
public String GetElementXPath(WebElement element, WebDriver driver)
{
return (String) ((JavascriptExecutor) driver).executeScript(
"getXPath=function(node)" +
"{" +
"if (node.id !== '')" +
"{" +
"return '//' + node.tagName.toLowerCase() + '[#id=\"' + node.id + '\"]'" +
"}" +
"if (node === document.body)" +
"{" +
"return node.tagName.toLowerCase()" +
"}" +
"var nodeCount = 0;" +
"var childNodes = node.parentNode.childNodes;" +
"for (var i=0; i<childNodes.length; i++)" +
"{" +
"var currentNode = childNodes[i];" +
"if (currentNode === node)" +
"{" +
"return getXPath(node.parentNode) +
'/' + node.tagName.toLowerCase() +
'[' + (nodeCount+1) + ']'" +
"}" +
"if (currentNode.nodeType === 1 && " +
"currentNode.tagName.toLowerCase() === node.tagName.toLowerCase())" +
"{" +
"nodeCount++" +
"}" +
"}" +
"};" +
"return getXPath(arguments[0]);", element);
}
This will return a correctly formatted, unique XPath from your WebElement.
//div[#id="deviceBlock-1111"]/div[2]/select[1]/option[5]
I would comment directly on dflems' answer, but I do not have the reputation to do so.
Converting the entire xpath to lower case is fine unless the xpath contains an id value that is not all lower-case. Below is a modified version of dflems' Javascript, but in Python instead of Java:
def get_xpath_from_element(driver, element):
return driver.execute_script("gPt=function(c){if(c.id!==''){return'id(\"'+c.id+'\")'}if(c===document.body){return c.tagName}var a=0;var e=c.parentNode.childNodes;for(var b=0;b<e.length;b++){var d=e[b];if(d===c){return gPt(c.parentNode)+'/'+c.tagName.toLowerCase()+'['+(a+1)+']'}if(d.nodeType===1&&d.tagName===c.tagName){a++}}};return gPt(arguments[0]);", element)
xpath selenium python javascript
public String getElementXPath(WebDriver driver, WebElement element) {
String javaScript = "function getElementXPath(elt){" +
"var path = \"\";" +
"for (; elt && elt.nodeType == 1; elt = elt.parentNode){" +
"idx = getElementIdx(elt);" +
"xname = elt.tagName;" +
"if (idx > 1){" +
"xname += \"[\" + idx + \"]\";" +
"}" +
"path = \"/\" + xname + path;" +
"}" +
"return path;" +
"}" +
"function getElementIdx(elt){" +
"var count = 1;" +
"for (var sib = elt.previousSibling; sib ; sib = sib.previousSibling){" +
"if(sib.nodeType == 1 && sib.tagName == elt.tagName){" +
"count++;" +
"}" +
"}" +
"return count;" +
"}" +
"return getElementXPath(arguments[0]).toLowerCase();";
return (String)((JavascriptExecutor)driver).executeScript(javaScript, element);
}
There is a way to get the elements XPath without the use of JavaScript.
Define starting point of outer XPath, for example body tag.
Check all possible inward tags with selenium for NoSuchElementException.
Check getText for the lists of XPaths generated.
win
public static String getXPathFromElement(WebElement element) {
String elementDescription = element.toString();
return elementDescription.substring(elementDescription.lastIndexOf("-> ") + 3, elementDescription.lastIndexOf("]"));
}
Web element toString() looks like this:
'[[FirefoxDriver: firefox on WINDOWS (ceb69f9f-bef4-455d-b626-ab439f195be6)] -> id: pageBeanfundDescription]'
I just extract the id/xpath.
/**
* This method return By reference for the WebElement passed to it as a parameter.
* #param element
* #return
*/
public static By convertWebElementToByReference(WebElement element)
{
By byLocator = null;
String elementDescription = element.toString();
String elementTypeAndValue[] = (elementDescription.substring(elementDescription.lastIndexOf("-> ") + 3, elementDescription.lastIndexOf("]"))).split(":");
switch (elementTypeAndValue[0].trim())
{
case "id": byLocator = By.id(elementTypeAndValue[1].trim());
break;
case "xpath": byLocator = By.xpath(elementTypeAndValue[1].trim());
break;
case "link text": byLocator = By.linkText(elementTypeAndValue[1].trim());
break;
case "tag name": byLocator = By.tagName(elementTypeAndValue[1].trim());
break;
case "class name": byLocator = By.className(elementTypeAndValue[1].trim());
break;
case "partial link text": byLocator = By.partialLinkText(elementTypeAndValue[1].trim());
break;
case "name": byLocator = By.name(elementTypeAndValue[1].trim());
break;
case "css selector": byLocator = By.cssSelector(elementTypeAndValue[1].trim());
break;
default:
throw new RuntimeException("Invalid locator type: " + elementTypeAndValue[0].trim());
}
return byLocator;
}

How to get ClientID of a TreeNode in a TreeView?

How to get ClientID of a TreeNode in a TreeView based on one of its rendered attributes,
for example, its title attribute (In my case it's unique)
,using either Server-Side or Client-Side code?
I go with this code, but it doesn't work, any suggestion?
// Retrieves TreeNode ClientID.
function GetTreeNodeID(nodeTitle)
{
var treeNodes = document.getElementById('tvMenu').childNodes;
var treeLinks;
for(var i=0 ; i<treeNodes.length ; i++)
{
treeLinks = treeNodes[i].getElementsByTagName('a');
for(var j=0 ; j<treeLinks.length ; j++)
{
if(nodeTitle == treeLinks[j].title && treeLinks[j].title != "");
{
alert("Par: " + nodeTitle);
alert("Title: " + treeLinks[j].title);
return treeLinks[j].id;
}
}
}
}
The above code that is mentioned with the question always returns the id of root node, any suggestion?
innerText or innerHtml or textContent ? Wich browser do you use ?
function GetTreeNodeID(nodeInnerText)
{
var tree = document.getElementById('tvMenu');
var treeLinks = tree.getElementsByTagName('A');
for(var element in treeLinks )
{
if((nodeInnerText == treeLinks[element].innerText) && (treeLinks[element].innerText != ""))
{
alert("Par: " + nodeInnerText);
alert("innerText: " + treeLinks[element].title);
return treeLinks[element].id;
}
}
}
Look here for a sample code.

Resources