I am beginning Windows Phone development with Silverlight and web services. I have a web services for User Login where I have two checks before the user is Allowed to log in. I am unable to perform both checks. Only one check is called. My code:
private void login_action(object sender, RoutedEventArgs e)
{
string _username = txtUser.Text;
string _password = txtPass.Password;
kollserviceClient client = new kollserviceClient();
client.validUserCredentialAsync(_username, _password);
client.validUserCredentialCompleted += Client_validUserCredentialCompleted;
client.isStudentUserAsync(_username);
client.isStudentUserCompleted += Client_isStudentUserCompleted;
}
private void Client_isStudentUserCompleted(object sender, isStudentUserCompletedEventArgs e)
{
if (!e.Result)
{
MessageBox.Show("User is Not a Student. Unable to Login", "Error", MessageBoxButton.OK);
return;
}
}
private void Client_validUserCredentialCompleted(object sender, validUserCredentialCompletedEventArgs e)
{
if (e.Result)
{
IsolatedStorageSettings.ApplicationSettings["lgusername"] = txtUser.Text;
NavigationService.Navigate(new Uri("/Home.xaml", UriKind.RelativeOrAbsolute));
}
}
If the Credentials are valid the user is able to log in whether he/she is a student user or not. How can I make both check to be executed?
The way this is coded, I don't believe that you can guarantee the order in which the service calls will return. Therefore, you could store the results from each call, then call a 3rd method that evaluates that both calls have returned. Another option would be to chain the calls so that it does not check if the user is a student until it returns from the credential check and passes, then you can navigate from the return of that call.
First option example:
private void login_action(object sender, RoutedEventArgs e)
{
string _username = txtUser.Text;
string _password = txtPass.Password;
kollserviceClient client = new kollserviceClient();
client.validUserCredentialAsync(_username, _password);
client.validUserCredentialCompleted += Client_validUserCredentialCompleted;
client.isStudentUserAsync(_username);
client.isStudentUserCompleted += Client_isStudentUserCompleted;
}
private bool? isStudent = null;
private bool? isAuthenticated = null;
private void Client_isStudentUserCompleted(object sender, isStudentUserCompletedEventArgs e)
{
isStudent = e.Result;
EvaluateAndNavigate();
}
private void Client_validUserCredentialCompleted(object sender, validUserCredentialCompletedEventArgs e)
{
isAuthenticated = e.Result;
if (isAuthenticated)
{
IsolatedStorageSettings.ApplicationSettings["lgusername"] = txtUser.Text;
}
EvaluateAndNavigate();
}
private void EvaluateAndNavigate()
{
if(isStudent.HasValue && isAuthenticated.HasValue) //both calls have returned
{
if(isStudent.Value && isAuthenticated.Value)
{
NavigationService.Navigate(new Uri("/Home.xaml", UriKind.RelativeOrAbsolute));
}
else
{
MessageBox.Show(string.Format("{0}Unable to Login", isStudent.Value ? "" : "User is Not a Student. " ), "Error", MessageBoxButton.OK);
}
}
}
Related
I'm making an app right now with VisualStudio, and I'm using XAML and C#.
I'm making an app where you can enter a password (existing of numbers only), by clicking on buttons.
If you click on "button 1", it will write a "1" in a label, and if you click on "button 2" afterwards, it will add a "2", making it "12" in total.
If you enter the correct code, like "331122", then you have to press on a button, and a message will pop up saying it is the correct code.
If you fail, then you'll get an error message.
I've also added a "clear" button, that wipes out what you've entered. So far so good. Now I want to add a new button, which will bring you to a passwindow where you can enter your current password (which is the default password: "331122"), and a new password.
If your entered password in the current-password-box matches the default password, your default password will change to the new password you've typed in, if you click on a button below.
If it's incorrect, you'll get an error saying it's incorrect. When you change your password, you should be able to type it in the MainWindow app (by clicking the buttons). The old password has to be completely wiped out, and you should be able to keep on changing your password.
I'm stuck on this.
Here's the code:
string defaultCode = "331122";
public MainWindow()
{
InitializeComponent();
}
//string defaultCode = "331122";
private void knop_1_Click(object sender, RoutedEventArgs e)
{
label_Combinatie.Content += "1";
}
private void knop_2_Click(object sender, RoutedEventArgs e)
{
label_Combinatie.Content += "2";
}
private void knop_3_Click(object sender, RoutedEventArgs e)
{
label_Combinatie.Content += "3";
}
private void knop_klaar_Click(object sender, RoutedEventArgs e)
{
if ((string)label_Combinatie.Content == defaultCode)
{
MessageBox.Show("Unlocked.");
}
else
{
MessageBox.Show("You've entered the wrong code. Please try again.");
}
}
private void knop_reset_Click(object sender, RoutedEventArgs e)
{
label_Combinatie.Content = "";
}
private void knop_verander_code_Click(object sender, RoutedEventArgs e)
{
passwindow w = new passwindow();
w.ShowDialog();
}
public passwindow w { get; set; }
private void button_changePw_Click(object sender, RoutedEventArgs e)
{
string new_code;
new_code = w.textBox_new_code.Text;
defaultCode = w.textBox_current_code.Text;
if (w.textBox_current_code.Text == defaultCode && w.textBox_new_code.Text == new_code)
{
defaultCode = "";
new_code += defaultCode;
new_code = "";
MessageBox.Show("Password changed.");
}
else
{
MessageBox.Show("You've entered an incorrect code. Please try again.");
}
}
Some of the code is in Dutch, so allow me to translate them.
"Knop" means "Button".
"Combinatie" --> "Combination".
"Klaar" -->"Done".
"Verander" --> "Change".
I noticed two issues in your code that may both in combination cause your problems.
First one:
private void knop_verander_code_Click(object sender, RoutedEventArgs e)
{
passwindow w = new passwindow();
w.ShowDialog();
}
public passwindow w { get; set; }
In your method knop_verander_code_Click you are declaring a local variable w, whereas in your class you have declared a property with the same name - the local variable will hide the property.
Second issue:
defaultCode = "";
new_code += defaultCode;
new_code = "";
Here you are basically clearing your defaultCode, adding nothing to your new_code and after all you clear new_code, too.
I am trying to validate windows form with try catch and so far I succeeded. My goal is when someone forgot to fill the gap or put in incorrect entry, catch returns messagebox with a warning. Now I also have Validating event on every control I want to validate so when somebody leave it empty or in incorrect format it will show the error next to the control. That seems ok so far (for me, at least) but my issue is, that if user doesn't even click to one box it only shows message box, but it won't highlight wrong controls.
Below is my code:
private void createButton_Click(object sender, EventArgs e)
{
try
{
Book newBook = new Book(titleBox.Text, authBox.Text, Convert.ToInt32(yearBox.Text), Convert.ToInt32(editBox.Text), pubComboBox.Text, descBox.Text);
bookList.Add(newBook);
booklistListBox.DataSource = bookList;
}
catch (FormatException)
{
MessageBox.Show("You probably missed a gap or put in incorrect form");
}
}
and those validating events:
private void titleBox_Validating(object sender, CancelEventArgs e)
{
if (titleBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(titleBox, "Title is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(titleBox, "");
}
}
private void authBox_Validating(object sender, CancelEventArgs e)
{
if (authBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(authBox, "Author is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(authBox, "");
}
}
private void yearBox_Validating(object sender, CancelEventArgs e)
{
if (yearBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(yearBox, "Year is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(yearBox, "");
}
}
private void editBox_Validating(object sender, CancelEventArgs e)
{
if (editBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(editBox, "Edition is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(editBox, "");
}
}
private void pubComboBox_Validating(object sender, CancelEventArgs e)
{
if (pubComboBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(pubComboBox, "Publisher is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(pubComboBox, "");
}
}
private void descBox_Validating(object sender, CancelEventArgs e)
{
if (descBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(descBox, "Description is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(descBox, "");
}
}
So is there way to, I don't know, change focus or something like that, forced with pressing the create button?
Thank You
Try using ValidateChildren():
private void createButton_Click(object sender, EventArgs e)
{
bool gotIssues = this.ValidateChildren();
if (gotIssues)
{
// someone didn't validate well...
}
}
So, the issue here is that you want to have it highlight in either of two scenarios:
1) When you leave the field and its contents are invalid (empty in this case)
2) When you click the create button and the field in question has invalid contents
And so I would create a single textBox_checkIfEmpty(object sender, EventArgs e) method:
private void textBox_checkIfEmpty(object sender, EventArgs e)
{
var asTb = sender as TextBox;
if (asTb != null && asTb.Text.Trim() == String.Empty)
{
errorProvider.SetError(asTb, "I'll leave it to you to abstract the error message appropriately");
e.Cancel = true;
}
else
{
errorProvider.SetError(asTb, "");
}
}
Then, you can set this method as the handler for your Validate event on your desired required controls, and you can also call the same method from the create button's handler, looping through the required TextBox instances and executing the method on each.
UPDATE
J. Hudler's ValidateChildren solution would be a more (developer) efficient tail to mine, as opposed to looping through the desired controls. That said, if the form has many children, and you only need to validate several, it might be helpful to loop still. Just depends on your specific scenario. My only other question is whether or not ValidateChildren is infinitely recursive, or if it only goes one level down (immediate children rather than all descendants).
the event validating for control call when the mouse click on the control and then leave it from the control. In your case when the user does not click on the control it will not trigger the validating event. U can do this by making your own function and call them on creat event.
private void button1_Click(object sender, EventArgs e)
{
textBox1_Validating(sender);
}
public void textBox1_Validating(object sender)
{
MessageBox.Show("validating");
errorProvider1.SetError(textBox1, "provide");
}
I have the following code to check that a query string has not changed:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
Label_Error.Visible = false;
string query_string = Request.QueryString["GUID"].ToString();
Session["GUID"] = query_string;
}
else
{
string GUID = "";
try
{
GUID = Session["GUID"].ToString();
}
catch (Exception)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
return;
}
if (GUID.Equals(Request.QueryString["GUID"].ToString()) == false)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
}
}
}
Now, I have this code in a button-click event handler to check that the value of the query string has not changed (again):
protected void ImageButton_LogIn_Click(object sender, ImageClickEventArgs e)
{
Validation val = new Validation();
string GUID = "";
string query_string = "";
try
{
GUID = Session["GUID"].ToString();
query_string = Request.QueryString["GUID"].ToString();
}
catch (Exception)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
return;
}
if (val.EmptyString(GUID) == true || val.checkTransactionGUIDExists(GUID) == false || GUID.Equals(query_string) == false)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
}
Now, the problems are two:
1) if I change the query string in the URL and click on the button, the user is not redirected to the error page.
2) if I change the query string in the URL and hit enter in the address bar, the user is not redirected to the error page.
What I want basically is that, when the user is redirected to the web page, it saves the query string into a session. If the user changes the value of the query string in the address bar, and either pressed enter in the address bar or presses my button, he is redirected to the error page.
However, my code is failing. Can anyone help please? Thanks :)
How about this instead?
protected void Page_Load(object sender, EventArgs e)
{
// Always get the query string no matter how the user go to this page
string query_string = Request.QueryString["GUID"].ToString();
// Only store the query string in Session if there is nothing in Session for it
if(null == Session["GUID"])
{
Session["GUID"] = query_string;
}
if (!this.IsPostBack)
{
Label_Error.Visible = false;
}
// Always check to see if the query string value matches what is in Session
string GUID = "";
try
{
GUID = Session["GUID"].ToString();
}
catch (Exception)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
return;
}
if (GUID.Equals(Request.QueryString["GUID"].ToString()) == false)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
}
This should solve your problem of the Session value being overwritten when a query string is put into the address bar and enter is pressed by the user.
I think you problem is that Response.Redirect needs the false at the final of the sentence like Response.Redirect("CheckOutErrorPage.htm", false); becouse that you have it inside the try cath the error will be throw.
I hope that help you.
After some actions I use this.Close(); in C#, which should close form with WebBrowser element. But after closing it my standard installed browser(Chrome) opens with the last URL from WebBrowser element. How can I avoid this?
Code I'm using
public Vk_connect()
{
string url = "https://oauth.vk.com/authorize?client_id=" + appID + "&scope=friends,photos,audio,video,docs,notes,wall,messages&redirect_uri=https://oauth.vk.com/blank.html&display=popup&response_type=token";
this.Text = "Connect to VK";
InitializeComponent();
this.vkconnect.Navigate(url);
vkconnect.Navigated += vkconnect_Navigated;
}
void vkconnect_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
token = vkconnect.Url.ToString();
if (token.Contains("#access_token"))
{
token = token.Split('#')[1];
id = token.Split('=')[3];
token = token.Split('&')[0];
token = token.Split('=')[1];
config.token = token;
config.userid = id;
vkconnect.Stop();
this.Close();
}
}
I am checking whether browser has finished all redirections by looking at webBrowser1.StatusText.
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
if (webBrowser1.StatusText.Equals("Done"))
{
this.Close();
}
}
I am creating a webpage re-loader and I am trying to get number of reload using input from user but I am not able to get number of input from user.
I am trying to get user input in textBox2.Text, but I am having this error:
input string was not in a currect format
This error is in this line kkk = System.Int32.Parse(textBox2.Text);
please help me how to get user input properly in an int value.
this is my program code:
public partial class Form1 : Form
{
public int kkk;
public Form1()
{
InitializeComponent();
}
private void progressBar1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (progressBar1.Value != kkk)
{
do
{
try
{
webBrowser1.Navigate(textBox1.Text);
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
if(webBrowser1.ReadyState == WebBrowserReadyState.Complete)
{
progressBar1.Value = progressBar1.Value + 1;
}
}
MessageBox.Show("Loaded");
}
catch(Exception)
{
MessageBox.Show("failed");
}
}
while(progressBar1.Value !=kkk);
}
}
private void Form1_Load(object sender, EventArgs e)
{
kkk = System.Int32.Parse(textBox2.Text);
progressBar1.Maximum = kkk;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
In your form load event you take the contents of textbox2. text and assign it to kkk. But at that point nothing is inside textBox2 so it throws the error, and rightfully so since the textbox is empty how can it parse to an Int32 if it has no value?
You should assign the value of kkk at some later time during the process. You can always handle the exception before it happens:
int number;
bool result = Int32.TryParse(txtBox2.Text, out number);
if (result)
{
//good conversion you can use number
}
else
{
//not so good
}
But again you are doing this at form load event and I highly doubt there is anything in that textbox based on your code by the time the load event is finished.
The line:
kkk = System.Int32.Parse(textBox2.Text);
is giving an error maybe because it is an empty string which is unable to get parsed to integer. Change it to:
kkk = textBox2.Text.Trim();
if( kkk.Length > 0 ) {
try {
kkk = System.Int32.Parse(kkk);
}
catch { }
}