C# if statement always returning false - c#

I have an if statement in a web service call that is always returning false. I want it to return an error message if there isn't the words "VERTICALPALLETS", or "PALLETLABELS" in it. Even if this field has those words in it, it is still returning an error. The query is not the correct one I am using in my application. Any help is much appreciated.
public bool ValidateDevice(string DeviceID, string sVersion, out string MachineID, out string MachineName, out string Plant, out string Printer1, out string Printer2, out string WrapStation, out string Location, out string sMessage)
{
MachineID = "";
MachineName = "";
Plant = "";
Printer1 = "";
Printer2 = "";
Plant = "";
WrapStation = "";
Location = "";
sMessage = "";
bool bTest = CheckVersion(sVersion, out sMessage);
if (bTest == false)
{
sMessage = "You do not meet the minimum version requirements. Contact MIS.";
return false;
}
try
{
SqlConnection connection = new SqlConnection(capmSADPConnectionString);
connection.Open();
string queryString = "select * from DATABASE";
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.Clear();
command.Parameters.AddWithValue("#DEVICEID", DeviceID);
command.Parameters.AddWithValue("#APPID", "VTP");
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows == false)
{
email myEmail = new email();
myEmail.SendErrorEmail("No Application Settings for VTP Device ID - " + DeviceID, "VTPError", "VTP Device Settings Error");
sMessage = "Could not find application settings for this device. Please enter settings.";
return false;
}
reader.Read();
MachineID = reader.GetValue(0).ToString();
MachineName = reader.GetValue(1).ToString();
Plant = reader.GetValue(2).ToString();
Location = reader.GetValue(3).ToString();
Printer1 = reader.GetValue(4).ToString();
Printer2 = reader.GetValue(5).ToString();
WrapStation = reader.GetValue(6).ToString();
reader.Close();
reader = null;
command = null;
connection.Close();
connection = null;
if ((Location.ToUpper().Contains("VERTICALPALLETS") == false) || (Location.ToUpper().Contains("PALLETLABELS") == false))
{
sMessage = "Please enter correct location in Application Setup and try again.";
return false;
}
return true;
}
catch (Exception e)
{
sMessage = "Unable to retrieve Application Settings for VTP. Please reopen the application.";
return false;
}
return true;
}

The problem here is with the structure of your if statement:
if ((Location.ToUpper().Contains("VERTICALPALLETS") == false) || (Location.ToUpper().Contains("PALLETLABELS") == false))
{
sMessage = "Please enter correct location in Application Setup and try again.";
return false;
}
You are saying:
If the location does not contain 'VERTICALPALLETS'
Or Else
If the location does not contain 'PALLETLABELS'
This will always be true unless the location contains both bits of text!
You need to change the Or Else to And Also (so || to &&) and therefore your code will work as expected.

Use AND
if ((Location.ToUpper().Contains("VERTICALPALLETS") == false) && (Location.ToUpper().Contains("PALLETLABELS") == false))
Alternative solution which is simpler to read.
if (!(Location.ToUpper().Contains("VERTICALPALLETS") || Location.ToUpper().Contains("PALLETLABELS"))

Sounds like the problem is that you'll always be looking for a "false" or "false" condition unless you are looking for a location that contains both VERTICALPALLETS PALLETLABELS
I suggest you try something like
if (! ( condtion1 || condition2) )
return message

This line
if ((Location.ToUpper().Contains("VERTICALPALLETS") == false) || (Location.ToUpper().Contains("PALLETLABELS") == false))
checks whether Location.ToUpper() does not contain "VERTICALPALLETS" or Location.ToUpper() does not contain "PALLETLABELS". If Location.ToUpper() does not happen to contain both, then the condition is true. You instead wanted to check whether Location.ToUpper() contains either of them:
if ((Location.ToUpper().Contains("VERTICALPALLETS") == false) && (Location.ToUpper().Contains("PALLETLABELS") == false))
{
//...
}
also, it does not makes much sense to calculate ToUpper several times, let's calculate it only once:
String upperLocation = Location.ToUpper();
if ((Location.ToUpper().Contains("VERTICALPALLETS") == false) && (Location.ToUpper().Contains("PALLETLABELS") == false))
{
//...
}

Related

CSV-injection in export functionality in asp.net application

While submitting a form, in one of the fields i am inserting vulnerable characters like =cmd|'/C calc'!A0. So in security terms it is termed as CSV-injection in export functionality
I have written code like this for above error. but its not working
[WebMethod]
public static string SaveRecord(RRSOCSaving RRSOCSaving, string Indication)
{
string strReturnId = "";
string strAppURL = ConfigurationManager.AppSettings["AppUrl"].ToString();
string strmail_Content = "";
CommonDB commonObj = new CommonDB();
try
{
// Cross site scripting issue code tag..!!
if (commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_CODE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.CITY)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME_LANDL_1)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME_LANDL_2)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_ASST_MANAGER_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_ASST_MANAGER_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_MANAGER_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.MANAGER_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.EMP_NEAREST_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.EMP_NEAREST_STORE_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SUPERVISOR_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SECURITY_SUP_NAME_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SECURITY_SUP_MOBNO_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_MOBNO))
{
strReturnId = "Something went wrong due to malicious script attack..!!!";
}
else
{
if (RRSOCSaving.ROLE_ASSIGNED == "SLP State Head")
{
bool blnState1 = Array.Exists(RRSOCSaving.ASSIGNED_STATE.ToString().ToUpper().Split(','), element => element == (RRSOCSaving.STATE).ToString().ToUpper());
if (blnState1)
{
strmail_Content = Get_Email_Content(RRSOCSaving.STORE_CODE, RRSOCSaving.UserName, Indication, RRSOCSaving.STATE, RRSOCSaving.SITE_STORE_FORMAT, RRSOCSaving.STORE_SITENAME);
// SendEmail(RRSOCSaving.UserName, RRSOCSaving.STORE_CODE, RRSOCSaving.SLP_EMAILID, ConfigurationManager.AppSettings["NHQEmail"].ToString(), strmail_Content, Indication);
strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving, Indication);
}
else
{
strReturnId = "User can add data for " + RRSOCSaving.ASSIGNED_STATE + " only";
}
}
else if (RRSOCSaving.ROLE_ASSIGNED == "NHQ Admin")
{
strmail_Content = Get_Email_Content(RRSOCSaving.STORE_CODE, RRSOCSaving.UserName, Indication, RRSOCSaving.STATE, RRSOCSaving.SITE_STORE_FORMAT, RRSOCSaving.STORE_SITENAME);
// SendEmail(RRSOCSaving.UserName, RRSOCSaving.STORE_CODE, RRSOCSaving.SLP_EMAILID, ConfigurationManager.AppSettings["NHQEmail"].ToString(), strmail_Content, Indication);
strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving, Indication);
//strReturnId = "Record Saved Succesfully";
}
}
// strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving);
}
catch (Exception)
{
throw;
}
return strReturnId;
}
public bool HackerTextExistOrNot(string Text)
{
bool flgValid = false;
Regex htmltags = new Regex(#"<.*?>");
Match chkMatch = htmltags.Match(Text);
if (chkMatch.Success)
{
flgValid = true;
}
return flgValid;
}
Please suggest how to stop this error.
Your HackerTextExistOrNot method is checking for the existance of html tags.
You should however check if the text is starting with one of the formular triggering characters.
To protect yourself against the injection attack ensure that none of the given text begins with any of the following characters:
Equals to ("=")
Plus ("+")
Minus ("-")
At ("#")
So you can check like this:
var attackChars = new char[]{'=','+','-','#'};
if(attackChars.Contains(text[0])
{
}

C# to Access connection in Visual Form OleDb No data exists for the row/column OR invalid output

I am trying to get a Text value from a single cell in an Access form, but this code gives me System.Data.OleDb.OleDbDataReader as an output instead. When I change Sell to *, and Convert.ToString(cusReader) to Convert.ToString(cusReader.getValue(1)), I get the error in the title.
How do I fix this?
Thanks, Jack.
OleDbCommand cmd = new OleDbCommand("SELECT Sell FROM Product WHERE ID = " + Count, conn);
OleDbDataReader cusReader = cmd.ExecuteReader();
if (Count != 0)
{
labelInsertedExtra.Visible = true;
labelInserted.Visible = true;
labelInsertedExtra.Text = Convert.ToString(cusReader);
}
else
{
labelInsertedExtra.Visible = false;
labelInserted.Visible = false;
}
cusReader.Close();
Indice start to 0
Convert.ToString(cusReader.getValue(0))
you should test dbnullvalue too
while (cusReader.Read())
{
if (Count != 0 && cusReader["Sell"] != DBNull.Value)
{
labelInsertedExtra.Visible = true;
labelInserted.Visible = true;
labelInsertedExtra.Text = cusReader["Sell"].ToString();
}
else
{
labelInsertedExtra.Visible = false;
labelInserted.Visible = false;
}
break;
}

How to fix a boolean method that returns true everytime asp.net

I designed my webpage to read a data string then display the results on labels in an html table. I am attempting to highlight the row that my database reads as a current order. My only problem is only one record is set to be active but they all highlight as if they were active. I use an array to set my data and I also use the label to get the ID I need (all is in code below). I have posted my method and where I use it in the asp page load. How can I fix my method to return correctly?
The implementing of the method in page load
if (lineData.IsCurrentOrderFind(L68.Text))
{
myTable.Rows[1].Cells[0].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[1].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[2].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[3].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[4].BgColor = "#FE2E2E";
}
Here is method that label above gets passed to
public bool IsCurrentOrderFind(string itemNumber)
{
StringBuilder sqlString = new StringBuilder();
sqlString.Append("SELECT * ");
sqlString.Append("FROM WorkOrder ");
sqlString.Append("WHERE LineNumber = " + ConfigurationManager.AppSettings["Line"] + " AND LineCompleted = 0 AND (ScaleGroup LIKE '%1' OR ScaleGroup LIKE '%3') ");
sqlString.Append(" AND CaseGenNum6 = #CaseGenNum6");
SqlDataReader reader = null;
SqlConnection dbConn = App_Code.DBHelper.getConnection();
SqlParameter[] parameters = new SqlParameter[] { new SqlParameter("#CaseGenNum6", itemNumber) };
try
{
reader = App_Code.DBHelper.executeQuery(dbConn, sqlString.ToString(), parameters);
while (reader.Read())
{
IsCurrentOrder = (reader["IsCurrentOrder"] != DBNull.Value && !string.IsNullOrEmpty(reader["IsCurrentOrder"].ToString())) ? true : false;
}
reader.Close();
reader.Dispose();
dbConn.Close();
dbConn.Dispose();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (dbConn != null)
{
try { dbConn.Close(); dbConn.Dispose(); }
catch { }
}
if (reader != null)
{
try { reader.Close(); reader.Dispose(); }
catch { }
}
}
if (IsCurrentOrder == true) I realize this is not necessary
{
return true;
}
else
{
return false;
}
}
The problem could be with this expression:
!string.IsNullOrEmpty(reader["IsCurrentOrder"].ToString())
Instead of calling ToString(), try simply casting it to a string:
!string.IsNullOrEmpty((string)reader["IsCurrentOrder"])
Possibly even better (the previous line might throw an exception if it's not really a string):
!string.IsNullOrEmpty(reader["IsCurrentOrder"] as string)
The reason being is that if the string is really null, calling ToString() will return a non-null string "null".
IsCurrentOrder is not declared locally. It seems to be declared at a higher scope. When you enter this function, nothing is initializing the variable (back to false). So, it is remaining at its last setting. Try this code instead:
public bool IsCurrentOrderFind(string itemNumber)
{
bool IsCurrentOrder = false;
//and the rest of your source code
the line
IsCurrentOrder = (reader["IsCurrentOrder"] != DBNull.Value && !string.IsNullOrEmpty(reader["IsCurrentOrder"].ToString())) ? true : false;
}
It's not actually checking the value of the field, only that it's not null or empty.
Try
if(
(reader["IsCurrentOrder"] != DBNull.Value
&&
!string.IsNullOrEmpty(reader["IsCurrentOrder"].ToString()))
)
{
IsCurrentOrder = reader["IsCurrentOrder"];
}
else
IsCurrentOrder = false;
I think there is a lot of refactoring you could do to this method though that will simplify the logic.

Getting compilation error with method: "not all code paths return a value"

I can't figure this out why I keep getting the compilation error: "not all code paths return a value". I am writing a simple class method that is supposed to return true if the account is available to use and false if the account is not available or is null/empty. The code for the method is below:
public static bool AccountAvailable(int AccountId)
{
try
{
bool accountavailable;
string queryTransaction = "Select Count(AccountID) FROM Accounts WHERE AccountID = " + AccountId.ToString() + " AND AccountUsed = 0";
//grab a connection to the database
Database database = DatabaseFactory.CreateDatabase();
//create an instance of the command
DbCommand command = database.GetSqlStringCommand(queryTransaction);
object dataobject = command.ExecuteScalar();
if (dataobject == null || string.IsNullOrEmpty(Convert.ToString(dataobject)))
{
accountavailable = false;
}
else if (Convert.ToInt32(dataobject) == 0)
{
accountavailable = false;
}
else if (Convert.ToInt32(dataobject) > 0)
{
accountavailable = true;
}
else
{
accountavailable = true;
}
return accountavailable;
}
catch
{
}
}
Any help or advice on this would be appreciated. Thanks!!
If an exception is thrown in your code before you return a value then control moves to the catch block. It then reaches the end of the method without returning anything.
Either return something within, or after, the catch block.
In your catch block, add a return:
catch (Exception ex)
{
// your code
return null;
}
The suggest to try this code
public static bool AccountAvailable(int AccountId)
{
bool accountavailable = false;
try
{
string queryTransaction = "Select Count(AccountID) FROM Accounts WHERE AccountID = " + AccountId.ToString() + " AND AccountUsed = 0";
//grab a connection to the database
Database database = DatabaseFactory.CreateDatabase();
//create an instance of the command
DbCommand command = database.GetSqlStringCommand(queryTransaction);
object dataobject = command.ExecuteScalar();
if (dataobject == null || string.IsNullOrEmpty(Convert.ToString(dataobject)))
{
accountavailable = false;
}
else if (Convert.ToInt32(dataobject) == 0)
{
accountavailable = false;
}
else if (Convert.ToInt32(dataobject) > 0)
{
accountavailable = true;
}
else
{
accountavailable = true;
}
}
catch
{
}
return accountavailable;
}

Code does not return if the condition is true

I need to validate if the user's provided information is in the database, i've tried to enter the correct condition and its not working it returns an error that it cannot be found on the database. Can you check my code and tell me what's going on? , I tried to debug it but the foreach loop continue to loop and does not go to if (isexist) statement
protected void btnSubmit_Click(object sender, EventArgs e)
{
token = FormsAuthentication.HashPasswordForStoringInConfigFile(txtUsername.Text.ToString() + txtAcctNo.Text.ToString(), "MD5");
try
{
bool isExist = false;
DataSet ds = new DataSet();
ds = startService.getAllUsersWithoutFilter();
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dRow in ds.Tables[0].Rows)
{
string userName = dRow["UserName"].ToString();
string acctNo = dRow["AccountNumber"].ToString();
string question = dRow["SecretQuestion"].ToString();
string answer = dRow["SecretAnswer"].ToString();
if (userName == txtUsername.Text.ToString() && acctNo == txtAcctNo.Text.ToString() && question == cboQuestion.Text.ToString() && answer == txtAnswer.Text.ToString())
{
isExist = true;
}
else
{
isExist = false;
}
}
if (isExist)
{
startService.sendTokenizer(txtUsername.Text.ToString(), token);
//update database to change password to standard password
startService.inserUserActivity(txtUsername.Text.ToString(), txtAcctNo.Text.ToString(), "Password Reset Request", HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
startService.requestReset(txtUsername.Text.ToString(), txtAcctNo.Text.ToString(), token);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "<br>We have sent an email to you for the instructions to reset your password. Please check your email.";
}
else
{
this.lblMessage.ForeColor = System.Drawing.Color.Red;
this.lblMessage.Text = "<br><br>Error - Information cannot be found. Please check and try again. Make sure all the fields are correct.";
}
}
}
catch
{
lblError.Text = "There was an error occured while processing your request. Please try again later.";
}
}
I think all you need is to break out of your foreach loop when you set isExist to true.
if (userName == txtUsername.Text.ToString() && acctNo == txtAcctNo.Text.ToString() && question == cboQuestion.Text.ToString() && answer == txtAnswer.Text.ToString())
{
isExist = true;
break; //Found it, so stop looking.
}
I think Joel's right about a direct answer to your question.
I would add that you should reconsider loading the entire users table and iterating through it on the web server. Why not just try to select a matching row from the database? If you get a match, the credentials were valid. If not, they were not valid.
#Dhenn: you need to make following changes in your code
protected void btnSubmit_Click(object sender, EventArgs e)
{
token = FormsAuthentication.HashPasswordForStoringInConfigFile(txtUsername.Text.ToString() + txtAcctNo.Text.ToString(), "MD5");
try
{
bool isExist = false;
DataSet ds = new DataSet();
ds = startService.getAllUsersWithoutFilter();
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dRow in ds.Tables[0].Rows)
{
string userName = dRow["UserName"].ToString();
string acctNo = dRow["AccountNumber"].ToString();
string question = dRow["SecretQuestion"].ToString();
string answer = dRow["SecretAnswer"].ToString();
if (userName == txtUsername.Text.ToString() && acctNo == txtAcctNo.Text.ToString() && question == cboQuestion.Text.ToString() && answer == txtAnswer.Text.ToString())
{
// if exist execute following code
startService.sendTokenizer(txtUsername.Text.ToString(), token);
//update database to change password to standard password
startService.inserUserActivity(txtUsername.Text.ToString(), txtAcctNo.Text.ToString(), "Password Reset Request", HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
startService.requestReset(txtUsername.Text.ToString(), txtAcctNo.Text.ToString(), token);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "<br>We have sent an email to you for the instructions to reset your password. Please check your email.";
}
else
{
// id not exist then execute following code
this.lblMessage.ForeColor = System.Drawing.Color.Red;
this.lblMessage.Text = "<br><br>Error - Information cannot be found. Please check and try again. Make sure all the fields are correct.";
}
}
}
}
catch
{
lblError.Text = "There was an error occured while processing your request. Please try again later.";
}
}

Categories

Resources