IDataReader runtime error - c#

I'm trying to populate my Request using the IDataReader but for some of the properties the values are coming back as null from the database, this then throws an exception because it doesn't like the null.
public static void Populate(IDataReader datareader, Request request)
{
request._requestID = datareader.IsDBNull(datareader.GetOrdinal("RequestID")) ? null : (int?)datareader.GetInt32(datareader.GetOrdinal("RequestID"));
request._appversion = datareader.GetString(datareader.GetOrdinal("AppVersion"));
request._apprequestguid = datareader.IsDBNull(datareader.GetOrdinal("AppRequestGUID")) ? null : datareader.GetString(datareader.GetOrdinal("AppRequestGUID"));
request._sourceip = datareader.IsDBNull(datareader.GetOrdinal("SourceIP")) ? null : datareader.GetString(datareader.GetOrdinal("SourceIP"));
request._cli = datareader.IsDBNull(datareader.GetOrdinal("CLI")) ? null : datareader.GetString(datareader.GetOrdinal("CLI"));
request._handsetid = datareader.IsDBNull(datareader.GetOrdinal("HandsetID")) ? null : datareader.GetString(datareader.GetOrdinal("HandsetID"));
request._service = datareader.IsDBNull(datareader.GetOrdinal("Service")) ? null : datareader.GetString(datareader.GetOrdinal("Service"));
request._requestrespcode = datareader.IsDBNull(datareader.GetOrdinal("RequestRespCode")) ? null : datareader.GetString(datareader.GetOrdinal("RequestRespCode"));
request._fraudmatchid = datareader.IsDBNull(datareader.GetOrdinal("FraudMatchID")) ? null : (int?)datareader.GetInt32(datareader.GetOrdinal("FraudMatchID"));
request._action = datareader.IsDBNull(datareader.GetOrdinal("Action")) ? null : datareader.GetString(datareader.GetOrdinal("Action"));
request._detail = datareader.IsDBNull(datareader.GetOrdinal("Detail")) ? null : datareader.GetString(datareader.GetOrdinal("Detail"));
request._apprespcode = datareader.IsDBNull(datareader.GetOrdinal("AppRespCode")) ? null : datareader.GetString(datareader.GetOrdinal("AppRespCode"));
request._createddttm = datareader.IsDBNull(datareader.GetOrdinal("CreatedDttm")) ? null : (DateTime?)datareader.GetDateTime(datareader.GetOrdinal("CreatedDttm"));
request._modifieddttm = datareader.IsDBNull(datareader.GetOrdinal("ModifiedDttm")) ? null : (DateTime?)datareader.GetDateTime(datareader.GetOrdinal("ModifiedDttm"));
}
I have tried adding but when I debug it doesn't reach the if statement.
if (request._appversion.Equals(null))
{
request._appversion = string.Empty;
}
What code can I add code so that it doesn't break if it gets a null from the database?

You can try this approach:
request._detail = Convert.ToString(datareader.Item("Detail"));
It should work because Convert.ToString(Convert.DBNull) = String.Empty.
Reference:
SqlDataReader.Item

Related

System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression. in c#

I am getting error on insert and update while i am providing number data in TXT_Firm_Pincode.Text and TXT_Firm_Bank_Ac_No.Text and when i am leaving this both fields empaty its working perfect can anybody help me out.
MC.Cmd_SQL = new OleDbCommand($#"Update TBL_Firm set
Firm_Owner = '{TXT_Firm_Owner.Text}',
Firm_Name = '{TXT_Firm_Name.Text}',
Firm_Address = '{TXT_Firm_Address.Text}',
Firm_City = '{TXT_Firm_City.Text}',
Firm_Pincode = #Firm_Pincode,
Firm_State= '{CB_Firm_State.Text}',
Firm_Con_Person = '{TXT_Firm_Con_Person.Text}',
Firm_Con_No = {TXT_Firm_Con_No.Text},
Firm_GSTN = '{TXT_Firm_GSTN.Text}',
Firm_Bank_Name = '{TXT_Firm_Bank_Name.Text}',
Firm_Bank_Ac_No = #Firm_Bank_Ac_No,
Firm_Bank_Branch = '{TXT_Firm_Bank_Branch.Text}',
Firm_Bank_IFSC= '{TXT_Firm_Bank_IFSC.Text}',
Firm_MailID = '{TXT_Firm_MailID.Text}'
where Firm_ID = {TXT_Firm_ID.Text}", MC.DB_Connection);
MC.Cmd_SQL.CommandType = CommandType.Text;
MC.Cmd_SQL.Parameters.AddWithValue("#Firm_Pincode" , TXT_Firm_Pincode.Text == "" ? DBNull.Value : (object)"Null");
MC.Cmd_SQL.Parameters.AddWithValue("#Firm_Bank_Ac_No", TXT_Firm_Bank_Ac_No.Text == "" ? DBNull.Value : (object)"Null");
MC.Cmd_SQL.ExecuteNonQuery();
Ternary operator condition ? operand1 : operand2 returns operand1 when condition is true and false - otherwise.
It is all right with your operand1 statement, but you need to change operand2 to put text box value in it:
MC.Cmd_SQL.Parameters.AddWithValue("#Firm_Pincode" ,
TXT_Firm_Pincode.Text == "" ? DBNull.Value : TXT_Firm_Pincode.Text);
MC.Cmd_SQL.Parameters.AddWithValue("#Firm_Bank_Ac_No",
TXT_Firm_Bank_Ac_No.Text == "" ? DBNull.Value : TXT_Firm_Bank_Ac_No.Text);

comboBox replace null to empty string

What can I do to detect when in comboBox I have null because user choose nothing, and replace it for empty string? I use for fill comboBox DataSource.
if (comboBoxTransport.SelectedItem.ToString() == null)
comboBoxMaintenance.SelectedItem = "";
this.dataGridViewOffer.DataSource = soc.FindOffer(comboBoxCountry.SelectedItem.ToString(), comboBoxAccommodation.SelectedItem.ToString(),
comboBoxTransport.SelectedItem.ToString(), comboBoxMaintenance.SelectedItem.ToString()).ToList();
I need it to correctly call method:
public List<Oferty1> FindOffer(string country, string accommodation, string transport, string maintenance) {...}
Or in how other way can I convert null to string in this case?
You can use Ternary Operator to check it wherever you need:
comboBoxTransport.SelectedItem == null ? String.Empty : comboBoxTransport.SelectedItem.ToString()
Complete Code:
if (comboBoxTransport.SelectedItem == null) //ToString can not be called if property is null
comboBoxMaintenance.SelectedItem = "";
this.dataGridViewOffer.DataSource =
soc.FindOffer(
comboBoxCountry.SelectedItem == null ? String.Empty : comboBoxCountry.SelectedItem.ToString(),
comboBoxAccommodation.SelectedItem == null ? String.Empty : comboBoxAccommodation.SelectedItem.ToString(),
comboBoxTransport.SelectedItem == null ? String.Empty : comboBoxTransport.SelectedItem.ToString(),
comboBoxMaintenance.SelectedItem == null ? String.Empty : comboBoxMaintenance.SelectedItem.ToString()
).ToList();

How can I check for a NullReferenceException in this C# LINQ to XML statement?

How can I check for a NullReferenceException in this C# LINQ to XML statement without wrapping the whole thing in a try/catch? If any of the properties are null, I would like it to still attempt to get the remaining data.
Thanks.
XElement doc = XElement.Load("test.xml");
var nodes =
from node in doc.Elements("Customer")
select new
{
Name = node.Element("FullName").Value,
Zip = node.Element("ZipCode").Value,
Active = node.Element("ActiveCustomer").Value,
};
Just use explicit cast. It will return null if the element wasn't found, won't cause an exception.
var nodes =
from node in doc.Elements("Customer")
select new
{
Name = (string)node.Element("FullName"),
Zip = (string)node.Element("ZipCode"),
Active = (string)node.Element("ActiveCustomer"),
};
Use the ternary operator.
Ternary Operator
XElement doc = XElement.Load("test.xml");
var nodes =
from node in doc.Elements("Customer")
select new
{
Name = node.Element("FullName") !=null ? node.Element("FullName").Value : null,
Zip = node.Element("ZipCode") !=null ? node.Element("ZipCode").Value : null,
Active = node.Element("ActiveCustomer") !=null ? node.Element("ActiveCustomer").Value : null
};
You could try this one:
select new
{
Name = node.Element("FullName")!=null ? node.Element("FullName").Value : null,
Zip = node.Element("ZipCode")!=null ? node.Element("ZipCode").Value : null,
Active = node.Element("ActiveCustomer")!=null ? node.Element("ActiveCustomer").Value : null
};
The ? is the conditional operator. For further documentation about this, please have a look here.
you can use ternary operator to check for null.
do like this:
var nodes =
from node in doc.Elements("Customer")
select new
{
Name = node.Element("FullName") !=null ? node.Element("FullName").Value : null,
Zip = node.Element("ZipCode") !=null ? node.Element("ZipCode").Value : null,
Active = node.Element("ActiveCustomer") !=null ? node.Element("ActiveCustomer").Value : null
};

Linq to XML to create 1 record per specific element

Here is an XML Element "inspection" with child Elements "driver", "vehicle" and "violation", for which I need the Attribute values.
I need to create one record for each inspection that also contains the other element's attribute values.
<inspection inspection_date="2012-07-08" report_state="IL" report_number="ILP4E1014879" level="1" time_weight="1">
<driver first_name="MELVIN" last_name="DANIELS" date_of_birth="1976-12-20" license_state="IL" License_number="D8505003"></driver>
<vehicle vehicle_id_number="1HSCNAPR74C501842" unit_type="Truck Tractor" license_state="IL" license_number="1234567"></vehicle>
<violations>
<violation code="122.4B2C" description="Lights" oos="N" basic="Vehicle Maint." severity_weight="4"></violation>
</violations>
</inspection>
Here is a snippet:
dotinspections = from el in inspectionList
select el;
foreach (var el in dotinspections)
{
if (el.Attribute("inspection_date") != null && el.Attribute("inspection_date").Value != null)
{ insDate = Convert.ToDateTime(el.Attribute("inspection_date").Value); }
state = el.Attribute("report_state") != null && (string)el.Attribute("report_state").Value != null ? el.Attribute("report_state").Value.Replace("'", "''") : null;
insNumber = el.Attribute("report_number") != null && el.Attribute("report_number").Value != null ? el.Attribute("report_number").Value.Replace("'", "''") : null;
if (el.Attribute("level") != null && el.Attribute("level").Value != null)
{ insLevel = Convert.ToInt32(el.Attribute("level").Value); }
These are in an IEnumerable "dotinspections". I have tried just about every method using .Elements, .Descendants, .Attributes etc.., but can only get an inspection record, then a driver record, then vehicle, etc.., not one record for each full inspection.
How can I get one record per inspection?
Lesson learned - thanks webdad3.
I didn't post all my code (for brevity). The problem was me not going deeper into the nested XElements. I needed to add "violations" and "vehicle" and other ancestors to my attributes:
licenseNumber1 = el.Element("vehicle").Attribute("license_number") != null && el.Element("vehicle").Attribute("license_number").Value != null ? el.Element("vehicle").Attribute("license_number").Value.Replace("'", "''") : null;
code = el.Element("violations").Element("violation").Attribute("code") != null && el.Element("violations").Element("violation").Attribute("code").Value != null ? el.Element("violations").Element("violation").Attribute("code").Value.Replace("'", "''") : null;
description = el.Element("violations").Element("violation").Attribute("description") != null && el.Element("violations").Element("violation").Attribute("description").Value != null ? el.Element("violations").Element("violation").Attribute("description").Value.Replace("'", "''") : null;

Handling null objects in object setters

I am trying to use a nice near object setter, but have null issues.
My code right now:
var Result = new RefundReplyObject
{
AuthorisationNumber = reply.refundResponse.transactionDetails.authorisationNumber,
ChargeValue = reply.refundResponse.transactionDetails.totalAmount.amount,
Message = reply.refundResponse.transactionDetails.message,
ReconciliationReference = reply.refundResponse.transactionDetails.reconciliationReference,
SettlementDate = reply.refundResponse.transactionDetails.settlementDate,
Status = TransactionStatusToLocalModel(reply.refundResponse.transactionDetails.status),
TransactionReference = reply.refundResponse.transactionDetails.transactionReference
};
BUT ... 'totalAmount' might be null. So, I get errors.
Is there a neat way to handle this, so that if 'totalAmount' is null, then set chargevalue to zero?
How about a ternary operator, that checks to see if total amount is null. If it isn't, then use it's amount, otherwise 0.
ChargeValue = (reply.refundResponse.transactionDetails.totalAmount != null) ? reply.refundResponse.transactionDetails.totalAmount.amount : 0,
You could do, for example:
ChargeValue = reply.refundResponse.transactionDetails.totalAmount != null ? reply.refundResponse.transactionDetails.totalAmount.amount : 0
ternary operator to the rescue!
ChargeValue = totalAmount ? totalAmount.amount : 0;
Something like this?
ChargeValue = (null == reply.refundResponse.transactionDetails.totalAmount)
? 0
: reply.refundResponse.transactionDetails.totalAmount.amount
You're not going to be able to do it on the setter side of things since the exception is occuring before you even get there. You can get what you're after (and clean up your code substantially in the process) by doing something like this:
var trans = reply.refundResponse.transactionDetails;
var Result = new RefundReplyObject
{
AuthorisationNumber = trans.authorisationNumber,
ChargeValue = trans.totalAmount == null ? 0 : trans.totalAmount.amount,
Message = trans.message,
ReconciliationReference = trans.reconciliationReference,
SettlementDate = trans.settlementDate,
Status = TransactionStatusToLocalModeltrans.status),
TransactionReference = trans.transactionReference
};

Categories

Resources