Using webdriver, I am able to run successfully for the first user & for next user it is failing at if condition. If condition is not working properly - webdriver

If condition is not working properly. I have some set of user id to login to my application, using webdriver, I am able to run successfully for the first user & for next user it is failing at if condition. Please find the code below and it has to check the more if conditions to run successfully.
for (int i = 1; i < sh.getRows(); i++)
{
while(iter.hasNext())
{
System.out.println("Main Window ID :"+iter.next());
}
driver.findElement(By.id("lgnLogin_UserName")).clear();
driver.findElement(By.id("lgnLogin_UserName")).sendKeys(sh.getCell(0,
i).getContents());
driver.findElement(By.id("lgnLogin_Password")).clear();
driver.findElement(By.id("lgnLogin_Password")).sendKeys(sh.getCell(1,
i).getContents());
driver.findElement(By.id("lgnLogin_LoginButton")).click();
Thread.sleep(5000L);
if(driver.findElements(By.linkText("Logout")) != null)
{
driver.findElement(By.id("ctl00_Header_Lbtn_Logout")).click();
msg ="Valid User Login";
System.out.println(msg);
}
else
if(driver.getTitle().contains("700Dealers Inc."))
{
driver.findElement(By.xpath("//table[#id='lgnLogin']/tbody
/tr/td/table/tbody/tr[4]/td")).getText();
System.out.println(msg);
}
else
if(driver.getTitle().contains("Security Question And Answers"))
{
driver.findElement(By.xpath("//table[#id='Table_01']/tbody
/tr[5]/td/table/tbody/tr/td/table/tbody/tr/td/span/span[1]")).getText();
System.out.println(msg);
}
else
if(driver.getTitle().contains("700 credit Change Password"))
{
driver.findElement(By.xpath("//div[#id='panelscreen']/table
/tbody/tr/th/span")).getText();
System.out.println(msg);
}
Please help me out in this issue. Help will be appreciated.

Thread.sleep(5000L); is probably the root of your problems.
So, you may want to replace that :
Thread.sleep(5000L);
if(driver.findElements(By.linkText("Logout")) != null)
with an explicit wait :
try {
WebElement logout = (new WebDriverWait(driver, 5))
.until(new ExpectedCondition<WebElement>(){
#Override
public WebElement apply(WebDriver d) {
return d.findElement(By.linkText("Logout"));
}});
//Logout found, do stuff
} catch(TimeoutException e) {
//No logout element, do stuff
}

Related

Alert Message When TextField is empty (javafx)

I would like for my code to check if the textfields in my form are empty & then show a pop up alert message. My problem is, even if the textfields are filled in this alert message pops up as soon as I hit "ENTER" anyway. Any help is appreciated !
BtnEnter.setOnAction((ActionEvent e) -> {
if (txtfName.getText().isEmpty() | txtlName.getText().isEmpty() |
txtMI.getText().isEmpty() | txtStreeAdd.getText().isEmpty()
| txtCity.getText().isEmpty() | txtZip.getText().isEmpty()
| txtPhone.getText().isEmpty() | txtEmail.getText().isEmpty()
| txtSecEmail.getText().isEmpty()) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Warning");
alert.setHeaderText("Required Fields Empty");
alert.setContentText("The fields highlighted in red must be filled "
+ "out.\nPlease try again.");
alert.showAndWait();
I believe part of the issue may be using the single pipe | for OR instead of the standard ||.
However, there's another approach you could take that may be a little easier to read. This is how I handle validation in my applications:
public boolean validate() {
StringBuilder errors = new StringBuilder();
// Confirm mandatory fields are filled out
if (txtfName.getText().trim().isEmpty()) {
errors.append("- Please enter a first name.\n");
}
if (txtlName.getText().trim().isEmpty()) {
errors.append("- Please enter a last name.\n");
}
if (txtMI.getText().trim().isEmpty()) {
errors.append("- Please enter a middle initial.\n");
}
if (txtStreetAdd.getText().trim().isEmpty()) {
errors.append("- Please enter a street address.\n");
}
if (txtCity.getText().trim().isEmpty()) {
errors.append("- Please enter a city.\n");
}
if (txtZip.getText().trim().isEmpty()) {
errors.append("- Please enter a ZIP code.\n");
}
if (txtPhone.getText().trim().isEmpty()) {
errors.append("- Please enter a phone number.\n");
}
if (txtEmail.getText().trim().isEmpty()) {
errors.append("- Please enter a primary email address.\n");
}
if (txtSecEmail.getText().trim().isEmpty()) {
errors.append("- Please enter a secondary email address.\n");
}
// If any missing information is found, show the error messages and return false
if (errors.length() > 0) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Warning");
alert.setHeaderText("Required Fields Empty");
alert.setContentText(errors.toString());
alert.showAndWait();
return false;
}
// No errors
return true;
}
This has the added benefit of letting the user know exactly what information is missing as well. With this, you simply call the validate() method when the user clicks the action button. If validate() comes back true, you know you have all the information needed.
You can also approach it in this another way without Alert alert = new Alert(Alert.AlertType.WARNING); Here is a piece of code:
public boolean validateForm() {
StringBuilder errors = new StringBuilder();
// Confirm mandatory fields are filled out
if (jTextField1.getText().trim().isEmpty()) {
errors.append("- Please enter a first name.\n");
jTextField1.requestFocusInWindow();
JOptionPane.showMessageDialog(null, errors, "Warning!", JOptionPane.ERROR_MESSAGE);
return false;
}
if (jTextField2.getText().trim().isEmpty()) {
errors.append("- Please enter a last name.\n");
jTextField2.requestFocusInWindow();
JOptionPane.showMessageDialog(null, errors, "Warning!", JOptionPane.ERROR_MESSAGE);
return false;
}
String s = ((JTextField)jDateChooser1.getDateEditor().getUiComponent()).getText();
if (s.equals("")) {
errors.append("- Please choose a date.\n");
jDateChooser1.requestFocusInWindow();
JOptionPane.showMessageDialog(null, errors, "Warning!", JOptionPane.ERROR_MESSAGE);
return false;
}
if (jTextField3.getText().trim().isEmpty()) {
errors.append("- Please enter the age.\n");
jTextField3.requestFocusInWindow();
JOptionPane.showMessageDialog(null, errors, "Warning!", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
In this way, you can check if users know what exactly missing and show them an alert message. Add a listener for the button.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(validateForm()) {
System.out.println("First name: "+jTextField1.getText());
System.out.println("Last name: "+jTextField2.getText());
System.out.println("Date: "+jDateChooser1.getDate());
System.out.println("Age: "+jTextField3.getText());
}
}

Firebase firestore document changes

I just want to ask how can I properly use the document changes in my app? Btw there are 3 types of that which is ADDED, MODIFIED and lastly REMOVED. TYPE.ADDED works perfectly fine, but in modified and removed it doesn't work well in modified it. I am using a recyclerview for that and here's my code. Am I wrong utilizing it? Also, I am using a instance oldindex and newindex to know the index which is affected by the action performed.
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if(doc.getType() == DocumentChange.Type.ADDED) {
PostsClass post = doc.getDocument().toObject(PostsClass.class).withId(doc.getDocument().getId());
postList.add(post);
Log.d(TAG, post.toString());
postsAdapter.notifyDataSetChanged();
}
else if (doc.getType() == DocumentChange.Type.MODIFIED) {
adoptList.clear();
AdoptClass adopt = doc.getDocument().toObject(AdoptClass.class).withId(doc.getDocument().getId());
adoptList.add(adopt);
adoptListAdapter.notifyItemChanged(oldIndex);
}
else if (doc.getType() == DocumentChange.Type.REMOVED) {
adoptList.remove(oldIndex);
adoptListAdapter.notifyItemRemoved(oldIndex);
}
}
below code worked for me in 3 conditions ADDED,MODIFIED,REMOVED (Android Firestore)
for (DocumentChange documentChange : queryDocumentSnapshots.getDocumentChanges()) {
if (documentChange.getType() == DocumentChange.Type.ADDED) {
String doc_id = documentChange.getDocument().getId();
PostModel postModel = documentChange.getDocument().toObject(PostModel.class).withDocId(doc_id);
postModelList.add(postModel);
} else if (documentChange.getType() == DocumentChange.Type.MODIFIED) {
// modifying
String docID = documentChange.getDocument().getId();
PostModel changedModel = documentChange.getDocument().toObject(PostModel.class).withDocId(docID);
if (documentChange.getOldIndex() == documentChange.getNewIndex()) {
// Item changed but remained in same position
postModelList.set(documentChange.getOldIndex(),changedModel);
postListAdapter.notifyItemChanged(documentChange.getOldIndex());
}else {
// Item changed and changed position
postModelList.remove(documentChange.getOldIndex());
postModelList.add(documentChange.getNewIndex(),changedModel);
postListAdapter.notifyItemMoved(documentChange.getOldIndex(),documentChange.getNewIndex());
}
postListAdapter.notifyDataSetChanged();
} else if (documentChange.getType() == DocumentChange.Type.REMOVED) {
// remove
postModelList.remove(documentChange.getOldIndex());
postListAdapter.notifyItemRemoved(documentChange.getOldIndex());
}
}

Sitecore: Show input option after using menu context item

I've added a menu context item to the TreelistEx. This menu item sends a messages that I later catch in a HandleMessage method.
In this method i create a new item ( template type and parent item are given in the source of the treelist field ).
All i need now is a way to ask the user for a name. But i haven't been able to find a simple way to do this.
class MyTreeListEx : TreelistEx, IMessageHandler
{
void IMessageHandler.HandleMessage(Message message)
{
if (message == null)
{ return; }
if (message["id"] == null)
{ return; }
if (!message["id"].Equals(ID))
{ return; }
switch (message.Name)
{
case "treelist:edit":
// call default treelist code
case "mytreelistex:add":
// my own code to create a new item
}
}
}
Does anyone have any suggestions on how to achieve this ?
Edit: added image & code + i'm using Sitecore 8 Update 1
I don't know which version of Sitecore you use but what you can try is SheerResponse.Input method.
You can use it like this:
using Sitecore.Configuration;
using Sitecore.Globalization;
using Sitecore.Shell.Applications.ContentEditor.FieldTypes;
using Sitecore.Web.UI.Sheer;
void IMessageHandler.HandleMessage(Message message)
{
...
case "mytreelistex:add":
Sitecore.Context.ClientPage.Start(this, "AddItem");
break;
}
protected static void AddItem(ClientPipelineArgs args)
{
if (args.IsPostBack)
{
if (!args.HasResult)
return;
string newItemName = args.Result;
// create new item here
// if you need refresh the page:
//SheerResponse.Eval("scForm.browser.getParentWindow(scForm.browser.getFrameElement(window).ownerDocument).location.reload(true)");
}
else
{
SheerResponse.Input("Enter the name of the new item:", "New Item Default Name", Settings.ItemNameValidation,
Translate.Text("'$Input' is not a valid name."), Settings.MaxItemNameLength);
args.WaitForPostBack();
}
}
This code will even validate your new item name for incorrect characters and length.

ASP.NET Entity Framework DataContext use issue

I 've built an ASP.NET website using EF. I created a DataContext class which implements the singleton pattern. My DAO classes (singletons too) instanciate this datacontext and store it in a property. They use it in order to query the SQLServer DataBase. This worked ok for 3 months but I suddenly got exception messages like :"Connection must be valid and open / connection already open". It seemed that datacontext was not disposed. The only change, according to me, was the data size and number of users increasing.
I then found multiple posts saying that singleton was a bad idea foe datacontext, so I tried to instanciate datacontext in a using statement in every request and that resolved the problem, except for update queries which had no effects in database. I had to attach the db object to the context and then set its EntityState to "modified" to have my SaveChanges work.
Like this :
public bool DoucheXpsu(as_headers session) {
using (MyDBEntities MyContext = new MyDBEntities()) {
try {
as_status status = GetStatus(session);
if (status != null) {
if (status.mainstatusvalue == 300) {
status.DateDoucheXpsu = DateTime.Now;
status.DoucheXpsu = 1;
MyContext.as_status.Attach(status);
MyContext.ObjectStateManager.ChangeObjectState(status, EntityState.Modified);
MyContext.SaveChanges();
return true;
} else {
return false;
}
} else {
return false;
}
} catch (OptimisticConcurrencyException) {
return false;
} catch (Exception) {
return false;
}
}
}
The problem is that it actually didn't work for ONE method (which has nothing different from the other update method) !
The exception occured as I tried to attach the object : "The object cannot be attached because it is already in the object context. An object can only be reattached when it is in an unchanged state. " So I had to comment the attach and ChangeObjectState methods to have it work as expected :
public bool SetSessionToDelete(string numSession) {
using (MyDBEntities MyContext = new MyDBEntities()) {
try {
view_headerStatus view = (from v in MyContext.view_headerStatus
where v.CodeSession == numSession
where v.lastinserted == 1
select v).First();
if (view != null) {
as_status status = (from s in MyContext.as_status
where s.jobclsid == view.jobclsid
where s.lastinserted == 1
select s).First();
if (status != null) {
status.DeleteSession = 1;
//MyContext.as_status.Attach(status);
//MyContext.ObjectStateManager.ChangeObjectState(status, EntityState.Modified);
MyContext.SaveChanges();
return true;
} else {
return false;
}
} else {
return false;
}
} catch (OptimisticConcurrencyException) {
return false;
} catch (Exception) {
return false;
}
}
}
The question is WHY should this one behave differently ???
I've read many posts about EF and dataContext but I feel I'm missing something. I would be glad if anyone can help.
Thanks.
In your first example, this line here:
as_status status = GetStatus(session);
I would assume this populates using a DIFFERENT context, and when it leaves the GetStatus() method the context it used to load is disposed. That is why your subsequent Attach() works. However in your second example you do not need to attach because it was loaded using the current (connected) context.
To solve you may want to either pass the context to your methods like GetStatus() resulting in no need to reattach. I don't typically reattach unless I am resurrecting an object over the wire or from a file.

How to persist search criteria and results of a c# .NET application page

Scenario:
User submits search criteria and selects an item from search results on the same page, which navigates to a new page of details for the selected item.
When the User returns to the search screen, the search criteria & results (including selected page and sort-order) should be preserved from their last visit.
Related information:
All form submissions are POSTs.
Navigation back to the search screen may not be available from last browser history (e.g. more than one details screen may be encountered, or the user may navigate directly to the search screen from an alternative menu.)
Search results are provided using Telerik RadGrid control.
I'm looking for a generic solution that will be able to be applied to different search screens.
In some instances, the item may be DELETED from within the details screen, and should therefore not appear in the search results when the screen is next encountered.
Thoughts:
I've read a lot of suggested methods for addressing various parts of this scenario, but I'm still confused; no comprehensively "correct" solution jumps to the forefront.
I guess I'm asking for recommendations/approach rather than a whole solution spelled out for me (although that would be nice! ;-)
The .NET VIEWSTATE would seem to do exactly what I'm after (with the exception of #5) - Is there some way of leveraging off this so that viewstate can be used between pages, and not just between postbacks to the same page? (e.g. can I store/restore viewstate to/from a session variable or something? I haven't seen this suggested anywhere and I'm wondering if there's a reason why.)
Thanks in advance.
Thanks for all the advice.
For the benefit of others, here is a solution to this issue (no doubt there's room for improvement, but this works satisfactorily for the moment).
4 functions...
StoreSearchCookie - Persist the state/values of a panel of search criteria and a results grid in a cookie with a specified UID.
RestoreSearchCookie_Criteria - Read the cookie and re-populate the search criteira
RestoreSearchCookie_Results - Read the cookie and restore the grid state.
FindFormControls - Helper method to recursively find form-input controls in a container (pinched & modified from elsewhere on Stack Overflow)
NB...
I haven't addressed the multiple-tabs issue because our application doesn't allow them anyway.
RestoreSearchResults utilises GridSettingsPersister.cs available from Telerik website, (but I had to modify it to store the page number as well)
Usage is as follows...
protected void Page_PreRender(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
// Store the state of the page
StoreSearchCookie("SomeSearchPage", pnlSearchCriteria, gridResults);
}
else
{
// Restore search criteria
RestoreSearchCookie_Criteria("SomeSearchPage");
// Re-invoke the search here
DoSearch(); // (for example)
// Restore the grid state
RestoreSearchCookie_Results("SomeSearchPage");
}
}
Code follows...
protected void StoreSearchCookie(string cookieName, Panel SearchPanel, RadGrid ResultsGrid)
{
try
{
HttpCookie cookieCriteria = new HttpCookie("StoredSearchCriteria_" + cookieName);
// 1. Store the search criteria
//
List<Control> controls = new List<Control>();
FindFormControls(controls, SearchPanel);
foreach (Control control in controls)
{
string id = control.ID;
string parentId = control.Parent.ID;
string uid = string.Format("{0}>{1}", parentId, id);
string value = "";
Type type = control.GetType();
bool isValidType = true; // Optimistic!
if (type == typeof(TextBox))
{
value = ((TextBox)control).Text;
}
else if (type == typeof(DropDownList))
{
value = ((DropDownList)control).SelectedValue;
}
else if (type == typeof(HiddenField))
{
value = ((HiddenField)control).Value;
}
else if (type == typeof(RadioButton))
{
value = ((RadioButton)control).Checked.ToString();
}
else if (type == typeof(CheckBox))
{
value = ((CheckBox)control).Checked.ToString();
}
else
{
isValidType = false;
}
if (isValidType)
{
cookieCriteria.Values[uid] = value;
}
}
cookieCriteria.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(cookieCriteria);
// 2. Persist the grid settings
//
GridSettingsPersister SavePersister = new GridSettingsPersister(ResultsGrid);
HttpCookie cookieResults = new HttpCookie("StoredSearchResults_" + cookieName);
cookieResults.Values["GridId"] = ResultsGrid.ID;
cookieResults.Values["GridSettings"] = SavePersister.SaveSettings();
cookieResults.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(cookieResults);
}
catch (Exception exception)
{
Logger.Write(exception);
}
}
protected void RestoreSearchCookie_Criteria(string cookieName)
{
try
{
HttpCookie cookieCriteria = Request.Cookies["StoredSearchCriteria_" + cookieName];
if (cookieCriteria != null)
{
foreach (string key in cookieCriteria.Values.AllKeys)
{
string value = cookieCriteria[key];
string[] ids = key.Split('>');
string parentId = ids[0];
string id = ids[1];
Control control = FindControl(parentId).FindControl(id);
Type type = control.GetType();
if (type == typeof(TextBox))
{
((TextBox)control).Text = value;
}
else if (type == typeof(DropDownList))
{
((DropDownList)control).SelectByValue(value);
}
else if (type == typeof(HiddenField))
{
((HiddenField)control).Value = value;
}
else if (type == typeof(RadioButton))
{
((RadioButton)control).Checked = Boolean.Parse(value);
}
else if (type == typeof(CheckBox))
{
((CheckBox)control).Checked = Boolean.Parse(value);
}
}
}
}
catch (Exception exception)
{
Logger.Write(exception);
}
}
protected void RestoreSearchCookie_Results(string cookieName)
{
try
{
HttpCookie cookieResults = Request.Cookies["StoredSearchResults_" + cookieName];
if (cookieResults != null)
{
string gridId = cookieResults.Values["GridId"];
string settings = cookieResults.Values["GridSettings"];
RadGrid grid = (RadGrid)FindControl(gridId);
GridSettingsPersister LoadPersister = new GridSettingsPersister(grid);
LoadPersister.LoadSettings(settings);
grid.Rebind();
}
}
catch (Exception exception)
{
Logger.Write(exception);
}
}
private void FindFormControls(List<Control> foundSofar, Control parent)
{
List<Type> types = new List<Type> { typeof(TextBox), typeof(DropDownList), typeof(RadioButton), typeof(CheckBox), typeof(HiddenField) };
foreach (Control control in parent.Controls)
{
if (types.Any(item => item == control.GetType()))
{
foundSofar.Add(control);
}
if (control.Controls.Count > 0)
{
this.FindFormControls(foundSofar, control); // Use recursion to find all descendants.
}
}
}

Resources