I'm working on autotest with noraui.
I would like to open a subdropdown (button => click => dropdown => passOver => subdropdown). This subdropdown can only appear with a passOver, if we click on the dropdownmenu, nothing happen.
But my passOver function doesn't work
protected void passOver(PageElement element) throws TechnicalException, FailureException {
try {
String javascript = "var evObj = document.createEvent('MouseEvents');" + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"
+ "arguments[0].dispatchEvent(evObj);";
((JavascriptExecutor) getDriver()).executeScript(javascript, Context.waitUntil(ExpectedConditions.presenceOfElementLocated(Utilities.getLocator(element))));
} catch (Exception e) {
new Result.Failure<>(e.getMessage(), Messages.format(Messages.FAIL_MESSAGE_UNABLE_TO_PASS_OVER_ELEMENT, element, element.getPage().getApplication()), true,
element.getPage().getCallBack());
}
}
The steps code
#When("I pass over on '(.*)-(.*)'")
public void passOver(String page, String toPassOver) throws TechnicalException, FailureException {
loggerStep.debug(page + " passOver: " + toPassOver);
passOver(Page.getInstance(page).getPageElementByKey('-' + toPassOver)); }
I'm looking for passOver works like a mouse hovering the dropdownmenu ("Mise à jour").
Related
My RPA Express project iterates through a number of URLs and if a certain condition is met, clicks on a icon that pops up a HTML "Confirm" modal dialog. The code clicks "OK" (tried also Keypress "Enter") and then goes into a next URL.
The problem is that after the first confirmation (click OK or press Enter) on the dialog box and processing to a next URL, all attempts to use Web Element (get by xpath) fail with:
Caused by: org.openqa.selenium.NoAlertPresentException: No modal dialog is currently open
I tried unsuccessfully:
to "CTRL+F5" the page on reload
set focus on the page (with MouseClick) after reload
It looks like the system does not recognize that the modal dialog was actually closed.
Any idea how to get it fixed?
Here is the main loop code:
event_id_list.each( {this_event_id ->
this_id = RString.of(RNumber.fromRepresentation("${this_event_id}","0;pl-PL").toRepresentation("0;pl-PL"))
this_url = event_url_patern.replaceFirstIgnoreCase("[id]", "${this_id}")
confirm_close_window = RBoolean.fromCanonical("false")
sleep(1000)
inDesktop {
sendKeys(StringTransformations.getKeyPressText(63, 0, 116, 2))
}
// Group of actions: Open Event URL
$(byImage("1536237127355-anchor-1536911026524.apng", Integer.valueOf(0), Integer.valueOf(0))).click()
setClipboardText(this_url as String)
inDesktop {
sendKeys(StringTransformations.getHotKeyText(97, 2))
}
inDesktop {
sendKeys(StringTransformations.getHotKeyText(118, 2))
}
inDesktop {
sendKeys(StringTransformations.getKeyPressText(28, 13, 10, 0))
}
def i1 = System.currentTimeMillis() + 8000
boolean i0 = true
while (i0) {
try {
$(byImage("1536912304113-anchor.apng")).getCoordinates()
even_opened = RBoolean.TRUE
break
} catch (Exception ignored) {
even_opened = RBoolean.FALSE
}
i0 = System.currentTimeMillis() < i1
}
$(byImage("1537167271142-anchor-1537167271149.apng", Integer.valueOf(0), Integer.valueOf(0))).click()
try {
this_crewx_vessel = RString.of($(byXpath("/html/body/form/div[3]/table[1]/tbody/tr[1]/td[2]/b")).text())
} catch (Exception i2) {
this_crewx_vessel = RString.of("N/A")
}
try {
this_crewx_port = RString.of($(byXpath("//*[#id=\"form1\"]/div[3]/table[1]/tbody/tr[1]/td[6]/b/a")).text())
} catch (Exception i3) {
this_crewx_port = RString.of("N/A")
}
sleep(4000)
Resource.append("${log_file_path}", "<p>Processing id ${this_id} (${this_crewx_vessel} at ${this_crewx_port}) - outcome: ", "UTF-8")
icon_src = RString.of($(byXpath("//*[#id=\"toggleEventImg\"]")).getAttribute("src"))
if ((RString.of("images/lock.gif")) in (icon_src)) {
$(byXpath("//*[#id=\"toggleEventImg\"]")).click()
def i5 = System.currentTimeMillis() + 3000
boolean i4 = true
while (i4) {
try {
$(byImage("1536910894370-anchor.apng")).getCoordinates()
confirm_close_window = RBoolean.TRUE
break
} catch (Exception ignored) {
confirm_close_window = RBoolean.FALSE
}
i4 = System.currentTimeMillis() < i5
}
if ((confirm_close_window) == (RBoolean.fromCanonical('true'))) {
inDesktop {
sendKeys(StringTransformations.getKeyPressText(28, 13, 10, 0))
}
sleep(4000)
Resource.append("${log_file_path}", "closed.</p>", "UTF-8")
// compare_item = RString.of($(byXpath("//*[#id=\"toggleEventImg\"]")).text())
} else {
sleep(4000)
Resource.append("${log_file_path}", "no action (confirm window no show)</p>", "UTF-8")
}
} else {
sleep(4000)
Resource.append("${log_file_path}", "no action (already closed).</p>", "UTF-8")
}
})
The error is thrown at:
icon_src = RString.of($(byXpath("//*[#id=\"toggleEventImg\"]")).getAttribute("src"))
Instead of clicking an image and typing in the url, try opening the URL using OpenIE or OpenChrome
openIE(UrlOperations.ensureProtocol("${this_url}"))
switchWindow does not work in IE
this.browser.windowHandles(function (result) {
var newWindow;
if (result.value.length > 1) {
this.browser.verify.equal(result.value.length, 2, 'There should be 2 windows open');
newWindow = result.value[1];
this.browser.switchWindow(newWindow)
.pause(1000, function() { // wait to load the 2nd window completly.
if(self.isInternetExplorer && self.isWin81){
self.browser.pause(20000);//IE on win 8.1 is slower
}
});
}
this.browser.waitForUrlToContain(rstl, true, 90000, function (doesIt, url) {
console.log(url);
this.browser.assert.ok(doesIt, 'URL ' + url + ' does not contain ' + rstl);
if(callback){
callback(this.browser, isFirstLogin, extraCallbackValues);
}
}.bind(this));
if (result.value.length > 1) {
this.browser.closeWindow();
this.browser.switchWindow(result.value[0]);
} else {
this.browser.back();
}
}.bind(this));
I have the code above. For some reason, switchWindow function is not working in IE. Is there an alternative?
Can anybody give me example of code for uploading and downloading different type of files by Using Custom Control in ASP .NET MVC4 by using PlUpload Plugin. I want to save files for my task, message with unique Ids in database and want to retrieve them too. Here is my code that I tried for uploading
server side
public ActionResult UploadFiles(string id)
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "Uploads/" + file.FileName);
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
and for plupload plugin code for client side for uploading file is
$("#file_attachments").pluploadQueue(
{
// General settings
runtimes: 'html5,flash,silverlight',
url: '/SideMenuBar/UploadFiles',
max_file_size: '100mb',
chunk_size: '1mb',
unique_names: true,
multipart: true,
// Specify what files to browse for
filters: [
{ title: "Image files", extensions: "jpg,gif,png" },
{ title: "Zip files", extensions: "zip" },
{ title: "Rar files", extensions: "rar" },
{ title: "Document files", extensions: "docx,doc,xlx,xlxs,ppt" },
],
// Flash settings
flash_swf_url: 'Script/lib/plupload/js/plupload.flash.swf',
// Silverlight settings
silverlight_xap_url: 'Script/lib/plupload/js/plupload.silverlight.xap',
// PreInit events, bound before any internal events
preinit: {
Init: function (up, info) {
//alert('[Init]'+ info+ 'Features:'+ up.features);
},
UploadFile: function (up, file) {
// alert('[UploadFile]', file);
// You can override settings before the file is uploaded
up.settings.url = '/SideMenuBar/UploadFiles?id=' + file.id;
//up.settings.multipart_params = {param1: 'value1', param2: 'value2'};
}
},
// Post init events, bound after the internal events
init:
UploadComplete: function (up, files) {
// destroy the uploader and init a new one
up.destroy();
}
}
});
var uploader = $('#file_attachments').pluploadQueue();
uploader.bind('FileUploaded', function (upldr, file, object) {
if (uploader.files.length == (uploader.total.uploaded + uploader.total.failed)) {
$(".file_upload_cancel").hide();
$(".file_upload_done").show();
}
});
uploader.bind("FilesAdded", function (up, filesToBeAdded) {
if (up.files.length > 5) {
up.files.splice(4, up.files.length - 5);
showStatus("Only 5 files max are allowed per upload. Extra files removed.", 3000, true);
return false;
}
return true;
});
$('.upload_files').click(function (e) {
e.preventDefault();
$(".file_up").show();
});
$('#new_message_form').submit(function (e) {
var uploader = $('#file_attachments').pluploadQueue();
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind('StateChanged', function () {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
//uncoment next line to submit form after all files are uploaded
//$('#new_message_form')[0].submit();
}
});
uploader.start();
}
return false;
});
}
How can I resolve problem
You are using an option called "chunk", which divides your file in the size of the chunk - it's a good practice, to prevent errors.
You have determined it with the property "chunk_size". For example: you have a file of 5mb. When you upload, you'll have 5 parts of 1mb - until the upload is complete. Then, you'll have to put them together.
I recommend you to see this link to more informations about chunk and how to make it work.
Here is an example of one of my implementation - with MVC 3 - of plupload with chunk.
I'll post the javascript code and the action. I think it will be good for you to know how to implement in your case.
function installFolderFileUploader(action, id, ProfileType, intMaxFilesPermitted, Folder, maxSizeMB) {
var uploaderRuntimes = 'html5, flash, silverlight';
var uploader = new plupload.Uploader({
runtimes: uploaderRuntimes,
browse_button: 'imgBtnPhotoUpload',
url: action,
flash_swf_url: '/Scripts/Plugins/Moxie.swf',
silverlight_xap_url: '/Scripts/Plugins/Moxie.xap',
multipart_params: { 'id': id, 'ProfileType': ProfileType },
multi_selection: true,
max_file_count: '5',
chunk_size: '100KB',
filters: {
max_file_size: maxSizeMB + 'MB'
},
init: {
FileUploaded: function (Up, File, Response) {
var jsonObj = jQuery.parseJSON(Response.response);
if (jsonObj.success) {
mountFileUploadFields(jsonObj, Folder, ProfileType);
}
},
PostInit: function () {
//meow
$('#imgBtnPhotoUpload').next().css({ 'top': '0', 'width': '146px', 'height': '28px', 'cursor': 'pointer' });
},
FilesAdded: function (up, files) {
var totalInPage = parseInt($('#dvFileContainer .BeeFileDetails').length);
if ((up.files.length + totalInPage) > parseInt(intMaxFilesPermitted)) {
jQuery.facebox({ div: "#dvMaxFilesPermitedError" });
up.splice();
up.refresh();
return false;
}
else {
if (totalInPage >= parseInt(intMaxFilesPermitted)) {
jQuery.facebox({ div: "#dvMaxFilesPermitedError" });
up.splice();
up.refresh();
return false;
}
else {
$('#dvFileList').css('margin-left', '2px');
$('#dvFileList').css('font-size', '10px');
$('#dvFileList').css('display', 'block');
plupload.each(files, function (file) {
$('#dvFileList').append('<div>');
$('#dvFileList').append('<div style="width:84%;margin-left:30px;float:left;" id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b></div>');
$('#dvFileList').append('<img class="removeFile" style="margin-top:2px;cursor:pointer;" src="/Content/images/cancel.png" id="' + file.id + '" />');
$('#dvFileList').append('</div>');
$('.removeFile').on('click', function () {
$('#' + file.id).remove();
$('img[id=' + file.id + ']').remove();
uploader.stop();
uploader.splice();
});
});
uploader.start();
}
}
},
UploadProgress: function (up, file) {
if (file.percent == 100) {
$('#' + file.id).remove();
$('img[id=' + file.id + ']').remove();
}
$('#' + file.id + ' b:eq(0)').html('<span> - ' + file.percent + '%</span>');
$('#' + file.id + ' b:eq(0)').append('<div id="fileUploaded" style="background-color:#0099FF;height:3px;width:' + file.percent + '%";></div>');
},
ChunkUploaded: function (up, file, info) {
var jsonObj = jQuery.parseJSON(info.response);
if (jsonObj.tempFile != "") {
uploader.settings.multipart_params.tempFile = jsonObj.tempFile;
}
else {
$('#' + file.id).remove();
$('img[id=' + file.id + ']').remove();
var totalInPage = parseInt($('#dvFileContainer .BeeFileDetails').length);
if (totalInPage > 0)
$('.BeeEditFileActions').fadeIn();
var fileName = uploader.settings.multipart_params.tempFile;
removeNonUsedFiles(id, fileName, 'File');
uploader.settings.multipart_params.tempFile = '';
uploader.stop();
uploader.splice();
uploader.refresh();
jQuery.facebox({ div: "#dvAddFolderFileError" });
}
},
Error: function (up, err) {
if (err.code != '-500')
jQuery.facebox({ div: "#dvAddFolderFileError" });
},
UploadComplete: function (a, Response) {
$('.BeeEditFileActions').fadeIn();
$('#dvFileList').empty();
uploader.splice();
uploader.refresh();
}
}
});
uploader.init();
}
And the Action:
[AllowAnonymous]
[HttpPost]
public JsonResult UploadFolderFile(string id, Domain.Profile.TypeProfile ProfileType, string tempFile, string name, int? chunk, int? chunks)
{
String strTempFile = string.Empty;
String strSaveLocation = string.Empty;
try
{
var fileData = Request.Files[0];
chunk = chunk ?? 0;
String strExtension = Path.GetExtension(name).ToLower();
Models.Identity.CustomIdentity objUser = new Models.Identity.CustomIdentity(System.Web.Security.FormsAuthentication.Decrypt(id));
DB.CompanyNetworkDB objCompanyDB = new DB.CompanyNetworkDB();
Int32 intMaxFileSize = objCompanyDB.getFileInFolderMaxSize(objUser.CompanyNetworkID) * 1024 * 1024;
if (objUser != null && objUser.IsAuthenticated && fileData.ContentLength <= intMaxFileSize)
{
////Get upload file.
String strSaveLocationURL = Domain.Profile.getUploadItemsFolder(objUser.CompanyNetworkID, ProfileType, Domain.Profile.UploadType.Folder);
strSaveLocationURL += "temp/";
strSaveLocation = Server.MapPath(strSaveLocationURL);
strTempFile = string.IsNullOrEmpty(tempFile) ? DateTime.Now.Ticks.ToString() + strExtension : tempFile;
long fileSize = 0;
using (var fs = new FileStream(Path.Combine(strSaveLocation, strTempFile), chunk == 0 ? FileMode.Create : FileMode.Append))
{
var buffer = new byte[fileData.InputStream.Length];
fileData.InputStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
fileSize = fs.Length;
}
if (fileSize <= intMaxFileSize)
{
if (chunk == chunks - 1)
{
return Json(new { success = true, OriginalFileName = Path.GetFileName(name), ServerFileName = strTempFile, SizeMB = fileSize });
}
else
{
return Json(new { success = true, tempFile = strTempFile });
}
}
else
{
return Json(new { success = false });
}
}
else
{
return Json(new { success = false });
}
}
catch (ArgumentOutOfRangeException)
{
System.IO.File.Delete(Path.Combine(strSaveLocation, strTempFile));
return Json(new { success = false, erro = "canceled" });
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
I think it could help.
I create a new WL.BusyIndicator via this code just before I start a long running process...
if (gblShowBusyIndicator) {
busyIndicator = new WL.BusyIndicator('loader',
{text: 'Refreshing local sales data...',
opacity: 0.85,
fullScreen: true});
busyIndicator.show();
}
Is it possible to update the "text" parameter intermittently during that process? I tried calling this function, but it didn't work. Any ideas?
function setBusyIndicatorStatus(status) {
try {
if (busyIndicator.isVisible()) {
busyIndicator({text: status});
}
} catch (e) {
if (gblLoggerOn) WL.Logger.debug(">> setBusyIndicatorStatus(" + status + ") failure... discarding");
}
}
After some additional thought, here's how I solved the problem, but I'd like to know if there's a better way than toggling show/hide w different status messages at certain points in my code.
Thanks!
function setBusyIndicatorStatus(view, status) {
if (gblLoggerOn) WL.Logger.debug(">> setBusyIndicatorStatus(" + view + ", " + status + ")");
try {
if (busyIndicator.isVisible()) busyIndicator.hide();
} catch (e) {
if (gblLoggerOn) WL.Logger.debug(">> setBusyIndicatorStatus(" + view + ", " + status + ") failure... discarding");
}
busyIndicator = null;
var options = {text: null, opacity: 0.85, fullScreen: true};
options.text = status;
busyIndicator = new WL.BusyIndicator(view, options);
busyIndicator.show();
}
I want to use WebDriver to select a line of text in browser screen(actually in CKEditor editing area) then change its text style from CKEditor toolbar. Any method can do that?
For example, a line with html code like below:
this is a sample line.
I try to use Actions to build a mouse action chain but no success due to not familiar with that. Thanks for any hints or answer.
I'm not sure this is actually possible with WebDriver. What you would want to do is to clickAndHold(...).moveByOffset(...).release(...). Unforunately, WebDriver only allows a WebElement as a parameter to clickAndHold().
My best advice to you is to emulate JavaScript events for this. You can then do something like this in your test:
((JavascriptExecutor) driver).executeScript(...);
I wrote code for emulating mouse events which I use with some of my Selenium tests. Although it doesn't do exactly what you want, hopefully it will be useful (hopefully you can just set the x/y coords and perhaps that will get it working):
var f = function() {
var id = "ext-gen1116";
var top = document.querySelector( '#ext-gen1116:nthchild(0)' );
var bot = document.getElementById( id ).childNodes[3];
var getX = function( obj ) {
if( obj == null ) {
return 0;
} else {
return obj.offsetLeft + getX( obj.offsetParent );
}
}
var getY = function( obj ) {
if( obj == null ) {
return 0;
} else {
return obj.offsetTop + getY( obj.offsetParent );
}
}
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("mousedown", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
bot.dispatchEvent(evt);
evt = document.createEvent("MouseEvents");
evt.initMouseEvent("mousemove", true, true, window,
0, 0, 0, getX( top ) - getX( bot ), getY( top ) - getY( bot ),
false, false, false, false, 0, null);
bot.dispatchEvent(evt);
var mouseup = function( elem ) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("mouseup", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
elem.dispatchEvent(evt);
}
setTimeout( mouseup, 500, bot );
};
f();
If it's possible for you to do what you want with the keyboard instead, this is by far the better solution. You can simply do driver.sendKeys(...). The Keys enum will be priceless for you in this case :-)
You can also try to do it with JavaScript:
let el = document.querySelectorAll("p")[0];
let range = document.createRange();
range.selectNodeContents(el);
window.getSelection().addRange(range);