Subtract from line and move to next - c#

I want to subtract from the line with oldest date and where counter > 0, and when it reaches 0 I want to subtract from the next oldest line with the same itemId and do some other updates on other tables.
My question is if there is a better way to do it and if my code has no bad efficiency. If it breaks down, will the code do a rollback? Do I need try/catch? Please if any suggestions, provide with some code.
Here is my code:
public static int insertOrder(Order order)
{
using (var db = new AWarehouseDataClassesDataContext())
{
using (TransactionScope ts = new TransactionScope())
{
tblOrder row = generateOrderToBeInserted(order);
db.tblOrders.InsertOnSubmit(row);
db.SubmitChanges();
order.orderId = row.OrderId;
foreach(var x in order.insertList)
{
int qt = x.qty;
while (qt > 0)
{
var line = db.tblInsertLines.First(r => r.ItemId == x.itemId && r.Counter > 0);
int c = line.Counter;
for (int a = c; a > 0 && qt > 0; a--)
{
line.Counter = line.Counter - 1;
qt--;
}
db.SubmitChanges();
}
tblOrderLine orderLine = generateOrderLine(order, x);
db.tblOrderLines.InsertOnSubmit(orderLine);
db.SubmitChanges();
var item = db.tblItems.Single(i => i.ItemId == x.itemId);
item.Qty = item.Qty - x.qty;
item.LastUpdate = order.orderDate;
item.UpdatedBy = order.user;
db.SubmitChanges();
}
ts.Complete();
return order.orderId;
}
}
}

Related

db.SaveChanges in ForEach causes 'New transaction is not allowed because there are other threads running in the session'

I have an excel file with about 21000 rows . I imported it into a temp Table in my database.
Now I want to do some conversions on my data and then put them into my main table.
When I do SaveChanges() inside a foreach I got the following error:
Microsoft.Data.SqlClient.SqlException: 'New transaction is not allowed because there are other threads running in the session
When I use it after the foreach no error occurs and the table has just 4 records inserted instead of all 21000 records that I expected.
public ActionResult FeedTempdataToMainDB()
{
var L = new Leave();
// var leaves = new List<Leave>();
foreach (var item in db.TempLeaves)
{
L.Pcode = Int32.Parse(item.Cod);
var z = int.Parse(item.LT) - 1;
if (z == 0) L.LT = Leave.LeaveType.Saati;
else L.LT = Leave.LeaveType.Roozane;
var o = int.Parse(item.DLT) - 1;
if (o == 0) L.DLT = Leave.DLType.Estehghaghi;
if (o == 1) L.DLT = Leave.DLType.Estelaji;
else L.DLT = Leave.DLType.Bihoghoogh;
L.LeaveDayStart = item.LeaveDayStart.Old6digToMiladi();
L.LeaveDayEnd = item.LeaveDayEnd.Old6digToMiladi();
L.LeaveTimeStart = StringToHour(item.LeaveTimeStart);
L.LeaveTimeEnd = StringToHour(item.LeaveTimeEnd);
L.LeaveDays = int.Parse(item.LeaveDays);
L.LeaveMinuts = SaatiLengh(item.LeaveMinuts);
L.RegDate = StringToHour(item.RegTime);
L.RegDate = item.RegDate.Old6digToMiladi().Date;
L.RegistrarCode = Int32.Parse(item.RegistrarCode);
L.HijriYear = L.LeaveDayStart.GetHijriYear();
var t = IsOk(item.RegTime);
if (L.DLT == 0 && t == false || L.LT == 0)
{
L.Calculate = false;
L.IsActive = false;
}
else { L.Calculate = true; L.IsActive = true; }
db.Leaves.Add(L);
db.SaveChangesAsync();
}
//db.SaveChanges();
return RedirectToAction("index");
You have a bug in your code. You declared and created L outside of the loop. Each time you add the same L , only with different data. In the end you have list of the same data that was created during the last foreach loop cicle.
try this:
foreach (var item in db.TempLeaves)
{
var z = int.Parse(item.LT) - 1;
var L = new Leave{
Pcode = Int32.Parse(item.Cod),
LeaveTimeStart = StringToHour(item.LeaveTimeStart),
LeaveTimeEnd = StringToHour(item.LeaveTimeEnd),
LeaveDays = int.Parse(item.LeaveDays),
LT = z == 0? Leave.LeaveType.Saati : Leave.LeaveType.Roozane
};
db.Leaves.Add(L);
}
or this
var leaves= new List<Leave>();
foreach (var item in db.TempLeaves)
{
var z = int.Parse(item.LT) - 1;
var L = new Leave{
Pcode = Int32.Parse(item.Cod),
LeaveTimeStart = StringToHour(item.LeaveTimeStart),
LeaveTimeEnd = StringToHour(item.LeaveTimeEnd),
LeaveDays = int.Parse(item.LeaveDays),
LT = z == 0? Leave.LeaveType.Saati : Leave.LeaveType.Roozane
};
leaves.Add(L);
}
if(leaves.Count>0)
{
db.Leaves.AddRange(leaves);
db.SaveChanges();
}
if you want to use async save you have to make async action at first.
The raison every time that foreach execute the savechnages there is a thread that your not note controlling. Since entity framework is managing the savechanges function. You have to execute your savechnages after the foreach or use async function.
here an example for the async:
private static async Task<Student> GetStudent()
{
Student student = null;
using (var context = new SchoolDBEntities())
{
Console.WriteLine("Start GetStudent...");
student = await (context.Students.Where(s => s.StudentID == 1).FirstOrDefaultAsync<Student>());
Console.WriteLine("Finished GetStudent...");
}
return student;
}
*This Code finally worked:
public ActionResult FeedTempdataToMainDB()
{
var leaves = new List<Leave>();
foreach (var item in db.TempLeaves)
{
var L = new Leave();
L.Pcode = Int32.Parse(item.Cod);
var z = int.Parse(item.LT) - 1;
if (z == 0) L.LT = Leave.LeaveType.Saati;
else L.LT = Leave.LeaveType.Roozane;
var o = int.Parse(item.DLT);
if (o == 0) L.DLT = Leave.DLType.Estehghaghi;
if (o == 1) L.DLT = Leave.DLType.Estelaji;
else L.DLT = Leave.DLType.Bihoghoogh;
L.LeaveDayStart = item.LeaveDayStart.Old6digToMiladi();
L.LeaveDayEnd = item.LeaveDayEnd.Old6digToMiladi();
L.LeaveTimeStart = StringToHour(item.LeaveTimeStart);
L.LeaveTimeEnd = StringToHour(item.LeaveTimeEnd);
L.LeaveDays = int.Parse(item.LeaveDays);
L.LeaveMinuts = SaatiLengh(item.LeaveMinuts);
L.RegDate = StringToHour(item.RegTime);
L.RegDate = item.RegDate.Old6digToMiladi().Date;
L.RegistrarCode = Int32.Parse(item.RegistrarCode);
L.HijriYear = L.LeaveDayStart.GetHijriYear();
var t = IsOk(item.RegTime);
if (L.DLT == 0 && t == false || L.LT == 0 && t == false)
{
L.Calculate = false;
L.IsActive = false;
}
else { L.Calculate = true; L.IsActive = true; }
leaves.Add(L);
}
if (leaves.Count > 0)
{
db.Leaves.AddRange(leaves);
db.SaveChanges();
}
return RedirectToAction("index");
}

I have SQLite db with 3 rows, when i delete data from row, data will lost but row will still, how can i delete that blank row?

I have xamarin app and I am using SQLite for saving data, if I have 3 rows and delete second row, then data will delete but row will be blank and its still here and problem is, that I need to load one column from every row. I am using for cycle and count to set maximum for it. But count says I have two rows so for cycle load just first and not second because second is on third line and second is blank.
I need to delete blank rows or to discover another solution how to load it. How can i delete blank DB?
Counting algorythm:
public int GetNumberPhotos()
{
var db = new SQLiteConnection(_dbPath);
db.CreateTable<Airplane>();
int count = 0;
if (db.Table<Airplane>().FirstOrDefault(l => l.Id == 1) != null)
count = db.Table<Airplane>().Count();
return count;
}
loading:
public int BetterUniReg()
{
int numberPhotos = GetNumberPhotos();
string[] allReg = new string[numberPhotos];
string[] uniReg = new string[numberPhotos];
int uniRegCnt = 0;
var db = new SQLiteConnection(_dbPath);
//db fill
for (int i = 0; i <= numberPhotos; i++)
{
if (db.Table<Airplane>().FirstOrDefault(b => b.Id == i) != null)
{
var rowData = db.Table<Airplane>().FirstOrDefault(c => c.Id == i);
i--;
allReg[i] = rowData.Registration;
i++;
}
}
Here is delete code:
private async void deleteButton_Clicked(object sender, EventArgs e)
{
var action = await DisplayAlert("Delete", "Do you want delete picture?", "Cancel", "Delete");
if (action)
{
}
else
{
var butto = sender as Button;
var frame = butto.Parent.Parent.Parent.Parent as Frame;
await frame.FadeTo(0, 600);
var button = (Button)sender;
var plane = (Airplane)button.BindingContext;
var db = new SQLiteConnection(_dbPath);
db.Delete<Airplane>(plane.Id);
Refresh();
}
}
I have done walkaround by adding if its last row and its null then do one more cycle.
Here is code:
for (int i = 1; i <= numberPhotos; i++)
{
if (db.Table<Airplane>().FirstOrDefault(c => c.Id == i) != null)
{
var rowData = db.Table<Airplane>().FirstOrDefault(c => c.Id == i);
allReg[regnumber] = rowData.Registration;
regnumber++;
}
if (db.Table<Airplane>().FirstOrDefault(c => c.Id == i) == null && i == numberPhotos)
{
numberPhotos = numberPhotos + 1;
}
}

Search DataGridView for duplicates

I have this code to find duplicate values in DataGridView and mark them with different colors.
var rows = dataGridView1.Rows.OfType<DataGridViewRow>().Reverse().Skip(1);
var dupRos = rows.GroupBy(r => r.Cells["Date"].Value.ToString()).Where(g =>
g.Count() > 1).SelectMany(r => r.ToList());
foreach (var r in dupRos)
{
r.DefaultCellStyle.BackColor = Color.Pink;
}
foreach (var r in rows.Except(dupRos))
{
r.DefaultCellStyle.BackColor = Color.Cyan;
}
The code works fine.
I have changed the code so it will write in the second column the word Unique or Duplicate and a counter number for the duplicate cells.
int counter = 1;
var rows = dataGridView1.Rows.OfType<DataGridViewRow>().Reverse().Skip(1);
//ignore the last empty line
var dupRos = rows.GroupBy(r => r.Cells["Date"].Value.ToString()).Where(g =>
g.Count() > 1).SelectMany(r => r.ToList());
foreach (var r in dupRos)
{
r.DefaultCellStyle.BackColor = Color.Pink;
r.Cells["Time"].Value = "Dup" + counter;
counter++;
}
foreach (var r in rows.Except(dupRos))
{
r.DefaultCellStyle.BackColor = Color.Cyan;
r.Cells["Time"].Value = "Unick";
}
My problem is that the counter continues to count for all the duplicate groups and not reset itself every time its start with a different group of duplicate values.
How can I fix it?
Please try this one. If it works you can replace string type for lastDupRowDate with actual date type.
int counter = 1;
var rows = dataGridView1.Rows.OfType<DataGridViewRow>().Reverse().Skip(1);
//ignore the last empty line
var dupRos = rows.GroupBy(r => r.Cells["Date"].Value.ToString()).Where(g =>
g.Count() > 1).SelectMany(r => r.ToList());
string lastDupRowDate = null;
foreach (var r in dupRos)
{
r.DefaultCellStyle.BackColor = Color.Pink;
counter = lastDupRowDate == r.Cells["Date"].Value.ToString() ? count + 1 : 1;
lastDupRowDate = r.Cells["Date"].Value.ToString();
r.Cells["Time"].Value = "Dup" + counter;
}
foreach (var r in rows.Except(dupRos))
{
r.DefaultCellStyle.BackColor = Color.Cyan;
r.Cells["Time"].Value = "Unick";
}

How can I simplify my nested for loops

I want to make my code short and simple using linq.
I have a list that contains leaveDates and every leaveDates contain number of leavelist.
Something like this:
{ leaves_date = {07-05-2018 18:30:00}, LeaveList = {System.Collections.Generic.List<TimeClock.Model.LeaveManagementModel>} }
{ leaves_date = {08-05-2018 18:30:00}, LeaveList = {System.Collections.Generic.List<TimeClock.Model.LeaveManagementModel>} }
{ leaves_date = {21-05-2018 18:30:00}, LeaveList = {System.Collections.Generic.List<TimeClock.Model.LeaveManagementModel>} }
leaveList contains UserId, LeaveType, Status fields
Now all I want is to count the number of leavedates per user who's status is 1 and leave type != 3
I have already tried using a for loop, but I want to do it with linq.
Here is my code with the for loop:
for (var i = 0; i < leavesresult.Count; i++) {
for (var a = 0; a < leavesresult[i].LeaveList.Count; a++) {
if (leavesresult[i].LeaveList[a].status == 1.ToString() && leavesresult[i].LeaveList[a].leave_type != 3.ToString()) {
var compair1 = leavesresult[i].LeaveList[a].user_id;
var compair2 = attendancelist.Any(z = >z.user_id == leavesresult[i].LeaveList[a].user_id);
if (attendancelist.Any(z = >z.user_id == leavesresult[i].LeaveList[a].user_id)) {
int index = attendancelist.FindIndex(y = >y.user_id == leavesresult[i].LeaveList[a].user_id);
if (leavesresult[i].LeaveList[a].check_halfday == 1) {
attendancelist[index].days = attendancelist[index].days
}
else {
attendancelist[index].days = attendancelist[index].days + 1;
}
}
else {
if (leavesresult[i].LeaveList[a].check_halfday == 1) {
attendancelist.Add(new AttendanceModel {
user_id = leavesresult[i].LeaveList[a].user_id,
days = 0.5
});
}
else {
attendancelist.Add(new AttendanceModel {
user_id = leavesresult[i].LeaveList[a].user_id,
days = 1
});
}
}
}
}
}
I could give you the query and you would learn nothing. Instead learn how to do this transformation yourself. The trick is to not try to do it all at once. Rather, we make a series of small, obviously correct transformations each one of which gets us closer to our goal.
Start by rewriting the inner for loop as a foreach:
for (var i = 0; i < leavesresult.Count; i++)
{
foreach (var leavelist in leavesresult[i].LeaveList)
{
if (leavelist.status == 1.ToString() && leavelist.leave_type != 3.ToString())
{
var compair1 = leavelist.user_id;
var compair2 = attendancelist.Any(z => z.user_id == leavelist.user_id);
if (attendancelist.Any(z => z.user_id == leavelist.user_id))
{
int index = attendancelist.FindIndex(y => y.user_id == leavelist.user_id);
if (leavelist.check_halfday == 1)
attendancelist[index].days = attendancelist[index].days
else
attendancelist[index].days = attendancelist[index].days + 1;
}
else
{
if (leavelist.check_halfday == 1)
attendancelist.Add(
new AttendanceModel {user_id = leavelist.user_id, days = 0.5});
else
attendancelist.Add(
new AttendanceModel {user_id = leavelist.user_id, days = 1});
}
}
}
}
Already your code is about 100 times easier to read with that change.
Now we notice a few things:
if (leavelist.status == 1.ToString() && leavelist.leave_type != 3.ToString())
That is a crazy way to write this check. Rewrite it into a sensible check.
var compair1 = leavelist.user_id;
var compair2 = attendancelist.Any(z => z.user_id == leavelist.user_id);
Neither of these variables are ever read, and their initializers are useless. Delete the second one. Rename the first one to user_id.
if (leavelist.check_halfday == 1)
attendancelist[index].days = attendancelist[index].days
else
attendancelist[index].days = attendancelist[index].days + 1;
The consequence makes no sense. Rewrite this.
OK, we now have
for (var i = 0; i < leavesresult.Count; i++)
{
foreach (var leavelist in leavesresult[i].LeaveList)
{
if (leavelist.status == "1" && leavelist.leave_type != "3")
{
var user_id= leavelist.user_id;
if (attendancelist.Any(z => z.user_id == leavelist.user_id))
{
int index = attendancelist.FindIndex(y => y.user_id == leavelist.user_id);
if (leavelist.check_halfday != 1)
attendancelist[index].days = attendancelist[index].days + 1;
}
else
{
if (leavelist.check_halfday == 1)
attendancelist.Add(
new AttendanceModel {user_id = leavelist.user_id, days = 0.5});
else
attendancelist.Add(
new AttendanceModel {user_id = leavelist.user_id, days = 1});
}
}
}
}
Use the helper variable throughout:
for (var i = 0; i < leavesresult.Count; i++)
{
foreach (var leavelist in leavesresult[i].LeaveList)
{
if (leavelist.status == "1" && leavelist.leave_type != "3")
{
var user_id = leavelist.user_id;
if (attendancelist.Any(z => z.user_id == user_id))
{
int index = attendancelist.FindIndex(y => y.user_id == user_id);
if (leavelist.check_halfday != 1)
attendancelist[index].days = attendancelist[index].days + 1;
}
else
{
if (leavelist.check_halfday == 1)
attendancelist.Add(
new AttendanceModel {user_id = user_id, days = 0.5});
else
attendancelist.Add(
new AttendanceModel {user_id = user_id, days = 1});
}
}
}
}
We realize that the Any and the FindIndex are doing the same thing. Eliminate one of them:
for (var i = 0; i < leavesresult.Count; i++)
{
foreach (var leavelist in leavesresult[i].LeaveList)
{
if (leavelist.status == "1" && leavelist.leave_type != "3")
{
var user_id = leavelist.user_id;
int index = attendancelist.FindIndex(y => y.user_id == user_id);
if (index != -1)
{
if (leavelist.check_halfday != 1)
attendancelist[index].days = attendancelist[index].days + 1;
}
else
{
if (leavelist.check_halfday == 1)
attendancelist.Add(
new AttendanceModel {user_id = user_id, days = 0.5});
else
attendancelist.Add(
new AttendanceModel {user_id = user_id, days = 1});
}
}
}
}
We notice that we are duplicating code in the final if-else. The only difference is days:
for (var i = 0; i < leavesresult.Count; i++)
{
foreach (var leavelist in leavesresult[i].LeaveList)
{
if (leavelist.status == "1" && leavelist.leave_type != "3")
{
var user_id = leavelist.user_id;
int index = attendancelist.FindIndex(y => y.user_id == user_id);
if (index != -1)
{
if (leavelist.check_halfday != 1)
attendancelist[index].days = attendancelist[index].days + 1;
}
else
{
double days = leavelist.check_halfday == 1 ? 0.5 : 1;
attendancelist.Add(new AttendanceModel {user_id = user_id, days = days});
}
}
}
}
Now your code is 1000x easier to read than it was before. Keep going! Rewrite the outer loop as a foreach:
foreach (var lr in leavesresult)
{
foreach (var leavelist in lr.LeaveList)
{
if (leavelist.status == "1" && leavelist.leave_type != "3")
{
var user_id = leavelist.user_id;
int index = attendancelist.FindIndex(y => y.user_id == user_id);
if (index != -1)
{
if (leavelist.check_halfday != 1)
attendancelist[index].days = attendancelist[index].days + 1;
}
else
{
double days = leavelist.check_halfday == 1 ? 0.5 : 1;
attendancelist.Add(new AttendanceModel {user_id = user_id, days = days});
}
}
}
}
And we notice a couple more things: we can put check_halfday into an explanatory variable, and eliminate days. And we can simplify the increment:
foreach (var lr in leavesresult)
{
foreach (var leavelist in lr.LeaveList)
{
if (leavelist.status == "1" && leavelist.leave_type != "3")
{
var user_id = leavelist.user_id;
int index = attendancelist.FindIndex(y => y.user_id == user_id);
bool halfday= leavelist.check_halfday == 1;
if (index != -1)
{
if (!halfday)
attendancelist[index].days += 1;
}
else
{
attendancelist.Add(new AttendanceModel {user_id = user_id, days = halfday ? 0.5 : 1});
}
}
}
}
Now we begin transforming this to a query. The key thing to understand is that mutations must not go in queries. Mutations only go into loops, never queries. Queries ask questions, they do not perform mutations.
You have a mutation of attendancelist, so that's got to stay in a loop. But we can move all the query logic out of the loop by recognizing that the nested foreach with a test inside the inner loop is equivalent to:
var query = from lr in leaveresult
from ll in lr.LeaveList
where ll.status == "1"
where ll.leave_type != "3"
select ll;
Excellent. Now we can use that in our foreach:
foreach(var ll in query)
{
var index = attendancelist.FindIndex(y => y.user_id == ll.user_id);
var halfday = ll.check_halfday == 1;
if (index != -1)
{
if (!halfday)
attendancelist[index].days += 1;
}
else
{
attendancelist.Add(
new AttendanceModel {user_id = ll.user_id, days = halfday? 0.5 : 1 });
}
}
Now that we have the loop in this extremely simple form, we notice that we can re-order the if to simplify it:
foreach(var ll in query)
{
var index = attendancelist.FindIndex(y => y.user_id == ll.user_id);
var halfday = ll.check_halfday == 1;
if (index == -1)
attendancelist.Add(
new AttendanceModel {user_id = ll.user_id, days = halfday? 0.5 : 1 });
else if (!halfday)
attendancelist[index].days += 1;
}
And we're done. All the computation is done by the query, all the mutations are done by the foreach, as it should be. And your loop body is now a single, extremely clear conditional statement.
This answer is to answer your question, which was how to convert an existing bunch of hard-to-read loops into an easy-to-read query. But it would be better still to write a query that clearly expressed the business logic you're trying to implement, and I don't know what that is. Create your LINQ queries so that they make it easy to understand what is happening at the business level.
In this case what I suspect you are doing is maintaining a per-user count of days, to be updated based on the leave lists. So let's write that!
// dict[user_id] is the accumulated leave.
var dict = new Dictionary<int, double>();
var query = from lr in leaveresult
from ll in lr.LeaveList
where ll.status == "1"
where ll.leave_type != "3"
select ll;
foreach(var ll in query)
{
var halfday = ll.check_halfday == 1;
if (!dict.ContainsKey(ll.user_id))
dict[ll.user_id] = halfday? 0.5 : 1;
else if (!halfday)
dict[ll.user_id] = dict[ll.user_id] + 1;
}
That seems like a nicer way to represent this than a list that you are constantly having to search.
Once we are at this point we can then recognize that what you are really doing is computing a per-user sum! The answer by JamieC shows that you can use the Aggregate helper method to compute a per-user sum.
But again, this is based on the assumption that you have built this whole mechanism to compute that sum. Again: design your code so that it clearly implements the business process in the jargon of that process. If what you're doing is computing that sum, boy, does that ever not show up in your original code. Strive to make it clearer what your code is doing.
This is basically 1 line of linq with a groupby, I'm not sure ill get it spot on with 1 try, but something along the lines of:
var attendancelist = leavesresult
.SelectMany(a => a.LeaveList) // flatten the list
.Where(a => a.status == "1" && a.type != "3") // pick the right items
.GroupBy(a => a.user_id) // group by users
.Select(g => new AttendanceModel(){ // project the model
user_id = g.Key,
days = g.Aggregate(0, (a,b) => a + (b.check_halfday == 1 ? 0.5 : 1))
})
.ToList();
Let me know any issues, and i'll try to fix as necessary.
edit1: Assuming AttendanceModel.days is an int you need to decide what to do as it is calculating a float.
Perhaps something like:
...
days = (int)Math.Ceiling(g.Aggregate(0, (a,b) => a + (b.check_halfday == 1 ? 0.5 : 1)))
...
Not a linq version but used foreach to simplify and make it more readable
var userLeaves = new Dictionary<int, double>();
foreach( var lr in leavesresult)
{
foreach (var leave in lr.LeaveList)
{
if (leave.Status == "1" && leave.LeaveType != "3")
{
var leaveDay = leave.check_halfday ==1 ? 0.5 : 1;
if (userLeaves.ContainsKey(leave.UserID))
userLeaves[leave.UserID] = userLeaves[leave.UserID] + leaveDay;
else
userLeaves.Add(leave.UserID, leaveDay);
}
}
}

how to check error conditions c#

I have group of conditions like
foreach
{
Condition a
condition b
}
So I am validating the values based on conditions.I am facing the problem: for example I have list of items like {1,2,3,4}. So I have a condition like if item 1 is fail then item 2,3,4 should be fail.
if item 2 is fail then item 3,4 should be fail and so on.
I am trying in below code.
foreach (SagaData item in lstPrm)
{
PriceDetail prevPrice = null;
PriceDetail currentPrice = null;
PriceDetail nextPrice = null;
bool bHasError = false;
int iPriceMasterId = 0;
int iPriceTypeId = 0;
string sMprCurrencyType = null;
string sPublisherCurrencyType = null;
int? iExpirationCalendarId = 0;
string sPRMMessage = string.Empty;
//a) If Change Indicator = C or A and Price = 0.00: Cannot change price value to zero.
if ((item.ChangeIndicator == 'C' || item.ChangeIndicator == 'A') && item.PostingPrice == 0)
{
bHasError = true;
sPRMMessage = "FAILURECannot change price value to zero";
}
//b) If Change Indicator = D and Price > 0.00: Invalid deactivation.
if ((item.ChangeIndicator == 'D') && (item.PostingPrice > 0) && (!bHasError))
{
bHasError = true;
sPRMMessage = "FAILUREInvalid deactivation";
}
so i have if condition a fail for item 1 then how should i keep maintain the error for next iteration.
Thanks for the help. if you want more info plz let me know.
You can go through your Collection with a simple for loop and use an ErrorArray:
bool[] bHasError = new bool[lstPrm.Count];
for (int i = 0; i < lstPrm.Count; i++)
{
...
bHasError[i] = true;
...
}
or you can define bHasError BEFORE the foreach if one error is enough for you to consider.

Categories