C# - WP8: error during validating if it is null? - c#

If the Password boxes are empty. It shows Passwords created Successfully. I dunno whats wrong I did here. But, if entered passwords are not matched, if condition works as per code. Error for validating null.
Code;
void savePassword(object sender, RoutedEventArgs e)
{
string password1 = createPassword.Password;
string password2 = repeatPassword.Password;
if (password1 != null || password2 != null)
{
if (password1 == password2)
{
MessageBox.Show("Password Created Successfully");
}
else
{
MessageBox.Show("Passwords did not match.");
}
}
else
{
MessageBox.Show("Both fields are required");
}
}

You can check if the PasswordBox is filled properly with the string.IsNullOrWhiteSpace or string.IsNullOrEmpty methods. Also, you might want to remove the != because your logic validates as soon as one of the PasswordBoxes has content.
Here's a sample:
//Is true only if both passwords have content
if(!string.IsNullOrWhiteSpace(password1) && !string.IsNullOrWhiteSpace(password2))

Try this
if (password1.Length == 0 || password2.Length == 0)

You have to check that password is empty or null
try this
if (!string.IsNullOrEmpty(password1) &&!string.IsNullOrEmpty(password2))
{
MessageBox.Show("Password Created Successfully");
}
else
{
MessageBox.Show("Passwords did not match.");
}

Related

Error Provider is not clearing itself even if the inputs are valid

I am using Windows Forms and Error Provider to validate my Textbox, the validation works as it intended but even if the input matches the validation, the Error Provider wont clear itself.
Here are some screenshots on the issue.
Here is my code, please advice me on how to fix it.
private void usernamet_Validating(object sender, CancelEventArgs e)
{
int username = usernamet.Text.Length;
ErrorProvider errorProvider = new ErrorProvider();
if (string.IsNullOrEmpty(usernamet.Text))
{
e.Cancel = true;
usernamet.Focus();
errorProvider.SetError(usernamet, "Username cannot be empty");
}
else if (username < 5 || username >= 20 )
{
e.Cancel = true;
usernamet.Focus();
errorProvider.SetError(usernamet, "Username must have more than 5 characters and less than 20 characters.");
}
else if (!Regex.IsMatch(usernamet.Text, #"^[a-zA-Z0-9#.]*$"))
{
e.Cancel = true;
usernamet.Focus();
errorProvider.SetError(usernamet, "Username cannot contain special characters.");
}
else
{
e.Cancel = false;
errorProvider.Clear();
errorProvider.SetError(usernamet, null);
}
}
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.errorprovider.clear?view=netframework-4.7.2
Calling this method clears all property settings for this ErrorProvider, restoring the properties to their default values. To clear the error message, call the SetError method and pass in Empty for the String value. This removes the error glyph from the specified Control.

Logout user after three unsuccesfull attempts - ASP.NET

I am new to programming. In my web application, user will receive a popup alert when he attempts to access restricted page. After three unsuccessful attempts i want him to be logged-out(i.e redirect to logout page). My question is, how to capture each failed attempts.
My existing code for giving alerts,
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Convert.ToString(Session["StaffID"]) != "1" || Convert.ToString(Session["StaffID"]) == null || Convert.ToString(Session["StaffID"]) == "")
{
Response.Write("<script language='javascript'>window.alert('You are not allowed to view this page');window.location='Mainpage.aspx';</script>");
}
}
You can capture each failed attemped by using another session . Please check below code. I am test this in ASP.NET MVC. Session["StaffID"] is your condition check or any condition so use another session to count attempt. Hope it will help you.
public ActionResult OnInit()
{
base.OnInit(e);
var accessCount = Convert.ToInt16(Session["AccessCount"]);
if (Convert.ToString(Session["StaffID"]) != "1" || Convert.ToString(Session["StaffID"]) == null || Convert.ToString(Session["StaffID"]) == "")
{
//Response.Write("<script language='javascript'>window.alert('You are not allowed to view this page');window.location='Mainpage.aspx';</script>");
accessCount++;
if (accessCount <= 3)
{
Session["AccessCount"] = accessCount;
return Content("<script>alert('You are not allowed to view this page')</script>");
}
else
{
Session["AccessCount"] = 0;
return RedirectToAction("logout");
}
}
}

Else does not work

I am not sure what I am doing wrong! The else command and the bracket above it seem not to act correctly:
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (username_txtb.Text == username && password_txtb.Text == password);
{
MessageBox.Show("You are now logged in!");
}
else ;
{
MessageBox.Show("Sorry, you have used the wrong username and password. Please try again.");
}
}
Note that:
else ;
is equivalent to:
else
{
}
So:
else ;
{
//some code
}
is equivalent to:
else
{
}
{
//some code
}
And more clearly, it's equivalent to:
else
{
}
// the conditional clauses are over,
// nothing special here except for an extra scope
// which is a valid construct (even though being useless here)
{
//some code
}
The second block is not really related to the condition - it just a code block in brackets creating a useless scope, and will be always executed.
The same rules apply after if.
else ;
should be
else
Remove the semicolon, it will prevent the body from executing.
private void button1_Click(object sender, EventArgs e)
{
if (username_txtb.Text == username && password_txtb.Text == password) //; - remove
{
MessageBox.Show("You are now logged in!");
}
else //; - remove
{
MessageBox.Show("Sorry, you have used the wrong username and password. Please try again.");
}
}
The presented code results in a syntax error that should read:
Invalid expression term 'else'
The syntax error is caused by the semicolon trailing the if (the semicolon after the else will result in "unexpected behavior" when running the program, and the same principle applies).
if (..);
{
..
}
else ..
Is equivalent to
if (..)
/* empty statement - no code run when if is true! */ ;
/* arbitrary code in a block *not associated* with the `if` */
{
..
}
else ..
In this case the "arbitrary code block" ends the if-statement grammar construct.
To fix the syntax error (and the semantic problem), remove the semi-colons after both the if and else statements:
if (..) /* no semicolon */
{
MessageBox.Show("..");
}
else /* no semicolon */
{
MessageBox.Show("..");
}

Check if unassigned variable exists in Request.QueryString

Within the context of an ASP.NET page, I can use Request.QueryString to get a collection of the key/value pairs in the query string portion of the URI.
For example, if I load my page using http://local/Default.aspx?test=value, then I can call the following code:
//http://local/Default.aspx?test=value
protected void Page_Load(object sender, EventArgs e)
{
string value = Request.QueryString["test"]; // == "value"
}
Ideally what I want to do is check to see if test exists at all, so I can call the page using http://local/Default.aspx?test and get a boolean telling me whether test exists in the query string. Something like this:
//http://local/Default.aspx?test
protected void Page_Load(object sender, EventArgs e)
{
bool testExists = Request.QueryString.HasKey("test"); // == True
}
So ideally what I want is a boolean value that tell me whether the test variable is present in the string or not.
I suppose I could just use regex to check the string, but I was curious if anybody had a more elegant solution.
I've tried the following:
//http://local/Default.aspx?test
Request.QueryString.AllKeys.Contains("test"); // == False (Should be true)
Request.QueryString.Keys[0]; // == null (Should be "test")
Request.QueryString.GetKey(0); // == null (Should be "test")
This behavior is different than PHP, for example, where I can just use
$testExists = isset($_REQUEST['test']); // == True
Request.QueryString.GetValues(null) will get a list of keys with no values
Request.QueryString.GetValues(null).Contains("test") will return true
I wrote an extension method to solve this task:
public static bool ContainsKey(this NameValueCollection collection, string key)
{
if (collection.AllKeys.Contains(key))
return true;
// ReSharper disable once AssignNullToNotNullAttribute
var keysWithoutValues = collection.GetValues(null);
return keysWithoutValues != null && keysWithoutValues.Contains(key);
}
Request.QueryString is a NameValueCollection, but items are only added to it if the query string is in the usual [name=value]* format. If not, it is empty.
If your QueryString was of the form ?test=value, then Request.QueryString.AllKeys.Contains("test") would do what you want. Otherwise, you're stuck doing string operations on Request.Url.Query.
I use this.
if (Request.Params["test"] != null)
{
//Is Set
}
else if(Request.QueryString.GetValues(null) != null &&
Array.IndexOf(Request.QueryString.GetValues(null),"test") > -1)
{
//Not set
}
else
{
//Does not exist
}
TRY this one, it solved my issue!
It will count either the query string has a value or empty and then you can check the required query string value with the Key.
if (!Page.IsPostBack)
{
if (Request.QueryString.Count > 0)
{
if (Request.QueryString["departmentId"] != null)
{
GetSurveyByDeptAndStatus(departmentId: Request.QueryString["departmentId"], status: "Not Surveyed");
rbListEmpsSurvey.Items[1].Selected = true;
}
else if (Request.QueryString["SurveyStatus"] != null)
{
SatisfactionStatus = Request.QueryString["SurveyStatus"] "";
GetSurveyByDeptAndStatus(status: SatisfactionStatus);
GetDepartments();
}}}
Request.QueryString.ToString().Contains("test")
This works in the special case where you're looking for a single querystring parameter, e.g. MyFile.aspx?test
For more complex, general, cases then other solutions would be better.

Run code when both text boxes are empty

In C# how do you display an error message if both text boxes are empty? Is there a code example or validator that can be used?
You will need to use a CustomValidator.
RequiredFieldValidator should do the job?
if you want to know more about validators then look here http://www.codeproject.com/KB/validation/aspnetvalidation.aspx
if (TextBox1.Text == String.Empty && TextBox2.Text == String.Empty)
{
Label1.Text = "Your error message here";
}
else
{
//continue your logic here
}
CustomValidator gives you a callback method. You can use it like any other validator, and write the following code in the [control name]_ServerValidate method:
args.IsValid = TextBox1.Text.Length > 0 && TextBox2.Text.Length > 0;
Abstract to a scalable function:
private bool Validate(params TextBox[] boxes) {
foreach (var box in boxes)
if (string.IsNullOrEmpty(box.Text))
return false;
return true;
}
then call with
if(Validate(TextBox1, TextBox2, ...)) {
/// Do the good stuff
} else {
/// throw error
}
protected submit_click()
{
if((TextBox1.Text=="")||(TextBox2.Text==""))
{
print that error message
}
}

Categories