I wasn't the one who coded this line of code, and I can't gt to understand whoever did it, why did this way on this line: res.Data.Find(itm => itm.Meta.ID.ToUpper() == i["MetaDataID"].ToString().ToUpper()).Value[i["LocaleID"].ToString()] = i["Value"].ToString();
And this line gives me a NullReferenceException. How can I get around it?
public static void LoadData(Value.Item _res)
{
DataTable Res = Connector.Run("SELECT * FROM Data WHERE ItemID='" + _res.ID + "'");
if (Res.Rows.Count != 0)
{
foreach (DataRow i in Res.Rows)
{
try
{
_res.Data.Find(itm => itm.Meta.ID.ToUpper() == i["MetaDataID"].ToString().ToUpper()).Value[i["LocaleID"].ToString()] = i["Value"].ToString();
}
catch (Exception)
{
_res.Data.Add(new Value.Data(
i["ID"].ToString(),
i["Value"].ToString(),
i["LocaleID"].ToString(),
i["MetaDataID"].ToString()
));
}
}
}
}
Thx a lot guys!!! Here is my working solution which hrows no Exceptions anymore!
public static void LoadData(Value.Item _res)
{
DataTable Res = Connector.Run("SELECT * FROM Data WHERE ItemID='" + _res.ID + "'");
if (Res.Rows.Count != 0)
{
foreach (DataRow i in Res.Rows)
{
bool _flagged = false;
var _result = _res.Data.Find(itm => itm.Meta.ID.ToUpper() == i["MetaDataID"].ToString().ToUpper());
if(_result != null && i["LocaleID"] != null)
{
if (i["Value"] == null || i["LocaleID"] == null || i["MetaDataID"] == null)
_flagged = true;
}
else
{
_flagged = true;
}
if (_flagged)
{
_res.Data.Add(new Value.Data(
i["ID"].ToString(),
i["Value"].ToString(),
i["LocaleID"].ToString(),
i["MetaDataID"].ToString()
));
}
//try
//{
// _res.Data.Find(itm => itm.Meta.ID.ToUpper() == i["MetaDataID"].ToString().ToUpper()).Value[i["LocaleID"].ToString()] = i["Value"].ToString();
//}
//catch (Exception)
//{
// _res.Data.Add(new Value.Data(
// i["ID"].ToString(),
// i["Value"].ToString(),
// i["LocaleID"].ToString(),
// i["MetaDataID"].ToString()
// ));
//}
}
}
}
Impossible to answer accurately without having the code under the debugger, however what is certain is that at least one of the following has a value of null:
_res.Data
itm.Meta
itm.Meta.ID
i["MetaDataID"]
i["LocaleID"]
i["Value"]
Old-skool debugging:
Break the statement down to it's consituent parts - using local variables. Step-through and find which one is null.
Check if one of the following are null:
i["MetaDataID"]
i["LocaleID"]
i["Value"]
Related
For some reason, my code doesn't seem to reach the last few lines.
I've added the stop point and the return point in the code.
I don't see anything wrong with the data source I use on that row whenever I check it out in debug.
The code seems to set the value there and jumps back to the top of the foreach loop.
foreach (DataGridViewRow row in dataGridView1.Rows) {
//We check if the user has already filled in some info
return point if (row.Cells[7].Value != null && row.Cells[6].Value != null && !askedTheUser)
{
//trigger for message if you want to replace them
Message m = new Message("There is already info present in the category and or size dropdown. Would you like to overwrite this?", "Overwrite", "YESNO");
if (m.Awnser) {
overwrite = true;
}
askedTheUser = true;
}
DataGridViewComboBoxCell cat = (DataGridViewComboBoxCell)row.Cells[6];
string toMatch = row.Cells[3].Value.ToString();
//Now we will start matching
//First we try to match with the package ( if that is filled in )
if (row.Cells[5].Value != null && (string)row.Cells[5].Value != "") {
toMatch = row.Cells[5].Value.ToString();
matchWithPackage = true;
}
Regex re = new Regex(#"([a-zA-Z]+)(\d+)");
Match result = re.Match(toMatch);
string alphaPart = result.Groups[1].Value;
string numberPart = result.Groups[2].Value;
Datagridview dgv = new Datagridview();
if (numberPart.Length < 4) {
numberPart = numberPart.PadLeft(4, '0');
}
#if DEBUG
Console.WriteLine(numberPart);
#endif
//Matching the category
if (CHIP != null && CHIP.Contains(alphaPart))
{
cat.Value = "CHIP";
}
else if (SOJ != null && SOJ.Contains(alphaPart))
{
cat.Value = "SOJ";
}
else if (PLCC != null && PLCC.Contains(alphaPart))
{
cat.Value = "PLCC";
}
else if (QFP != null && QFP.Contains(alphaPart))
{
cat.Value = "QFP";
}
else if (SOP != null && SOP.Contains(alphaPart))
{
cat.Value = "SOP";
}
else {
if (cat.Value != "") {
cat.Value = "";
}
cat.FlatStyle = FlatStyle.Flat;
cat.Style.BackColor = Color.DarkRed;
continue;
}
//Setting the matched color
cat.FlatStyle = FlatStyle.Flat;
cat.Style.BackColor = Color.SpringGreen;
//Adding the dropdownlist to the size cb
(row.Cells[7] as DataGridViewComboBoxCell).DataSource = dgv.AddSeconderyCombobox(dataGridView1, row.Cells[6].Value.ToString());
if (!matchWithPackage) {
continue;
}
//Matching the size
Stop Point List<string> sizeList = (List<string>)(row.Cells[7] as DataGridViewComboBoxCell).DataSource;
Doesn't reach this and beyond List<string> matchedList = sizeList.FindAll(stringToCheck => stringToCheck.Contains(numberPart));
if (matchedList.Count > 0) {
(row.Cells[7] as DataGridViewComboBoxCell).DataSource = matchedList;
}
}
So i fixt my own problem and i'm going to awnser my own question i case somebody comes across a similar problem.
if (sizeList != null) {
List<string> matchedList = sizeList.FindAll(stringToCheck => stringToCheck.Contains(numberPart));
if (matchedList.Count > 0)
{
(row.Cells[7] as DataGridViewComboBoxCell).DataSource = matchedList;
}
}
After adding the few last lines in an extra check that needed to be done I noticed that the code was being executed, but the matchedlist.count was always 0.
So what was happening is that the code after that was redundant as the matchList was 0 and the debugger just skipped jumping to these lines ( a bit confusing if you ask me ).
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 have some LINQ to Object Query Code:
List<ePayDocumentOperation> additionalDocuments = new List<ePayDocumentOperation>();
try
{
additionalDocuments = (from op in possibleClientDocuments
let senderAccountID = GetSenderAccountID(con, op)
where Filter.Wallets.Contains(senderAccountID)
select op).ToList();
}
catch (Exception ex)
{
// some catcher
}
possibleClientDocuments object contains about 3 000 records. Not so much but the query freeze and I don't get result. I don't get any execeptions. I try to select code to try catch block but I don't see any exceptions and at the same time I don't get result too.
How to check the problem of query and why I don't getting result?
Thanks!
P.S.
private static long GetSenderAccountID(LavaPayEntities Con, ePayDocumentOperation operation)
{
long result = default(long);
// Payment
if (operation.OperationPatternID == Chart.Operations.PS_Payment)
{
var ipnRequest = Con.eIPNRequests.FirstOrDefault(ir => ir.OperationID == operation.ID);
if (ipnRequest == null) return result;
if (ipnRequest.ClientAccountID != null && ipnRequest.ClientAccountID != 0) return (long)ipnRequest.ClientAccountID;
var clientAccount = Con.eAccounts.FirstOrDefault(a => a.Email.Email == ipnRequest.ClientEmail);
if (clientAccount != null)
{
result = clientAccount.ID;
}
else
{
var client = ipnRequest.Client;
if (client != null)
{
clientAccount = client.Accounts.FirstOrDefault();
if (clientAccount != null)
{
result = clientAccount.ID;
}
}
}
}
// Other Operations
else
{
result = operation.SenderAccountID.HasValue ? operation.SenderAccountID.Value : 0;
}
return result;
}
I have a problem that drives me nuts. I am using a generic List that throws an ArgumentOutOfRangeException whenever I try to assign its first (or last?) index to a variable. It's a pretty large pile of code, hence I'll try to extract only the relevant stuff. So here it is:
private string GetRuleByName(string name, List<string> rules)
{
if(rules != null)
{
List<string> todo = new List<string>();
todo.AddRange(rules);
while(rules.Count != 0)
{
string r = todo[0]; // <- Error 'ArgumentOutOfRangeException' here
todo.RemoveAt(0);
// ...
}
}
}
That's how I call the method:
void treeView_AfterSelect(object sender, TreeViewEventArgs e)
{
string currentRule = GetRuleByName(treeView.SelectedNode.FullPath, ruleCollection)
// the string list "ruleCollection" always contains
// strings and thus is never empty
}
Even though it's not a very detailed presentation of what's going on, as I had to cut off a piece of some complicated code, I really hope someone else might see what produces the error.
Big thanks in advance for at least having a look!
EDIT:
This is how the method looks like. I haven't altered anything, to show what's really inside it. I hope it makes sense for somebody:
private Rule GetRuleByNameOrId(string stName, List<Rule> rules)
{
if(rules != null)
{
string searchName = stName.ToLower().Trim();
string subName = "";
int slashPos = searchName.IndexOf('/');
if(slashPos != -1)
{
if(slashPos != searchName.Length)
subName = searchName.Substring(slashPos + 1);
searchName = searchName.Substring(0, slashPos);
}
List<Rule> todo = new List<Rule>();
todo.AddRange(rules);
while(todo.Count != 0)
{
Rule r = (Rule)todo[0];
todo.RemoveAt(0);
if(r.Name.ToLower() == searchName || r.Id.ToLower() == searchName)
{
if(subName != "")
{
Rule subRule = GetRuleByNameOrId(subName, r.Children);
if(subRule != null)
return subRule;
}
else
{
return r;
}
}
if(r.Children != null && r.Children.Count != 0)
todo.AddRange(r.Children);
}//end while
}//end if(rules != null)
return null;
}
Sounds like you want the following:
private string GetRuleByName(string name, List<string> rules)
{
if(rules != null)
{
List<string> todo = new List<string>();
todo.AddRange(rules);
while(todo.Count != 0) // <-- Minor mod here
{
string r = todo[0];
todo.RemoveAt(0);
// ...
}
}
}
Otherwise you are infinitely looping on rules.Count as the size of rules is not changing
This works fine until todo is empty, then you get the exception because element 0 no longer exists as you've removed them all!
Are you sure you don't want this instead:
while(rules.Count != 0)
{
string r = rules[0]; // <- Error 'ArgumentOutOfRangeException' here
rules.RemoveAt(0);
?
The way you've written it now, you've got a loop that would actually be infinite, except that you eventually remove all the elements from the todo list, at which point you throw the exception (because in an empty list even the 0-th element doesn't exist).
I have banners on a site. When banner showed then I increment field in DB.
This is code:
public Banner GetBanner(CategoryBanner type)
{
var banners = Database.Banners.Where(b => b.IsPublish.Value &&
b.Category.Value == (int)type &&
b.PeriodShowCountAlready < b.PeriodShowCount || b.IsPublish.Value && b.Category.Value == (int)type &&
b.ShowNext < DateTime.Now);
var count = banners.Count();
if (count != 0)
{
var skip = new Random().Next(banners.Count() - 1);
Banner banner = banners.Skip(skip).FirstOrDefault();
if (banner != null)
{
UpdatePeriodShowCountAlready(banner); // problem is inside this method
if (banner.ShowStart == null)
UpdateShowStartAndEnd(banner);
return banner;
}
}
return null;
}
private void UpdatePeriodShowCountAlready(Banner banner)
{
try
{
if (banner != null)
{
banner.PeriodShowCountAlready++;
if (banner.PeriodShowCountAlready >= banner.PeriodShowCount && banner.ShowNext < DateTime.Now)
{
banner.PeriodShowCountAlready = 0;
banner.ShowStart = null;
banner.ShowNext = null;
}
Database.SubmitChanges();
}
}
catch (Exception ex)
{
ErrorLog.GetDefault(null).Log(new Error(ex));
}
}
And, I get the following error:
System.Data.Linq.ChangeConflictException
Row not found or changed.
This error is simple to reproduce:hold down the F5 is enough for a few seconds.
I understand why this error is occur, but how to rewrite my code properly?
Thanks.