problem with RegisterClientScriptBlock - 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.

Related

How can I get carousel on page at Umbraco?

I want to create a carousel, firstly I create a nested content then I added it on my homepage but when I called, it's not working.
#{
string carouselId = "mainCarousel";
IEnumerable<IPublishedContent> carousel = Model.Value<IEnumerable<IPublishedContent>>(carouselId); }
I got error like this object reference not set to an instance of an object. I tried many things but I failed to reach on solve. Btw I'm using v8.1.12.
I fixed this problem with this code;
var page = Umbraco.Content(Guid.Parse("eea1803b-f093-42f6-8483-b27df3323c2d"));
var carousel = page.Value<IEnumerable<IPublishedElement>>("mainCarousel");

Can HTAs be used to automate web browsing?

I am new to HTAs. I just read https://msdn.microsoft.com/en-us/library/ms536496%28v=vs.85%29.aspx and am a bit confused.
Can I use HTAs to automate browsing? Say I want to download a web page and fill in a form automatically, i.e. from a script. How would an HTA help me do this, if at all? It's important that the JavaScript code in the downloaded page is run as usual. I should be able to enter somehow and fill in the form after it has finished initializing, just as if I were a human agent.
First, you need to open an IE window, as follows:
var IE = new ActiveXObject("InternetExplorer.Application");
Then navigate the IE window to the webpage you want:
IE.Navigate("www.example.com");
Wether your IE window is visible or invisible, it's up to you. Use Visible property to make it visible:
IE.Visible = true;
Then, you should wait until the webpage is completely loaded and then run a function that takes your desired actions. To do so, first, get the HTML document object from the webpage using Document property of IE object, then repeatedly check the readyState property of document object. In the code below, it is assumed that you have a function named myFunc, which takes your desired actions on the webpage. (For example, modifying the contents of the webpage.)
var doc = IE.Document;
interval = setInterval(function() {
try
{
if (doc.readyState == "complete")
{
myFunc();
clearInterval(interval);
}
}
catch (e) {}
}, 1000);
In the function myFunc, you can do anything you want with the webpage since you have HTML document object stored in doc variable. You can also use parentWindow property to get the HTML window object.

'sendKeys' are not working in Selenium WebDriver

I am not able to put any value in my application using WebDriver. My application is using frames.
I am able to clear the value of my textbox with driver.findElement(By.name("name")).clear();, but I'm unable to put any value using driver.findElement(By.name("name")).sendKeys("manish");. The click command works for another button on the same page.
I also had that problem, but then I made it work by:
myInputElm.click();
myInputElm.clear();
myInputElm.sendKeys('myString');
Before sendkeys(), use the click() method (i.e., in your case: clear(), click(), and sendKeys()):
driver.findElement(By.name("name")).clear();
driver.findElement(By.name("name")).click(); // Keep this click statement even if you are using click before clear.
driver.findElement(By.name("name")).sendKeys("manish");
Try clicking on the textbox before you send keys.
It may be that you need to trigger an event on the field before input and hopefully the click will do it.
I experienced the same issue and was able to collect the following solution for this:
Make sure element is in focus → try to click it first and enter a string.
If there is some animation for this input box, apply some wait, not static. you may wait for an element which comes after the animation. (My case)
You can try it out using Actions class.
Clicking the element works for me too, however, another solution I found was to enter the value using JavaScript, which doesn't require the element to have focus:
var _element= driver.FindElement(By.Id("e123"));
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].setAttribute('value', 'textBoxValue')", _element);
Use JavaScript to click in the field and then use sendkeys() to enter values.
I had a similar problem in the past with frames. JavaScript is the best way.
First pass the driver control to the frame using:
driver.switchTo().frame("pass id/name/index/webelement");
After that, perform the operation which you want to do on the webelement present inside the frame:
driver.findElement(By.name("name")).sendKeys("manish");
I have gone with the same problem where copy-paste is also not working for that text box.
The below code is working fine for me:
WebDriver driver = new FirefoxDriver();
String mobNo = "99xxxxxxxx";
WebElement mobileElementIrs =
driver.findElement(By.id("mobileNoPrimary"));
mobileElementIrs.click();
mobileElementIrs.clear();
mobileElementIrs.sendKeys(mobNo);
I had a similar problem too, when I used
getDriver().findElement(By.id(idValue)).clear();
getDriver().findElement(By.id(idValue)).sendKeys(text);
The value in "text" was not completely written into the input. Imagine that "Patrick" sometimes write "P" another "Pat",...so the test failed
The fix is a workaround and uses JavaScript:
((JavascriptExecutor)getDriver()).executeScript("$('#" + idValue + "').val('" + value + "');");
Now it is fine.
Instead of
driver.findElement(By.id("idValue")).sendKeys("text");
use,
((JavascriptExecutor)getDriver()).executeScript("$('#" + "idValue" + "').val('" + "text" + "');");
This worked for me.
I had a similar problem recently and tried some of the suggestions above, but nothing worked. In the end it fell back on a brute-force retry which retries if the input box wasn't set to what was expected.
I wanted to avoid thread.sleep for obvious reasons and saw different examples of it failing that looked like some kind of race or timing condition.
public void TypeText(string id, string text)
{
const int numberOfRetries = 5;
for (var i = 1; i < numberOfRetries; i++)
{
try
{
if (TryTypeText())
return;
}
catch (Exception)
{
if (i == numberOfRetries)
throw;
}
}
bool TryTypeText()
{
var element = _webDriver.FindElement(By.Id(id));
element.Click();
element.Clear();
element.SendKeys(text);
if (element.TagName.ToLower() == "input"
&& !DoesElementContainValue(element, text, TimeSpan.FromMilliseconds(1000)))
{
throw new ApplicationException($"Unable to set the type the text '{text}' into element with id {id}. Value is now '{element.GetAttribute("value")}'");
}
return true;
}
}
private bool DoesElementContainValue(IWebElement webElement, string expected, TimeSpan timeout)
{
var wait = new WebDriverWait(_webDriver, timeout);
return wait.Until(driver =>
{
try
{
var attribute = webElement.GetAttribute("value");
return attribute != null && attribute.Contains(expected);
}
catch (StaleElementReferenceException)
{
return false;
}
});
}
In my case, I had some actions.keyDowns(Keys.CONTOL).XXXX;
But I forgot to add the keyUp for that button and that prevented from sending keys and resulted in weird behaviors
Adding X.keyUp() after the x.keyDown() fixed the issue
Try using JavaScript to sendkeys().
WebElement element = driver.findElement(By.name("name"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
More information on JavaScript Executor can be found at
JavascriptExecutor - Selenium.
Generally I keep a temporary variable. This should work.
var name = element(by.id('name'));
name.clear();
name.sendKeys('anything');

Switching to a window with no name

Using the Codeception testing framework and Selenium 2 module to test a website, I end up following a hyperlink that opens a new window with no name. As a result the switchToWindow() function will not work because it is trying to switch to the parent window (which I'm currently on). Without being able to switch to the new window I cannot perform any testing on it.
<a class="external" target="_blank" href="http://mylocalurl/the/page/im/opening">
View Live
</a>
Using both Chrome and Firefox debugging tools I can confirm the new window doesn't have a name, and I cannot give it one because I cannot edit the HTML page I am working on. Ideally I would have changed the HTML to use javascript onclick="window.open('http://mylocalurl/the/page/im/opening', 'myPopupWindow') however this is not possible in my case.
I've looked around on the Selenium forums without any clear method to tackle this problem, and Codeception doesn't appear to have much functionality around this.
After searching around on the Selenium forum and some helpful prods from #Mark Rowlands, I got it to work using raw Selenium.
// before codeception v2.1.1, just typehint on \Webdriver
$I->executeInSelenium(function (\Facebook\WebDriver\Remote\RemoteWebDriver $webdriver) {
$handles=$webdriver->window_handles();
$last_window = end($handles);
$webdriver->focusWindow($last_window);
});
Returning back to the parent window was easy because I could just use Codeception's switchToWindow method:
$I->switchToWindow();
Building on the accepted answer, in Codeception 2.2.9 I was able to add this code to the Acceptance Helper and it seems to work.
/**
* #throws \Codeception\Exception\ModuleException
*/
public function switchToNewWindow()
{
$webdriver = $this->getModule('WebDriver')->webDriver;
$handles = $webdriver->getWindowHandles();
$lastWindow = end($handles);
$webdriver->switchTo()->window($lastWindow);
}
Then in the test class I can do this:
$I->click('#somelink');
$I->switchToNewWindow();
// Some assertions...
$I->switchToWindow(); // this switches back to the previous window
I had a heck of a time trying to figure out how to do this by just searching google, so I hope it helps someone else.
Try this,
String parentWindowHandle = browser.getWindowHandle(); // save the current window handle.
WebDriver popup = null;
Iterator<String> windowIterator = browser.getWindowHandles();
while(windowIterator.hasNext()) {
String windowHandle = windowIterator.next();
popup = browser.switchTo().window(windowHandle);
}
make sure to return on parent window using,
browser.close(); // close the popup.
browser.switchTo().window(parentWindowHandle); // Switch back to parent window.
I hope will help you.
Using Codeception 2.2+ it looks like this:
$I->executeInSelenium(function (\Facebook\WebDriver\Remote\RemoteWebDriver $webdriver) {
$handles = $webdriver->getWindowHandles();
$lastWindow = end($handles);
$webdriver->switchTo()->window($lastWindow);
});

Problems with adding/removing ContentPanes in AccordionContainer

I'm a complete newbie at Dojo, and Adobe AIR, which is my target. I'm
trying to put some panes into an AccordionContainer like so:
var mainview = dijit.byId("mainview");
var rand = randomString();
var widg = gtd_create_entry_widget(rand)
air.trace(mainview);
air.trace(widg);
mainview.addChild(widg);
"mainview" is my AccordionContainer, and gtd_create_entry_widget() is:
function gtd_create_entry_widget(id) {
var entry = new dijit.layout.ContentPane();
entry.attr("id",id);
entry.attr("title","title "+id);
return entry;
}
The pane shows up in the container, with the correct id and title, and
no errors, however, if I try to add another pane, the next one shows
up too, but I get the error:
TypeError: Result of expression '_7' [undefined] is not an object.
I get the same error if I run
var mainview = dijit.byId("mainview");
mainview.destroyDescendants();
and also, only one pane is destroyed at a time, and I understand this
method should destroy all the children.
I can include full project code if required.
Thanks a lot
Garry
I'm not exactly sure if this is going to fix your problem, but you're supposed to use dijit.layout.AccordianPane (http://www.dojotoolkit.org/api/dijit/layout/AccordionPane.html) with the AccordianContainer.