Escape double quote in velocity - velocity

I'm using velocity 1.7 and the template is below.
var jsCode = "${code}";
eval(jsCode);
if code is "var id = 123", then the actual js code is
var jsCode = "var id = 123";
eval(jsCode);
there is no problem.
However, if the code is "var name = "lucy"", then the actual js code is
var jsCode = "var name = "lucy"";
eval(jsCode);
obviously there is syntax error.
And if the code is var jsonStr = "{\"id\":1, \"name\":\"lucy\"}", the the problem is more serious.
The code is unknown, it can be anything.
How to solve this problem?

Velocity developed also EscapeTool inside velocity-tools project which escape with different options
Tool for working with escaping in Velocity templates. It provides methods to escape outputs for Velocity, Java, JavaScript, HTML, HTTP, XML and SQL
In your case it's javascript so use $esc.javascript( example:
$javascript -> He didn't say, "Stop!"
$esc.javascript($javascript) -> He didn\'t say, \"Stop!\"

Related

Google Docs script, return text value in the middle of specified text

[current result][1]
[1]: https://i.stack.imgur.com/O8AGa.png
The problem is that they all apply to the same line
I want to get the values individually from the same line
Rule
▶random text◁
→ Change only values between ▶ and ◁
Script currently in use
var body = DocumentApp.getActiveDocument().getBody();
var foundElement = body.findText('▶([^\S]+)◁');
while (foundElement != null) {
// Get the text object from the element
var foundText = foundElement.getElement().asText();
// Where in the element is the found text?
var start = foundElement.getStartOffset();
var end = foundElement.getEndOffsetInclusive();
// Set Bold
foundText.setBold(start, end, true);
// Change the Foreground color
foundText.setForegroundColor(start, end, "#ff326d");
// Find the next match
foundElement = body.findText('▶([^\S]+)◁', foundElement);
}
Some regular expressions are not fully supported
As per the documentation A subset of the JavaScript regular expression features are not fully supported, such as capture groups and mode modifiers.
I'd recommend to open a feature request on Google Issue Tracker as recommended here

jspdf Some data is being cut

The jspdf library is being used to generate PDF files in html.
That's a really good thing.
But I have a problem with pdf.
The data is about three pages long, but if check the downloaded pdf file, I see only one page and the rest will be truncated.
Here's my code:
let pdfName = this.contractlist_detail.title
var doc = new jsPDF();
var NotoSansCJKjp;
doc.addFileToVFS('NotoSansCJKjp-Regular.ttf', VFS);
doc.addFont('NotoSansCJKjp-Regular.ttf', 'NotoSansCJKjp', 'Bold');
doc.setFont('NotoSansCJKjp', 'Bold');
doc.setFontSize(12);
var paragraph = data;
var lines = doc.splitTextToSize(paragraph, 150);
doc.text(15, 15, lines)
doc.save(pdfName + '.pdf');
How do I make all of my data visible to downloaded pdf without being truncated?
jspdf library doesn't handle multi-pages by its own. You need to add pages manually when content is cropped (you need also to calculate manually if text is cropped).
Here is the method to add a new page :
addPage method
a demo is available in section "two page hello world" to know how to use this method
enter link description here

%%GLOBAL variables not working in custom Bigcommerce templates

I want to customise the product template, but not for all cases hence I am creating a new template layout file.
I have tried to do this two ways, however both don't work and encounter the same issue with %%GLOBAL variables not working.
Using Product.html as a base, I created _Product.html and changed %%Panel.ProductDetails%% to my custom ProductDetails file %%Panel._ProductDetails%%, which I haven't customised at all at this stage. I then change a test product to use that template. When viewing the product, console errors ar produced and the page doesn't show properly. The cause of the first console error is a syntax error where script variables are being set to a %%GLOBAL variable. Looking at the page source, this is the result:
<script type="text/javascript">//<![CDATA[
var ThumbURLs = new Array();
var ProductImageDescriptions = new Array();
var CurrentProdThumbImage = ;
var ShowVariationThumb =false;
var ProductThumbWidth = ;
var ProductThumbHeight = ;
var ProductMaxZoomWidth = ;
var ProductMaxZoomHeight = ;
var ProductTinyWidth = ;
var ProductTinyHeight = ;
where the template is
<script type="text/javascript">//<![CDATA[
var ThumbURLs = new Array();
var ProductImageDescriptions = new Array();
var CurrentProdThumbImage = %%GLOBAL_CurrentProdThumbImage%%;
var ShowVariationThumb =false;
var ProductThumbWidth = %%GLOBAL_ProductThumbWidth%%;
var ProductThumbHeight = %%GLOBAL_ProductThumbHeight%%;
var ProductMaxZoomWidth = %%GLOBAL_ProductMaxZoomWidth%%;
var ProductMaxZoomHeight = %%GLOBAL_ProductMaxZoomHeight%%;
var ProductTinyWidth = %%GLOBAL_ProductMaxTinyWidth%%;
var ProductTinyHeight = %%GLOBAL_ProductMaxTinyHeight%%;
The weird part is that there are %%global variables just above it that work fine.
<script type="text/javascript" src="%%GLOBAL_CdnAppPath%%/javascript/jquery/plugins/jCarousel/jCarousel.js?%%GLOBAL_JSCacheToken%%"></script>
gets correctly gets interpreted as
<script type="text/javascript" src="http://cdn3.bigcommerce.com/r-8a870c678fbffbf4184af752aed70da3f3454036/javascript/jquery/plugins/jCarousel/jCarousel.js?"></script>
The second way I tried was to include everything in the top level template. Instead of linking to %%Panel._ProductDetails%%, I inserted the contents of that panel into _Product.html, however this also encounters exactly the same issue.
Does anyone know why neither of these options work and how I can achieve what I want?
You have to call Panel.ProductDetails prior to using those variables.
Even if you are using a custom product details alternative panel you need to reference the standard one first. Then your global variables will work.
This is because GLOBALS in the BigCommerce system will only print a value where they have been permitted by the BigCommerce development team. This can be a pain, especially for the values you are after, and what you want to do makes perfect sense.
At this time however, I suggest you make it known to the developers you want this at http://ideas.bigcommerce.com.
I can't say whether this will change anytime soon as the main reason for the GLOBALS being banned in certain areas is for security, although the ones you are after are useful, and I don't see why they aren't enabled either. Who knows, the developers may surprise us.

Selenium 2: How to save a HTML page including all referenced resources (css, js, images...)?

In Selenium 2, the WebDriver object only offers a method getPageSource() which saves the raw HTML page without any CSS, JS, images etc.
Is there a way to also save all referenced resources in the HTML page (similar to HtmlUnit's HtmlPage.save())?
I know I'm royally late with my answer, but I didn't really find an answer for this question when I was searching myself. So I did something myself, hope I can help some people still.
For c# here's how I did it:
using system.net;
string DataDirectory = "C:\\Temp\\AutoTest\\Data\\";
string PageSourceHTML = Driver.PageSource;
string[] StringSeparators = new string[] { "<" };
string[] Result = PageSourceHTML.Split(StringSeparators, StringSplitOptions.None);
string CSSFile;
string FileName = "filename.html";
System.IO.File.WriteAllText(DataDirectory + FileName, PageSourceHTML);
foreach(string S in Result)
{
if(S.Contains("stylesheet"))
{
CSSFile = S.Substring(28); // strip off "link rel="stylesheet" href="
CSSFile = CSSFile.Substring(0,CSSFile.Length-10); // strip off characters behind, like " />" and newline, spaces until next "<" was found. Can and probably will be different in your case.
System.IO.Directory.CreateDirectory(DataDirectory + "\\" + CSSFile.Substring(0, CSSFile.LastIndexOf("/"))); //create the CSS direcotry structure
var Client = new WebClient();
Client.DownloadFile(Browser.Browser.WebUrl + "/" + CSSFile, DataDirectory + "\\" + CSSFile); // download the file and save it with the same filename under the same relative path.
}
}
I'm sure it could be improved to include any unforeseen situations, but for my website in test it will always work like this.
Nope. If you can, go for HtmlUnit for this particular task.
The best you could do, I think, is Robot. Press Ctrl + S simultaneously, the confirm with Enter. It's blind, it's imperfect, but it's the closest thing to your need.
You can use the selenium interactions to handle it.
using OpenQA.Selenium.Interactions;
There are a few ways to do it as well. One of the ways that I handle something like this, is to find an item central to the page, or whichever area that you wish to save, and do an actions builder.
var htmlElement = driver.FindElement(By.XPath("//your path"));
Actions action = new Actions(driver);
try
{
action.MoveToElement(htmlElement).ContextClick(htmlElement).SendKeys("p").Build().Perform();
}
catch(WebDriverException){}
This will simply right click on the area, and then send the key "p" which is the 'Save Page As' hotkey in firefox when right clicking. Another way is to have the builder send the keys.
var htmlElement = driver.FindElement(By.Xpath("//your path"));
action.MoveToElement(htmlElement);
try
{
action.KeyDown(Keys.Control).SendKeys("S").KeyUp(Keys.Control).Build().Perform();
}
catch(WebDriverException){}
Note that in both cases, if you leave the scope of the driver, say a windows form, then you will have to switch your case / code to handle the windows form when it pops up. Selenium will also have issues with nothing being returned after the keys are sent, so the Try Catches are there for that. If anyone has a way to work around that, it would be awesome.

problem with RegisterClientScriptBlock

i have to run following javascript through one of my method. But its not running
Whats wrong with the code.
private void fillGrid1()
{
GridView1.DataSource = myDocCenter.GetDsWaitingForMe(Session["UserID"].ToString());
HiddenField1.Value = { myDocCenter.GetDsWaitingForMe(Session["UserID"].ToString()).Tables[0].Rows.Count).ToString();
GridView1.DataBind();
String csname1 = "PopupScript1";
String csname2 = "ButtonClickScript1";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
{
StringBuilder cstext2 = new StringBuilder();
cstext2.Append("<script type=\"text/javascript\"> ");
// You can add JavaScript by using "cstext2.Append()".
cstext2.Append("var count = document.getElementById('ctl00_ContentPlaceHolder1_HiddenField2');");
cstext2.Append("var count = '100';");
cstext2.Append("document.getElementById('sp2').innerHTML = count;");
cstext2.Append("script>");
cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
}
}
Your script tag is not properly closed.
Change
cstext2.Append("script>");
to
cstext2.Append("</script>");
On top of what adamantium said, your JS looks a bit strange. You seem to declare and set the count variable twice - did you mean to do this.
Following that, best thing to do, render the page then view source. is your JS getting rendered to the page? try and stick an alert in there... is it firing?
> cstext2.Append("var count =
> document.getElementById('ctl00_ContentPlaceHolder1_HiddenField2');");
I would use the ClientID property here. HiddenField2.ClientID
RegisterClientScriptBlock emits the script just after the <form> tag openning. Browser executes this script just after the tag openning as well but referenced elements are not processed yet at this time - browser cannot find them.
RegisterStartupScript method emits the script just before the <form> tag ending. Nearly all page elements are processed by the browser at this place and getElementById could find something.
See http://jakub-linhart.blogspot.com/2012/03/script-registration-labyrinth-in-aspnet.html for more details.