Check Null or Empty String For Two Values C# [duplicate] - c#

This question already has answers here:
How can I fix the error : "Unreachable Code Detected"
(4 answers)
Closed 3 years ago.
I want to check for empty string or null values for Subject Code and Subject Name so that empty string of subject code and subject name will not be store in the database. I'm new to c#. There is an error to the code. It stated cannot convert from bool to string. I tried so many ways but the error is still there. After fixing the error for converting from bool to string, it returned me an Not Found error. How should I change the return NotFound() error?
public IHttpActionResult PostAddSubjectCode([FromBody] ConfigSubjectCode SubjectCodes)
{
string Subject_Code = SubjectCodes.Subject_Code;
string Subject_Name = SubjectCodes.Subject_Name;
if (String.IsNullOrEmpty(Subject_Code) && String.IsNullOrEmpty(Subject_Name))
{
return NotFound();
}
else
{
string sql = "INSERT INTO[dbo].[GEO_SUBJECT_CODES] ([Subject_Code],[Subject_Name_BY_CLASS]) VALUES " +
"('" + Subject_Code + "', '" + Subject_Name + "');";
DBConnection dbConnection = new DBConnection();
dBConnection.UpdateTable(sql);
return Ok();
}
}

The error states exactly what the problem is: You're passing a boolean (Subject_Code == "" && Subject_Name == "") to String.IsNullOrEmpty which expects a string
You're setting empty string to the variables you're checking, making the if check pointless
Your SQL is open to injection
Strongly suggested: Getting started with ASP.NET MVC 5, it will also have links to newer Core examples.
I'll keep this here since we had a thread going and to point out the issues listed.
// These will make the if statement useless, it will never hit else
// string Subject_Code = "";
// string Subject_Name = "";
//Assumptions: Subject_Codes contians these props
if(string.IsNullOrEmtpy(SubjectCodes.Subject_Code) && string.IsNullOrEmpty(SubjectCodes.Subject_Name)){
// whatever you want to do...
} else {
//sql here - I'll skip the comments on why your sql is bad - re: use parameters
// return after successful sql - look into a try/catch
}
Look into DataAnnotations [Required] in your model instead - you gain both server and client side validation. I strongly suggest you go over extensive tutorials instead of piecemeal stuff.

Based on the above code what you have tried to do is compare boolean value to a string value which would give you an error try the solution below.
if (String.IsNullOrEmpty(Subject_Code) && String.IsNullOrEmpty(Subject_Name)){
return NotFound();
} else{
try{
//SQL Code
} catch (Exception ex){
//Your Code
}
}
Note: This is a quick fix for OP's problem, not the best practice.

Since your if/else both return, it will never get to the actual update code. And you were assigned both variable to a fixed empty string, which would never cause the if/else to work in any case. You want something like this:
public IHttpActionResult PostAddSubjectCode([FromBody] ConfigSubjectCode SubjectCodes)
{
string Subject_Code = SubjectCodes.Subject_Code; // these can't be fixed ""
string Subject_Name = SubjectCodes.Subject_Name; // these can't be fixed ""
if (String.IsNullOrEmpty(Subject_Code) && String.IsNullOrEmpty(Subject_Name))
{
return NotFound();
}
else
{
string sql = "INSERT INTO[dbo].[GEO_SUBJECT_CODES] ([Subject_Code],[Subject_Name_BY_CLASS]) VALUES " +
"('" + Subject_Code + "', '" + Subject_Name + "');";
DBConnection dBConnection = new DBConnection();
dBConnection.UpdateTable(sql);
return Ok();
}
}

Related

JObject Parse Data with a variable as the value

I am trying to decipher the correct syntax for using JObject Parse when I need to have one of the values set by a variable. This is for using Algolia to push a new object to my search index.
songIndexHelper.PartialUpdateObject(JObject.Parse(#"{""ApprovalFL"":"true",
""objectID"":"'+Accepted.Value+'"}"));
I receive Accepted.Value from my function argument. For example, Accepted.Value could equal something like 98. Also, true should be formatted as boolean instead of a string. The above is my attempt. How should I fix my syntax?
I'm following this documentation from Algolia: https://www.algolia.com/doc/api-reference/api-methods/partial-update-objects/
For more context, here is the above line in the function:
public ActionResult Index(int? Accepted, int? Denied)
{
var accountInfo = EntityDataAccess.GetAccountInfoByUserID(User.Identity.GetUserId());
if(accountInfo == null || accountInfo.AdminFL == false || accountInfo.LabelFL == true)
{
return RedirectToAction("Index", "Home");
}
else
{
if(Accepted != null)
{
EntityDataAccess.AcceptSong(Accepted.Value);
var songIndexHelper = HttpContext.Application.Get("SongIndexHelper") as IndexHelper<SongAlgoliaModel>;
songIndexHelper.PartialUpdateObject(JObject.Parse(#"{""ApprovalFL"":""true"",
""objectID"":""Accepted.Value""}"));
}
This should produce what you are looking for:
String json = "{\"ApprovalFL\":true,\"objectID\":" + Accepted.Value.ToString() + "}";
which is:
{"ApprovalFL":true,"objectID":98}
songIndexHelper.PartialUpdateObject(JObject.Parse(#"{""ApprovalFL"":""true"",
""objectID"":""Accepted.Value""}"));
should be:
songIndexHelper.PartialUpdateObject(JObject.Parse(#"{""ApprovalFL"":true,
""objectID"":" +Accepted.Value+ "}"));
The key is to use + to concatenate in the value of Accepted, and not wrap true in quotes.
Another approach I would suggest is not using strings at all. Consider an approach like:
var bob = new { ApprovalFL = true, objectID = Accepted.Value};
var obj = JObject.FromObject(bob);
songIndexHelper.PartialUpdateObject(obj);

How would you match a record from a select statement against a string in c#?

I'm trying to create a statement to check data from a foxpro database against a string in c#
however I can't seem to get it working, would using parameterised queries here help to achieve what I'm trying to do?
string PROPCODE = "IMPORT_" + ID;
string leadtenant = clcodet;
using (OleDbCommand tenantpopulation = new OleDbCommand(#"SELECT
CLCODE,
CLCODEDESC
FROM CLIENT WHERE PROPCODET = " + PROPCODE, importConnection))
{
string tenants = "";
if (#"CLCODE" = leadtenant)
{
if (tenants != String.Empty)
{
//do something
}
}
}
To Clarify, i want to check whether CLCODE, called from tenantpopulation, matches leadtenant, defined elsewhere in the code
As others already noted using parameters is the way to go (not only in VFP but any SQL database). They are not only for preventing SQL injection attacks, using parameters the drivers take care of converting into correct string, adding/removing braces, quotes etc.
string PROPCODE = "IMPORT_" + ID;
string leadtenant = clcodet;
using (OleDbCommand tenantpopulation = new OleDbCommand(#"SELECT
CLCODE
FROM CLIENT WHERE PROPCODET = ?", importConnection))
{
tenantpopulation.Parameters.AddWithValue("p", PROPCODE);
// rest of code seem to be meaningless
// and I didn't see any code where you run your query
// depending on your requirement, I assume PROPCODET is a primary key?
// if so then you to do the check you only need to return the CLCODE
// with ExecuteScalar:
importConnection.Open();
var clcode = (string)tenantpopulation.ExecuteScalar();
importConnection.Close();
string tenants = "";
// in C# equality check is done with == NOT = (assingment)
if (clcode == leadtenant)
{
// tenants is always String.Empty here
if (tenants != String.Empty)
{
//do something
}
}
}
PS: Have you ever thought, using Tom Brother's LinqToVFP from codeplex? With Linq, you don't need to know these SQL dialects much and instead you use Object query (and intellisense).

Getting errors with SqlParameter and ExecuteScalar

public TransImport()
{
ConnString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
conn_new = new SqlConnection(ConnString);
command_serial_new = conn_new.CreateCommand();
command_serial_new.CommandText = "SELECT 1 FROM YSL00 WHERE SERLNMBR = #slnr";
var p = new SqlParameter("#slnr", SqlDbType.NVarChar, 50);
command_serial_new.Parameters.Add(p);
//Here you will start reading flat file to get serialnumber.
//Here I have shown a simple call using one value 12345 but it will be 1000's of
//lines from flatfile.
if (CheckSerialNumber('12345'))
DisplayMessage("Good serialnumber"); //this function is not copied here.
}
private Boolean CheckSerialNumber(string SerialNumber)
{
command_serial_new.Parameters["#slnr"].Value = SerialNumber;
try
{
var itExists = (Int32)command_serial_new.ExecuteScalar() > 0;
if (itExists)
{
return true;
}
}
catch (Exception ex)
{
LogException(ex, "Error in CheckSerialNumber =>"+ command_serial_new.CommandText.ToString());
}
return false;
}
I get error in the above catch. It mentions
object reference not set to an instance of object
It is failing with the line that has ExecuteScalar.
I guess I am doing something wrong here, but unable to figure out so far.
Update 1: I have modified this question. Basically I created another question with an issue I am facing.. Also I have marked it as answered.
Here is the NEW question I have posted just now.
Getting timeout errors with SqlTransaction on same table
This happens if the ExecuteScalar() returns null. (eg, because no rows matched)
Since int is a value type, it cannot be null; therefore, you get an error.
Instead, you can cast it to int?, which is nullable.
#SLaks answer is correct.
Here is one more way to avoid the error. No need of null checking etc, Convert.ToInt32 takes care of everything.
var itExists = Convert.ToInt32(command_serial_new.ExecuteScalar()) > 0;
try:
int i;
object o = command_serial_new.ExecuteScalar();
if(o != null && Convert.ToInt32(o.ToString()) > 0)
{
//....
}
to verify that your query returned something

Error for Null value when opening a registry key in C#

I'm having an issue for C# (I'm new to it), when trying to fix a Null value.
Therefore I have a variable "verif" (String verif = String.Empty;), which I used it to read some key from Windows Registry. My code works if the key exists, but when it doesn't I got the error"NullReferanceException was unhandled".
I tried several ways, to catch the exception, to put an "If" statement but I failed miserable.
My code is something like this:
RegistryKey key_user;
RegistryKey key_pwd;
String code = String.Empty;
String tara = String.Empty;
String tot = String.Empty;
String pwd_mdw = String.Empty;
String user_mdw = String.Empty;
String user_uca = String.Empty;
String pwd_uca = String.Empty;
String verif = String.Empty;
private void button1_Click(object sender, EventArgs e)
{tot = listBox1.SelectedValue.ToString();
//MessageBox.Show(tot);
tara = tot.Substring(tot.Length - 2, 2);
//MessageBox.Show(tara);
code = listBox1.SelectedValue.ToString().Substring(0, 2);
user_mdw = textBox1.Text;
//MessageBox.Show(user_mdw);
pwd_mdw = textBox2.Text;
//MessageBox.Show(pwd_mdw);
if (code == "CC")
{
verif = Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials").GetValue("user_mdw_" + tara + "_CC").ToString();
MessageBox.Show("Verif",verif);
MessageBox.Show(user_mdw, "user_mdw");
if (verif==null)
{
key_user = Registry.CurrentUser.CreateSubKey("Software\\TDCredentials");
key_user.SetValue("user_mdw_" + tara + "_CC", user_mdw);
key_user.Close();
key_pwd = Registry.CurrentUser.CreateSubKey("Software\\TDCredentials");
key_pwd.SetValue("pass_mdw_" + tara + "_CC", pwd_mdw);
key_pwd.Close();
MessageBox.Show("User and Password inserted successfully!");
textBox1.Clear();
textBox2.Clear();
}
else
{...
Any hints?
Many thanks in advance, Bogdan.
Looking at what you're trying to do, this line is most likely (one of) your problems;
verif = Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials")
.GetValue("user_mdw_" + tara + "_CC").ToString();
If the key does not exist, OpenSubKey will return null, and you call GetValue() on it without checking.
You can change the line to add a check, something like;
var key = Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials");
var value = key != null ? key.GetValue("user_mdw_" + tara + "_CC") : null;
verif = value != null ? value.ToString() : null;
if(verif == null) {
...
First of all you need to check
Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials")
that this is not null. Then call the getvalue method. Beause if the above key is null then the following getvalue will throw exception.
Try the following check to test if Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials") is not null else it will bomb:
if (code == "CC")
{
if (Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials") != null)
{
verif =
Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials").GetValue("user_mdw_" + "Test" + "_CC").
ToString();
}
Try checking for NULL on OpenSubKey() & GetValue() methods prior to using ToString() method.
You're trying to do too much in one line, without checking the results as you go.
First of all, as others have already said, you need to check that OpenSubKey doesn't return null. You also need to make sure that the key is closed when you're finished, with a using statement:
using (var key = Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials"))
{
if (key == null)
{
// Couldn't open the key, now what?
// You need to make a decision here.
// If you read the documentation for CreateSubKey,
// you'll see that it can *also* return null, so don't rely on it.
}
else
{
// OK, opened the key, and the using statement will close it.
// Now we can try reading values. See the next part of the answer.
}
}
If you successfully open the key, you can try to read the value. Even if you successfully open the key, the value might not exist, or it might not be a string (it could be a DWORD, for instance, or a binary value).
If the value doesn't exist, GetValue returns null, so calling ToString without checking will throw NullReferenceException.
Even if the value exists, calling ToString on it is the wrong thing to do, because it might not be a string value in the registry. If it's a binary value, for example, calling ToString on it will give you the string System.Byte[]. You need to check that it is actually a string.
else
{
// OK, opened the key, and the using statement will close it.
// Now we can try reading values.
string verif = key.GetValue("user_mdw_" + tara + "_CC") as string;
if (verif == null)
{
// The value does not exist, or is not the type you expected it to be (string).
// Now what? You need to make a decision here.
}
else
{
// OK, do something with verif.
}
}
Make sure to read the documentation for these methods, and handle the special cases they mention, especially the circumstances under which they return null:
CreateSubKey
OpenSubKey
GetValue

NullReferenceException error C# [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 9 years ago.
QueryClass Query;
string UserName = "";
int UserId = 0;
string email = txtEmail.Text;
string name = txtUserName.Text;
string phone = txtPhone.Text;
byte[] buffer = new byte[100];
UserName = Query.GetUserName(email); //returns a string value
if (UserName != null)
{
MessageBox.Show(UserName + " is already in the database");
}
if (Query.AddNewUser(name, email, phone) == true) //returns a bool value
{
UserId = Query.GetUserId(email); //returns a int value
if (Query.AddNewImage(UserId, buffer) == true) //returns a bool value
{
MessageBox.Show("Done..!!");
}
}
MessageBox.Show("Error");
I'm getting the following error after I click the insert button (above code) of my program.
System.NullReferenceException
Message="Object reference not set to an instance of an object."
I'm getting that exception on following places. (i didn't check other places) code just stops these places and gives the error.
UserName = Query.GetUserName(email); //returns a string value
if (Query.AddNewUser(name, email, phone) == true) //returns a bool value
Can anyone please help me to fix this error? I'm using Visual studio 2010.
You're using Query without actually setting it to anything. You likely need to construct an instance:
// Change: QueryClass Query;
QueryClass Query = new QueryClass();
Without creating an instance, when you call:
UserName = Query.GetUserName(email);
At this point, Query is still the default value (which is null for a reference type), and you'll get a NullReferenceException upon trying to use it.
On a side note, you might want to consider naming this variable query (lower case), and the class Query (or, better yet, a more descriptive name), in order to follow the normal .NET naming guidelines.

Categories