How to run this login program successfully? - webdriver

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();
}
}

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.

Testing login api Spring Security with Postman

I am Working on a spring boot project for an e-commerce website, As a beginner, I try to add spring security in it so the problem is when I try to test my rest login API using postman I have a status code 200 and the body is always the default login page of spring security. I will be thankful for any advice or any solution.
Here is my user class :
public class User implements Serializable {
private static final long serialVersionUID = -2800960695811489984L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String firstName;
private String lastName;
#Column(nullable = false, unique = true)
private String username;
#Column(nullable = false)
private String address;
#Column(nullable = false, unique = true)
private String email;
private String password;
private boolean isEnabled;
#Column(name = "role" , nullable = false)
#Enumerated(EnumType.STRING)
private Role role;
Here is my Role enum :
public enum Role {
USER ,ADMIN
}
MyUserDetails Class :
public class MyUserDetails implements UserDetails {
String ROLE_PREFIX ="ROLE_";
private String email;
private String password;
private boolean active;
private Role role;
public MyUserDetails(User user) {
super();
this.email = user.getEmail();
this.password = user.getPassword();
this.active = user.isEnabled();
this.role = role;
}
public MyUserDetails(String email, String password, boolean enabled, Role role) {
super();
}
public static MyUserDetails create(User user) {
return new MyUserDetails(user.getEmail(), user.getPassword() ,user.isEnabled(), user.getRole());
}
Here is MyUserDetailsService :
#Service
#ToString
public class MyUserDetailsService implements UserDetailsService {
UserRepository userRepository;
#Autowired
public MyUserDetailsService(UserRepository userRepository) {
super();
this.userRepository = userRepository;
}
#Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
if (email == null || email.isEmpty()) {
throw new UsernameNotFoundException("email is Empty");
}
User user = userRepository.findByEmail(email);
if (user != null) {
return user.toCurrentUserDetails();
}
throw new UsernameNotFoundException( email + "is not found !!!");
}
}
Here is my RestController :
#CrossOrigin(origins = "*")
#RestController
#RequestMapping("/home")
public class HomeController {
private AuthenticationManager authenticationManager;
private MyUserDetailsService userDetailsService;
private UserRepository userRepository;
private Jwt jwtUtil;
#Autowired
public HomeController(AuthenticationManager authenticationManager, MyUserDetailsService userDetailsService
, UserRepository userRepository, Jwt jwtUtil) {
this.authenticationManager = authenticationManager;
this.userDetailsService = userDetailsService;
this.userRepository = userRepository;
this.jwtUtil = jwtUtil;
}
#PostMapping("/signin")
public ResponseEntity<ServerResp> addUser(#RequestBody User user) {
ServerResp response = new ServerResp();
try {
if (Validator.isUserEmpty(user)) {
response.setStatus(ResponseCode.BAD_REQUEST_CODE);
response.setMessage(ResponseCode.BAD_REQUEST_MESSAGE);
} else if (!Validator.isValidEmail(user.getEmail())) {
response.setStatus(ResponseCode.BAD_REQUEST_CODE);
response.setMessage(ResponseCode.INVALID_EMAIL_FAIL_MSG);
} else {
user.setRole(Role.USER);
user.setEnabled(true);
User reg = userRepository.save(user);
response.setStatus(ResponseCode.SUCCESS_CODE);
response.setMessage(ResponseCode.CUST_REG);
}
} catch (Exception e) {
response.setStatus(ResponseCode.FAILURE_CODE);
response.setMessage(e.getMessage());
}
return new ResponseEntity<ServerResp>(response, HttpStatus.ACCEPTED);
}
#PostMapping("/login")
public ResponseEntity<ServerResp> authentification(#RequestBody HashMap<String, String> credential) {
final String email = credential.get(WebConstants.USER_EMAIL);
final String password = credential.get(WebConstants.USER_PASSWORD);
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(email, password));
} catch (BadCredentialsException e) {
throw new UserNotFoundException(email);
}
final UserDetails userDetails = userDetailsService.loadUserByUsername(email);
final String jwt = jwtUtil.generateToken(userDetails);
ServerResp resp = new ServerResp();
resp.setStatus(ResponseCode.SUCCESS_CODE);
resp.setMessage(ResponseCode.SUCCESS_MESSAGE);
resp.setAUTH_TOKEN(jwt);
return new ResponseEntity<ServerResp>(resp, HttpStatus.OK);
}
}
Here is my Security Configuration Class :
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private MyUserDetailsService userDetailsService;
private JwtFilter jwtFilter;
#Autowired
DataSource datasource;
#Autowired
public SecurityConfiguration(MyUserDetailsService userDetailsService, JwtFilter jwtFilter) {
this.userDetailsService = userDetailsService;
this.jwtFilter = jwtFilter;
}
public SecurityConfiguration(boolean disableDefaults, MyUserDetailsService userDetailsService, JwtFilter jwtFilter) {
super(disableDefaults);
this.userDetailsService = userDetailsService;
this.jwtFilter = jwtFilter;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/resources/**", "/static/**", "/public/**").permitAll()
.antMatchers("/home/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**")
.hasRole("USER")
.anyRequest().authenticated().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http
.formLogin()
//.loginPage("/home/login")
.usernameParameter("email")
.passwordParameter("password")
.permitAll()
.and()
.logout()
.permitAll();
http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
// TODO Auto-generated method stub
return super.authenticationManagerBean();
}
#Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
Here is my user in the database ( MySQL):
user in database
And finally, this is the result of the test in postman :
Test in Postman
Try sending your credentials using Authorization tab in postman, select authorization type to basic Auth.
I do the following steps with my Spring Boot app that has Spring Security. Note than my set up is most likely different from yours but the key here is the csfr token.
These are the steps I am following to do the login in Postman:
Start my Server
Open a chrome tab and go to developer tools and then the Network tab.
In the Network tab, I go to the DOC tab.
I then enter the url: http://localhost:9005/mywarehouse and press enter
This takes me to the Login Form where I then click on Create User
After the user is created I am taken back to the login form and login with the new user credentials.
In Postman, I submit a GET request such as http://localhost:9005/mywarehouse/products which returns the HTML of my login form instead of JSON.
Now back in chrome developer tab on the Doc tab I go to the last entry which is my login and I right click on it and select "Copy as cURL (bash)"
I then go back into Postman and click on the Import button and select "raw text" and then paste.
I then click on Continue and then Import. This opens up a new tab with a POST request and I click on send.
This returns HTML code. I locate the csfr token and copy it and then go to the Body tab and replace the csfr token that is currently there with the one returned from the HTML.
I then resend the POST request created by the Import and then I go back to my original GET request tab and resend and this time I get the JSON response I was expecting.
I have faced this same issue and I got a solution.
In postman go to the settings --> In General section --> turn off the automatically follow redirects.

Add Firebase Storage service credentials in json file to Heroku config vars for a spring boot app

I have a spring boot app deployed on Heroku which is also using Firebase Storage to store files. Everything works fine locally as I am able to authenticate to Firebase Storage by specifying the path to the firebase admin sdk service account key like this:
FileInputStream serviceAccount =
new FileInputStream("path/to/key.json");
StorageOptions.newBuilder()
.setProjectId(projectId)
.setCredentials(GoogleCredentials.fromStream(serviceAccount)).build();
it is not safe to add the service account key to the project which would then be committed to git. How can this be externalized such that the service key is part of Heroku's config vars when deployed to Heroku? I have tried adding the raw json content to the application.properties and reading to a temp file but I get an error when I try to set the credentials from the temp file path.
Path tempFile = createTempFile();
if (tempFile == null) throw new Exception("google storage credentials not found");
FileInputStream serviceAccount =
new FileInputStream(tempFile.toString);
StorageOptions.newBuilder()
.setProjectId(projectId)
.setCredentials(GoogleCredentials.fromStream(serviceAccount)).build();
//create temp file
private Path createTempFile() {
Path path = null;
try {
path = Files.createTempFile("serviceaccount", ".json");
System.out.println("Temp file : " + path);
//writing data
String credentials = environment.getRequiredProperty("GOOGLE_APPLICATION_CREDENTIALS");
byte[] buffer = credentials.getBytes();
Files.write(path, buffer);
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
this works for me -
custom.firebase.credentials is the json i.e. just copy the contents of the json file and blindly paste it
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseAuth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
#Configuration
public class FirebaseConfig {
private final String firebaseCredentials;
public FirebaseConfig(#Value("${custom.firebase.credentials}") String firebaseCredentials) {
this.firebaseCredentials = firebaseCredentials;
}
#Primary
#Bean
public FirebaseApp firebaseApp() throws IOException {
if (FirebaseApp.getApps().isEmpty()) {
InputStream credentialsStream = new ByteArrayInputStream(firebaseCredentials.getBytes());
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(GoogleCredentials.fromStream(credentialsStream)).build();
FirebaseApp.initializeApp(options);
}
return FirebaseApp.getInstance();
}
#Bean
public FirebaseAuth firebaseAuth() throws IOException {
return FirebaseAuth.getInstance(firebaseApp());
}
}
I don't have enough reputation yet to comment directly on it, but keemahs solution worked perfectly and was super easy! Just paste the entire json as a config var in the heroku console like so.
Config vars
I finally got an idea from discussions with a friend on a way to go about this. First, I had to create a class that contains fields to hold the contents of the json credentials. The class is as follows:
public class FirebaseCredential {
private String type;
private String project_id;
private String private_key_id;
private String private_key;
private String client_email;
private String client_id;
private String auth_uri;
private String token_uri;
private String auth_provider_x509_cert_url;
private String client_x509_cert_url;
public String getType() {
return type;
}
public String getProject_id() {
return project_id;
}
public String getPrivate_key_id() {
return private_key_id;
}
public String getPrivate_key() {
return private_key;
}
public String getClient_email() {
return client_email;
}
public String getClient_id() {
return client_id;
}
public String getAuth_uri() {
return auth_uri;
}
public String getToken_uri() {
return token_uri;
}
public String getAuth_provider_x509_cert_url() {
return auth_provider_x509_cert_url;
}
public String getClient_x509_cert_url() {
return client_x509_cert_url;
}
public void setType(String type) {
this.type = type;
}
public void setProject_id(String project_id) {
this.project_id = project_id;
}
public void setPrivate_key_id(String private_key_id) {
this.private_key_id = private_key_id;
}
public void setPrivate_key(String private_key) {
this.private_key = private_key;
}
public void setClient_email(String client_email) {
this.client_email = client_email;
}
public void setClient_id(String client_id) {
this.client_id = client_id;
}
public void setAuth_uri(String auth_uri) {
this.auth_uri = auth_uri;
}
public void setToken_uri(String token_uri) {
this.token_uri = token_uri;
}
public void setAuth_provider_x509_cert_url(String auth_provider_x509_cert_url) {
this.auth_provider_x509_cert_url = auth_provider_x509_cert_url;
}
public void setClient_x509_cert_url(String client_x509_cert_url) {
this.client_x509_cert_url = client_x509_cert_url;
}}
I then created the following environment properties to hold the values of the json credentials file:
FIREBASE_BUCKET_NAME=<add-the-value-from-config.json>
FIREBASE_PROJECT_ID=<add-the-value-from-config.json>
FIREBASE_TYPE=<add-the-value-from-config.json>
FIREBASE_PRIVATE_KEY_ID=<add-the-value-from-config.json>
FIREBASE_PRIVATE_KEY=<add-the-value-from-config.json>
FIREBASE_CLIENT_EMAIL=<add-the-value-from-config.json>
FIREBASE_CLIENT_ID=<add-the-value-from-config.json>
FIREBASE_AUTH_URI=<add-the-value-from-config.json>
FIREBASE_TOKEN_URI=<add-the-value-from-config.json>
FIREBASE_AUTH_PROVIDER_X509_CERT_URL=<add-the-value-from-config.json>
FIREBASE_CLIENT_X509_CERT_URL=<add-the-value-from-config.json>
With the properties set up, it is possible to read the environment values and set them in a FirebaseCredential object, serialize the object to a json string and finally convert it to an InputStream object as seen below:
private InputStream createFirebaseCredential() throws Exception {
//private key
String privateKey = environment.getRequiredProperty("FIREBASE_PRIVATE_KEY").replace("\\n", "\n");
FirebaseCredential firebaseCredential = new FirebaseCredential();
firebaseCredential.setType(environment.getRequiredProperty("FIREBASE_TYPE"));
firebaseCredential.setProject_id(projectId);
firebaseCredential.setPrivate_key_id("FIREBASE_PRIVATE_KEY_ID");
firebaseCredential.setPrivate_key(privateKey);
firebaseCredential.setClient_email(environment.getRequiredProperty("FIREBASE_CLIENT_EMAIL"));
firebaseCredential.setClient_id(environment.getRequiredProperty("FIREBASE_CLIENT_ID"));
firebaseCredential.setAuth_uri(environment.getRequiredProperty("FIREBASE_AUTH_URI"));
firebaseCredential.setToken_uri(environment.getRequiredProperty("FIREBASE_TOKEN_URI"));
firebaseCredential.setAuth_provider_x509_cert_url(environment.getRequiredProperty("FIREBASE_AUTH_PROVIDER_X509_CERT_URL"));
firebaseCredential.setClient_x509_cert_url(environment.getRequiredProperty("FIREBASE_CLIENT_X509_CERT_URL"));
//serialization of the object to json string
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(firebaseCredential);
//convert jsonString string to InputStream using Apache Commons
return IOUtils.toInputStream(jsonString);
}
The resulting InputStream object is used to initialize the Firebase Storage or Admin as the case may be.
InputStream firebaseCredentialStream = createFirebaseCredential();
StorageOptions.newBuilder()
.setProjectId(projected)
.setCredentials(GoogleCredentials.fromStream(firebaseCredentialStream))
.build();

How to login into Salesforce application using selenium 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.

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;
}
}
}

Resources