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;
}
}
}
Related
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.
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);
I am getting data from a web service and I am loading it in Picker. Now I want to call a new web service to get some data related to selected item. But I am not getting that selected item.
I am using below class model to get data from web service and loading it in Picker.
public class ModelGetEmployeeList
{
public string ServiceStatus { get; set; }
public List<EmployeeList> EmpList { get; set; }
}
public class EmployeeList
{
public string uid { get; set; }
public string fname { get; set; }
public string lname { get; set; }
}
This is how I loaded data in Picker:
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync ();
var Items = JsonConvert.DeserializeObject <ModelGetEmployeeList> (content);
foreach(EmployeeList emp in Items.EmpList)
{
pickerEmployee.Items.Add(emp.uid.ToString()+"-"+emp.fname.ToString()+" "+emp.lname.ToString());
}
}
Now I am implementing SelectedIndexChanged event like this:
public void PickerEmployee_SelectedIndexChanged(object sender, SelectedItemChangedEventArgs e)
{
if (pickerEmployee.SelectedIndex == -1)
{
//Message
}
else
{
var item = sender as EmployeeList;
var selectedItem = item.uid;
DisplayAlert (selectedItem.ToString (), "OK", "OK");
}
}
But its giving me an error that above method has wrong signature.
You can take sellected value with this:
string selectedEmployee = string.Empty;
selectedEmployee = pickerEmployee.Items[pickerEmployee.SelectedIndex];
According to the Xamarin.Forms Picker documentation SelectedIndexChanged event is expecting delegate which matches EventHandler delegate (EventHandler documentation)
So, you have to change signature of your method :
public void PickerEmployee_SelectedIndexChanged(object sender, EventArgs e)
{
...
}
Your signature is wrong.
Also the following code is wrong:
var item = sender as EmployeeList;
var selectedItem = item.uid;
Please find the corrected version below :
public void PickerEmployee_SelectedIndexChanged(object sender, EventArgs e)
{
if (pickerEmployee.SelectedIndex == -1)
{
//Message
}
else
{
var selectedItem = PickerEmployee[SelectedIndex];
DisplayAlert (selectedItem, "OK", "OK");
}
}
The Xamarin Forms picker will get you only the string which was added to the list and not the object.
If you need the object either you can use the selectedIdex on your orginal lsit to get the object as :
var selectedEmp = Items.EmpList[SelectedIndex];
Or you can use a Bindable Picker.
public void PickerEmployee_SelectedIndexChanged(object sender, EventArgs e)
{
if (pickerEmployee.SelectedIndex == -1)
{
//Message
}
else
{
var selectedItem = (EmployeeList)PickerEmployee.SelectedItem;
DisplayAlert (selectedItem.fname, "OK", "OK");
}
}
public void PickerEmployee_SelectedIndexChanged(object sender, SelectedItemChangedEventArgs e)
{
if (pickerEmployee.SelectedIndex == -1)
{
//Message
}
else
{
var item = sender as Picker;
var selectedItem = item.SelectedItem as EmployeeList;
var uid =selectedItem.uid;
DisplayAlert (uid .ToString (), "OK", "OK");
}
}
The Items collection is a list of strings so you can get the currently selected value using SelectedIndex
var selectedValue = picker.Items [picker.SelectedIndex];
If you are using binding then yes, the exposed property is the SelectedIndex.
For more info click here
//How to get value of picker in Xamarin forms
//We are getting Text and Value from API
//xaml page
<controls:BorderlessPicker
x:Name="Pickdoctype"
ItemDisplayBinding="{Binding text}"
SelectedIndexChanged="Pickdoctype_SelectedIndexChanged"
HorizontalOptions="FillAndExpand"
Title="Enter Document Type"
FontSize="20"
TextColor="Gray">
</controls:BorderlessPicker>
// xaml.cs page
private void Pickdoctype_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
DocumentTypeModel selectedItem = (DocumentTypeModel)Pickdoctype.SelectedItem;
updatePickerValue = selectedItem.value;
}
catch (Exception ex)
{
}
}
// class
public class DocumentTypeModel
{
public string text { get; set; }
public string value { get; set; }
}
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.
I am trying to get a sample to work using MVVM Light and the Messaging Class. In the sample, I have a test project created from the MVVM Template for Silveright 4. I have added a button on the main page. When the button is clicked, it updates a property on the ViewModel. When the property is updated, I want to show a messagebox with the new value.
The key line of code is:
Messenger.Default.Register(this, new Action(ShowMessage));
I can get this to work in WPF, but not silverlight. It should call ShowMessage with the string parameter when the property changes, but it does not. If I use:
Messenger.Default.Send("Hello MVVM");
This works and the string is sent as a message to ShowMessage.
However, the message does not get sent if the property changes, even though the property was created with the MVVMINPC snippet and has the following line:
RaisePropertyChanged(MyPropertyPropertyName, oldValue, value, true);
This should have the same effect as Messager.Default.Send but it seems to be ignored. ThePropertyChangedEvent is indeed raised, but the messanger part seems to be disconnected.
Am I doing something wrong? Here is the full MainViewModel:
public class MainViewModel : ViewModelBase
{
public RelayCommand MyRelayCommand { get; set; }
public const string MyPropertyPropertyName = "MyProperty";
private string _myProperty = "test";
public string MyProperty
{
get
{
return _myProperty;
}
set
{
if (_myProperty == value)
{
return;
}
var oldValue = _myProperty;
_myProperty = value;
RaisePropertyChanged(MyPropertyPropertyName, oldValue, value, true);
}
}
public void DoSomething()
{
//Messenger.Default.Send("Hello MVVM"); //Works
this.MyProperty = "Hello World"; //Doesn't work.
}
public void ShowMessage(string message)
{
MessageBox.Show(message);
}
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
Messenger.Default.Register(this, new Action<string>(ShowMessage));
MyRelayCommand = new RelayCommand(new Action(DoSomething));
this.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(MainViewModel_PropertyChanged);
}
void MainViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
MessageBox.Show(e.PropertyName);
}
}public class MainViewModel : ViewModelBase
{
public RelayCommand MyRelayCommand { get; set; }
public const string MyPropertyPropertyName = "MyProperty";
private string _myProperty = "test";
public string MyProperty
{
get
{
return _myProperty;
}
set
{
if (_myProperty == value)
{
return;
}
var oldValue = _myProperty;
_myProperty = value;
RaisePropertyChanged(MyPropertyPropertyName, oldValue, value, true);
}
}
public void DoSomething()
{
//Messenger.Default.Send("Hello MVVM"); //Works
this.MyProperty = "Hello World"; //Doesn't work.
}
public void ShowMessage(string message)
{
MessageBox.Show(message);
}
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
Messenger.Default.Register(this, new Action<string>(ShowMessage));
MyRelayCommand = new RelayCommand(new Action(DoSomething));
this.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(MainViewModel_PropertyChanged);
}
void MainViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
MessageBox.Show(e.PropertyName);
}
}v
OK, I found that the Register line should look like this:
Messenger.Default.Register(this, new Action<PropertyChangedMessage<string>>(ShowMessage));
The point being there are different types of messages, and you have to register the PropertyChangedMessage type to recieve property changed messages.
Then also, the Action that recieves the message needs to take the correct parameter, like this:
public void ShowMessage(PropertyChangedMessage<string> e)
{
MessageBox.Show(e.NewValue.ToString());
}