How to login into Salesforce application using selenium webdriver? - webdriver

public class LoginPage {
private final WebDriver driver;
public LoginPage(WebDriver driver)
{
this.driver = driver;
}
public void loginAs(String username, String password)
{
/* driver.get("https://login.salesforce.com/?locale=uk");
driver.manage().timeouts().implicitlyWait(05, TimeUnit.SECONDS);
System.out.println("READ");
// System.out.println(driver.findElement(By.id("pwcaps")).getText());
//driver.findElement(By.id(username)).sendKeys("sambit");
//driver.findElement(By.className(password)).sendKeys("PWD");
//driver.findElement(By.id(username)).sendKeys("Password");
/*if (driver.findElement(By.className("loginButton")).isEnabled())
{
System.out.println("entered If loop");
System.out.println("login Button is enabled");
driver.findElement(By.className("loginButton")).click();
}
else
{
driver.close();
}*/
if (driver.findElement(By.id("Account_Tab")).isEnabled())
{
System.out.println("Account tab is enabled");
}
else
{
System.out.println("Account tab is not enabled");
}
}
public static void main(String[] args){
// TODO Auto-generated method stub
LoginPage login = new LoginPage(new InternetExplorerDriver());
login.loginAs("sambit.sabyasachi", "check");
}
The webpage shows that this field does not enable automatic filling of the form

Please check this code it work fine for me
public class login
{
public static void main(String[] args)
{
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
WebDriver iedriver = new InternetExplorerDriver(ieCapabilities);
iedriver.get("https://login.salesforce.com/?locale=uk");
try {
Thread.sleep(4000);
} catch (Exception e) {
// TODO: handle exception
}
driver.findElement(By.id("username")).sendKeys("username");
driver.findElement(By.id("password")).sendKeys("password");
driver.findElement(By.id("Login")).click();
}
}

try the following login function.
public void login(String username, String password){
driver.findElement(By.name("username")).sendKeys(username);
driver.findElement(By.cssSelector("input[type='password']")).sendKeys(password);
driver.findElement(By.cssSelector("input[type='submit']")).click();
}
I am not sure what your intentions are once you are logged in, but this works for us for our salesforce based application testing.
You would call this function after loading up the login page.

Related

Enabling basic authentication in webview without custom WebViewClient in Xamarin Forms

I'm using a webview in my Xamarin Forms project with Hybrid Renderer and webview, because I have to inject javascript code inside the page.
In my main project I have a CustomWebview.cs:
namespace ClotureSiadForms.Renderer
{
public class CustomWebView : WebView
{
public string js = "";
public CustomWebView()
{
Navigating+= WebViewNavigating;
Navigated+=WebViewNavigated;
}
private void WebViewNavigated(object sender, WebNavigatedEventArgs args)
{
EvaluateJavaScriptAsync(js);
}
public void WebViewNavigating(object sender, WebNavigatingEventArgs args)
{
if (args.Url.StartsWith("tel:"))
{
var tel = args.Url.Split(':')[1];
args.Cancel = true;
Xamarin.Essentials.PhoneDialer.Open(tel);
}
else if (!args.Url.StartsWith("http") || args.Url.EndsWith(".apk") || args.Url.EndsWith(".pdf") || args.Url.EndsWith(".zip"))
{
args.Cancel = true;
Xamarin.Essentials.Launcher.OpenAsync(args.Url);
}
}
}
}
In my Android project I have a HybridWebViewRenderer.cs:
[assembly: ExportRenderer(typeof(CustomWebView), typeof(HybridWebViewRenderer))]
namespace ClotureSiadForms.Droid.Renderer
{
internal class HybridWebViewRenderer : WebViewRenderer
{
public HybridWebViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (Control != null)
{
CustomWebView webview = e.NewElement as CustomWebView;
Control.Settings.JavaScriptEnabled = true;
Control.Settings.DomStorageEnabled = true;
Control.Settings.SavePassword = true;
}
}
}
}
As is, it worked and was able to download files
But as I needed basic authentication, I added a custom webviewclient inside HybridWebViewRenderer.cs:
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (Control != null)
{
CustomWebView webview = e.NewElement as CustomWebView;
Control.Settings.JavaScriptEnabled = true;
Control.Settings.DomStorageEnabled = true;
Control.Settings.SavePassword = true;
var login = Preferences.Get("login", "");
var password = Preferences.Get("password", "");
Control.SetWebViewClient(new AuthWebViewClient(login, password));
}
}
public class AuthWebViewClient : WebViewClient
{
private string Username;
private string Password;
public AuthWebViewClient(string username, string password)
{
Username = username;
Password = password;
}
public override void OnReceivedHttpAuthRequest(Android.Webkit.WebView view, HttpAuthHandler handler, string host, string realm)
{
handler.Proceed( Username,Password);
}
}
And authentication works, but WebViewNavigating is now called once, then the custom client is set and then WebViewNavigating is never more called.
Then my question is, can't I use basic auth without a custom client or is there a way to keep using my customwebview with the client ?
And authentication works, but WebViewNavigating is now called once, then the custom client is set and then WebViewNavigating is never more called.
I tested the code you provided and added Breakpoint to WebViewNavigating method. Even if you do not add webviewclient, it will only call WebViewNavigating once.
You can put the code in WebViewNavigating to ShouldInterceptRequest:
public class AuthWebViewClient : WebViewClient
{
...
public override WebResourceResponse ShouldInterceptRequest(Android.Webkit.WebView view, IWebResourceRequest request)
{
var url = request.Url;
...
}
}
Whenever the WebView begins loading a new page, it will call ShouldInterceptRequest.

Navigate from a view model in xamarin forms

I am trying to push a view in xamrian forms from the view model but I cant appear to get it to work its really when the user has entered correct username and password it should show the home page.
You will see I have the on submit command this is just mock data at present so dont mind the design of code at this stage will change.
Usually I would use
var stocktakepage = new StockTake();
await Navigation.PushAsync(stocktakepage);
But the model does not no about the navigation stack in the class is their another way to navigate from the view model thanks.
public class LoginViewModel : INotifyPropertyChanged
{
public Action DisplayInvalidLoginPrompt;
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private string email;
public string Email
{
get { return email; }
set
{
email = value;
PropertyChanged(this, new PropertyChangedEventArgs("Email"));
}
}
private string password;
public string Password
{
get { return password; }
set
{
password = value;
PropertyChanged(this, new PropertyChangedEventArgs("Password"));
}
}
public ICommand SubmitCommand { protected set; get; }
public LoginViewModel()
{
SubmitCommand = new Command(OnSubmit);
}
public void OnSubmit()
{
if (email != "handheld1" || password != "test123")
{
DisplayInvalidLoginPrompt();
}else
{
}
}
}
I found the answer here
https://forums.xamarin.com/discussion/21822/call-navigation-pushasync-from-viewmodel But also on my main login page i have this. What this does is act like a delegate and allows you to push the view from the original calling page.
public Login()
{
var vm = new LoginViewModel();
this.BindingContext = vm;
Password.Completed += (object sender, EventArgs e) =>
{
vm.SubmitCommand.Execute(null);
};
}
You can also use the below in order to Navigate from your ViewModel. You can do this for each type of page you want. Check below examples:
await App.Current.MainPage.Navigation.PushAsync(new PageName());
also
await App.Current.MainPage.Navigation.PushModalAsync(new NavigationPage(new PageName()) { BarBackgroundColor = Color.FromHex("#101010"), BarTextColor = Color.White, }, true);

How to run this login program successfully?

import java.io.File;
public class LoginPage {
private final WebDriver driver;
public LoginPage(WebDriver driver) {
this.driver = driver; }
public void loginAs(String username, String password) {
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
// WebDriver driver = new InternetExplorerDriver(ieCapabilities);
driver.get("https://login.salesforce.com/?locale=uk");
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.id("Login")).click();ogin.loginAs("username", "password");}}
}
public static void main(String[] args){
File file = new File("C:/Users/E20039504/Desktop/Selenium Jar/IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
LoginPage login = new LoginPage(new InternetExplorerDriver());
login.loginAs("username", "password");
}
}
I am trying to login to a Salesforce application but this code snipet of mine is not working.Kindly help.
The Id of the password text input is "password" and not "pwd".
To press to Login button, you should also use its Id, which is "Login"
Used password instead of pwd and login instead of login_button
driver.findElement(By.id("pwd")).sendKeys(password);
driver.findElement(By.className("Login_button")).click();
This code is work for me correctly
public class login
{
public static void main(String[] args)
{
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
WebDriver driver = new InternetExplorerDriver(ieCapabilities);
driver.get("https://login.salesforce.com/?locale=uk");
try {
Thread.sleep(4000);
} catch (Exception e) {
// TODO: handle exception
}
driver.findElement(By.id("username")).sendKeys("username");
driver.findElement(By.id("password")).sendKeys("password");
driver.findElement(By.id("Login")).click();
}
}

Show login form after pressing F12 Key

I have an App in Winforms. VS 2010 C#.
What i am trying to do is when the user that is logged in. presses the F12 key the Login form shows up and another user enters the username and password and logs in.
I have attached my Login.cs, Program.cs and Form1.cs
In my main form(Form1.cs) when the user presses the F12 key i am able to show the login form but when i enter the username and password nothing happens.
Right now i am capturing the username when the user first time logs in. I also want to capture the new user when presses the F12 key and logs in.
i am showing the username in a label
label1.Text = myuser.getUserName();
I have tried some code in FORM.CS under Keypress event but it doesn't work
//////////**Program.CS**////////////////
namespace BusinessLayer
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
DialogResult result;
var loginForm = new Login();
result = loginForm.ShowDialog();
if (result == DialogResult.OK)
{
// login was successful
Application.Run(new Form1(loginForm.usr));
}
}
}
}
///////////////////////////////////**Login.CS**/////////////////////
namespace BusinessLayer
{
public partial class Login : Form
{
UserName myuser;
public Login()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
if (CheckPasswordManager.CheckPassword(txtUserID.Text, txtPassword.Text) > 0)
{
usr = new UserName(txtUserID.Text);
DialogResult = DialogResult.OK;
}
else
{
MessageBox.Show("wrong");
}
}
public UserName usr
{
get
{
return myuser;
}
set
{
myuser = value;
}
}
}
}
//////////////////////**Form1.CS**////////////////
namespace BusinessLayer
{
public partial class Form1 : Form
{
UserName myuser;
public Form1(UserName usr)
{
myuser = usr;
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = BookingManager.GetList();
label1.Text = myuser.getUserName();
int GetBookEntryID = Int32.Parse(this.dataGridView1.CurrentRow.Cells["booking_entry_id"].Value.ToString());
dataGridView2.DataSource = ProcessManager.GetList(GetBookEntryID);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
String s = e.KeyCode.ToString();
switch (s)
{
case "F12":
var loginForm = new Login();
this.Hide();
var loginForm = new Login();
loginForm.Show();
}
}
}
}
////////////////username.cs
namespace PassUsername
{
public class Username
{
string userName;
public Username(string uName)
{
userName = uName;
}
public string getUserName()
{
return userName;
}
}
}

JSF custom panel with button - action not invoked

I have built a custom component button, but somehow the action is not invoked. When debugging the getAction-Method within the component and invoking the supplied MethodeExpression the Bean-Method is called as expected. But due to some reason, the Expression is not invoked when pressing the button in the browser.
Is there some kind of additional Interface necessary to pass the action to the embedded button-component?
Any help is very appreciated since I am stuck at this issue for some days now
MyClass:
public class MyClass extends UIPanel implements SystemEventListener
{
private UIForm form;
private HtmlCommandButton buttonOk;
public MyClass()
{
FacesContext context = getFacesContext();
UIViewRoot root = context.getViewRoot();
root.subscribeToViewEvent(PostAddToViewEvent.class, this);
}
#Override
public void processEvent(SystemEvent event)
{
this.form = new UIForm();
this.buttonOk = new HtmlCommandButton();
this.buttonOk.setId("okButtonId");
this.buttonOk.setActionExpression(getAction());
this.buttonOk.setValue("OK");
this.form.getChildren().add(this.buttonOk);
getChildren().add(this.form);
}
private enum PropertyKeys
{
action, text, titel
}
public MethodExpression getAction()
{
return (MethodExpression) getStateHelper().eval(PropertyKeys.action);
}
public void setAction(MethodExpression actionExpression)
{
getStateHelper().put(PropertyKeys.action, actionExpression);
}
public String getText()
{
return (String) getStateHelper().eval(PropertyKeys.text);
}
public void setText(String text)
{
getStateHelper().put(PropertyKeys.text, text);
}
public String getTitel()
{
return (String) getStateHelper().eval(PropertyKeys.titel);
}
public void setTitel(String titel)
{
getStateHelper().put(PropertyKeys.titel, titel);
}
#Override
public void encodeAll(FacesContext context) throws IOException
{
ResponseWriter writer = context.getResponseWriter();
writer.startElement(HTML.DIV_ELEM, this);
writer.writeText(getText(), null);
this.form.encodeAll(context);
writer.endElement(HTML.DIV_ELEM);
}
#Override
public void encodeChildren(FacesContext context) throws IOException
{
}
#Override
public boolean isListenerForSource(Object source)
{
return (source instanceof MyClass);
}
}
MyClassHandler:
public class MyClassHandler extends ComponentHandler
{
public MyClassHandler(ComponentConfig config)
{
super(config);
}
#SuppressWarnings("rawtypes")
#Override
protected MetaRuleset createMetaRuleset(Class type)
{
return super.createMetaRuleset(type).addRule(new MethodRule("action", String.class, new Class[] { ActionEvent.class }));
}
}
myView Method:
...
public String myMethod()
{
System.err.println("myMethod");
return "/some/path/yadayada.xhtml";
}
...
MyView.xhtml
<myTag action="#{myView.myMethod}" id="id1" titel="bla" text="bleh" />
Exdending UICommand is enough, since you only want one action to be executed.
You have to provide two additional MethodExpressions via the tag-attributes and within the decode-method you can check which button has been pressed and redirect the particular MethodExpression to the standard-action provided by UICommand. This way, you dont have to worry about the legacy-interface ActionSource, or how Events are broadcasted.
public void decode(FacesContext contex)
{
Map<String,String> map = context.getExternalContext.getRequestParameterMap();
// your rendered buttons need a name you check for
final boolean okPressed = map.containsKey( getClientId + ":ok" );
final boolean cancelPressed = map.containsKey( getClientId + ":cancel" );
if(okPressed || cancelPressed)
{
MethodExpression exp = null;
if(okPressed)
{
exp = getActionOk();
}
else
{
exp = getActionCancel();
}
// redirect to standard action
setActionExpression(exp);
queueEvent(new ActionEvent(this));
}
}
In order to make use of of this you need two attributes (actionOk and actionCancel) which use Method Expressions (setter and getter). Those have to be configured by a ComponentHandler as you did for the action-attribute.

Resources