Duplicate JavaScript without a debugger statement? - asp.net

I have and ASP.NET 3.5 page where I need to debug some JavaScript code.
function checkAll(isChecked)
{
debugger;
var dataGridElements = document.getElementById('" + DataGridSearchResults.ClientID + #"').getElementsByTagName('input');
for (var i = 0; i < dataGridElements.length; i++)
{
var e = dataGridElements[i];
if ((e.type=='checkbox') && (!e.disabled))
{
e.checked = isChecked;
}
}
}
As you can see, I added a debugger statement in the first line. For some reason, when i execute the page, the javascript (which is in a string variable and registered with Page.ClientScript.RegisterClientScript statement) is in my source code twice! The second block doesn't have my debugger statement either! I checked the project, this block of Javascript is only listed once in the project.
Any ideas? (the client i am running on is IE8 if that makes a difference)

Figured it out. The base page that this control was on (the javascript was in an ASCX file) was a page that had a tab strip on it. One of the other tabs had the code copy and pasted with the exact same signature, just a grid name difference. Once i changed the signature on my set of code, it worked fine.

Related

Find broken images in page & image replace by another image

Hi I am using selenium webdriver 2.25.0 & faceing the some serious issues,
how to find broken images in a page using Selenium Webdriver
How to find the image is replace by another image having same name (This is also bug) using webdriver.
Thanks in advance for your value-able suggestions.
The accepted answer requires that you use a proxy with an extra call to each image to determine if the images are broken or not.
Fortunately, there is another way you can do this using only javascript (I'm using Ruby, but you can use the same code in any executeScript method across the WebDriver bindings):
images = #driver.find_elements(:tag_name => "img")
broken_images = images.reject do |image|
#driver.execute_script("return arguments[0].complete && typeof arguments[0].naturalWidth != \"undefined\" && arguments[0].naturalWidth > 0", image)
end
# broken_images now has an array of any images on the page with broken links
# and we want to ensure that it doesn't have any items
assert broken_images.empty?
To your other question, I would recommend just taking a screenshot of the page and having a human manually verify the resulting screenshot has the correct images. Computers can do the automation work, but humans do have to check and verify its results from time to time :)
The next lines are not optimized, but they could find broken images:
List<WebElement> imagesList = _driver.findElements(By.tagName("img"));
for (WebElement image : imagesList)
{
HttpResponse response = new DefaultHttpClient().execute(new HttpGet(image.getAttribute("src");));
if (response.getStatusLine().getStatusCode() != 200)
// Do whatever you want with broken images
}
Regarding your second issue, I think I didn't understand it correctly. Could you explain it with more detail?
Based on the other answers, the code that eventually worked for me in an angular / protractor / webdriverjs setting is:
it('should find all images', function () {
var allImgElts = element.all(by.tagName('img'));
browser.executeAsyncScript(function (callback) {
var imgs = document.getElementsByTagName('img'),
loaded = 0;
for (var i = 0; i < imgs.length; i++) {
if (imgs[i].naturalWidth > 0) {
loaded = loaded + 1;
};
};
callback(loaded);
}).then(function (loadedImagesCount) {
expect(loadedImagesCount).toBe(allImgElts.count());
});
});
The webdriver code counts the number of img elements, and the function executed within the browser context counts the number of successfully loaded elements. These numbers should be the same.

jQuery UI autocomplete is not displaying results fetched via AJAX

I am trying to use the jQuery UI autocomplete feature in my web application. What I have set up is a page called SearchPreload.aspx. This page checks for a value (term) to come in along with another parameter. The page validates the values that are incoming, and then it pulls some data from the database and prints out a javascript array (ex: ["item1","item2"]) on the page. Code:
protected void Page_Load(object sender, EventArgs e)
{
string curVal;
string type ="";
if (Request.QueryString["term"] != null)
{
curVal = Request.QueryString["term"].ToString();
curVal = curVal.ToLower();
if (Request.QueryString["Type"] != null)
type = Request.QueryString["Type"].ToString();
SwitchType(type,curVal);
}
}
public string PreLoadStrings(List<string> PreLoadValues, string curVal)
{
StringBuilder sb = new StringBuilder();
if (PreLoadValues.Any())
{
sb.Append("[\"");
foreach (string str in PreLoadValues)
{
if (!string.IsNullOrEmpty(str))
{
if (str.ToLower().Contains(curVal))
sb.Append(str).Append("\",\"");
}
}
sb.Append("\"];");
Response.Write(sb.ToString());
return sb.ToString();
}
}
The db part is working fine and printing out the correct data on the screen of the page if I navigate to it via browser.
The jQuery ui autocomplete is written as follows:
$(".searchBox").autocomplete({
source: "SearchPreload.aspx?Type=rbChoice",
minLength: 1
});
Now if my understanding is correct, every time I type in the search box, it should act as a keypress and fire my source to limit the data correct? When I through a debug statement in SearchPreload.aspx code behind, it appears that the page is not being hit at all.
If I wrap the autocomplete function in a .keypress function, then I get into the search preload page but still I do not get any results. I just want to show the results under the search box just like the default functionality example on the jQuery website. What am I doing wrong?
autocomplete will NOT display suggestions if the JSON returned by the server is invalid. So copy the following URL (or the returned JSON data) and paste it on JSONLint. See if your JSON is valid.
http://yourwebsite.com/path/to/Searchpreload.aspx?Type=rbChoice&term=Something
PS: I do not see that you're calling the PreLoadStrings function. I hope this is normal.
A couple of things to check.
Make sure that the path to the page is correct. If you are at http://mysite.com/subfolder/PageWithAutoComplete.aspx, and your searchpreload.aspx page is in another directory such as http://mysite.com/anotherFolder/searchpreload.aspx the url that you are using as the source would be incorrect, it would need to be
source: "/anotherFolder/Searchpreload.aspx?Type=rbChoice"
One other thing that you could try is to make the method that you are calling a page method on the searchpreload.aspx page. Typically when working with javascript, I try to use page methods to handle ajax reqeusts and send back it's data. More on page methods can be found here: http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx
HTH.

.toggle(true) throw null in $(document).ready(function())

I am toggling row siblings. I wrote .toggle(true) when document ready. see below picture. I think row sibling are not availble before this function calls.
$(document).ready(function() {
$('tr[#class^=RegText]').hide().children('td');
list_Visible_Ids = [];
var idsString, idsArray;
idsString = $('#myVisibleRows').val();
idsArray = idsString.split(',');
$.each(idsArray, function() {
if (this != "") {
$(this).siblings('.RegText').toggle(true);
list_Visible_Ids[this] = 1;
}
});
How to resolve this? why sliblings are not avaible in when document is ready?
Your posted code doesn't match the debugger code, your code has this, which is (almost!) correct:
$(this).siblings('.RegText').toggle(true);
The debugger has this, which is incorrect:
$(this).siblings(('.RegText').toggle(true));
You need to update whatever you're actually debugging to that code without the extra parenthesis, otherwise you're going to get some pretty funky behavior there.
Also you need a # in there since your debugger shows you're not storing the hash mark in the array, which is perfectly fine. You're currently calling $("row10") (which looks for <row10> elements), but what you need is $("#row10") (which looks for id="row10" elements), so adjust your call like this:
$('#' + this).siblings('.RegText').toggle(true);

Popup a CalendarBehavior from Javascript

How can I embbed all the scripts needed by the CalendarBehavior in a page, without actually using the server-side control (CalendarExtender). The reason I can't use a server side extender is that I have a page with, possibly, hundreds of Date controls; I want to be able lazy-load the calendars as needed (when the user clicks in the control).
The code that creates the calendar from javascript is the following:
cal = $create(AjaxControlToolkit.CalendarBehavior,
{ 'id': owner.id + '_calendar', 'cssClass': 'calExt', 'format': format },
null, null, owner);
The problem is that without including all the needed js from the AjaxControlToolkit resources, it will throw the error:
AjaxControlToolkit is undefined.
Thank you very much,
Florin S.
I've found the following hack that will register all the scripts and css references exposed by the CalendarExtender. I think the solution is generic so that it can be used with other extenders:
ScriptManager manager = ScriptManager.GetCurrent(Page);
if (manager != null)
{
foreach (ScriptReference reference in ScriptObjectBuilder.GetScriptReferences(typeof(CalendarExtender)))
{
manager.Scripts.Add(reference);
}
CalendarExtender extender = new CalendarExtender();
Page.Form.Controls.Add(extender);
ScriptObjectBuilder.RegisterCssReferences(extender);
Page.Form.Controls.Remove(extender);
}
The temporary extender instance is needed for the RegisterCssReferences call, otherwise it will throw an error.
It works, but YMMV.
I had the same issue.
I found that, in javascript-land, instead of AjaxControlToolkit you should use Sys.Extended.UI.
So, instead of:
cal = $create(AjaxControlToolkit.CalendarBehavior, ...
you do this:
cal = $create(Sys.Extended.UI.CalendarBehavior, ...

ASP.Net Custom Client-Side Validation

I have a custom validation function in JavaScript in a user control on a .Net 2.0 web site which checks to see that the fee paid is not in excess of the fee amount due.
I've placed the validator code in the ascx file, and I have also tried using Page.ClientScript.RegisterClientScriptBlock() and in both cases the validation fires, but cannot find the JavaScript function.
The output in Firefox's error console is "feeAmountCheck is not defined". Here is the function (this was taken directly from firefox->view source)
<script type="text/javascript">
function feeAmountCheck(source, arguments)
{
var amountDue = document.getElementById('ctl00_footerContentHolder_Fees1_FeeDue');
var amountPaid = document.getElementById('ctl00_footerContentHolder_Fees1_FeePaid');
if (amountDue.value > 0 && amountDue >= amountPaid)
{
arguments.IsValid = true;
}
else
{
arguments.IsValid = false;
}
return arguments;
}
</script>
Any ideas as to why the function isn't being found? How can I remedy this without having to add the function to my master page or consuming page?
Try changing the argument names to sender and args. And, after you have it working, switch the call over to ScriptManager.RegisterClientScriptBlock, regardless of AJAX use.
When you're using .Net 2.0 and Ajax - you should use:
ScriptManager.RegisterClientScriptBlock
It will work better in Ajax environments then the old Page.ClientScript version
Also you could use:
var amountDue = document.getElementById('<%=YourControlName.ClientID%>');
That will automatically resolve the client id for the element without you having to figure out that it's called 'ctl00_footerContentHolder_Fees1_FeeDue'.
While I would still like an answer to why my javascript wasn't being recognized, the solution I found in the meantime (and should have done in the first place) is to use an Asp:CompareValidator instead of an Asp:CustomValidator.

Resources