How to combine multiple IF statements in C# - c#

I have some flawed logic here..my goal is if all of the fields have "" value then return true, otherwise return false. How can I fix this in C# ?
public bool CheckFieldsAreEmpty()
{
Driver.WaitForElementValueNull(smtpHostInputField);
if (smtpHostInputField.GetAttribute("value") == "")
return true;
Driver.WaitForElementValueNull(smtpPortInputField);
if (smtpPortInputField.GetAttribute("value") == "")
return true;
Driver.WaitForElementValueNull(usernameInputField);
if (usernameInputField.GetAttribute("value") == "")
return true;
Driver.WaitForElementValueNull(passwordInputField);
if (passwordInputField.GetAttribute("value") == "")
return true;
Driver.WaitForElementValueNull(senderInputField);
if (senderInputField.GetAttribute("value") == "")
return true;
Driver.WaitForElementValueNull(receiverInputField);
if (receiverInputField.GetAttribute("value") == "")
return true;
else return false;

I believe something like this should work. I couldn't find what class all of those variables belong to, but replace var with the proper class and I think this should work.
logic: Add all variables to a List, use a lambda function to return if all of the list match GetAttribute("value") == ""
// Replace var with class type, or parent
List<var> allFields = new List<var> { smtpHostInputField, smtpPortInputField, sernameInputField, passwordInputField, senderInputField, receiverInputField };
foreach (var field in allFields) { Driver.WaitForElementValueNull(field); }
return allFields.All(t => t.GetAttribute("value") == "");

To illustrate #madreflection’s (correct) suggestion from the comments, consider this code:
public bool CheckFieldsAreEmpty()
{
Driver.WaitForElementValueNull(smtpHostInputField);
if (smtpHostInputField.GetAttribute("value") != "")
return false;
Driver.WaitForElementValueNull(smtpPortInputField);
if (smtpPortInputField.GetAttribute("value") != "")
return false;
Driver.WaitForElementValueNull(usernameInputField);
if (usernameInputField.GetAttribute("value") != "")
return false;
Driver.WaitForElementValueNull(passwordInputField);
if (passwordInputField.GetAttribute("value") != "")
return false;
Driver.WaitForElementValueNull(senderInputField);
if (senderInputField.GetAttribute("value") != "")
return false;
Driver.WaitForElementValueNull(receiverInputField);
if (receiverInputField.GetAttribute("value") != "")
return false;
return true;
}
Of course, as #Daniel-Lord’s answer highlights, you can centralize this repetitive logic using either a loop or a LINQ query.

Another way to solve this would be to extract WaitForElementValueNull call and empty string check to a separate method. Something like that:
private static bool WaitForElementValueNullAndEmpty(InputFieldType inputField)
{
Driver.WaitForElementValueNull(inputField);
return inputField.GetAttribute("value") == "";
}
public bool CheckFieldsAreEmpty()
{
return WaitForElementValueNullAndEmpty(smtpHostInputField) ||
WaitForElementValueNullAndEmpty(smtpPortInputField) ||
WaitForElementValueNullAndEmpty(usernameInputField) ||
WaitForElementValueNullAndEmpty(passwordInputField) ||
WaitForElementValueNullAndEmpty(senderInputField) ||
WaitForElementValueNullAndEmpty(receiverInputField);
}
The code above will match the algorithm that was provided, however if you want to check if ALL the values is empty then || should be replaced with && (As it was noticed by Jeremy Caney)

Related

determine function out type based on input Enum c#

I have 3rd party DLL
which have an enum with 70 values
and a function that based on that get that enum and set the return value
but my problem that the this functions 19 overloads on the out value
if there a clean way to do it(not using if-else, or create a huge dictionary)
here's my sample code (i used 3 out values as an example but there are much more options)
public static dynamic getHardwareValue(HardwareValue hardwareValue)
{
string strResult;
byte[] byteArrResult = new byte[256];
byte byteResult;
int intResult;
bool boolResult;
if (HardwareValue.Apci1DeviceId == hardwareValue || HardwareValue.Apci2DeviceId == hardwareValue || ..)
{
if (NativeMethods.AdiGetHardwareValue(hardwareValue, out strResult))
return strResult;
else
return false;
}
else if (HardwareValue.Apci1Eeprom == hardwareValue || HardwareValue.Apci2Eeprom == hardwareValue || ..)
{
if(NativeMethods.AdiGetHardwareValue(hardwareValue, byteArrResult))
return byteArrResult;
else
return false;
}
else if (HardwareValue.Apci1Variant == hardwareValue || HardwareValue.Apci2Variant == hardwareValue || ..)
{
if (NativeMethods.AdiGetHardwareValue(hardwareValue, out byteResult))
return byteResult;
else
return false;
}
return null;
}

Can't get the correct Bool result in C#

I have a form where I would like to check for validation before processing the form. My form has 2 sections so I want to make sure that at least one item from each section is selected when they press submit button, and if they did then go to Dashboard.aspx. Even if I put all the required info when it checks for result1 and result2, I get false. Result1 and Result2 won't get the correct value. Even if the values are True again it passes false.
Here is my code:
protected void btnSumbit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
bool result1 = false;
bool result2 = false;
CheckWireFromValidation(result1);
CheckWireToValidation(result2);
if (result1 == true && result2 == true)
{
Response.Redirect("~/DashBoard.aspx");
}
}
public bool CheckWireFromValidation (bool result1)
{
if (drpFromCoporate.SelectedIndex != 0 || drpFromCapital.SelectedIndex != 0 || drpFromProperty.SelectedIndex != 0)
{
result1 = true;
}
else
{
result1 = false;
ShowAlertMessage("You need to choose at least one filed from Wire From drop downs!!");
}
return result1;
}
public bool CheckWireToValidation(bool result2)
{
if (drpToCapital.SelectedIndex != 0 || drpToCoporate.SelectedIndex != 0 || drpToProperty.SelectedIndex != 0 || drpToTemplate.SelectedIndex != 0 || txtCorpAmt.Text != "" || txtCapAmt.Text != "" || txtPropAmt.Text != "" || txtTempelateAmt.Text != "")
{
result2 = true;
}
else
{
ShowAlertMessage("You need to choose at least one filed from Wire To drop downs!!");
}
return result2;
}
You're not using the results of CheckWireToValidation. You're using the false value you allocate initially.
Try this
bool result1 = false;
bool result2 = false;
if (CheckWireFromValidation(result1) && CheckWireToValidation(result2))
{
Response.Redirect("~/DashBoard.aspx");
}
Edit
The behavior you're expecting is that of the out parameter modifier. But please don't write code that way ...
I edited your code to get rid of .. em .. cruft. This should be more readable.
protected void btnSumbit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
if (CheckWireFromValidation() && CheckWireToValidation())
{
Response.Redirect("~/DashBoard.aspx");
}
}
public bool CheckWireFromValidation ()
{
if (drpFromCoporate.SelectedIndex != 0 || drpFromCapital.SelectedIndex != 0 || drpFromProperty.SelectedIndex != 0)
{
return true;
}
else
{
ShowAlertMessage("You need to choose at least one filed from Wire From drop downs!!");
return false;
}
}
public bool CheckWireToValidation ()
{
if (drpToCapital.SelectedIndex != 0 || drpToCoporate.SelectedIndex != 0 || drpToProperty.SelectedIndex != 0 || drpToTemplate.SelectedIndex != 0 || txtCorpAmt.Text != "" || txtCapAmt.Text != "" || txtPropAmt.Text != "" || txtTempelateAmt.Text != "")
{
return true;
}
else
{
ShowAlertMessage("You need to choose at least one filed from Wire To drop downs!!");
return false;
}
}
Since you are passing Result1 and Result2 in as parameters instead assigning them. The results will never be set.
Here's one correct way of doing this
bool result1 = CheckWireFromValidation(result1);
bool result2 = CheckWireToValidation(result2);
if (result1 == true && result2 == true)
{
Response.Redirect("~/DashBoard.aspx");
}
and also a side note. I think we can safely remove the boolean parameter from the CheckWireFromValidation methods. Since the return value doesn't depends on the input variable.
Hope this helps.

How to optimize this piece of code? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I have the following piece of code:
protected StoreDetailModel GetSelectedStore()
{
if (StoresWithDepartmentType != null && StoresWithDepartmentType.Any())
{
StoreDetailModel currentUserStore = WebsiteContext.GetCurrentUserStore();
if (currentUserStore != null && currentUserStore.Item != null)
{
StoreDetailModel store =
StoresWithDepartmentType.FirstOrDefault(x => x.Item.ID ==
currentUserStore.Item.ID);
if (store == null)
{
store = StoresWithDepartmentType.First();
}
return store;
}
}
return null;
}
Too many ifs make this code hardly readable. How can I optimize it and make it clearer?
You could write
return StoresWithDepartmentType.FirstOrDefault(x => x.Item.ID == currentUserStore.Item.ID) ?? StoresWithDepartmentType.First();
instead of
StoreDetailModel store =
StoresWithDepartmentType.FirstOrDefault(x => x.Item.ID ==
currentUserStore.Item.ID);
if (store == null)
{
store = StoresWithDepartmentType.First();
}
return store;
but some people don't like that. Ifs are necessary by the look of it, they don't bother me.
Your code is expecting to return the current users store or null if one cannot be found. It can be simplified as follows.
protected StoreDetailModel GetSelectedStore()
{
if (StoresWithDepartmentType == null) return null; // There are no stores
// Get the user store or return the first available store
StoreDetailModel currentUserStore = WebsiteContext.GetCurrentUserStore();
return currentUserStore ?? StoresWithDepartmentType.First();
}
If there are no stores to lookup, then nothing can be returned.
Otherwise return the user's store, or If user's store cannot be found, then the first available can be returned.
The simplification works because the lookup on StoresWithDepartmentType appears to return the same object.
It is not necessary to nest if-blocks, so i flatted structure for readability.
Line of last 'return' statement comes from the answer of artm.
protected StoreDetailModel GetSelectedStore()
{
if (StoresWithDepartmentType == null || !StoresWithDepartmentType.Any())
{
return null;
}
StoreDetailModel currentUserStore = WebsiteContext.GetCurrentUserStore();
if (currentUserStore == null || currentUserStore.Item == null)
{
return null;
}
return StoresWithDepartmentType.FirstOrDefault(x => x.Item.ID == currentUserStore.Item.ID) ?? StoresWithDepartmentType.First();
}
I'd split it up into a number of well-named methods.
This won't compile (because I don't know all the types you're using) but hopefully it will give you the idea:
protected StoreDetailModel GetSelectedStore()
{
if (anyStoresWithDepartmentType())
return storeWithCurrentlySelectedItem();
return null;
}
private bool anyStoresWithDepartmentType()
{
return (StoresWithDepartmentType != null) && StoresWithDepartmentType.Any();
}
private StoreDetailModel storeWithCurrentlySelectedItem()
{
var itemId = currentUserStoreItemId();
if (itemId == null)
return null;
return storeWithItem(itemId);
}
private StoreItemId currentUserStoreItemId()
{
StoreDetailModel currentUserStore = WebsiteContext.GetCurrentUserStore();
if (currentUserStore != null && currentUserStore.Item != null)
return currentUserStore.Item.ID;
return null;
}
private StoreDetailModel storeWithItem(StoreItemId itemId)
{
StoreDetailModel store = StoresWithDepartmentType.FirstOrDefault(x => x.Item.ID == itemId);
if (store != null)
return store;
return StoresWithDepartmentType.First();
}

How do i Check if a xml Sibling has attributes?

My program is doing weird stuff if i delete one of my Attributes because it is not able to handle Siblings without Attributes. Now i googled for a while but i am not able to find a good way to check for attributes.
Whats the way you prefer checking for attributes?
while (FXMLNode != null)
{
if (FXMLNode.Name.ToLower() == "datei")
{
xmlInformationen oInfo = new xmlInformationen();
oInfo.Dateipfad = FXMLNode.InnerText;
if (FXMLNode.Attributes["checked"].Value.ToString() == "true")
oInfo.CheckBox = true;
else if (FXMLNode.Attributes["checked"].Value.ToString() == "false")
oInfo.CheckBox = false;
else if(FXMLNode == null)
oInfo.CheckBox = true;
else
oInfo.CheckBox = true;
lstAttribute.Add(oInfo);
iCounter++;
if (FXMLNode.NextSibling == null)
{
FXMLNode = FXMLNode.FirstChild;
}
else
{
FXMLNode = FXMLNode.NextSibling;
}
}
else
{
if (FXMLNode.NextSibling == null)
{
FXMLNode = FXMLNode.FirstChild;
}
else
{
FXMLNode = FXMLNode.NextSibling;
}
}
}
You are accessing the value of an attribute without knowing if the attribute exists or not. Rewrite your code to check for the attribute first:
oInfo.CheckBox = true;
if(FXMLNode == null) oInfo.CheckBox = true; //not sure why you set it to true here
else if (FXMLNode.HasAttribute("checked"))
{
if (FXMLNode.Attributes["checked"].Value.ToString() == "true")
oInfo.CheckBox = true;
else if (FXMLNode.Attributes["checked"].Value.ToString() == "false")
oInfo.CheckBox = false;
}
Please note that checking if the Xml element is null should be the first thing you do. If it's null then it surely won't have any attributes but you'll have an exception.
you can just check thats the attribute in not null like this
if (FXMLNode.Attributes["checked"]!=null)
and then check the value

How can I validate something without using regular expressions in C#?

HI how can I validate a string, but without using regular expressions. For example how can validate this: xxx/xxxx where x is a digit? thanks
Something like that:
bool ValidateExpression(string expression)
{
string[] parts = expression.Split("/");
if (
parts.Length != 2
|| parts[0].Length != 3
|| parts[1].Length != 4
) return false;
int parsed;
return Int32.TryParse(parts[0], out parsed) && Int32.TryParse(parts[1], out parsed);
}
To be used later as
bool isValid = ValidateExpression("123/4567");
You can use Char.IsDigit to check if characters are a digit. For your specific case, you could do something like this:
public bool IsMyStringValid(string myString)
{
foreach(var c in myString)
if(!Char.IsDigit() && !c == '/') return false;
return true;
}
This is actually more specific to your case (3 digits, one '/' at index 3, followed by 4 digits):
public bool IsMyStringValid(string myString)
{
if(myString.Length != 8) return false;
for(var i = 0; i <8, i++)
if(!Char.IsDigit(myString[i]) || (i == 3 && myString[i] == '/') return false;
return true;
}
For that specific format you can use:
bool valid =
value.Length == 8 &&
value.Take(3).All(Char.IsDigit) &&
value[3] == '/' &&
value.Skip(4).All(Char.IsDigit);
Try this :
public bool ValidateString(string str)
{
var strArr = str.Split('/');
return strArr[0].All(char.IsDigit) && strArr[1].All(char.IsDigit);
}
hope this help;
I would use the .All to check something like this so no matter what the string is
if there is a non digit in it, it will not pass
public static bool IsMyStringValid(string strValidateString)
{
bool boolIsValid = false;
if (strValidateString.All(Char.IsDigit))
{
boolIsValid = true;
}
return boolIsValid;
}

Categories