public bool VerifyId(List<string> sheetData)
{
if (sheetData.Where(q => q == "-1007401").First())
return true;
else
return false;
}
I have this bool function where if it finds that string, it returns true. But why is the Where not working?
I was able to fix it by using the list.Contains(string) function.
if (sheetData.Contains("-1007401")
return true
else
return false
Related
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)
I want to script our sap. Actually, I'm scripting the comboboxes. But I don't know, how to select a specific item.
SAPFEWSELib.dll included as refernece
public static bool SelectComboBoxItem(string ItemText)
{
int i = 0, ItInd = -1;
SAPFEWSELib.GuiComboBox GCB = GetComboBox(GFW, Criteria, Type); /*This function returns the SAPFEWSELib.GuiComboBox and works correctly*/
if (GCB != null)
{
foreach (SAPFEWSELib.GuiComboBoxEntry Entry in GCB.Entries)
{
if (Entry.Value.ToUpper().IndexOf(Item.ToUpper()) != -1)
{
/*How to select this Entry?*/
/*GCB.Entries.Item(Entry.Pos).Select() is a not contained methode*/
/*GCB.Entries.Item(Entry.Pos).Selected = true This functions for GuiTableRows and GuiGridViewRows, but not here*/
return true;
} else {
i++;
}
}
}else{
throw new System.Exception("ERROR: Unable to find combobox with current criteria!");
}
return false;
}
Does anybody has an Idea?
Ok, got it.
GCB.Value = Entry.Value;
In my testcase, the combobox was not changeable, so it never functioned.
Sometimes I find myself writing a bool method that looks like this:
public bool isRunning()
{
if (!(move == Moving.None) && staminaRegan == true)
{
if (keyState.IsKeyDown(Keys.Space))
{
EntityAnimation.interval = 10;
return true;
}
else
{
EntityAnimation.interval = 65;
return false;
}
}
else
{
EntityAnimation.interval = 65;
return false;
}
}
(This is XNA by the way) As you can see, I have a bool isRunning in which I made an if statement where Im checking if (Player is moving) && (regains stamina, which is set to false once stamina reaches value lesser than 6.0f)
and then I simply check if Space is pressed, if yes then my Animation is faster(the smaller the interval, the faster is spritesheet changing), and then It sends true value, which means that Player is running, else Im not cause Space is not pressed.
And then I have to repeat this 'else' code outside of the first if statement so it sends that Player is not running if Player is not moving or his stamina Regan is false;
So I was just wondering is this kind of a bool method considered a bad practice(where you retrun true and false value in nested if, and then return false outside nested if and repeat the same code) ?
The method has a side effect, that's why it's a bad practice:
public bool isRunning()
When looking on method's signature we expect just true/false answer and nothing more. However, the method changes the instance's state:
...
if (!(move == Moving.None) && staminaRegan == true)
{
if (keyState.IsKeyDown(Keys.Space))
{
EntityAnimation.interval = 10; // <- Aaa! The interval is changed
return true;
}
...
I suggest splitting the initial method into a property and a method
// No side effect: just answer is running or not
public bool IsRunning {
get {
return (move != Moving.None) && staminaRegan && KeyState.IsKeyDown(Keys.Space);
}
}
// Put the right interval based on instance internal state
// (if it's running etc.)
public void AdjustInterval() {
if (IsRunning) // and may be other conditions
EntityAnimation.interval = 10; //TODO: move magic number into constant
else
EntityAnimation.interval = 65; //TODO: move magic number into constant
}
It is a good practice to have one return statement inside a method. Some argue about this, but it is an opinion.
it is also a good practice to make the if statement clear by removing unnecessary code:
public bool isRunning()
{
bool result = false;
if (move != Moving.None && staminaRegan)
{
if (keyState.IsKeyDown(Keys.Space))
{
EntityAnimation.interval = 10;
result = true;
}
else
{
EntityAnimation.interval = 65;
}
}
else
{
EntityAnimation.interval = 65;
}
return result;
}
You can rewrite the code as follows; then the code isn't repeated:
public bool isRunning()
{
if (move != Moving.None && staminaRegan && keyState.IsKeyDown(Keys.Space))
{
EntityAnimation.interval = 10;
return true;
}
else
{
EntityAnimation.interval = 65;
return false;
}
}
Or if you don't want the redundant else:
public bool isRunning()
{
if (move != Moving.None && staminaRegan && keyState.IsKeyDown(Keys.Space))
{
EntityAnimation.interval = 10;
return true;
}
EntityAnimation.interval = 65;
return false;
}
I would consider introducing a named boolean to self-document somewhat, and I'd rename staminaRegan to staminaIsRegenerating
public bool isRunning()
{
bool isMovingQuickly = (move != Moving.None) && staminaIsRegenerating && keyState.IsKeyDown(Keys.Space);
if (isMovingQuickly)
EntityAnimation.interval = 10;
else
EntityAnimation.interval = 65;
return isMovingQuickly;
}
Most importantly, though, you should rename the method to more accurately describe what it's doing:
public bool CheckIfRunningAndSetAnimationInterval()
I think we write code for people(other developers), of course machine execute a code but 80% of developer's work is reading the code.
Based on that I think flow of reading must be exactly same as flow of executing code - that's why I think multiply return statement not a bad thing, even better then only one return statement on the bottom of your method.
I like this style and i use it too. First, you can read the code more easily and second it has a debugging advantage as you can set breakpoints for the individual else cases. Otherwise you would need to use breakpoint conditions.
I have the following line of code:
public bool dcpl_radar()
{
if (radar == null)
return false;
else
{
if (radar != null)
{
if (radar.InvokeRequired)
radar.BeginInvoke(new MethodInvoker(delegate()
{
radar.Visible = false;
}));
else
this.radar.Visible = false;
radar = null;
}
return true;
}//end of else statement
}
but VStudio keeps throwing an error on the invoke line. I've checked the Debugger and if (radar == null) is true, yet VStudio is trying to evaluate a part of the code it shouldn't be in. Can someone explain why it's doing this please?
Wait a minute... I think we have a race condition.
Lets say you BeginInvoke, almost immediately you set radar = null.
There really is no telling when your anonymous delegate will be executed.
I would imagine this should solve your issue.
public bool dcpl_radar()
{
if (radar != null)
{
if (radar.InvokeRequired)
{
radar.BeginInvoke(new MethodInvoker(HideRadar));
}
else
{
HideRadar();
}
return true;
}
return false;
}
private void HideRadar()
{
this.radar.Visible = false;
this.radar = null;
}
What is happening:
The anonymous delegate is being called after you set the radar to null.
How to fix it
public bool dcpl_radar()
{
if (radar == null)
return false;
else
{
if (radar != null)
{
if (radar.InvokeRequired)
radar.BeginInvoke(new MethodInvoker(delegate()
{
radar.Visible = false;
radar = null;
}));
else {
this.radar.Visible = false;
radar = null;
}
}
return true;
}//end of else statement
}
(Note where I've moved your 'null' assignments).
Though I am a bit worried about the point of setting a variable to null, it's generally a sign of a bad design.
I am getting a formatexception with the following code. Any one know how to make BooleanConverter convert from 0/1 to true/false.
bool bVal=true;
string sVal = "0";
Console.WriteLine(TypeDescriptor.GetConverter(bVal).ConvertFrom(sVal));
Thanks for the help!
Try the following
public static bool ConvertToBasedOnIntValue(string value) {
// error checking omitted for brevity
var i = Int32.Parse(value);
return value == 0 ? false : true;
}
Or you could use the following which won't throw exceptions but it will consider everything that is quite literally not 0 to be true
public static bool ConvertToBasedOnIntValue(string value) {
if ( 0 == StringComparer.CompareOrdinal(value, "0") ) {
return false;
}
return true;
}
If you're going to use Int32.Parse, use Int32.TryParse instead. It doesn't throw if the conversion fails, instead returning true or false. This means that it's more performant if all you're doing is checking to see if your input is a value. Example:
public static bool ConvertToBool(string value)
{
int val = 0;
return (int.TryParse(value, out val) && val == 0) ? false : true;
}
I have a tendency to go overboard on the ternary operator (x ? y : z), so here's a slightly easier-to-read version:
public static bool ConvertToBool(string value)
{
int val = 0;
if (int.TryParse(value, out val))
{
return val == 0 ? false : true;
}
return false;
}
(I tested them both. "1" returns true, "0" returns false.)
There are only two cases so can just check for them explicitly.
I just built a helper function that will handle the special case of booleans:
Private Shared Function StringConverter(ByVal colValue As String, ByVal propertyType As Type) As Object
Dim returnValue As Object
'Convert the string value to the correct type
Select Case propertyType
Case GetType(Boolean)
'Booleans need to be coded separately because by default only "True" and "False" will map to a Boolean
'value. SQL Server will export XML with Booleans set to "0" and "1". We want to handle these without
'changing the xml.
Select Case colValue
Case "0"
returnValue = False
Case "1"
returnValue = True
Case "False"
returnValue = False
Case "True"
returnValue = True
Case Else
Throw New ArgumentException("Value of '" & colValue & "' cannot be converted to type Boolean.")
End Select
Case Else
'Let .Net Framework handle the conversion for us
returnValue = TypeDescriptor.GetConverter(propertyType).ConvertFromString(colValue)
End Select
Return returnValue
End Function
Your original code was good enough, only you can't set the string value to "0" and "1". In your code, TypeConverter.ConvertFrom() will eventually invoke Boolean.TryParse(), the code for which looks like this (thanks Reflector!)
public static bool TryParse(string value, out bool result)
{
result = false;
if (value != null)
{
if ("True".Equals(value, StringComparison.OrdinalIgnoreCase))
{
result = true;
return true;
}
if ("False".Equals(value, StringComparison.OrdinalIgnoreCase))
{
result = false;
return true;
}
if (m_trimmableChars == null)
{
char[] destinationArray = new char[string.WhitespaceChars.Length + 1];
Array.Copy(string.WhitespaceChars, destinationArray, string.WhitespaceChars.Length);
destinationArray[destinationArray.Length - 1] = '\0';
m_trimmableChars = destinationArray;
}
value = value.Trim(m_trimmableChars);
if ("True".Equals(value, StringComparison.OrdinalIgnoreCase))
{
result = true;
return true;
}
if ("False".Equals(value, StringComparison.OrdinalIgnoreCase))
{
result = false;
return true;
}
}
return false;
}
So make the following change to your code and you should be good:
bool bVal = true;
string sVal = "false";
Console.WriteLine(TypeDescriptor.GetConverter(bVal).ConvertFrom(sVal));
string _sOne = "1";
string _sTrue = "TrUe";
bool _bRandom = !Convert.ToBoolean(__sTrue);
string _sResult = Convert.ToBoolean(_sOne);
string _sResultB = Convert.ToBoolean(_sTrue);
string _sResultC = _bRandom.ToString();