SQL Server Database Getting NULL values - c#

I'm using a SQL Server database to store data for my project. I have some functions (c#) which use SQL queries to get null values.
My query goes perfect but I'm not able handle null value in my code.
public satic string getValue(int paramOne, string alternateString)
{
var db = Database.Open("MyDatabase");
var query = "SELECT * FROM UserData WHERE ColumnOne = #0 AND ColumnTwo = SomeValue";
var row = db.QuerySingle(query, paramOne);
var data = row.data;
var returnValue = "";
// Here comes the problem
if(data == null)
{
returnValue = alternateString;
}
else
{
returnValue = data;
}
return returnValue;
}
When I execute this function, I get error
Cannot perform runtime binding on a null reference
Any help will be appreciated. Thank you!

If you SQL query does not returns anything, then row (as result of db.QuerySingle) will be null.
So you have to check it before accessing row.data something like this:
var returnValue = "";
if(row != null && row.data != null)
returnValue = row.data;
else
returnValue = alternateString;

Related

Find the null value of a Datatable

I am building a AWS lambda function .net core.
The issue I am encountering is, when there is no data in the row / column of the datatable I still get a count of one, in turn getData != null && getData.Count() > 0 defaults true and then throws a NullRefrenceError since the value is null when it goes to the loop, I have tried checking for multiple null types in datatable with them still defaulting to true.
Is there another way to check for nullable values, to avoid the assignment causing the error in a datatable column / row.
public object emailGets ( AType invoiceNum, ILambdaContext context )
{
Connection conn = new Connection();
try
{
string query = "SELECT QUERY";
conn.getData(query);
DataRow[] getData = conn.Dt.Select();
if(getData != null && getData.Count() > 0)
{
foreach (var item in getData)
{
string yourItem = item.Field<String>("email").ToString();
}
return new userData { email = yourItem};
}
else
{
return new userEmailAddress { email = null};
}
} catch ( Exception e )
{
throw e;
}
}
}
public class userEmailAddress
{
public string email { get; set; }
}
ToString() will throw a NullReferenceException when the source is null. So when you do
string yourItem = item.Field<String>("email").ToString();
and the item.Field<String>("email") part returns null, you'll get that exception.
Luckily, that ToString() call is redundant, so you can simply remove it and just have:
string yourItem = item.Field<String>("email");
Keep in mind that yourItem can now be null here.

Failed to enable constraints using TableAdapters

I'm trying to check if a username exists in my table when everytime a character is entered in the TextBox. Here is my code:
Within the register.aspx.cs file I have a TextChanged event on the TextBox:
protected void username_txt_TextChanged(object sender, EventArgs e)
{
string check = authentication.checkUsername(username_txt.Text);
if(check == "false")
{
username_lbl.Text = "Available";
}
else
{
username_lbl.Text = "Not Available";
}
}
It calls this method:
public static string checkUsername(string Username)
{
userInfoTableAdapters.usersTableAdapter userInfoTableAdapters = new userInfoTableAdapters.usersTableAdapter();
DataTable userDataTable = userInfoTableAdapters.checkUsername(Username);
DataRow row = userDataTable.Rows[0];
int rowValue = System.Convert.ToInt16(row["Users"]);
if (rowValue == 0)
{
return "false";
}
else
{
return "true";
}
}
The query that is being executed is:
SELECT COUNT(username) AS Users FROM users WHERE (username = #Username)
For some reason, it keeps breaking on this line:
DataTable userDataTable = userInfoTableAdapters.checkUsername(Username);
It gives an error that says:
Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
Just incase, the username field in my table is Unique and Not Null, I have tried just executing the query itself and it works perfectly so it isn't at the query end.
Does anyone understand what I am doing wrong?
Your query doesn't return the row - so using a TableAdapter query that returns the DataTable is inappropriate in this case.
I'd recommend using your query with something like the function below. I took the liberty of actually returning boolean....
public static bool checkUsername(string userName)
{
SqlClient.SqlCommand withCmd = new SqlClient.SqlCommand();
bool result = false;
withCmd.Connection.Open();
withCmd.CommandType = CommandType.text;
withCmd.CommandText = "SELECT COUNT(username) AS Users FROM users WHERE (username = #Username)"
withCmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#Username", System.Data.SqlDbType.VarChar, 16)).Value = userName;
try {
int intResult;
object scalarResult = withCmd.ExecuteScalar();
if ((scalarResult != DBNull.Value)
&& (scalarResult != null)
&& (int.TryParse(scalarResult, out intResult)))
result = (intResult==1);
} catch (Exception ex) {
result = false; // hmm, bad...can't tell handle error...
} finally {
// only close if we opened the connection above ...
withCmd.Connection.Close();
}
}
return result;
}
A TableAdapter does support scalar queries on the Table Object, when you add and name your query, check the properties of that query and be sure its ExecuteMode is Scalar. It will then return the integer value, not the row!
On the other hand, if you want to keep your structure, change the query to actually return the row, something like
SELECT uu.* AS dbo.Users uu FROM users WHERE (username = #Username)
and make the result of the checkUsername() function depend on the number of rows returned (which should be 1 or zero....)

To Check Session is null or not

In the below code I have Session variable in which I want to check whether it is null or not. Please help me to do this.
(SearchDoc) is class.
var SearchDoc = (SearchDoc)Session["Documentname"];
var oDocumentID = SearchDoc.ClientID;
var Documentid = SearchDoc.DocumentID;
if (SearchDoc == null)
{
}
This is the safest approach :
if ((HttpContext.Current.Session !=null && Session["Documentname"] as SearchDoc!= null))
{
//do what you want with
((SearchDoc)Session["Documentname"])
}
2 things to notice :
Yes , sometime the session object is null. ( probably occurs with AShX's without appropriate interface)
use the AS operator. - once it's ok , you can safely cast to SearchDOC
Try this
if(Session["Documentname"] != null)
{
var SearchDoc = (SearchDoc)Session["Documentname"];
var oDocumentID = SearchDoc.ClientID;
var Documentid = SearchDoc.DocumentID;
if (SearchDoc == null)
{
}
}
You can simply try this:
string oDocumentID = string.Empty;
string Documentid = string.Empty;
if(Session["Documentname"] != null){
var SearchDoc = (YourSearchDocType)Session["Documentname"];
oDocumentID = SearchDoc.ClientID;
Documentid = SearchDoc.DocumentID;
// some code
}
dont try to access some property of object which can be null

Why my query doesn't update the table with my input parameters?

I don't know why the following query doesn't executed with my expected parameters !!
cmdTxt.Append("UPDATE sd32depart SET currentcredit = currentcredit + ? WHERE year = ? AND main_code = ? ");
paramList.Add("currentcredit", value.ToString().TrimEnd());
paramList.Add("year", year.ToString().TrimEnd());
paramList.Add("main_code", main_code.ToString().TrimEnd());
res = ConnectionObj.Execute_NonQueryWithTransaction(cmdTxt.ToString(), CommandType.Text, paramList);
I get
res = 1and although currentcredit = 180 as a parameter
when i check my table i found currentcredit NULL !!
public int Execute_NonQueryWithTransaction(string cmdText)
{
string return_msg = "";
int return_val = -1;
//check if connection closed then return -1;
if (connectionstate == ConnectionState.Closed)
return -1;
command.CommandText = cmdText;
command.CommandType = CommandType.Text;
command.Transaction = current_trans;
try
{
return_val = command.ExecuteNonQuery();
}
catch (IfxException ifxEx)// Handle IBM.data.informix : mostly catched
{
return_val = ifxEx.Errors[0].NativeError;
return_msg = return_val.ToString();
}
catch (Exception ex)// Handle all other exceptions.
{
return_msg = ex.Message;
}
finally
{
if (!string.IsNullOrEmpty(return_msg))//catch error
{
//rollback
current_trans.Rollback();
Close_Connection();
}
}
return return_val;
}
From the comments:
currentcredit is null before the update, what should i do
Ah, that's the problem then. In SQL, null is sticky. null + anything is: null. If this was TSQL (i.e. SQL Server), the solution would be ISNULL:
UPDATE sd32depart SET currentcredit = ISNULL(currentcredit,0) + ?
where the result of ISNULL(x, y) is x if x is non-null, otherwise y. In C# terms, it is the equivalent of x ?? y (and indeed, ISNULL(x, y) is identical to COALESCE(x, y), except that COALESCE is varadic).
So: find the informix equivalent of ISNULL or COALESCE, and use that.
From a brief search, it seems that in informix the NVL function does this, so try:
UPDATE sd32depart SET currentcredit = NVL(currentcredit,0) + ?

Invalid Cast DateTime?

I have a class with the following code
public cCase(string pCaseNo, string pMode)
{
if (pMode == "new")
{
this._caseNo = Validate_CaseNo(pCaseNo);
}
if (pMode == "existing")
{
try
{
int intValidatedCaseNo = Validate_CaseNo(pCaseNo);
string sqlText = "SELECT * FROM tblCases WHERE CaseNo = #CaseNo;";
string strConnection = cConnectionString.BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnection);
linkToDB.Open();
SqlCommand sqlCom = new SqlCommand(sqlText, linkToDB);
sqlCom.Parameters.Add("#CaseNo", SqlDbType.Int);
sqlCom.Parameters["#CaseNo"].Value = intValidatedCaseNo;
SqlDataReader caseReader = sqlCom.ExecuteReader();
if (caseReader.HasRows)
while (caseReader.Read())
{
this._claimant = caseReader["Claimant"].ToString();
this._defendant = caseReader["Defendant"].ToString();
this._caseType = caseReader["CaseType"].ToString();
this._occupation = caseReader["Occupation"].ToString();
this._doa = (DateTime?)caseReader["DOA"];
this._dateClosed = (DateTime?)caseReader["DateClosed"];
this._dateSettled = (DateTime?)caseReader["DateSettled"];
this._dateInstructed = (DateTime?)caseReader["DateInstructed"];
this._status = caseReader["Status"].ToString();
this._instructionType = caseReader["InstructionType"].ToString();
this._feeEstimate = (decimal?)caseReader["FeeEstimate"];
this._amountClaimed = (decimal?)caseReader["AmountClaimed"];
this._amountSettled = (decimal?)caseReader["AmountSettled"];
this._caseManager = caseReader["CaseManager"].ToString();
}
caseReader.Close();
linkToDB.Close();
linkToDB.Dispose();
}
catch (Exception eX)
{
throw new Exception("Error finding case" + Environment.NewLine + eX.Message);
}
}
}
However the Datetime? casts fail with an 'Invalid Cast'.
I've checked the SQL database and the field is storing valid dates
So I cant work out why, as I extract info via the DataReader into my app, the datetime fields are causing an Invalid Cast.
Please help.
You're going to want to change the line that reads:
this._doa = (DateTime?)caseReader["DOA"];
to:
if (caseReader["DOA"] != DBNull.Value)
this._doa.Value = (DateTime)caseReader["DOA"];
As well as all similar lines.
DBNull values cannot be casted from Nullable types.
Your DateTime fields probably hold a DBNull value which you cannot convert directly.
However, I'd use an extension method on your DataReader for convinience.
public static class DataReaderExtensions
{
public static DateTime? ReadNullableDateTime(this IDataReader reader, string column)
{
return reader.IsDBNull(column) ? (DateTime?)null : reader.GetDateTime(column);
}
}
// Usage
this._dateInstructed = CaseReader.ReadNullableDateTime("DateInstructed");
You should use
DateTime.TryParse Method
this not throw exception, like
var mydate =(DateTime)datetimeString
or
var mydate =DateTime.Parse(datetimeString)
does!!!
Try with the following code part
this._doa = (caseReader["DOA"] == DBNull.Value ? DBNull.Value : Convert.ToDateTime(caseReader["DOA"]);
Try to Convert Date Time as
this._doa = Convert.ToDateTime(caseReader["DOA"]);
I often deal with DBNull.Value...
So I use this method that will return the value of the object or the default value of the given value type if object's value is DBNull.Value.
public static object GetValueOrDefault(object value, Type type)
{
if (value != DBNull.Value)
return value;
if (type.IsValueType == false)
return null;
Array array = Array.CreateInstance(type, 1);
return array.GetValue(0);
}
Usage:
GetValueOrDefault(dataRecord.GetValue(fieldIndex), dataRecord.GetFieldType(fieldIndex)

Categories

Resources