Wrapping multiple method calls into one if statement - c#

I have a validation method that I call to validate the fields on my form. I want to put these in an if statement check to see if they return true then in my else statement insert them into my database. i already have the method declared and the insert method declared. How can I write this if statement to check to see if all the validation methods return true?
My method validation calls:
formValidation(firstnameTextBox.Text);
formValidation(lastnameTextBox.Text);
formValidation(usernameTextBox.Text);
formValidation(passwordTextBox.Text);
formValidation(emailTextBox.Text);
formValidation(cellnumberTextBox.Text);

Just use the AND operator (&&)
if(formValidation(firstnameTextBox.Text) &&
formValidation(lastnameTextBox.Text) &&
formValidation(usernameTextBox.Text) &&
formValidation(passwordTextBox.Text) &&
formValidation(emailTextBox.Text) &&
formValidation(cellnumberTextBox.Text))
{
}
As mentioned in the comments, if you want all of the methods to be run (to display the relevant errors for each field) no matter what, and to not stop as soon as it hits the first error, you can use a non-short circuiting AND, which is the & operator.
Alternatively, you could put the textboxes into a collection and act on that collection:
var fieldsToValidate = new TextBox[]{firstnameTextBox, lastnameTextBox, ...}
if(fieldsToValidate.All(field => formValidation(field.Text));

Related

'var' is null on at least one execution path - sonarqube or is it?

while analyzing my code using sonarqube i came across 'variableProducerAgreements' is null on at least one execution path in the following code (the foreach loop):
however, upon looking at it and trying various things, variableProducerAgreements seems to never be null in this foreach loop. during a code review, i'm being told that it can "totally" be null and should add conditional logic to handle it. but i'm not understanding how it can be null and thus not sure how to add a conditional. any ideas?
I can't see a way in which variableProducerAgreements could be null since you have the null guard in place at the top (and assuming you don't have any crazy code in your property getters).
if (userProfile?.ProducerProfile == null)
return result;
The Where and FindAll methods in .NET doesn't return null.
However, it is possible the use of a null-conditional every time you access ProducerProfile is confusing some tools and people. Since you're returning early if it is null, you should remove them:
if (IsActingAsDelegate && userProfile.ProducerProfile.IsInactiveProducer)
{
variableProducerAgreements = userProfile.ProducerProfile.ProducerAgreements.FindAll(ag => ag.IsActive && ag.IsVariableBranchContract);
}
else
{
variableProducerAgreements = userProfile.ProducerProfile.ActiveAgreements.Where(a => a.IsVariableContract);
}
If there was a way for it to be null before the if statement, you would also risk a NullReferenceException when you access the IsInactiveProducer property.
Also, the reviewer should be able to explain his/her reasoning.

Property Initialization and Comparison Timing

Context: C#, WPF, MVVM
In my viewmodels I have been using initialization logic for some of my properties that is basically a check to see if the backing property is null and, if so, initialize it. Finally, return the backing property. Here's an example for list that allows a user to select items to filter by:
List<CBPicklistString> _clientClassificationFilterList;
public List<CBPicklistString> ClientClassificationFilterList
{
get
{
Debug.WriteLine("ClientClassificationFilterList - Get: " + _clientClassificationFilterList?.Count ?? "Null");
if (_clientClassificationFilterList == null)
{
_clientClassificationFilterList = CBPicklists.PicklistStrings(CBPicklists.CLIENT_CLASSIFICATIONS).ToList();
_clientClassificationFilterList.Insert(0, new CBPicklistString() { PicklistStringId = 0, PicklistStringValue = "(All Client Classes)" });
SelectedClientClassificationFilter = _effectiveClientClassificationFilter = _clientClassificationFilterList[0];
OnPropertyChanged("SelectedClientClassificationFilter");
}
return _clientClassificationFilterList;
}
}
My method to apply the filter logic has this code:
if (_effectiveClientClassificationFilter != ClientClassificationFilterList[0])
ActiveClientFilters.Add(new ActiveFilter(_effectiveClientClassificationFilter.PicklistStringValue, "ClientClassification"));
On the initial run, the getter should initialize the list and _effectiveClientClassificationFilter and the if statement should see the comparison as false (objects are equal), meaning that there is no active filter to set. But what I am seeing is that the if statement is behaving as if it sees a true (objects are not equal). When I check the values in the debugger, they are, in fact, equal. It's acting as if there is a concurrency issue where the initialization isn't finishing prior to the comparison. But this isn't a multi-threaded bit of code. Is .Net (or WPF) doing its own thing, here? Is this not a valid way to approach the list initialization? I use this logic paradigm all over the place, (and have been, for years) but this is the first time and the only place I am seeing this funky behavior. There's not a lot of other related code involved.
What am I missing?
I am not sure, but i think the initial value of _effectiveClientClassificationFilter being first in the comparison is used and then the ClientClassificationFilterList is calculated changing the value of _effectiveClientClassificationFilter which i suppose it does not know. So if you reverse the order of condition, it will work correctly.
Instead of
if (_effectiveClientClassificationFilter != ClientClassificationFilterList[0])
use
if (ClientClassificationFilterList[0] != _effectiveClientClassificationFilter)

What should go in CanExecute?

I think that there is a specific answer to this.
If I have a command binding
private bool CanExecute(Object args){
// Should this just be null checks?
// Should it also contain logic?
// example:
return this.SelectedObject != null;
// or
return this.SelectedObject != null && this.SelectedObject.Status == 1;
}
private void Executed(Object args){
//Or should logic be reserved for the Executed command
if(this.SelectedObject.Status == 1)
//Do stuff
else
//Don't do stuff
}
It seems redundant to have a can execute method if we do additional data validation within the executed method.
if the logic of your command assumes, that it must not be executed, when some conditions have met, then CanExecute have to check these conditions.
Otherwise, CanExecute must return true.
It doesn't matter, what is the nature of conditions, but you should note, that long running checks may hit UI thread performance.
The way that I see it is that there is a distinction of whether something CAN happen and if something SHOULD happen.
An example of this can be a save button or something. The user may not have rights to save an entity so the action CAN'T happen.
If the user does have rights, all of the required fields may not be filled in so it SHOULDN'T happen.
Its in the semantics.

Checking two attributes in an object

I am coding a C# MVC5 Internet Application and have a question about checking an objects attributes.
I retrieve an Asset object from a DbSet, and I want to check to ensure that the Asset has either a userName of the current user, or a category of DefaultMapMarker. If neither of these are true, I wish to show a HttpNotFound page.
Is the below code correct?
if (!asset.category.Equals("DefaultMapMarker" || asset.userName != User.Identity.GetUserName()))
{
return HttpNotFound();
}
Thanks in advance
EDIT
I meant to ask if the above code achieves the same as this following code:
if (!asset.category.Equals("DefaultMapMarker"))
{
if (asset.userName != User.Identity.GetUserName())
{
return HttpNotFound();
}
}
Of course not. The first will pass if only one condition is correct. But the second will check both conditions to excecute the action.
the second is equal to:
if (!asset.category.Equals("DefaultMapMarker") && asset.userName != User.Identity.GetUserName()))
{
return HttpNotFound();
}
No, this does not achieve the same thing.
Your first statement with the logical or says "If this condition is met OR the other is met: {...}"
Your second statement says "If condition is met AND this condition is met {...}", which could be translated into:
if (!asset.category.Equals("DefaultMapMarker" && asset.userName != User.Identity.GetUserName()))
{
return HttpNotFound();
}
So the answer to your question is: No, they don't achieve the same thing. If you want a HttpNotFoundException to be raised if both conditions are met you have to chain your conditions with a logical AND (&&)
//edit: before the nitpicking starts. Yes I am aware, that the order is relevant in his second code snippet, but I choose to ignore it for the sake of the problem.

how to achieve the project requirement

I have a method Modify() shown below
// Convert SortedList of objects
if (retval) //
{
// Release the database lock
Debug.Verbose(func, "Unloc");
The functionality which i want to achieve is if flag RuntimeUp true and m_reconnectInProgress false that means if(RuntimeUp && !m_reconnectInProgress) i have to do the entire procees in the Modify() method otherwise i need to return 'retval' as false .We will get retval from ClientModify(col) method also which is processed by some other side
If i put check if(RuntimeUp && !m_reconnectInProgress) on the very begginning and down side
else part returning retval = false is sufficient or is there any other convenient way to do that so that we can avoid bad logic
I did above assumption based on this comment obtained"" There is no need to create the list of modified objects[col.Add(dmo);] if the RuntimeUp == false and m_reconnectInProgress ==true. You can just return false at the top of the Modify method that means You can perform these checks at the beginning of the Modify method rather than waiting until the call to ClientModify ""
If I understand correctly I'd just add the lines
if(!RuntimeUp || m_reconnectInProgress)
return false;
At the very top of the method, which I think is a perfectly acceptable way of avoiding running the method if the application isn't in the correct state for running it right then.
However, the comment bit of your question does not mention that it should check for reconnect in progress, so I'm not sure if you should be doing that?

Categories