My code is like this
string statuscodeToSet;
if (xElementAltItem != null && (generalstatuscode.Contains(currentstatuscode) && xElementAltItem.Value.Trim() =="null"))
{
statuscodeToSet = "1";
}
if (xElementupdateDate != null && (xElementAltItem != null && (generalstatuscode.Contains(currentstatuscode) && xElementAltItem.Value.Trim() == "null") && xElementupdateDate.Value == "01-JAN-2099"))
{
statuscodeToSet = "2";
}
if (xElementupdateDate != null && (xElementAltItem != null && (generalstatuscode.Contains(currentstatuscode) && xElementAltItem.Value.Trim() == "null") && xElementupdateDate.Value != "01-JAN-2099"))
{
statuscodeToSet = "3";
}
if (xElementAltItem != null && (generalstatuscode.Contains(currentstatuscode) && xElementAltItem.Value.Trim() != "null"))
{
statuscodeToSet = "4";
}
if (xElementAltItem != null && (currentstatuscode == "Act-NotOrd" && xElementAltItem.Value.Trim() == "null"))
{
statuscodeToSet = "5";
}
Obviously I don't think this is the best way to code this.Is there any way I can shorten this code and looks it more standard. May be using Linq
This seems to be the simplest possible, but I don't think this is simple.
if (xElementAltItem != null)
{
if (xElementAltItem.Value.Trim() == "null")
{
if (generalstatuscode.Contains(currentstatuscode))
{
statuscodeToSet = "1";
if (xElementupdateDate != null)
{
if (xElementupdateDate.Value == "01-JAN-2099")
{
statuscodeToSet = "2";
}
if (xElementupdateDate.Value != "01-JAN-2099")
{
statuscodeToSet = "3";
}
}
}
if ((currentstatuscode == "Act-NotOrd"))
{
statuscodeToSet = "5";
}
}
else
{
if (generalstatuscode.Contains(currentstatuscode))
{
statuscodeToSet = "4";
}
}
}
You really need to tease out the logic here by creating some meaningful variable names to make the conditions read like English otherwise your code is vulnerable to bugs.
Update: I seem to have introduced a difference wrt the original in the handling of the update date as it appears I collapsed three states into two (whoops!) which appears in steps #2/#3. In any case, I believe the following is still an applicable template to follow.
Step #1: Eliminate the duplicate conditional checks with variables.
This simplifies the conditionals greatly and makes it easier to see what is "supposed" to happen.
var nullAlt = xElementAltItem != null ? xElementAltItem.Value.Trim() == "null" : false;
var hasCurrentStatus = generalstatuscode.Contains(currentstatuscode);
var updateDate = xElementupdateDate != null ? xElementupdateDate.Value : "";
if (nullAlt && hasCurrentStatus)
{
statuscodeToSet = "1";
}
if (nullAlt && hasCurrentStatus && updateDate == "01-JAN-2099"))
{
statuscodeToSet = "2";
}
if (nullAlt && hasCurrentStatus && updateDate != "01-JAN-2099"))
{
statuscodeToSet = "3";
}
if (!nullAlt && hasCurrentStatus)
{
statuscodeToSet = "4";
}
if (nullAlt && currentstatuscode == "Act-NotOrd")
{
statuscodeToSet = "5";
}
Step #2: Group the separate conditions and rewrite the code with "nested" and "else" conditionals.
This should eliminate most (if not all) of the duplicate checks and provide "one path" through the entire conditional structure. The order of grouping depends upon the logical importance of each condition and how well it eliminates duplicates between branches. In this case the code is grouped by nullAt and then hasCurrentState.
// ..
if (nullAlt) {
if (hasCurrentStatus) {
statuscodeToSet = "1";
if (updateDate == "01-JAN-2099"))
{
statuscodeToSet = "2";
} else { /* updateDate != "01-JAN-2099" */
{
statuscodeToSet = "3";
}
} else if (currentstatuscode == "Act-NotOrd")
{
statuscodeToSet = "5";
}
} else { /* !nullAlt */
if (hasCurrentStatus)
{
statuscodeToSet = "4";
}
}
Step #3: Place the code into a separate function and return the result.
That is, don't assign the "status" to a variable. Besides maintaining tidy code separation and self-documentation, this is useful because then invalid code paths/logic can be more easily spotted.
For instance, return "1" makes no sense where it is located (as then neither status "2" nor "3" could be reached and if it removed then status "1" is never returned!) and there are some "otherwise" cases not handled.
string GetStatusCode (..) {
// ..
if (nullAlt) {
if (hasCurrentStatus) {
// whoops! What was this doing??
return "1";
if (updateDate == "01-JAN-2099"))
{
return "2";
} else { /* updateDate != "01-JAN-2099" */
{
return "3";
}
} else if (currentstatuscode == "Act-NotOrd")
{
return "5";
} else {
// return what here?
}
} else { /* !nullAlt */
if (hasCurrentStatus)
{
return "4";
} else {
// return what here?
}
}
}
At this final stage, the usage of the intermediate variables could be reverted without losing much readability because the duplicate expressions have been eliminated. However, excepting in cases where lazy evaluation is strictly required, separate variables are perfectly valid - use them if they make the code cleaner.
Using enumerations or constants would also be an improvement: a status value of NeedsUpdate is more informative than "3".
I recommend keeping it simple and following the approach outlined above.
YMMV.
Try this:
if (xElementAltItem == null)
return;
statuscodeToSet = "1";
if (xElementAltItem.Value.Trim() == "null")
if (generalstatuscode.Contains(currentstatuscode))
statuscodeToSet = xElementupdateDate != null && xElementupdateDate.Value != "01-JAN-2099" ? "3" : "2";
statuscodeToSet = currentstatuscode == "Act-NotOrd" ? "5" : null;
else
statuscodeToSet = generalstatuscode.Contains(currentstatuscode) ? "4" : null;
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 have a datatable which fetches some records. So there is one column name as UPDATED_STATUS. In that column either Pre Hoto or Post Hoto value will come.
So what I want is, Either any one of those values should be their in that column then only the it should move ahead otherwise it should prompt alert as
Either Pre Hoto or Post Hoto can be their
Below is sample image for reference
Below is the code for getting the datatable with the UPDATED_STATUS column
if (strFlag == "")
{
dtStatus = GET_STATUS_FROM_SAPID_FOR_HOTO(dtExcelRows.Rows[i]["Current SAPID"].ToString());
if (dtStatus == null && dtStatus.Rows.Count < 0)
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('Status cannot be blank for SAP ID entered');", true);
}
else
{
dtExcelRows.Rows[i]["UPDATED_STATUS"] = dtStatus.Rows[0][1].ToString();
dtExcelRows.AcceptChanges();
}
}
Your current check (if (dtStatus == null && dtStatus.Rows.Count < 0)) is wrong:
when dtStatus is null, you continue checking dtStatus.Rows, which throws a nullref exception (you just found out that it was null);
Rows.Count is never less than zero.
Try if (dtStatus == null || dtStatus.Rows.Count == 0) to check whether there is no status at all (it is null) or no status rows (count is zero). The || will prevent checking for dtStatus.Rows when it was found that dtStatus is null.
&& means that both sides must be true at the same time.
|| means that at least of the sides must be true (both true is also fine).
Both don't evaluate the second test when the first already decided the outcome (false && whatever is always false, true || whatever is always true)
Are you looking for like this !
foreach (DataRow row in dtStatus.Rows)
{
if (string.IsNullOrEmpty(Convert.ToString(row["UPDATED_STATUS"])) ||
(Convert.ToString(row["UPDATED_STATUS"]).ToLower() != "pre hoto" &&
Convert.ToString(row["UPDATED_STATUS"]).ToLower() != "post hoto"))
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('Status cannot be blank for SAP ID entered');", true);
break;
}
else { }
}
I have got a way to get this done.. Here I go
if (strFlag == "")
{
dtStatus = GET_STATUS_FROM_SAPID_FOR_HOTO(dtExcelRows.Rows[i]["Current SAPID"].ToString());
if (dtStatus == null && dtStatus.Rows.Count < 0)
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('Status cannot be blank for SAP ID entered');", true);
}
else
{
dtExcelRows.Rows[i]["UPDATED_STATUS"] = dtStatus.Rows[0][1].ToString();
dtExcelRows.AcceptChanges();
}
}
}
DataTable dtGetHotoPre = null;
var rows = dtExcelRows.AsEnumerable().Where(x => x.Field<string>("UPDATED_STATUS") == "PRE HOTO");
if (rows.Any())
{
dtGetHotoPre = rows.CopyToDataTable();
}
DataTable dtGetHotoPost = null;
var rowsPost = dtExcelRows.AsEnumerable().Where(x => x.Field<string>("UPDATED_STATUS") == "POST HOTO");
if (rowsPost.Any())
{
dtGetHotoPost = rowsPost.CopyToDataTable();
}
string strFlagStatus = "";
if (dtGetHotoPre != null)
{
if (dtGetHotoPost != null)
{
strFlagStatus = "No Process";
}
else
{
strFlagStatus = "Process";
grdDvHoto.DataSource = dtGetHotoPost;
}
}
else
{
if (dtGetHotoPost != null)
{
strFlagStatus = "Process";
grdDvHoto.DataSource = dtGetHotoPre;
}
else
{
strFlagStatus = "No Process";
}
}
// if(dtGetHotoPre != null && dtGetHotoPost != null)
if (strFlagStatus == "No Process")
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('The sites contains both Pre and Post Hoto Status, so it cannot be uploaded');", true);
}
else
{
// will move ahead.
grdDvHoto.DataBind();
}
I want to convert below condition to ternary
if (!string.IsNullOrEmpty(objModel.Status))
{
if (objModel.Status == "0")
{
Model.Sort = "Result1";
}
else if (objModel.Status == "8")
{
Model.Sort = "Result2";
}
else
{
Model.Sort = "Result3";
}
}
I have tried as below but it went upto if and else not else if
Model.Sort = !string.IsNullOrEmpty(Model.Status)
? (Model.Status == "0" ? Retult1 : string.Empty)
: string.Empty;
Keep a local variable for simplification
var x = objModel.Status;
if (string.IsNullOrEmpty(x))
{
Model.Sort = x=="0" ? "Result1" :
x=="8" ? "Result2" :
"Result3";
}
you can have ternary operator like this
a ? b : c ? d : e
to get this:
if (a) {
b
}
else if (c) {
{
d
}
else {
e
}
in your case
objModel.Status == "0" ? Model.Sort = "Result1" : objModel.Status == "8" ? Model.Sort = "Result2" : Model.Sort = "Result2";
I hope this helps.
You can write your code using ternary operators like this:
Model.Sort = string.IsNullOrEmpty(objModel.Status) // if (string.IsNullOrEmpty(Status))
? Model.Sort // Model.Sort = Model.Sort;
: objModel.Status == "0" // else if (Status == "0")
? "Result1" // Model.Sort = "Result1";
: objModel.Status == "8" // else if (Status == "8")
? "Result2" // Model.Sort = "Result2";
: "Result3"; // else Model.Sort = "Result3";
Where the first condition represents the if condition, and then each statement after a : operator that is a comparison represents an else if, and finally the result after the last : represents the final else assignment.
The first condition is kind of a "dummy" condition (because if it's true nothing really changes*), but is required if we want to include the IsNullOrEmpty check in the ternary operations, since the ternary operator has to return a value in both the true and false cases.
I'm not sure if the dummy assignment would get optimized away or if the setter is called in that "dummy" case. If the setter is called then potentially this could have a different effect than your original code, depending on what the setter code does.
How do I break if-else-if.....Why its not working? its just checking all the conditions instead of performing the tasks. following is my code. I have checked it through breakpoints its moving to all conditions why it doesn't get stop after meeting the correct condition. even it is not going into the if activity it just read all the conditions and do nothing at the end.
private void ShowHash()
{
inpic = pb_selected.Image;
Bitmap image = new Bitmap(inpic);
byte[] imgBytes = new byte[0];
imgBytes = (byte[])converter.ConvertTo(image, imgBytes.GetType());
string hash = ComputeHashCode(imgBytes);
txt_selectedText.Text = hash;
GetHash();
}
private void GetHash()
{
if (txt_sel1.Text == null && (txt_sel2.Text == null || txt_sel3.Text == null || txt_sel4.Text == null || txt_sel5.Text == null ))
{
txt_sel1.Text = txt_selectedText.Text;
return;
}
else if (txt_sel1.Text != null && (txt_sel2.Text == null || txt_sel3.Text == null || txt_sel4.Text == null || txt_sel5.Text == null))
{
txt_sel2.Text = txt_selectedText.Text;
return;
}
else if (txt_sel2.Text != null && (txt_sel3.Text == null || txt_sel4.Text == null || txt_sel5.Text == null))
{
txt_sel3.Text = txt_selectedText.Text;
return;
}
else if (txt_sel3.Text != null && (txt_sel4.Text == null || txt_sel5.Text == null))
{
txt_sel4.Text = txt_selectedText.Text;
return;
}
else if (txt_sel4.Text != null && (txt_sel5.Text == null))
{
txt_sel5.Text = txt_selectedText.Text;
return;
}
}
I strongly suspect the problem is that the Text property is never null for any of txt_sel*. Assuming these are text boxes in a UI, it's much more likely that if there's no text in the text box, the Text property will return "" instead of null. That's the way most UI frameworks handle empty controls.
I would also suggest extracting the conditions into local variables first:
bool hasSel1 = txt_sel1.Text != "";
bool hasSel2 = txt_sel2.Text != "";
bool hasSel3 = txt_sel3.Text != "";
bool hasSel4 = txt_sel4.Text != "";
bool hasSel5 = txt_sel5.Text != "";
if (!hasSel1 && (!hasSel2 || !hasSel3 || !hasSel4 || !hasSel5)
{
...
}
And ideally, give your controls more meaningful names - a collection of variables with the same prefix but then a numeric suffix is very rarely a good idea, in terms of readability.
Reason:
If there is nothing in those textboxes, textbox.Text will return an empty string ("") not null.
Solution:
Check against "" not null:
private void GetHash()
{
if (txt_sel1.Text == "" && (txt_sel2.Text == "" || txt_sel3.Text == "" || txt_sel4.Text == "" || txt_sel5.Text == ""))
{
txt_sel1.Text = txt_selectedText.Text;
return;
}
else if (txt_sel1.Text != "" && (txt_sel2.Text == "" || txt_sel3.Text == "" || txt_sel4.Text == "" || txt_sel5.Text == ""))
{
txt_sel2.Text = txt_selectedText.Text;
return;
}
....
....
EDIT: You don't have to do ==true for boolean variables. If statement checks it against true by default. Use ! to check against false:
if (hasValue1 && (hasValue2 || hasValue3 || hasValue4 || hasValue5))
{
txt_sel1.Text = txt_selectedText.Text;
return;
}
else if (hasValue2 && (!hasValue1 ||hasValue3 || hasValue4 || hasValue5))
{
txt_sel2.Text = txt_selectedText.Text;
return;
}
else if (hasValue3 && (!hasValue1 || hasValue2 || hasValue4 || hasValue5))
{
txt_sel3.Text = txt_selectedText.Text;
return;
}
....
....
I think for string better to use inbuild null and whitespace check function:
bool hasValue1 = string.IsNullOrWhiteSpace(txt_sel1.Text);
bool hasValue2= string.IsNullOrWhiteSpace(txt_sel2.Text);
bool hasValue3= string.IsNullOrWhiteSpace(txt_sel3.Text);
bool hasValue4= string.IsNullOrWhiteSpace((txt_sel4.Text);
bool hasValue5 = string.IsNullOrWhiteSpace(txt_sel5.Text);
And then define if condition on these bool. This case can handle unexpected null or white space values.
That is bacause it probably doesn't find any of those conditions true.
If it would find a true condition it would execute that if block and won't event check the others.
To add to what others have said, you should really have a final else statement in there to catch issues such as this:
else
{
throw new InvalidOperationException("My If Statement is Broken");
}
Thanks to you all! My problem is solved by changing the conditions and your suggested alteration, following is the code may be helped some beginner like me.
private void GetHash()
{
bool hasValue1 = string.IsNullOrWhiteSpace(txt_sel1.Text);
bool hasValue2 = string.IsNullOrWhiteSpace(txt_sel2.Text);
bool hasValue3 = string.IsNullOrWhiteSpace(txt_sel3.Text);
bool hasValue4 = string.IsNullOrWhiteSpace(txt_sel4.Text);
bool hasValue5 = string.IsNullOrWhiteSpace(txt_sel5.Text);
if (hasValue1 && (hasValue2 || hasValue3 || hasValue4 || hasValue5))
{
txt_sel1.Text = txt_selectedText.Text;
return;
}
else if (hasValue2 && (!hasValue1 ||hasValue3 || hasValue4 || hasValue5 ))
{
txt_sel2.Text = txt_selectedText.Text;
return;
}
else if (hasValue3 && (!hasValue1 || !hasValue2 || hasValue4 || hasValue5 ))
{
txt_sel3.Text = txt_selectedText.Text;
return;
}
else if (hasValue4 && (!hasValue1 || !hasValue2 || !hasValue3 || hasValue5 ))
{
txt_sel4.Text = txt_selectedText.Text;
return;
}
else if (hasValue5 && (!hasValue1 || !hasValue2 || !hasValue3 || !hasValue4 ))
{
txt_sel5.Text = txt_selectedText.Text;
return;
}
else
{
CompareHash();
}
}
private void getUserLoginDepartment(string AccessID, string UserPROFid)
{
try
{
DBWPAccountRecordsDataContext DBACCOUNT = new DBWPAccountRecordsDataContext();
var query = (from i in DBACCOUNT.WP_UserAccessPorts
join
z in DBACCOUNT.WP_Departments on i.AccessPortID equals z.Dept_ID
where i.AccessPortID == AccessID && i.ProfileUser_ID == UserPROFid
select new
{
PORT1 = i.AccessPoint1,
PORT2 = i.AccessPoint2,
PORT3 = i.AccessPoint3,
PORT4 = i.AccessPoint4,
DEPT = z.Dept_DESC,
DEPTPORT = z.Dept_PortNo
}).FirstOrDefault();
if (query.PORT1.ToString() != null || query.PORT1.ToString() != string.Empty)
{ Session["Port1"] = query.PORT1; }
else { Session["Port1"] = ""; }
if (query.PORT2.ToString() != null || query.PORT2.ToString() != string.Empty)
{ Session["Port2"] = query.PORT2; }
else { Session["Port2"] = ""; }
if (query.PORT3.ToString() != null || query.PORT3.ToString() != string.Empty)
{ Session["Port3"] = query.PORT3; }
else { Session["Port3"] = ""; }
if (query.PORT4.ToString() != null || query.PORT4.ToString() != string.Empty)
{ Session["Port4"] = query.PORT4; }
else { Session["Port4"] = ""; }
}
finally
{
}
}
The Error occures when i reach break point 1st IF Statement the record on my database shows that its not empty which its value is "WebAdmin" but then suppost to be it should pick it up and store it to the Session["PORT1"] that i have made is there something i missed or i'm doing it wrong on my linq Query. NOTE:*This is an ASP.NET C# Application
EDIT 10/2/2013 0420PM:
It's still an Error After using that method sir.
1) you should check query for null when you use FirstOrDefault
2) you need to check each PORTX for null
3) use string.IsNullOrEmpty( ) to check if the string of PORTX is null
var query = ( ... ).FirstOrDefault( );
if( query != null )
{
if( query.PORT1 != null && !string.IsNullOrEmpty( query.PORT1.ToString( ) ) )
{
}
else { ... }
}
You have to check query.PORT1 for null before calling ToString on it, you can use String.IsNullOrEmpty to check both conditions. Before checking query.PORT1 you need to check if query is null or not. You also need to use && instead of or operator as || will cause the right side of or operator to be evaluated if left is false and on right side calling ToString on null will again through exception.
if (query != null && query.PORT1 != null && query.PORT1.ToString() != string.Empty)
{ Session["Port1"] = query.PORT1; }
Using IsNullOrEmpty
if(query != null && !String.IsNullOrEmpty(query.PORT1))
{
Session["Port1"] = query.PORT1;
}