I am very new to xml and I am 95% done with my project for work, But when I try and do the last insert into a table it always duplicates my one value.
For example if I have transactions that needs to be inserted into the table and all the transactions are enclosed in a stage node. each stage has transactions.
Now when I insert stage 1 and it has 5 transactions it must take the id of stage 1 then when the insert is done it must then go to stage 2 and then insert 10 transactions.
My issue is when I insert the transactions it will only take the first stage id for all the trans inserts.
Here is my method how I am inserting the transactions
private List<XMLTransaction> GetAllTransForStage(List<XElement> allTransDetails, string path, int curStage, int nxtStage, int journeyEnd, int IDStage, int IDJourney, int IDDuty, int IDModule, string BoardingStages)
{
var end = nxtStage > 0 ? nxtStage : journeyEnd;
var doc = XDocument.Load(path);
List<XElement> StageRersult = GetTranseDetails(doc);
var transForCurrentStage = StageRersult.Where(s => Int32.Parse(s.Attribute("Position").Value.ToString()) > curStage && Int32.Parse(s.Attribute("Position").Value.ToString()) < end).ToList();
var transactions = new List<XMLTransaction>();
string TripBal = "";
string serial = "";
int IDTranse = 0;
int hexClassValue = 0;
int second = 0;
double seconds = 0;
TimeSpan t;
string formatedTime = "";
string date = "";
string issueDate = "";
string issueTime = "";
int stageno = 0;
int HexClasValue = 0;
int Fare = 0;
DataTable dt4 = new DataTable();
dt4.Columns.AddRange(new DataColumn[17] {
new DataColumn("id_Trans",typeof(int)),
new DataColumn("id_Stage", typeof(int)),
new DataColumn("id_Journey", typeof(int)),
new DataColumn("id_Duty",typeof(int)),
new DataColumn("id_Module",typeof(int)),
new DataColumn("int2_BoardingStageID",typeof(int)),
new DataColumn("int2_AlightingStageID",typeof(int)),
new DataColumn("int2_Class",typeof(int)),
new DataColumn("int4_Revenue",typeof(int)),
new DataColumn("int4_NonRevenue",typeof(int)),
new DataColumn("int2_TicketCount",typeof(int)),
new DataColumn("int2_PassCount",typeof(int)),
new DataColumn("int2_Transfers",typeof(int)),
new DataColumn("dat_TransDate",typeof(DateTime)),
new DataColumn("dat_TransTime",typeof(DateTime)),
new DataColumn("str_SerialNumber",typeof(string)),
new DataColumn("int4_TripBal",typeof(int))
});
int batchID = Convert.ToInt32(dtImportDateTime.ToString("yyyyMMdd"));
XDocument xdoc3 = XDocument.Load(path);
XDocument xdoc4 = XDocument.Load(path);
//////////////
string ConString = Settings.Default.ebusimporterConnectionString;
using (SqlConnection con = new SqlConnection(ConString))
{
string sql = "SELECT TOP 1 id_Trans FROM Trans ORDER BY 1 DESC";
SqlCommand cmd = new SqlCommand(sql, con);
try
{
con.Open();
object val = cmd.ExecuteScalar();
if (val != null)
{
IDTranse = Convert.ToInt32(val);
IDTranse = IDTranse + 1;
}
else if (val == null)
{
IDTranse = Convert.ToInt32(val);
IDTranse = IDTranse + 1;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
foreach (var tran in transForCurrentStage)
{
string Hex = tran.Element("TicketType").Value.ToString();
string stageN = tran.Element("StageNo").Value.ToString();
string Issuetime = tran.Element("IssueTime").Value.ToString();
string fares = tran.Element("Fare").Value.ToString();
string Issuedate = tran.Element("IssueDate").Value.ToString();
string TicketSerialNo = tran.Element("TicketSerialNo").Value.ToString();
// string TicketType = item.TicketType.ToString();
hexClassValue = int.Parse(Hex, NumberStyles.HexNumber);
stageno = Int32.Parse(stageN);
HexClasValue = hexClassValue;
second = Int32.Parse(Issuetime);
seconds = second;
t = TimeSpan.FromSeconds(seconds);
formatedTime = string.Format("{0:D2}:{1:D2}:{2:D2}",
t.Hours,
t.Minutes,
t.Seconds);
Fare = Int32.Parse(fares);
string dateLength = Issuedate;
if (dateLength.Length == 5 && HexClasValue == 17 || HexClasValue == 18 || HexClasValue == 33 || HexClasValue == 34 || HexClasValue == 65 || HexClasValue == 66)
{
date = "0" + Issuedate;
issueDate = DateTime.ParseExact(date, "dMMyy", null).ToString("yyyy-MM-d");
issueTime = issueDate + " " + formatedTime;
//Cash
if (HexClasValue == 17 || HexClasValue == 18 || HexClasValue == 33 || HexClasValue == 34 || HexClasValue == 65 || HexClasValue == 66)
{
dt4.Rows.Add(IDTranse, IDStage, IDJourney, IDDuty, IDModule, Convert.ToInt16(BoardingStages), Convert.ToInt16(stageN), Convert.ToInt16(HexClasValue), Fare, 0, 1, 0, 0, Convert.ToDateTime(issueDate), Convert.ToDateTime(issueTime), TicketSerialNo, Convert.ToInt32(0));
IDTranse++;
}
}
if (dateLength.Length == 6 && HexClasValue == 17 || HexClasValue == 18 || HexClasValue == 33 || HexClasValue == 34 || HexClasValue == 65 || HexClasValue == 66)
{
date = Issuedate;
issueDate = DateTime.ParseExact(date, "dMMyy", null).ToString("yyyy-MM-d");
issueTime = issueDate + " " + formatedTime;
//Cash
if (HexClasValue == 17 || HexClasValue == 18 || HexClasValue == 33 || HexClasValue == 34 || HexClasValue == 65 || HexClasValue == 66)
{
dt4.Rows.Add(IDTranse, IDStage, IDJourney, IDDuty, IDModule, Convert.ToInt16(BoardingStages), Convert.ToInt16(stageN), Convert.ToInt16(HexClasValue), Fare, 0, 1, 0, 0, Convert.ToDateTime(issueDate), Convert.ToDateTime(issueTime), TicketSerialNo, Convert.ToInt32(0));
IDTranse++;
}
}
}
string ConnString4 = Settings.Default.ebusimporterConnectionString;
if (HexClasValue == 11000)
{
}
else if (dt4.Rows.Count != 0)
{
using (SqlConnection con4 = new SqlConnection(ConnString4))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con4))
{
//revenuebal = 0
sqlBulkCopy.DestinationTableName = "dbo.Trans";
sqlBulkCopy.ColumnMappings.Add("id_Trans", "id_Trans");
sqlBulkCopy.ColumnMappings.Add("id_Stage", "id_Stage");
sqlBulkCopy.ColumnMappings.Add("id_Journey", "id_Journey");
sqlBulkCopy.ColumnMappings.Add("id_Duty", "id_Duty");
sqlBulkCopy.ColumnMappings.Add("id_Module", "id_Module");
sqlBulkCopy.ColumnMappings.Add("int2_BoardingStageID", "int2_BoardingStageID");
sqlBulkCopy.ColumnMappings.Add("int2_AlightingStageID", "int2_AlightingStageID");
sqlBulkCopy.ColumnMappings.Add("int2_Class", "int2_Class");
sqlBulkCopy.ColumnMappings.Add("int4_Revenue", "int4_Revenue");
sqlBulkCopy.ColumnMappings.Add("int4_NonRevenue", "int4_NonRevenue");
sqlBulkCopy.ColumnMappings.Add("int2_TicketCount", "int2_TicketCount");
sqlBulkCopy.ColumnMappings.Add("int2_PassCount", "int2_PassCount");
sqlBulkCopy.ColumnMappings.Add("int2_Transfers", "int2_Transfers");
sqlBulkCopy.ColumnMappings.Add("dat_TransDate", "dat_TransDate");
sqlBulkCopy.ColumnMappings.Add("dat_TransTime", "dat_TransTime");
sqlBulkCopy.ColumnMappings.Add("str_SerialNumber", "str_SerialNumber");
sqlBulkCopy.ColumnMappings.Add("int4_TripBal", "int4_TripBal");
con4.Open();
sqlBulkCopy.WriteToServer(dt4);
con4.Close();
}
}
}
LogwriterSuccess("ImportTrans", path);
return transactions;
}
Related
I pass a list of class to the Stimulsoft report inside the Bussines object.
I do not have any issues in the report file.
When I render report variables fill current and the list of columns repeated but the data don't display.
I don't have any errors in action!
The type of columns in class is Double and The type of fields of report is Float.
Action code :
public ActionResult PumpsStatusDailySummarySnapshot()
{
try
{
DateTime dateTimeStart = (DateTime)Session[_sessionList.PumpsStatusDailySummaryDateTimeStart];
DateTime dateTimeEnd = (DateTime)Session[_sessionList.PumpsStatusDailySummaryDateTimeEnd];
string time = Session[_sessionList.PumpsStatusDailySummaryTime] as string;
List<PumpsStatu> pumpsStatus = new List<PumpsStatu>();
int pumpCount;
using (SPMSEntities db = new SPMSEntities())
{
pumpCount = db.Packages.First().TotalPumpCount;
}
if (HttpContext.Cache[_cacheList.PumpsStatusDailySummary] == null)
{
using (SPMSEntities db = new SPMSEntities())
{
pumpsStatus = db.PumpsStatus.ToList();
HttpContext.Cache.Insert(_cacheList.PumpsStatusDailySummary, pumpsStatus, null, DateTime.Now.AddMinutes(15),
Cache.NoSlidingExpiration);
}
}
else
{
pumpsStatus = HttpContext.Cache[_cacheList.PumpsStatusDailySummary] as List<PumpsStatu>;
}
pumpsStatus = pumpsStatus.Where(x => x.Date >= dateTimeStart && x.Date <= dateTimeEnd).ToList();
//Collect report data
List<PumpsStatusDailySummaryClass> list = new List<PumpsStatusDailySummaryClass>();
List<PumpsStatusDailySummaryClass> reportList = new List<PumpsStatusDailySummaryClass>();
DateTime dateTimeTemp = dateTimeStart;
int preDay = -1;
int prePumpCountInWork = 1;
long currentId = 0;
long lastItemId = pumpsStatus.Last().Id;
int runTime = 0;
foreach (var item in pumpsStatus)
{
currentId = item.Id;
//تاریخ امروز ؟
int dayOfYear = item.Date.DayOfYear;
if (preDay == -1)
{
preDay = dayOfYear - 1;
}
//======================================================================
if (item.Frequency1 > 0)
{
PumpsStatusDailySummaryClass dailySummary = new PumpsStatusDailySummaryClass();
dailySummary.Current = item.Current1;
dailySummary.Efficiency = item.Efficiency1; //calc
dailySummary.Frequency = item.Frequency1;
//dailySummary.RunTime = 1;
dailySummary.Power = item.Power1;
dailySummary.Flow =
item.Frequency1 == 41 ? 65 :
item.Frequency1 == 42 ? 69 :
item.Frequency1 == 43 ? 74 :
item.Frequency1 == 44 ? 78 :
item.Frequency1 == 45 ? 85 :
item.Frequency1 == 46 ? 88 :
item.Frequency1 == 47 ? 92 :
item.Frequency1 == 48 ? 97 :
item.Frequency1 == 49 ? 101 : 50;
dailySummary.SolarDate = item.SolarDateTime;
dailySummary.Id = (int)item.Id;
list.Add(dailySummary);
}
//======================================================================
//Fill date
if (dayOfYear - preDay > 1 || dayOfYear < preDay || item.Id == lastItemId)
{
if (list.Count == 0)
{
continue;
}
PumpsStatusDailySummaryClass dailySummary = new PumpsStatusDailySummaryClass();
dailySummary.Current = Math.Round(list.Average(x => x.Current), 1);
dailySummary.Efficiency = Math.Round(list.Average(x => x.Efficiency), 1);
dailySummary.Frequency = Math.Round(list.Average(x => x.Frequency), 1);
dailySummary.Power = Math.Round(list.Average(x => x.Power), 1);
dailySummary.RunTime = list.Count / 60;
dailySummary.SolarDate = list.First().SolarDate;
dailySummary.Flow = Math.Round(list.Average(x => x.Flow), 1);
reportList.Add(dailySummary);
preDay = dayOfYear - 1;
list.Clear();
}
//dailySummary.Date =
dateTimeTemp = dateTimeTemp.AddDays(1);
}
string userFullName;
string PackageName;
using (SPMSEntities db = new SPMSEntities())
{
string userId = User.Identity.GetUserId();
Profile profile = db.Profiles.First(x => x.UserId == userId);
userFullName = profile.FirstName + " " + profile.LastName;
PackageName = db.Packages.First().Name;
}
StiReport report = new StiReport();
report.Load(Server.MapPath("~/Content/Reports/PumpsStatusDailySummary.mrt"));
report.Dictionary.Variables.Add(new StiVariable("Params", "TodayPersianDate", Convertor.ToPersianDate(DateTime.Now)));
report.Dictionary.Variables.Add(new StiVariable("Params", "StartPersianDate", Convertor.ToPersianDate(dateTimeStart)));
report.Dictionary.Variables.Add(new StiVariable("Params", "EndPersianDate", Convertor.ToPersianDate(dateTimeEnd)));
report.Dictionary.Variables.Add(new StiVariable("Params", "UserFullName", userFullName));
report.Dictionary.Variables.Add(new StiVariable("Params", "PackageName", PackageName));
report.RegBusinessObject("Data", reportList);
report.Compile();
return StiMvcViewer.GetReportSnapshotResult(report);
}
catch (Exception e)
{
HelperStoreSqlLog.WriteError(e, "PumpsStatusDailySummarySnapshot");
return View();
}
}
when looping through this datatable im unable to use the stored values in an if else statement i get the following error
The system cannot execute the specified program.
what i expected to happen is the if else block to check the toValue and go from there
ps - a continuation from a prior question looping thru datatable values
edit* added the full code block for clarity
string conString = "user id =user1; password =password;" + "data source = database.home.org";
OracleConnection con = new OracleConnection
{
ConnectionString = conString
};
con.Open();
var pullRecord = new OracleCommand("select * FROM email_records", con);
var dt= new DataTable();
var da = new OracleDataAdapter(pullRecord);
da.Fill(dt);
for (int x = 0; x < dt.Rows.Count; x++)
{
string toValue = (dt.Rows[x].ItemArray[0].ToString() + " ");
string ccValue = (dt.Rows[x].ItemArray[1].ToString() + " ");
string bodyValue = (dt.Rows[x].ItemArray[4].ToString() + " ");
if(toValue == "one" || toValue == "two" || toValue == "three")
{
Console.WriteLine(bodyValue);
}
else if (toValue == "four" || toValue == "five")
{
Console.WriteLine(bodyValue);
}
else if (toValue == "six" || toValue == "seven")
{
Console.WriteLine(bodyValue);
}
else if (toValue == "eight" || toValue == "nine")
{
Console.WriteLine(bodyValue);
}
else if (toValue == "ten" || toValue == "eleven")
{
Console.WriteLine(bodyValue);
}
else if (toValue == "twelve")
{
Console.WriteLine(bodyValue);
}
else if (toValue == "thirteen")
{
Console.WriteLine(bodyValue);
}
else
{
Console.WriteLine(bodyValue);
}
}
I have an array of phrases, like
"6 days, 7 months, 2 years"
and I need to go through the array to find the longest time and return that value. I've built something to insert into my application as a custom action but it crashes my application. It does not generate an error message.
bool booDayFound = false;
bool booMonthFound = false;
bool booYearFound = false;
string DayPrognosisLength = null;
string MonthPrognosisLength = null;
string YearPrognosisLength = null;
string strOutValue = null;
int LongestDayLength = 0;
int LongestMonthLength = 0;
int LongestYearLength = 0;
string[] arrDayLength = null;
string[] arrMonthLength = null;
string[] arrYearLength = null;
string strPrognosis = Extracted_Prognosis;
char charSeperator = ',';
String[] arrPrognosis = strPrognosis.Split(charSeperator);
foreach (var varPrognosis in arrPrognosis)
if (varPrognosis.Contains("Day") || varPrognosis.Contains("Days") || varPrognosis.Contains("day") || varPrognosis.Contains("days"))
{
booDayFound = true;
DayPrognosisLength = Regex.Replace(varPrognosis, "[^0-9]", "");
DayPrognosisLength = DayPrognosisLength + ",";
arrDayLength = DayPrognosisLength.Split(',');
LongestDayLength = arrDayLength.Max(c => int.Parse(c));
}
else
{
booDayFound = false;
DayPrognosisLength = "";
}
foreach (var varPrognosis in arrPrognosis)
if (varPrognosis.Contains("Months") || varPrognosis.Contains("Month") || varPrognosis.Contains("months") || varPrognosis.Contains("month"))
{
booMonthFound = true;
MonthPrognosisLength = Regex.Replace(varPrognosis, "[^0-9]", "");
MonthPrognosisLength = MonthPrognosisLength + ",";
arrMonthLength = MonthPrognosisLength.Split(',');
LongestMonthLength = arrMonthLength.Max(c => int.Parse(c));
}
else
{
booMonthFound = false;
MonthPrognosisLength = "";
}
foreach (var varPrognosis in arrPrognosis)
if (varPrognosis.Contains("Year") || varPrognosis.Contains("Years") || varPrognosis.Contains("year") || varPrognosis.Contains("years"))
{
booYearFound = true;
YearPrognosisLength = Regex.Replace(varPrognosis, "[^0-9]", "");
YearPrognosisLength = YearPrognosisLength + ",";
arrYearLength = YearPrognosisLength.Split(',');
LongestYearLength = arrYearLength.Max(c => int.Parse(c));
}
else
{
booYearFound = false;
YearPrognosisLength = "";
}
if (booYearFound == true)
{
strOutValue = "Year:" + LongestYearLength.ToString();
localsmartobj.DCONavSetValue(ExtractedPrognosisLocation, strOutValue);
AdmiralLog("Longest prognosis length is " + LongestYearLength.ToString() + "Years(s)");
}
else if (booMonthFound == true)
{
strOutValue = "Month:" + LongestMonthLength.ToString();
localsmartobj.DCONavSetValue(ExtractedPrognosisLocation, strOutValue);
AdmiralLog("Longest prognosis length is " + LongestMonthLength.ToString() + "Month(s)");
}
else if (booDayFound == true)
{
strOutValue = "Day:" + LongestDayLength.ToString();
localsmartobj.DCONavSetValue(ExtractedPrognosisLocation, strOutValue);
AdmiralLog("Longest prognosis length is " + LongestDayLength.ToString() + "Day(s)");
}
return true;
}
catch (Exception ex)
{
AdmiralLog(ex.Message);
return false;
}
}
I've trimmed some Datacap specific functions and I know that my code is not the cleanest but I would like to know what am I missing here?
First, we have to come to terms: let's assume that
1 month == 30 days
1 year == 365 days
Then we can implement Duration function: given a string return duration in days:
Func<string, string, int> DurationTerm = (src, mask) => Regex
.Matches(
src,
$#"(?<number>[0-9]+)\s*{mask.TrimEnd('s', 'S')}s?",
RegexOptions.IgnoreCase)
.Cast<Match>()
.Select(match => int.Parse(match.Groups["number"].Value))
.DefaultIfEmpty()
.Sum();
//TODO: I've assumed 1 Month == 30 days, 1 Year == 365 days
// Correct the logic if required
Func<string, int> Duration = (src) =>
DurationTerm(src, "day") +
// DurationTerm(src, "week") * 7 + //TODO: Add more terms if you want
DurationTerm(src, "month") * 30 +
DurationTerm(src, "year") * 365;
Now we are ready to find out the longest time:
using System.Linq;
...
string[] arrPrognosis = ...
int LongestDayLength = arrPrognosis
.Max(item => Duration(item));
I have Task.Factory.StartNew in C# code with args argument. I am not quite understand what value will arg be. So what value will args be and how the value is determined?
int count = table.Rows.Count;
Dictionary<int, string> expDic = new Dictionary<int, string>();
List<Task> taskList = new List<Task>();
for (int f = 0; f < count; f++)
{
DataRow tempformula = table.Rows[f];
string formulaSymbol = Convert.ToString(tempformula[Common.Systems.Sustainability.Constants.IndicatorFormula.Symbol]);
var t = Task.Factory.StartNew(new Action<object>((args) => {
int i = (int)args;
_sem.Wait();
StringBuilder expression = new StringBuilder(1024);
DataRow formula = table.Rows[i];
int indID = Convert.ToInt32(formula[Common.Systems.Sustainability.Constants.IndicatorFormula.IndicatorID]);
int sequence = Convert.ToInt32(formula[Common.Systems.Sustainability.Constants.IndicatorFormula.Sequence]);
int? referenceIndID = Common.Util.TryToConvertToInt32(formula, Common.Systems.Sustainability.Constants.IndicatorFormula.ReferenceIndicatorID);
decimal? val = Common.Util.TryToConvertToDecimal(formula, Common.Systems.Sustainability.Constants.IndicatorFormula.Value);
string symbol = Convert.ToString(formula[Common.Systems.Sustainability.Constants.IndicatorFormula.Symbol]);
string formulaOutputUnit = Convert.ToString(formula[Common.Systems.Sustainability.Constants.Indicator.Unit]);
if (!string.IsNullOrWhiteSpace(callerAcceptedUnit)) // added by HC on 2016-05-27
{
formulaOutputUnit = callerAcceptedUnit;
}
if (referenceIndID == null)
{
if (val == null)
{
DataSet indicator = GetIndicatorByIDFromCache(companyID, indID); // added by HC on 2017-05-12, for performance tuning.
//using (DataSet indicator = indicatorMgr.GetIndicatorByID(companyID, indID))
{
DataRow dr = indicator.Tables[0].Rows[0];
int indicatorType = Convert.ToInt32(dr[Common.Systems.Sustainability.Constants.Indicator.IndicatorType]);
if (indicatorType == (int)Common.Systems.Sustainability.Constants.IndicatorTypes.Currency
|| indicatorType == (int)Common.Systems.Sustainability.Constants.IndicatorTypes.Numeric)
{
decimal? total = SumTotal(companyID, indID, indicatorType, fromDate, toDate, formulaOutputUnit, callerIndicatorID, breakToMonthly, specifiedLocations, approvalStatus
, usageDataSet, interval
, indicatorIDsChain
, allowNull
);
expression.Append(total.ToString());
}
else if (symbol == "+"
|| symbol == "-"
|| symbol == "*"
|| symbol == "/")
{
expression.Append(symbol);
}
}
}
else
{
expression.Append(val.ToString());
}
}
else
{
string exp = GetExpression(companyID, fromDate, toDate, referenceIndID.Value.ToString(), indID.ToString(), formulaOutputUnit, breakToMonthly, specifiedLocations, approvalStatus
, usageDataSet, interval
, indicatorIDsChain
);
//expression.Append(exp);
using (DataTable dt = new DataTable())
{
// fault tolerance, for in-case users assigned symbol in the last line of formula
if (exp.EndsWith("+")
|| exp.EndsWith("-")
|| exp.EndsWith("*")
|| exp.EndsWith("/"))
{
exp = exp.Substring(0, exp.Length - 1);
}
object result = dt.Compute(exp, "");
expression.Append(result);
}
} // end if (referenceIndID == null)...
if ("IF".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| "THEN".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| "ELSE IF".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| "ELSE".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| ">".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| ">=".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| "=".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| "<=".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| "<".Equals(symbol, StringComparison.OrdinalIgnoreCase)
)
{
//--------------------------------------------------------
// Begin, added by HC on 2016-12-14
// as requested by CQS users, add "IF" statement for GRI indicators
string exp = HandleIFCondition(table, i, companyID, fromDate, toDate, indicatorIDs, callerIndicatorID, callerAcceptedUnit, breakToMonthly, specifiedLocations, approvalStatus, usageDataSet, interval, indicatorIDsChain);
expression.Append(exp);
// End, added by HC on 2016-12-14
//--------------------------------------------------------
// Find End if, added by Alex Poon on 20190306
int ifIndex = i;
for (var j = ifIndex; j < count; j++)
{
string endIfSymbol = Convert.ToString(table.Rows[j][Common.Systems.Sustainability.Constants.IndicatorFormula.Symbol]);
if ("END IF".Equals(endIfSymbol, StringComparison.OrdinalIgnoreCase))
{
i = j;
break;
}
}
}
else
{
if (!string.IsNullOrWhiteSpace(symbol)
&& expression.Length > 0 // added by HC on 2016-06-24
)
{
if (i + 1 >= count && symbol != ")")
{
// ignore the symbol
}
else if (expression.ToString() != symbol)
{
expression.Append(symbol);
}
}
else if (expression.Length == 0 && symbol == "(")
{
expression.Append(symbol);
}
if (symbol == "days")
{
// added by HC on 2017-01-23, a new requirements for calculating average values by days.
if (fromDate != null && toDate != null)
{
int days = toDate.Value.Subtract(fromDate.Value).Days + 1;
expression.Append(days);
}
else
{
expression.Append(1);
}
}
} // end if ("IF".Equals(symbol, StringComparison.OrdinalIgnoreCase)...
if (expDic != null && expression != null)
{
expDic.Add(i, expression.ToString());
}
_sem.Release();
}), f);
taskList.Add(t);
if ("IF".Equals(formulaSymbol, StringComparison.OrdinalIgnoreCase))
{
for (var j = f; j < count; j++)
{
string endIfSymbol = Convert.ToString(table.Rows[j][Common.Systems.Sustainability.Constants.IndicatorFormula.Symbol]);
if ("END IF".Equals(endIfSymbol, StringComparison.OrdinalIgnoreCase))
{
f = j;
break;
}
}
}
}
Task.WaitAll(taskList.ToArray());
List<int> keys = expDic.Keys.ToList();
keys.Sort();
string finalExpression = "";
foreach (var key in keys)
{
finalExpression += expDic[key];
}
return finalExpression;
}
args in your case is data that will be passed to a delegate specified by Action<object> parameter.
See docs.
When using overload of StartNew with Action<object>, you need to supply next argument of type object, which will be used in passed delegate.
Task.Factory.StartNew((o) => {/* 1 will be used here */}, 1, token, options, scheduler);
MSDN
The args argument (referred to as "state" in the documentation) is a parameter you need to specify when you call to Task.Factory.StartNew.
state (Object): An object containing data to be used by the action delegate.
Sample:
object param = somevalue;
Task.Factory.StartNew( (arg) =>
{ /* get the arg value here.*/
}, param);
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);
}
}
}