How to recheck field A from field B by using TextChanged? - c#

I am having a little problem here. Here is my situation:
I am typing user name: tester (valid user name; avoiding all checks) and then type password: testerr (valid password; avoiding all checks). Problem is that I am checking for the same inputs. And in my code when both inputs are the same I will see a notification. Now, when I type tester as user name and password I get the error, but when I add additional character to my password 'testerr' I am making password valid, but user name is checked as invalid saying that both are still the same and making my validation impossible.
How can avoid this? I was thinking of rechecking user name field from field 2, but I'm not sure how.
bool passIsValid, userIsValid;
public AuthenticationWindow()
{
InitializeComponent();
// Creating TextChanged events which till validate input fields.
txtUserName.TextChanged += new EventHandler(txtUserName_TextChanged);
txtPassword.TextChanged += new EventHandler(txtPassword_TextChanged);
}
private void txtUserName_TextChanged(object sender, EventArgs e)
{
// Checking for empty user name field.
if (string.IsNullOrEmpty(txtUserName.Text))
{
lblMessageUser.Text = "User Name field cannot be empty!";
lblMessageUser.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
userIsValid = false;
}
// Making sure that user name is at least 6 characters long.
else if (txtUserName.Text.Length < 6)
{
lblMessageUser.Text = "User Name field must be at least 6 characters long!";
lblMessageUser.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
userIsValid = false;
}
// Checking for user name made of same repeating character.
// Invalid example: 'aaaaaa'
else if (!txtUserName.Text.Distinct().Skip(1).Any())
{
lblMessageUser.Text = "User Name cannot be made of repeating the same characters!";
lblMessageUser.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
userIsValid = false;
}
// Making sure that password and user name aren't the same.
else if (txtUserName.Text == txtPassword.Text)
{
lblMessageUser.Text = "User Name and Password can not be the same!";
lblMessagePass.Text = "User Name and Password can not be the same!";
lblMessageUser.ForeColor = Color.IndianRed;
lblMessagePass.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
userIsValid = false;
passIsValid = false;
}
// If all other checks aren't trigered; enable authentication.
else
{
lblMessageUser.Text = "User Name is valid.";
lblMessageUser.ForeColor = Color.Green;
userIsValid = true;
if (passIsValid && userIsValid)
{
btnAuthenticate.Enabled = true;
}
}
}
private void txtPassword_TextChanged(object sender, EventArgs e)
{
// Checking for Null or Empty string in password field.
if (string.IsNullOrEmpty(txtPassword.Text))
{
lblMessagePass.Text = "Password field cannot be empty!";
lblMessagePass.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
passIsValid = false;
}
// Making sure that password is at least 6 characters long.
else if (txtPassword.Text.Length < 6)
{
lblMessagePass.Text = "Password field must be at least 6 characters long!";
lblMessagePass.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
passIsValid = false;
}
// Checking for password made of same repeating character.
// Invalid example: 'aaaaaa'
else if (!txtPassword.Text.Distinct().Skip(1).Any())
{
lblMessagePass.Text = "Password cannot be made of repeating the same characters!";
lblMessagePass.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
passIsValid = false;
}
// Making sure that user name and password are not the same.
// Security measure.
else if (txtUserName.Text == txtPassword.Text)
{
lblMessageUser.Text = "User Name and Password can not be the same!";
lblMessagePass.Text = "User Name and Password can not be the same!";
lblMessageUser.ForeColor = Color.IndianRed;
lblMessagePass.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
userIsValid = false;
passIsValid = false;
}
// If all other checks aren't trigered; enable authentication.
else
{
lblMessagePass.Text = "Password is valid.";
lblMessagePass.ForeColor = Color.Green;
passIsValid = true;
if (passIsValid && userIsValid)
{
btnAuthenticate.Enabled = true;
}
}
}

You can merge your both events into one, then the user sees all errors and your check could be successful.
bool passIsValid, userIsValid;
public AuthenticationWindow()
{
InitializeComponent();
// Creating TextChanged events which till validate input fields.
txtUserName.TextChanged += new EventHandler(txtCheck_TextChanged);
txtPassword.TextChanged += new EventHandler(txtCheck_TextChanged);
}
private void txtCheck_TextChanged(object sender, EventArgs e)
{
// Checking for empty user name field.
if (string.IsNullOrEmpty(txtUserName.Text))
{
lblMessageUser.Text = "User Name field cannot be empty!";
lblMessageUser.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
userIsValid = false;
}
// Making sure that user name is at least 6 characters long.
else if (txtUserName.Text.Length < 6)
{
lblMessageUser.Text = "User Name field must be at least 6 characters long!";
lblMessageUser.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
userIsValid = false;
}
// Checking for user name made of same repeating character.
// Invalid example: 'aaaaaa'
else if (!txtUserName.Text.Distinct().Skip(1).Any())
{
lblMessageUser.Text = "User Name cannot be made of repeating the same characters!";
lblMessageUser.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
userIsValid = false;
}
else
{
userIsValid = true;
lblMessageUser.Text = "Password is valid.";
lblMessageUser.ForeColor = Color.Green;
}
// Checking for Null or Empty string in password field.
if (string.IsNullOrEmpty(txtPassword.Text))
{
lblMessagePass.Text = "Password field cannot be empty!";
lblMessagePass.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
passIsValid = false;
}
// Making sure that password is at least 6 characters long.
else if (txtPassword.Text.Length < 6)
{
lblMessagePass.Text = "Password field must be at least 6 characters long!";
lblMessagePass.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
passIsValid = false;
}
// Checking for password made of same repeating character.
// Invalid example: 'aaaaaa'
else if (!txtPassword.Text.Distinct().Skip(1).Any())
{
lblMessagePass.Text = "Password cannot be made of repeating the same characters!";
lblMessagePass.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
passIsValid = false;
}
else
{
passIsValid = true;
lblMessagePass.Text = "Password is valid.";
lblMessagePass.ForeColor = Color.Green;
}
// Making sure that user name and password are not the same.
// Security measure.
if (txtUserName.Text == txtPassword.Text)
{
lblMessageUser.Text = "User Name and Password can not be the same!";
lblMessagePass.Text = "User Name and Password can not be the same!";
lblMessageUser.ForeColor = Color.IndianRed;
lblMessagePass.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
userIsValid = false;
passIsValid = false;
}
// If all other checks aren't trigered; enable authentication.
if (passIsValid && userIsValid)
{
btnAuthenticate.Enabled = true;
}
}

Related

Cant seem to find why this Xunit test wont work in .net, it works on the frondend

I am trying to test a Food waste sytem in which students can reserve mealboxes so they can pick them up at a cheap price.
the test im trying to run is as follows: Dont allow someone to reserve 2 mealboxes for the same pickup date
[Fact]
//unhappy
public void MealBox_Student_Already_Reserved_Same_Date()
{
// Arrange
var repositoryManagerMock = new Mock<IRepositoryManager>();
ServiceManager _ss = new ServiceManager(repositoryManagerMock.Object);
var MealboxList = new List<MealBox>();
var Student = new Student
{
Id = 1,
FirstName = "Test",
LastName = "Student",
Email = "test#gmail.com",
DateOfBirth = DateTime.Now.AddYears(-15),
StudentNumber = "210897",
StudyCity = City.Breda,
MobileNumber = "0612345678",
ReservedMealBoxes = MealboxList
};
MealboxList.Add(new MealBox
{
Id = 1,
Name = "Test MealBox",
PickupDateTime = DateTime.Now.AddDays(1),
LatestPickupTime = DateTime.Now.TimeOfDay,
IndicationalIs18Plus = false,
IsHotMeal = false,
Price = 10,
MealType = MealType.ColdLunch,
ExampleProductsBasedOnHistory = new List<Product>(),
ReservedBy = Student,
ReservedById = 1,
OfferedAtCanteen = null,
OfferedAtCanteenId = 1
});
var MealBox = new MealBox
{
Id = 2,
Name = "Test MealBox",
PickupDateTime = DateTime.Now.AddDays(1),
LatestPickupTime = DateTime.Now.TimeOfDay,
IndicationalIs18Plus = false,
IsHotMeal = false,
Price = 10,
MealType = MealType.ColdLunch,
ExampleProductsBasedOnHistory = new List<Product>(),
ReservedBy = null,
ReservedById = null,
OfferedAtCanteen = null,
OfferedAtCanteenId = 1
};
repositoryManagerMock.Setup(x => x.MealBox.GetById(2)).Returns(MealBox);
repositoryManagerMock.Setup(x => x.Student.GetByEmail(Student.Email)).Returns(Student);
// Act
ServiceResponse message = _ss.MealBox.Reserve(2, Student.Email);
// Assert
Assert.Equal("You have already reserved a mealbox for this date", message.Message);
}
this is my validator
public ServiceResponse Reserve(int id, string email)
{
var response = new ServiceResponse();
var student = _repositoryManager.Student.GetByEmail(email);
if (student == null)
{
response.Success = false;
response.Message = "Student not found";
return response;
}
var mealBox = _repositoryManager.MealBox.GetById(id);
if (mealBox == null)
{
response.Success = false;
response.Message = "MealBox not found";
return response;
}
var resultOfChecks = MealBoxReserveChecks(response, mealBox, student);
if (!resultOfChecks.Success)
{
return resultOfChecks;
}
mealBox.ReservedById = student.Id;
try
{
_repositoryManager.MealBox.Update(mealBox);
_repositoryManager.Save();
}
catch (Exception ex)
{
throw ex;
}
response.Success = true;
response.Message = "MealBox reserved successfully!";
return response;
}
private ServiceResponse MealBoxReserveChecks(ServiceResponse response, MealBox mealBox, Student student)
{
if (mealBox.ReservedBy != null)
{
response.Success = false;
response.Message = "MealBox already reserved";
return response;
}
if (mealBox.IndicationalIs18Plus)
{
int hasToBePickedUp = Int32.Parse(mealBox.PickupDateTime.ToString("yyyyMMdd"));
int dateOfBirth = Int32.Parse(student.DateOfBirth.ToString("yyyyMMdd"));
if (((hasToBePickedUp - dateOfBirth) / 10000) < 18)
{
response.Success = false;
response.Message = "You are not 18+ and cannot reserve this mealbox";
return response;
}
}
var reservedMealBoxes = _repositoryManager.MealBox.GetAll().Where(mb => mb.ReservedById == student.Id).ToList();
if (reservedMealBoxes.Any(mb => mb.PickupDateTime.Day == mealBox.PickupDateTime.Day))
{
response.Success = false;
response.Message = "You have already reserved a mealbox for this date";
return response;
}
response.Success = true;
return response;
}
in Xunit with this code my mealbox will still be reserved succesfully, which is so weird
someone know the answer to my problem?
I tried many things such as changing the way the mealbox is added to the user, but nothing worked.
the goal is to get the error that you already have a mealbox reserved for this date

How To Use Nested Ternary Operator In C#?

Here i have used if , else if condition to show an error message and make some label visible and invisible, but i am trying to use ternary operator to do so but i am quite unfamiliar with ternery operator and unable to use it for all condition i have in my if else code.
So any help with my code will be highly appreciated. Thank you.
Below is my code
catch (Exception ex)
{
if (ex.Message == "Parent Menu Title Required")
{
metroLabel4.Visible = true;
metroLabel5.Visible = false;
metroLabel6.Visible = false;
metroLabel4.Text = ex.Message;
}
else if (ex.Message == "Menu Title Required")
{
metroLabel4.Visible = false;
metroLabel5.Visible = true;
metroLabel6.Visible = false;
metroLabel5.Text = ex.Message;
}
else if (ex.Message == "Form Name Required")
{
metroLabel4.Visible = false;
metroLabel5.Visible = false;
metroLabel6.Visible = true;
metroLabel6.Text = ex.Message;
}
else
{
metroLabel4.Visible = true;
metroLabel5.Visible = true;
metroLabel6.Visible = true;
metroLabel4.Text = "Parent Menu Title Required";
metroLabel5.Text = "Menu Title Required";
metroLabel6.Text = "Form Name Required";
}
}
The ternary operator is not a good fit for your problem. It is used to set the value of one variable to one of two values, based on a predicate:
var thingToSet = predicateA ?
ifPredicateAIsTrue :
ifPredicateAIsFalse;
This is the same as:
if (predicateA)
thingToSet = ifPredicateAIsTrue;
else
thingToSet = ifPredicateAIsFalse;
To nest ternary expressions, place a new ternary expression in the value to set:
var otherThingToSet = predicateB ? (
predicateC ?
ifPredicateCIsTrue :
ifPredicateCIsFalse
) : (
predicateD ?
ifPredicateDIsTrue :
ifPredicateDIsFalse
);
This is equivalent to:
if (predicateB)
{
if (predicateC)
otherThingToSet = ifPredicateCIsTrue;
else
otherThingToSet = ifPredicateCIsFalse;
}
else
{
if (predicateD)
otherThingToSet = ifPredicateDIsTrue;
else
otherThingToSet = ifPredicateDIsFalse;
}
As you can see, this is not really a good fit for your problem, as you're trying to set the value of several variables, based on the exception message.
A better fit for your problem would be a switch statement:
switch (ex.Message)
{
case "Parent Menu Title Required":
metroLabel4.Visible = true;
metroLabel5.Visible = false;
metroLabel6.Visible = false;
metroLabel4.Text = ex.Message;
break;
case "Menu Title Required":
metroLabel4.Visible = false;
metroLabel5.Visible = true;
metroLabel6.Visible = false;
metroLabel5.Text = ex.Message;
break;
case "Form Name Required":
metroLabel4.Visible = false;
metroLabel5.Visible = false;
metroLabel6.Visible = true;
metroLabel6.Text = ex.Message;
break;
default:
metroLabel4.Visible = true;
metroLabel5.Visible = true;
metroLabel6.Visible = true;
metroLabel4.Text = "Parent Menu Title Required";
metroLabel5.Text = "Menu Title Required";
metroLabel6.Text = "Form Name Required";
break;
}
Your code is equivalent to:
const string ParMnuTitReq ="Parent Menu Title Required";
const string MnuTitReq ="Menu Title Required";
const string FrmNamReq ="Form Name Required";
string m = ex.Message;
metroLabel4.Visible = m != MnuTitReq && m != FrmNamReq;
metroLabel5.Visible = m != ParMnuTitReq && m != FrmNamReq;
metroLabel6.Visible = m != ParMnuTitReq && m != MnuTitReq;
// This can be done in the form designer
metroLabel4.Text = ParMnuTitReq;
metroLabel5.Text = MnuTitReq;
metroLabel6.Text = FrmNamReq;
You don't need ternary expressions. Instead, you can combine logical expressions. In the case of the Visible property which is of type bool, you can directly assign the result of the logical expression.
You can always assign the same text to the labels, as they won't be visible if the text does not apply. You could even drop the 3 last code lines and instead assign the text in the form designer. This reduces your original 23 lines of code (not counting lines with braces only) to 7.
Nested or chained ternary expressions can be used if you must be able to assign more than 2 different values.
string t = x == 1 ? "case 1" : x == 2 ? "case 2" : x == 3 ? "case 3" : "other case";
Is equivalent to
string t;
if (x == 1) {
t = "case 1";
} else if (x == 2) {
t = "case 2";
} else if (x == 3) {
t = "case 3";
} else {
t = "other case";
}

Asp.net visible button when 2 parameters match

Hello I want to make a button visibile when UserId stored in database match with current UserId.
string clientId = Context.User.Identity.GetUserId();
JobDescriptions job = new JobDescriptions();
if (job.PostedBy == clientId)
{
Button2.Visible = true;
else
{
Button2.Visible = false;
}
PostedBy is the Id of the user who posted on website saved on jobs table. Problem is that button is not visibile when my statement should work.
The solution
if (!String.IsNullOrWhiteSpace(Request.QueryString["id"]))
{
int id = Convert.ToInt32(Request.QueryString["id"]);
JobReqModel model = new JobReqModel();
JobDescriptions job = model.GetJob(id);
string clientId = Context.User.Identity.GetUserId();
if (job.PostedBy == clientId)
{
Button2.Visible = true;
}
else
{
Button2.Visible = false;
}
}

how to do i change the value of data from server side?

i am trying to set a value from server side in this code. i have a textbox to enter ticket number and when the ticket is validated and activated, i want the used property of this particulare ticket to be changed to true.
i have this code :
TicketBLL Tickets = new TicketBLL();
ClientDeviceBLL Devices = new ClientDeviceBLL();
if (String.IsNullOrEmpty(txtTicket.Text))
{
CVUsed.Visible = false;
CVUsed.Enabled = false;
CVMember.Enabled = false;
CVMember.Visible = false;
CVInValid.Enabled = false;
CVInValid.Visible = false;
lblMessages.Text = MessageFormatter.GetFormattedErrorMessage("You can login using a Ticket Number.");
txtTicket.Focus();
}
else
{
Ticket = Tickets.GetTicketByTicketNumber(txtTicket.Text);
////// we must enter the value of the correct SN and the Client ID
Device = Devices.GetClientDeviceBySN(txtSN.Text , Convert.ToInt32(txtClientID.Text));
if (Ticket != null)
{
//Correct Ticket number
CVInValid.Visible = false;
CVInValid.Enabled = false;
if (Ticket.Used == true)
{
//ticket was used, internet forbidden
CVUsed.Visible = true;
CVUsed.Enabled = true;
CVMember.Enabled = false;
CVMember.Visible = false;
CVUsed.IsValid = false;
}
else
{
//if exists but not used, Ticket accepted
//check if device is a member if client divices
if (Device != null)
{
//internet access garanteed
CVUsed.Visible = false;
CVUsed.Enabled = false;
CVMember.Enabled = false;
CVMember.Visible = false;
CVUsed.IsValid = true;
CVMember.IsValid = true;
//here is my error.
//ticket.used is not changing in the database so the next
//time he enters the same ticket number it would go through
//again.
Ticket.Used = true;
Response.Redirect("http://www.google.com");
}
else
{
//device not member, internet access forbidden
CVMember.Enabled = true;
CVMember.Visible = true;
CVUsed.Visible = false;
CVUsed.Enabled = false;
CVUsed.IsValid = true;
CVMember.IsValid = false;
}
}
}
else
{
//Ticket Number is not valid
CVUsed.Visible = false;
CVUsed.Enabled = false;
CVMember.Enabled = false;
CVMember.Visible = false;
CVInValid.Enabled = true;
CVInValid.Visible = true;
CVInValid.IsValid = false;
}
}
how can i automatically update the ticket.used value in the database?!
Without making a connection to database you cannot update the value of ticket.used. If you want to know how to connect to database and update, use stored procedures of direct queries to do your work. Take a look at this.

Active Directory Creating An User

I'm trying to add an user to the active directory via a C# script. I've found this script on the internet (I didn't made it myself). The problem is that I get this error when I'm trying to add an user:
The specified directory service attribute or value does not exist.
This is the code I have right now:
private void buttonCreateUser_Click(object sender, EventArgs e)
{
CreateADSUser(textboxUsername.Text, textboxPassword.Text);
}
public string CreateADSUser(string username, string password)
{
String RootDSE;
try
{
DirectorySearcher DSESearcher = new DirectorySearcher();
RootDSE = DSESearcher.SearchRoot.Path;
RootDSE = RootDSE.Insert(7, "CN=Users,");
DirectoryEntry myDE = new DirectoryEntry(RootDSE);
DirectoryEntries myEntries = myDE.Children;
DirectoryEntry myDirectoryEntry = myEntries.Add("CN=" + username, "user");
myDirectoryEntry.Properties["userPrincipalName"].Value = username;
myDirectoryEntry.Properties["name"].Value = username;
myDirectoryEntry.Properties["Password"].Value = password;
myDirectoryEntry.Properties["samAccountName"].Value = username;
myDirectoryEntry.Properties["FullName"].Value = username;
myDirectoryEntry.Properties["AccountDisabled"].Value = 0;
myDirectoryEntry.Properties["PasswordRequired"].Value = 1;
// Permanent Password?
myDirectoryEntry.Properties["permpass"].Value = 1;
myDirectoryEntry.CommitChanges();
DSESearcher.Dispose();
myDirectoryEntry.Dispose();
textboxReports.Text = "Worked!";
return "Worked!";
}
catch (Exception ex)
{
textboxReports.Text = ex.Message;
return ex.Message;
}
}
Nevermind, I've got the fix!
This is what it looks like right now:
using (var pc = new PrincipalContext(ContextType.Domain))
{
using (var up = new UserPrincipal(pc))
{
up.SamAccountName = textboxUsername.Text; // Username
up.EmailAddress = textboxEmail.Text; // Email
up.SetPassword(textboxPassword.Text); // Password
up.Enabled = true;
up.ExpirePasswordNow();
up.Save();
}
}
The issue here is that none of these properties actually exist:
myDirectoryEntry.Properties["Password"].Value = password;
myDirectoryEntry.Properties["FullName"].Value = username;
myDirectoryEntry.Properties["AccountDisabled"].Value = 0;
myDirectoryEntry.Properties["PasswordRequired"].Value = 1;
myDirectoryEntry.Properties["permpass"].Value = 1;
This one isn't one you write to:
myDirectoryEntry.Properties["name"].Value = username;
In order (from top to bottom) here are the actual attribute names:
Password - unicodePwd
FullName - displayName
AccountDisabled - userAccountControl
PasswordRequired - userAccountControl (actually you set the inverse - only if a password isn't required)
permPass - unicodePwd (not sure what the goal was with this one)
By System.DirectoryServices.AccountManagement ..
PrincipalContext ouContex = new PrincipalContext(ContextType.Domain, "TestDomain.local", "OU=TestOU,DC=TestDomain,DC=local");
for (int i = 0; i < 3; i++)
{
try
{
UserPrincipal up = new UserPrincipal(ouContex);
up.SamAccountName = "TestUser" + i;
up.SetPassword("password");
up.Enabled = true;
up.ExpirePasswordNow();
up.Save();
}
catch (Exception ex)
{
}
}
By System.DirectoryServices
To use this namespace you need to add reference System.DirectoryServices.dll
DirectoryEntry ouEntry = new DirectoryEntry("LDAP://OU=TestOU,DC=TestDomain,DC=local");
for (int i = 3; i < 6; i++)
{
try
{
DirectoryEntry childEntry = ouEntry.Children.Add("CN=TestUser" + i, "user");
childEntry.CommitChanges();
ouEntry.CommitChanges();
childEntry.Invoke("SetPassword", new object[] { "password" });
childEntry.CommitChanges();
}
catch (Exception ex)
{
}
}

Categories

Resources