.StartsWith not working as expected? - c#

I have a url where I need to check that it does not start with http:// or https:// and the length of the url is no longer than 493 characters.
So far I have this conditional statement:
else if (!url.Text.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
!url.Text.StartsWith("https://", StringComparison.OrdinalIgnoreCase) &&
url.Text.Length > 493)
IsValid = false;
However this returns true when urls do have http:// or https://
Not to sure why this is?

You need && instead of ||, suppose you string starts with https then first check StartsWith("http://" will give true. The same is applied if Text starts with http
else if (!url.Text.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !url.Text.StartsWith("https://", StringComparison.OrdinalIgnoreCase) && url.Text.Length > 493)
IsValid = false;
You can combine both condition with || and negate the result with !
if (!(url.Text.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || url.Text.StartsWith("https://", StringComparison.OrdinalIgnoreCase) && url.Text.Length > 493)

You need to change the || in to a &&

Urls will either start with http or https, that means that one of them will always be true. You need to check them with &&

Its the || and && logic thats causing the problem
Re-write it as a nested if to make it clearer
private static bool IsValidUrl(string url)
{
if(url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
if(url.Text.Length < 493)
return true;
return false;
}

Related

Selenium C# displaying custom exceptions if booleans marked false?

I am coding a selenium test case to verify all elements are present on a web page and Im fairly green at coding so bear with me here. I have boolean vars set up for each element and if not found, I mark them false. At the end of my code/test, I want to display custom exceptions for each false boolean encountered. What's the easiest way to go about this?
if (!headerLogoPresent || !headerMsgDropPresent || !headerMsgDropSubGeneralPresent || !headerUserDropPresent || !headerUserDropSubProfilePresent ||
!headerUserDropSubCredentialsPresent || !headerUserDropSubSettingsPresent || !headerUserDropSubChgPassPresent || !headerUserDropSubRstGridPresent ||
!headerUserDropSubLogOffPresent || !headerSupportDropPresent || !headerSupportDropSubBasePresent || !headerSupportDropSubFaqPresent || !headerSupportDropSubTicketPresent
|| !emailTextInputFieldPresent || !saveButPresent || !bodyTextProfilePresent || !bodyTextEmailPresent || !bodyTextCopyrightPresent)
{
//then throw custom exception for each variable marked false;
}

Why .NET executes code on false IF statement?

I have following code:
var dateFrom = DateTime.Parse(string.Format(string.Format("01.04.{0}", dateProperty.Value.AddYears(-1).Year))
if (object.nullablebool.HasValue ? object.nullablebool.Value : false
&& (string == "V" || string == "N")
&& someDate.HasValue && object.SomeOtherDate.HasValue
&& someDate.Value.Date > dateFrom.Date)
{
>> Code
}
I have tested adding .Date or even specifiing exact year from the DateTime struct, but nothing worked.
When executing the code, even if
someDate.Value.Date > dateFrom.Date
equals 1700 > 2018, the code executed as if it was true, even though the debugger says it´s false.
When I removed this part from the condition, following code:
someDate.HasValue && object.SomeOtherDate.HasValue
When I made someDate null, so someDate.HasValue is false, the if statement still executes as true.
What did it fix? Taking these two conditions to another if:
var dateFrom = DateTime.Parse(string.Format(string.Format("01.04.{0}", dateProperty.Value.AddYears(-1).Year))
if (object.nullablebool.HasValue ? object.nullablebool.Value : false
&& (string == "V" || string == "N"))
{
if (someDate.HasValue && object.SomeOtherDate.HasValue
&& someDate.Value.Date > dateFrom.Date)
{
>> Code
}
else
{
>> Code
}
}
The code works, but it´s way too ugly. I'm running on Visual Studio 2017 Pro.
Any ideas why it behaves like that? Executing false statements?
Thanks
Your if statement performs different then expected, because it is parsed different as you wouls expect.
object.nullablebool.HasValue ? object.nullablebool.Value : false && ... is parsed as object.nullablebool.HasValue ? object.nullablebool.Value : (false && ...). So if object.nullablebool has a value, thats the result of the condition. To fix this you have to add parenthesis like this:
if ((object.nullablebool.HasValue ? object.nullablebool.Value : false )
&& (string == "V" || string == "N")
&& someDate.HasValue && object.SomeOtherDate.HasValue
&& someDate.Value.Date > dateFrom.Date)
{
// if body
}
Let's brush up your code (please, get rid of names like string, object; change them into meanful names):
// You don't want any formatting but a simple constructor
var dateFrom = new DateTime(dateProperty.Value.Year - 1, 4, 1);
// object.nullablebool == true - if object.nullablebool has value and the value is true
if (object.nullablebool == true && (string == "V" || string == "N")) {
// if someDate.Value is null the result will be false
// All we have to do is to propagate the null: ?. in someDate?.Date
if (someDate?.Date > dateFrom.Date && object.SomeOtherDate.HasValue) {
// Code
}
else {
// Code
}
}

How to translate conditions (without brackets) correctly?

I have condition, where are no ( ) brackets inside coded by programmer... How can I bracket such ugly coded correctly?
if( c_1 && c_2 || c_3 || c_4 && c_5 || c_6 && c_7 || c_8 || c_9 && c_10)
&& has higher precedence1 in C# than ||. That means your expression is effectively:
if ((c_1 && c_2) || c_3 || (c_4 && c_5) || (c_6 && c_7) || c_8 || (c_9 && c_10))
For further readability, I'd probably extract conditions into local variables with meaningful names. For example:
bool recentlyActive = (c_1 && c_2) || c_3;
bool passwordDisabled = (c_4 && c_5) || (c_6 && c_7);
bool userBanned = c_8 || (c_9 && c_10);
if (recentlyActive || passwordDisabled || userBanned)
{
...
}
1 Precedence in C# is documented in the specification, but it really comes directly out of the grammar. I'm glad of that documentation though, because I wouldn't want to have to read the grammar every time I wanted to understand how operators bind...

C# compiler error for single line if statement with 2 actions

It was hard to find a good title explaining the issue. I will try to explain the problem in detail. I try to use a single line if statement with 2 actions inside another if statement. However, this usage fails the parent if statement's result.
Before going into deep I have to stress that the method below returns FALSE:
draggedItem.GetComponent<PreparedItem> ().CheckPreparationAvailability ()
The method above is included inside two if clauses below. Therefore I expect the result FALSE immediately. The only changing part is the last statement, focus there.
Problematic version without parentheseses:
if (acceptedTypeID == draggedItem.CurrentTypeID.foodTypePart1
&& draggedItem.GetComponent<PreparedItem> () != null
&& draggedItem.GetComponent<PreparedItem> ().CheckPreparationAvailability () // RETURNS FALSE, DO NOT FORGET
&& rootTransform.GetComponentsInChildren<DragAndDropItem> ().Length <= 0
&& draggedItem.RootTransform.GetComponentInChildren<PlateCell>()
&& (true)? true : true) { // problem here
'if' is considered as TRUE and the inside is executed ...
}
Working version with parentheseses:
if (acceptedTypeID == draggedItem.CurrentTypeID.foodTypePart1
&& draggedItem.GetComponent<PreparedItem> () != null
&& draggedItem.GetComponent<PreparedItem> ().CheckPreparationAvailability () // RETURNS FALSE, DO NOT FORGET
&& rootTransform.GetComponentsInChildren<DragAndDropItem> ().Length <= 0
&& draggedItem.RootTransform.GetComponentInChildren<PlateCell>()
&& ((true)? true : true)) { // WORKS AS EXPECTED
'if' is considered as FALSE which is expected and the inside is NOT executed ...
}
Consider this:
bool a = true;
bool b = false;
Console.WriteLine(a && b && (true) ? true : true); // Prints true
Console.WriteLine(a && b && ((true) ? true : true)); // Prints false
This happens because the precedence of the ?: operator is such that in the first WriteLine above, it is as if you wrote this:
(a && b && (true)) ? true : true
which is always going to result in true.
The second, of course, is parenthesized so that it works as you expected.
Without the explicit parentheses the statement is executed the same way as if the parentheses would be placed as following, as everything left of the ? is considered as the condition for the inline-if:
if ((acceptedTypeID == draggedItem.CurrentTypeID.foodTypePart1
&& draggedItem.GetComponent<PreparedItem> () != null
&& draggedItem.GetComponent<PreparedItem> ().CheckPreparationAvailability () // RETURNS FALSE, DO NOT FORGET
&& rootTransform.GetComponentsInChildren<DragAndDropItem> ().Length <= 0
&& draggedItem.RootTransform.GetComponentInChildren<PlateCell>()
&& (true)) ? true : true)
So your second example is the valid solution for such a case.

If statement clarification of AND/OR

I'm sorry to ask such an easy question.. I just need some clarifications, because sometimes I mix the differences up.
Can somebody please help me by explaining the difference between the following if statements?
sending = true;
if (sending && e.AssetType == AssetType.Notecard) //#1
vs.
if ((sending) && (e.AssetType == AssetType.Notecard)) //#2
vs.
if (sending || e.AssetType == AssetType.Notecard) //#3
vs.
if ((sending) || (e.AssetType == AssetType.Notecard)) //#4
In this specific case, I need it to evaluate to something like:
"If(sending == true AND e.AssetType == AssetType.Notecard)"
In an other case I need the if statement to check one string and contents of a list like:
"If(string == "Name" OR List.Contains("string"))
The first and the second statements are the same (parenthesis are not obligatory in this case, because of C# evaluation priorities!)
if (sending && e.AssetType == AssetType.Notecard)
if ((sending) && (e.AssetType == AssetType.Notecard))
just as:
if ((sending == true) && e.AssetType == AssetType.Notecard))
if ((sending) && (e.AssetType == AssetType.Notecard))
Also the 3° and the 4° statement will give the same result, for the same reason mentioned above: http://msdn.microsoft.com/en-us/library/6a71f45d.aspx
I would use these statements:
if (sending && (e.AssetType == AssetType.Notecard))
and:
if ((string == "Name") || List.Contains("string"))
(but please take care of string comparison modes, such as upper/lower cases and cultures:
String.Compare(string, "Name", StringComparison.CurrentCultureIgnoreCase) == 0
compares strings without regard of the case and with the current culture)
There is no any difference in those codes.
if ((sending) && (e.AssetType == AssetType.Notecard)) and if (sending && e.AssetType == AssetType.Notecard) evaluates into the same thing.
if(sending == true) or if(sending) is the same thing too.
If you're asking about difference between || and &&:
|| is a LOGICAL-OR. It's enough that only one condition would be TRUE to pass if
&& is a LOGICAL-AND. All conditions must be TRUE in order to pass if
In both cases the evaluation will be done from the left to right.
Example of sequence:
if ((sending) && (e.AssetType == AssetType.Notecard)) => if sending==true AND ..rest..
For the first and second statements produce the same result and for the third and fourth statements also produce the same result.
A couple of things to clarify:
In this case, parentheses are not required and it is just extra code.
When you use Logical-AND operation, the first part is always evaluated, and the second part will only be evaluated if the first part is true.
When you use Logical-OR operation, both parts are always evaluated.
When you have more than +2 expressions, then use parentheses to clarify your intentions. e.g. if(A && B || C) is the same as if((A && B) || C) because the Operators Precedence. but if you want the logical-OR operation to be execute first, then you must use parentheses to override the precedence if(A && (B || C))
Furthermore, if(A && B == C) is the same as if(A && (B == C)) because Equality operation has higher precedence than logical-AND

Categories

Resources