public LogisticMap(double mu, double r0, double rmax, double dr) { mapData.ChartType = SeriesChartType.Point ; mapData.MarkerSize = 1; mapData.MarkerColor = Color.Black; int numberOfThreadsInMap =1 ; List<double> activeThreadValues; double eps = .005; for(double r = r0; r < rmax; r+= dr ){ activeThreadValues = new List<double>(); Func<double, double> log = i => r * i * (1 - Math.Pow(i, mu)); for (int i = 150; i < 260; i++) { var A = new Sequence(log, .2).GetElementAt(i); if (A > double.MaxValue || A < double.MinValue) { break; } if (activeThreadValues.Where(j => j < A + eps && j > A - eps).Count() == 0) activeThreadValues.Add(A); mapData.Points.AddXY(r, A); } if (activeThreadValues.Count > numberOfThreadsInMap) { Console.WriteLine("Bifurcation point: " + r.ToString() + " " + activeThreadValues.Count.ToString() + " threads."); numberOfThreadsInMap = activeThreadValues.Count(); eps /= numberOfThreadsInMap; } } }
static void Main(string[] args) { int totalCount = 3; List<Student> listStudent = new List<Student>(); for (int i = 0; i < 3; i++) { Student objStudent = new Student(); Console.Write("Please enter the Student ID: "); objStudent.StudentId = Int32.Parse(Console.ReadLine()); Console.Write("Please enter the Student Name: "); objStudent.Name = Console.ReadLine(); listStudent.Add(objStudent); } //Query to get by name - only first occurence //Student student = listStudent.First(x => x.Name == "Karthik"); Student student = listStudent.FirstOrDefault(x => x.Name == "Karthik"); if(student != null) Console.WriteLine(string.Format("ID: {0} Name: {1}", student.StudentId, student.Name)); //Query to get by name - all occurences //IEnumerable<Student> stdList = listStudent.Where(x => x.Name == "Karthik"); IEnumerable<Student> stdList = listStudent.Where(x => x.StudentId >= 20); foreach (var student1 in stdList) { Console.WriteLine(string.Format("ID: {0} Name: {1}", student1.StudentId, student1.Name)); } listStudent.Sort((std1, std2) => std1.Name.CompareTo(std2.Name)); listStudent.ForEach(x=>Console.WriteLine(x.Name)); }
private List<CalendarItem> MergeItems(List<CalendarItem> newItems, List<CalendarItem> fromRepo) { var result = new List<CalendarItem>(); var newModels = newItems.Except(fromRepo, new CalendarItemEqualityComparer()).ToList(); var updatet = fromRepo.Except(newModels,new CalendarItemEqualityComparer()).ToList(); updatet.ForEach(x => { var model = newItems.FirstOrDefault(y => y.Id == x.Id); if (model != null) { model.SyncStatus.CalenadCalendarItemStatus = IsModified(model, x) ? CalendarItemStatus.Updated : CalendarItemStatus.Unmodified; result.Add(model); } }); var deleted = fromRepo.Where(x => x.Start.Date >= DateTime.Now.Date).Except(newItems).Except(updatet); newModels.ForEach(x => x.SyncStatus.CalenadCalendarItemStatus = CalendarItemStatus.New); deleted.ForEach(x => { x.SyncStatus.CalenadCalendarItemStatus = CalendarItemStatus.Deleted; result.Add(x); }); result.AddRange(newModels); return result.OrderBy(x => x.Start).ToList(); }
private static void LambdaExpression(List<Student> students) { List<Student> selectedStudents = students.Where(s => s.GroupNumber == 2) .OrderBy(s => s.FirstName) .ToList(); selectedStudents.ForEach(s => Console.WriteLine("First name: {0}, Group number: {1}", s.FirstName, s.GroupNumber)); }
/// <summary>Returns numeric indicator of market activity. Higher value means higher activity (i.e. lot of trades with higher volume).</summary> /// <param name="tradeHistory">Description of last executed trades of exchange</param> /// <param name="now">Current local time of the exchange</param> /// <returns>Coeficient in [0.0, 1.0] where 0.0 means totally peacefull market, 1.0 is wild.</returns> internal static float GetMadness(List<Trade> tradeHistory, DateTime now) { //Trades of past 4mins List<Trade> trades = tradeHistory.Where(trade => trade.Time >= now.AddSeconds(-240)).ToList(); if (!trades.Any()) { return 0.0f; } //Group by time, so that single trade with big volume doesn't look like many trades var groupped = new Dictionary<string, Trade>(); foreach (var trade in trades) { var key = trade.timestamp + "_" + trade.type; if (!groupped.ContainsKey(key)) { groupped.Add(key, new Trade(trade.price, trade.amount, trade.Type)); } else { groupped[key].amount += trade.amount; if (TradeType.BUY == trade.Type && trade.amount > groupped[key].amount) groupped[key].amount = trade.amount; else if (TradeType.SELL == trade.Type && trade.amount < groupped[key].amount) groupped[key].amount = trade.amount; } } // Console.WriteLine("DEBUG: {0} trades in past 90sec, {1} groupped by time", tradeHistory.Count, groupped.Count); const int MIN_TRADES = 4; const int MAX_TRADES = 14; float intenseCoef; if (groupped.Count < MIN_TRADES) //Too few trades intenseCoef = 0.0f; else if (groupped.Count >= MAX_TRADES) //Too many trades intenseCoef = 1.0f; else intenseCoef = (float)(groupped.Count - MIN_TRADES) / (MAX_TRADES - MIN_TRADES); const double MIN_AVG_VOLUME = 20; const double MAX_AVG_VOLUME = 50; float volumeCoef; double avgVolume = groupped.Sum(trade => trade.Value.amount) / groupped.Count; // Console.WriteLine("DEBUG: avgVolume={0}", avgVolume); if (avgVolume < MIN_AVG_VOLUME) volumeCoef = 0.0f; else if (avgVolume >= MAX_AVG_VOLUME) volumeCoef = 1.0f; else volumeCoef = (float)((avgVolume - MIN_AVG_VOLUME) / (MAX_AVG_VOLUME - MIN_AVG_VOLUME)); // Console.WriteLine("DEBUG: intensityCoef={0}, volumeCoef={1}", intenseCoef, volumeCoef); //Average of volume and frequency coeficients return (intenseCoef + volumeCoef) / 2; }
private static void Expression(List<Student> students) { var selectedStudents = students.Where(s => s.Group.DepartmentName.Equals("Mathematics")) .ToList(); foreach (var student in selectedStudents) { Console.WriteLine("Name: {0}, Department: {1}", student.FirstName + " " + student.LastName, student.Group.DepartmentName); } }
private static void Expression(List<Student> students) { var selectedStudents = students.Where(s => s.Marks.Count > 0 && s.Marks.Contains(6)) .Select(s => new { FullName = s.FirstName + " " + s.LastName, Marks = s.MarksPrint() }); foreach (var student in selectedStudents) { Console.WriteLine("{0} {1}", student.FullName, student.Marks); } }
private static void Main() { List<Student> list = new List<Student>(); for (int i = 0; i < 20; i++) { Student student = new Student(GenerateRandom.Text(10), GenerateRandom.Text(10)); student.Age = GenerateRandom.Number(15, 35); list.Add(student); } Console.WriteLine("\nAll:\n"); list.ForEach(x => Console.WriteLine(x)); Console.WriteLine("\nFilterd 1:\n"); var sorted1 = list.Where(x => x.Age >= 18 && x.Age <= 24) .Select(x => new { FirstName = x.FirstName, LastName = x.LastName, Age = x.Age }).ToList(); sorted1.ForEach(x => Console.WriteLine(x.FirstName + " " + x.LastName + " " + x.Age)); Console.WriteLine("\nFilterd 2:\n"); var sorted2 = from s in list where s.Age >= 18 && s.Age <= 24 select new { FirstName = s.FirstName, LastName = s.LastName, Age = s.Age }; foreach (var x in sorted2) { Console.WriteLine(x.FirstName + " " + x.LastName + " " + x.Age); } }
private static void Expression(List<Student> students) { var selectedStudents = students.Where(s => s.Fn.ToString().Substring(s.Fn.ToString().Length - 2, 2) == "06") .Select(s => new { Fn = s.Fn, Marks = s.Marks }); foreach (var student in selectedStudents) { Console.Write(student.Fn + ": "); foreach (var mark in student.Marks) { Console.Write("{0} ", mark); } Console.WriteLine(); } }
private WeatherInfo AggregateInternal(List<WeatherInfo> weatherInfos) { var weatherInfo = new WeatherInfo(); var existingWeatherInfos = weatherInfos.Where(p => p != null).ToList(); weatherInfo.Country = existingWeatherInfos.GetOneResult(info => info.Country != null, info => info.Country); weatherInfo.Description = existingWeatherInfos.GetOneResult(info => info.Description != null, info => info.Description); weatherInfo.Elevation = existingWeatherInfos.GetOneResult(info => info.Elevation != null, info => info.Elevation); weatherInfo.RelativeHumidity = existingWeatherInfos.GetOneResult(info => info.RelativeHumidity != null, info => info.RelativeHumidity); weatherInfo.WindDirection = existingWeatherInfos.GetOneResult(info => info.WindDirection != null, info => info.WindDirection); var latititudes = existingWeatherInfos.GetMultipleResults(p => p.Latitude.HasValue, p => p.Latitude); weatherInfo.Latitude = latititudes.Any() ? latititudes.Average() : null; var longitudes = existingWeatherInfos.GetMultipleResults(p => p.Longitude.HasValue, p => p.Longitude); weatherInfo.Longitude = longitudes.Any() ? longitudes.Average() : null; var pressuresInMb = existingWeatherInfos.GetMultipleResults(p => p.PressureMb.HasValue, p => p.PressureMb); weatherInfo.PressureMb = pressuresInMb.Any() ? MathExtensions.Floor(pressuresInMb.Average()) : null; var temperaturesCelcius = existingWeatherInfos.GetMultipleResults(p => p.TemperatureCelcius.HasValue, p => p.TemperatureCelcius); weatherInfo.TemperatureCelcius = temperaturesCelcius.Any() ? temperaturesCelcius.Average() : null; var visibilityDistances = existingWeatherInfos.GetMultipleResults(p => p.VisibilityDistance.HasValue, p => p.VisibilityDistance); weatherInfo.VisibilityDistance = visibilityDistances.Any() ? visibilityDistances.Average() : null; var windAngles = existingWeatherInfos.GetMultipleResults(p => p.WindAngle.HasValue, p => p.WindAngle); weatherInfo.WindAngle = windAngles.Any() ? MathExtensions.Floor(windAngles.Average()) : null; var windSpeedsKph = existingWeatherInfos.GetMultipleResults(p => p.WindSpeedKph.HasValue, p => p.WindSpeedKph); weatherInfo.WindSpeedKph = windSpeedsKph.Any() ? windSpeedsKph.Average() : null; var windSpeedsMs = existingWeatherInfos.GetMultipleResults(p => p.WindSpeedMs.HasValue, p => p.WindSpeedMs); weatherInfo.WindSpeedMs = windSpeedsMs.Any() ? windSpeedsMs.Average() : null; return weatherInfo; }
/// <summary> /// 消费数据分析 /// </summary> /// <returns></returns> bool cosumeRecordAnalysis() { this._IsRunning = true; bool res = true; try { bool canStart = false; TimeSpan tsNow = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); foreach (TimeSpan item in this._ListCollectSpan) { TimeSpan tsEnd = new TimeSpan(); if (item.Hours == 23) { tsEnd = new TimeSpan(23, 59, 59); } else { tsEnd = new TimeSpan(item.Hours + 1, item.Minutes, 0); } if (tsNow > item && tsNow < tsEnd) { canStart = true; break; } } if (!canStart) { this._IsRunning = false; return false; } //消费机最后同步时间 DateTime dtMacSync = DateTime.MinValue; //找出消费机主档信息,检查是否全部收数完毕,是则进行平数处理,否则不操作 #region 找出消费机主档信息,检查是否全部收数完毕,是则进行平数处理,否则不操作 List<ConsumeMachineMaster_cmm_Info> listMachineInfos = this._IConsumeMachineBL.SearchRecords(new ConsumeMachineMaster_cmm_Info() { cmm_cStatus = Common.DefineConstantValue.ConsumeMachineStatus.Using.ToString(), }); if (listMachineInfos == null) { this._IsRunning = false; return false; } else { if (listMachineInfos != null && listMachineInfos.Count > 0) { if (listMachineInfos != null && listMachineInfos.Count > 0) { dtMacSync = listMachineInfos[0].cmm_dLastAccessTime; } } List<ConsumeMachineMaster_cmm_Info> listUnSyncMachineInfos = listMachineInfos.Where(x => x.cmm_dLastAccessTime.Hour != dtMacSync.Hour).ToList(); if (listUnSyncMachineInfos != null && listUnSyncMachineInfos.Count > 0) { this._IsRunning = false; return false; } List<ConsumeMachineMaster_cmm_Info> listUnConnMachineInfos = listMachineInfos.Where(x => x.cmm_lIsActive == true && x.cmm_lLastAccessRes == false ).ToList(); if (listUnConnMachineInfos == null || (listUnConnMachineInfos != null && listUnConnMachineInfos.Count > 0)) { this._IsRunning = false; return false; } } #endregion //就餐时段 #region 学生真实就餐时段列表 List<CodeMaster_cmt_Info> listMealTimeSpan = this._ICodeMasterBL.SearchRecords(new CodeMaster_cmt_Info() { cmt_cKey1 = Common.DefineConstantValue.CodeMasterDefine.KEY1_MealTimeSpan }); if (listMealTimeSpan == null || (listMealTimeSpan != null && listMealTimeSpan.Count < 1)) { this._IsRunning = false; return false; } #endregion //定餐时段 #region 学生定餐设置生成时间列表 List<CodeMaster_cmt_Info> listBookingMealTimeSpan = this._ICodeMasterBL.SearchRecords(new CodeMaster_cmt_Info() { cmt_cKey1 = Common.DefineConstantValue.CodeMasterDefine.KEY1_BWListUploadInterval }); if (listBookingMealTimeSpan == null || (listBookingMealTimeSpan != null && listBookingMealTimeSpan.Count < 1)) { this._IsRunning = false; return false; } #endregion //未结算的未可确认扣费的消费记录 #region 获取当前所有未结算的未可确认扣费的消费记录 List<PreConsumeRecord_pcs_Info> listUnSettlePreCost = this._IPreConsumeRecordBL.SearchRecords(new PreConsumeRecord_pcs_Info() { pcs_cConsumeType = Common.DefineConstantValue.ConsumeMoneyFlowType.IndeterminateCost.ToString() }); List<PreConsumeRecord_pcs_Info> listWaitSettlePreCost = this._IPreConsumeRecordBL.SearchRecords(new PreConsumeRecord_pcs_Info() { pcs_cConsumeType = Common.DefineConstantValue.ConsumeMoneyFlowType.AdvanceMealCost.ToString() }); listUnSettlePreCost.AddRange(listWaitSettlePreCost); if (listUnSettlePreCost != null) { //条件分开两次进行筛选,方便数据观察 listUnSettlePreCost = listUnSettlePreCost.Where(x => x.pcs_lIsSettled == false//需要状态为未结算 ).ToList(); listUnSettlePreCost = listUnSettlePreCost.Where(x => x.pcs_dConsumeDate <= dtMacSync//使用消费机最后同步时间之前的未结算数据进行同步 ).ToList(); } #endregion //对冲平数记录 #region 获取当前所有对冲数据记录 List<PreConsumeRecord_pcs_Info> listHedge = this._IPreConsumeRecordBL.SearchRecords(new PreConsumeRecord_pcs_Info() { pcs_cConsumeType = Common.DefineConstantValue.ConsumeMoneyFlowType.HedgeFund.ToString() }); listHedge = listHedge.Where(x => x.pcs_lIsSettled == false//需要为未结算状态 && x.pcs_dConsumeDate <= dtMacSync//需要为消费机最后同步前的数据 ).ToList(); #endregion //未结算的消费记录 #region 获取当前所有状态为未结算的打卡消费数据 List<ConsumeRecord_csr_Info> listUnSettleCardCost = this._IConsumeRecordBL.SearchRecords(new ConsumeRecord_csr_Info() { IsSettled = false }); if (listUnSettleCardCost != null && listUnSettleCardCost.Count > 0) { listUnSettleCardCost = listUnSettleCardCost.Where(x => x.csr_dConsumeDate <= dtMacSync//需要为消费机最后同步前的数据 ).ToList(); } #endregion /*<Start-------------------------------------------用于最后数据处理的容器-------------------------------------------------->*/ //待更新的打卡消费记录 List<ConsumeRecord_csr_Info> listUpdate_Consume = new List<ConsumeRecord_csr_Info>(); //待更新的预扣费记录 List<PreConsumeRecord_pcs_Info> listUpdate_PreCost = new List<PreConsumeRecord_pcs_Info>(); //无需要处理预扣费的消费记录 List<ConsumeRecord_csr_Info> listUpdate_UnMealConsume = new List<ConsumeRecord_csr_Info>(); //待删除的多余预扣费记录 List<PreConsumeRecord_pcs_Info> listDelete_PreCost = new List<PreConsumeRecord_pcs_Info>(); /*<End-------------------------------------------用于最后数据处理的容器--------------------------------------------------->*/ if (listUnSettleCardCost != null && listUnSettleCardCost.Count > 0)//存在未结算处理的消费记录时 { #region 处理打卡数据(定餐打卡,饮料打卡,加菜打卡,热水打卡) //逐条消费数据进行比对,用作处理未确认扣款记录和对冲记录 foreach (ConsumeRecord_csr_Info consumeItem in listUnSettleCardCost) { if (consumeItem.csr_cConsumeType == DefineConstantValue.ConsumeMachineType.StuSetmeal.ToString()) { #region 处理定餐消费记录 //判断为定餐消费记录,用于消除未确定消费记录 List<PreConsumeRecord_pcs_Info> listResPreCost = listUnSettlePreCost.Where(x => x.pcs_cUserID == consumeItem.csr_cCardUserID//需为消费用户对应ID && x.MealType == consumeItem.csr_cMealType//餐类型需要相同 //&& x.pcs_dConsumeDate.Date == consumeItem.csr_dConsumeDate.Date && x.pcs_dAddDate.Date == consumeItem.csr_dConsumeDate.Date//以添加时间为准,找出 && Math.Abs(x.pcs_fCost) == Math.Abs(consumeItem.csr_fConsumeMoney)//消费金额需一致 ).ToList(); if (listResPreCost != null && listResPreCost.Count > 0)//!要注意这里会不会搜索出两条记录出来 { if (listResPreCost.Count > 1) { bool lSign = true;//标识特殊case:同一条打卡消费记录对应两条定餐未结算记录 } //消费数据符合该条未确认数据记录的条件,更新该条消费记录的状态为已结,并更新对应的未确定扣费定餐记录置为已结状态 consumeItem.csr_lIsSettled = true; consumeItem.csr_dSettleTime = DateTime.Now; listUpdate_Consume.Add(consumeItem); //按升序排序多条待付款预扣费记录 List<PreConsumeRecord_pcs_Info> listPreTmp = listResPreCost.OrderBy(x => x.pcs_dAddDate).ToList(); for (int i = 0; i < listPreTmp.Count; i++) { PreConsumeRecord_pcs_Info preCost = listPreTmp[i]; preCost.pcs_cSourceID = consumeItem.csr_cRecordID;//转换预付款记录的源记录ID,原为定餐记录,现为消费记录 preCost.pcs_lIsSettled = true; preCost.pcs_dSettleTime = DateTime.Now; preCost.pcs_cConsumeType = Common.DefineConstantValue.ConsumeMoneyFlowType.SetMealCost.ToString(); preCost.pcs_dConsumeDate = consumeItem.csr_dConsumeDate; PreConsumeRecord_pcs_Info resCompUp = listUpdate_PreCost.Find(x => x.pcs_cRecordID == preCost.pcs_cRecordID); PreConsumeRecord_pcs_Info resCompDel = listDelete_PreCost.Find(x => x.pcs_cRecordID == preCost.pcs_cRecordID); if (resCompUp == null && resCompDel == null) { if (i == 0) { listUpdate_PreCost.Add(preCost); } else { listDelete_PreCost.Add(preCost); } } else { bool lSign = true;//异常数据标识 } } } else { //无符合该消费记录的待付款记录 listUpdate_UnMealConsume.Add(consumeItem); } #endregion } else { //判断为非定餐消费记录,用于消减冲数记录 consumeItem.csr_lIsSettled = true; consumeItem.csr_dSettleTime = DateTime.Now; listUpdate_Consume.Add(consumeItem); } } #endregion } //找出有定餐但无打卡数据的未确定预消费记录 #region 筛选出定餐但无打卡的数据 int iCount = 0; int iCOunt2 = 0; foreach (PreConsumeRecord_pcs_Info unMealPreCost in listUnSettlePreCost) { PreConsumeRecord_pcs_Info resUnMeal = listUpdate_PreCost.Find(x => x.pcs_cRecordID == unMealPreCost.pcs_cRecordID); PreConsumeRecord_pcs_Info resDelMeal = listDelete_PreCost.Find(x => x.pcs_cRecordID == unMealPreCost.pcs_cRecordID); if (resUnMeal == null && resDelMeal == null) { unMealPreCost.pcs_cConsumeType = Common.DefineConstantValue.ConsumeMoneyFlowType.SetMealCost.ToString(); unMealPreCost.pcs_dAddDate = DateTime.Now; unMealPreCost.pcs_cAdd = this._ServiceName; listUpdate_PreCost.Add(unMealPreCost); iCount++; } else { iCOunt2++; } } #endregion //消减平账冲数记录 #region 消减平账记录 var groupUserHedge = listHedge.GroupBy(x => x.pcs_cUserID); foreach (var userItem in groupUserHedge) { //以人为单位组成数据组别 Guid userID = userItem.Key; //找出本次收数得到的指定用户的打卡记录 List<ConsumeRecord_csr_Info> listUserConsume = listUpdate_Consume.Where(x => x.csr_cCardUserID == userID).ToList(); //找出未被处理到类型的打卡记录,并添加到打卡对比记录列表 List<ConsumeRecord_csr_Info> listUnMealConsume = listUpdate_UnMealConsume.Where(x => x.csr_cCardUserID == userID).ToList(); if (listUnMealConsume != null && listUnMealConsume.Count > 0) { listUserConsume.AddRange(listUnMealConsume); } if (listUserConsume == null || (listUserConsume != null && listUserConsume.Count < 1)) { continue; } //以对冲记录产生的时间升序排列,时间早的靠前 List<PreConsumeRecord_pcs_Info> listUserHedge = userItem.OrderBy(x => x.pcs_dConsumeDate).ToList(); if (listUserHedge != null && listUserHedge.Count > 0) { for (int i = 0; i < listUserHedge.Count; i++) { List<ConsumeRecord_csr_Info> listConsumeComp = new List<ConsumeRecord_csr_Info>(); if (i > 0 && i == listUserHedge.Count - 1) { //对冲记录数大于0,且为最后一条记录时,找出是否存在打卡记录在最后一条对冲记录和倒数第二条对冲记录之间 listConsumeComp = listUserConsume.Where(x => x.csr_dConsumeDate <= listUserHedge[i].pcs_dConsumeDate && x.csr_dConsumeDate > listUserHedge[i - 1].pcs_dConsumeDate).ToList(); } else if (i < listUserHedge.Count - 1) { listConsumeComp = listUserConsume.Where(x => x.csr_dConsumeDate < listUserHedge[i + 1].pcs_dConsumeDate && x.csr_dConsumeDate >= listUserHedge[i].pcs_dConsumeDate).ToList(); } else if (i == 0 && listUserHedge.Count == 1) { listConsumeComp = listUserConsume.Where(x => x.csr_dConsumeDate <= listUserHedge[i].pcs_dConsumeDate).ToList(); } if (listConsumeComp == null) continue; if (listConsumeComp.Count > 1) { decimal fComp = Math.Abs(listUserHedge[i].pcs_fCost) - Math.Abs(listConsumeComp.Sum(x => x.csr_fConsumeMoney)); if (fComp <= 0) { listUserHedge[i].pcs_lIsSettled = true; listUserHedge[i].pcs_dSettleTime = DateTime.Now; listUpdate_PreCost.Add(listUserHedge[i]); } else { listUserHedge[i].pcs_dConsumeDate = DateTime.Now; listUserHedge[i].pcs_fCost = fComp; listUpdate_PreCost.Add(listUserHedge[i]); } foreach (ConsumeRecord_csr_Info item in listConsumeComp) { ConsumeRecord_csr_Info consumeHedge = listUpdate_Consume.Find(x => x.csr_cRecordID == item.csr_cRecordID); if (consumeHedge == null) { consumeHedge = listUpdate_UnMealConsume.Find(x => x.csr_cRecordID == item.csr_cRecordID); consumeHedge.csr_lIsSettled = true; consumeHedge.csr_dSettleTime = DateTime.Now; listUpdate_Consume.Add(consumeHedge); } else { consumeHedge.csr_lIsSettled = true; consumeHedge.csr_dSettleTime = DateTime.Now; } } } else { if (listUserHedge[i].pcs_dConsumeDate < dtMacSync) { //若无对应的消费记录,且时间早于收数时间,则删除此对冲记录 listDelete_PreCost.Add(listUserHedge[i]); } } } } } #endregion //如没有被1、定餐冲数;2、平数记录冲数,则进行结算处理 if (listUpdate_UnMealConsume != null && listUpdate_UnMealConsume.Count > 0) { foreach (ConsumeRecord_csr_Info item in listUpdate_UnMealConsume) { if (!item.csr_lIsSettled) { item.csr_lIsSettled = true; item.csr_dSettleTime = DateTime.Now; listUpdate_Consume.Add(item); } } } if (listUpdate_PreCost.Count > 0 || listUpdate_Consume.Count > 0) { ReturnValueInfo rvInfo = this._ICardUserAccountBL.BatchSyncAccountDetail(listUpdate_PreCost, listDelete_PreCost, listUpdate_Consume); if (rvInfo.boolValue && !rvInfo.isError) { this._LocalLogger.WriteLog("同步账户数据成功!" + DateTime.Now.ToString(), string.Empty, SystemLog.SystemLog.LogType.Trace); res = true; } else { if (rvInfo.isError) { this._LocalLogger.WriteLog("同步账户数据失败!" + DateTime.Now.ToString() + rvInfo.messageText, string.Empty, SystemLog.SystemLog.LogType.Error); } else { this._LocalLogger.WriteLog("同步账户数据失败!" + DateTime.Now.ToString() + rvInfo.messageText, string.Empty, SystemLog.SystemLog.LogType.Warning); } res = false; } } else { this._IsRunning = false; return true; } } catch (Exception ex) { this._LocalLogger.WriteLog(ex.Message, string.Empty, SystemLog.SystemLog.LogType.Error); res = false; } this._IsRunning = false; return res; }
/// <summary> /// 显示子窗体 /// </summary> /// <param name="sender">发送显示请求的按钮或其他控件</param> /// <param name="dpnlContainer">显示容器</param> /// <param name="strTabName">卡位位置</param> /// <param name="strTabName">显示卡位位置</param> public void ShowSubForm(object sender, DockPanel dpnlContainer, string strTabName, DockState state) { string strFormName = string.Empty; MenuItem itemMenu = sender as MenuItem; if (itemMenu != null) { strFormName = (itemMenu.Tag as Sys_FormMaster_fom_Info).fom_cExePath; } else { ToolStripButton itemBtn = sender as ToolStripButton; if (itemBtn != null) { strFormName = (itemBtn.Tag as Sys_FormMaster_fom_Info).fom_cExePath; } } if (!string.IsNullOrEmpty(strFormName)) { if (!string.IsNullOrEmpty(strFormName)) { BaseForm frmTarget = GetFormIn(strFormName); frmTarget.EditState = this.EditState; frmTarget.BaseParam = this.BaseParam; frmTarget.UserInformation = this.UserInformation; if (!string.IsNullOrEmpty(strTabName)) { frmTarget.TabText = strTabName; } if (frmTarget == null) { ShowErrorMessage("生成子窗体异常,请联系管理员。"); } else { //var tmpList = dpnlContainer.Contents.Where(x => x.DockHandler.TabText == frmTarget.TabText).ToList(); var tmpList = dpnlContainer.Contents.Where(x => x.DockHandler.Form.Name == frmTarget.Name).ToList(); if (tmpList != null && tmpList.Count < 1) { frmTarget.BaseDockPanel = dpnlContainer; frmTarget.Show(dpnlContainer, state); } else if (tmpList != null && tmpList.Count > 0)//當使用相同窗體不同編輯模式時,Form相同,需要外加編輯狀態屬性判斷是否已被打開該窗體 { List<BaseForm> listCompForm = new List<BaseForm>(); foreach (var panItem in tmpList) { BaseForm bsTarget = panItem.DockHandler.Form as BaseForm; if (bsTarget != null) { listCompForm.Add(bsTarget); } } var listTmp = listCompForm.Where(x => x.EditState == this.EditState).ToList(); if (listTmp != null && listTmp.Count < 1) { frmTarget.BaseDockPanel = dpnlContainer; frmTarget.Show(dpnlContainer, state); } else if (listTmp != null && listTmp.Count > 0) { listTmp[0].DockHandler.Activate(); } } } } else { ShowErrorMessage("发送显示请求的对象没有携带窗口信息,请联系管理员。"); } } else { ShowErrorMessage("发送显示请求的对象有误,请联系管理员。"); } }
public static IEnumerable<ExigoService.Calendar> GetCalendars(GetCalendarsRequest request) { var context = Exigo.ODataCalendars(); var corporateCalendarContext = Exigo.OData(); var calendars = new List<Calendar>(); var cacheKey = "GetCalendars/{0}/{1}".FormatWith(request.CustomerID ?? 0, request.IncludeCalendarSubscriptions); var cache = (HttpContext.Current != null) ? HttpContext.Current.Cache : null; // Check the cache to see if we've already made this call recently if (cache == null || cache[cacheKey] == null) { GlobalUtilities.RunAsyncTasks( // Add the customer's personal calendars () => { if (request.CustomerID != null) { var apiCalendars = context.Calendars .Where(c => c.CustomerID == (int)request.CustomerID) .ToList(); foreach (var apiCalendar in apiCalendars) { calendars.Add((ExigoService.Calendar)apiCalendar); } } }, // Include the customer's calendar subscriptions if applicable () => { if (request.CustomerID != null && request.IncludeCalendarSubscriptions) { var calendarSubscriptions = GetCustomerCalendarSubscriptions((int)request.CustomerID); var calendarSubscriptionsIDs = calendarSubscriptions.Select(c => c.CalendarID).ToList(); if (calendarSubscriptionsIDs.Count > 0) { var apiCalendars = context.Calendars .Where(calendarSubscriptionsIDs.ToOrExpression<CalendarContext.Calendar, Guid>("CalendarID")) .ToList(); foreach (var apiCalendar in apiCalendars) { calendars.Add((ExigoService.Calendar)apiCalendar); } } } }, // Include any additional requested calendars () => { if (request.CalendarIDs != null && request.CalendarIDs.Count() > 0) { var apiCalendars = context.Calendars .Where(request.CalendarIDs.ToList().ToOrExpression<CalendarContext.Calendar, Guid>("CalendarID")) .ToList(); foreach (var apiCalendar in apiCalendars) { calendars.Add((ExigoService.Calendar)apiCalendar); } } } ); // If we asked for a specific customer's calendars, and none of the calendars belong to that customer, create a default calendar and add it to the collection. if (request.CustomerID != null && calendars.Where(c => c.CustomerID == (int)request.CustomerID).Count() == 0) { var defaultCalendar = CreateDefaultCalendar((int)request.CustomerID); calendars.Add(defaultCalendar); } if (cache != null) { cache.Insert(cacheKey, calendars, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); } } else { calendars = (List<ExigoService.Calendar>)cache[cacheKey]; } // Return the calendars foreach (var calendar in calendars) { yield return calendar; } }
private static void Expression(List<Student> students) { List<Student> selectedStudents = students.Where(s => s.Tel.Substring(0, s.Tel.IndexOf('/')) == "02").ToList(); selectedStudents.ForEach(student => Console.WriteLine("{0} {1} {2}", student.FirstName, student.LastName, student.Tel)); }
//根據事業單位綁定區域 private void BindcboMachineBigArea(string description) { var allarea = MasterBLLFactory.GetBLL<IAreaMasterBL>(MasterBLLFactory.AreaMaster).SearchRecords(new AreaMaster_amr_Info()); List<AreaMaster_amr_Info> alldescription = new List<AreaMaster_amr_Info>(); foreach (AreaMaster_amr_Info item in allarea) { alldescription.Add(item); } alldescription = alldescription.Where(d => d.amr_cPublicInstitution.Trim().ToUpper() == description.ToUpper().Trim()).ToList(); cboMachineBigArea.DisplayMember = "amr_cAreaName"; cboMachineBigArea.ValueMember = "amr_cRecordID"; cboMachineBigArea.DataSource = alldescription; cboMachineBigArea.SelectedIndex = -1; }
public ActionResult SaveStructPic(string x, string y, string id, string cat, string pid) { string path = Server.MapPath("~") + "/config/"; List<StructPoint> points = new List<StructPoint>(); XmlHelper.DeserializerXML(string.Format("{1}structPointConfig{0}.xml", pid, path), ref points); StructPoint searchPoint = points.Where(m => m.id.Equals(id) && m.type.Equals(cat)).FirstOrDefault<StructPoint>(); if (searchPoint != null) { searchPoint.x = x; searchPoint.y = y; } else points.Add(new StructPoint { x = x, y = y, id = id, type = cat }); XmlHelper.SerializerXML(string.Format("{1}structPointConfig{0}.xml", pid, path), points); return Content("ok"); }
private void DeleteFinishedTasksFromQueues(ref List<Tuple<string, IEnumerable<ActiveEstimatedTask>, IEnumerable<EstimatedTask>, IEnumerable<TasksDepenendency>>>wfs) { try { foreach (var currentTask in nodeCurrent.ToList()) { // if there is a task executed on this node if (currentTask.Value != null) { int wfId = currentTask.Value.Item1, taskId = currentTask.Value.Item2; var global = taskIDs.Where(t => t.Value.Item1 == wfId && t.Value.Item2 == taskId); string wfKey = wfIDs.FirstOrDefault(x => x.Value == wfId).Key; // if current task is in ActiveEstimated tasks, it is not finished yet // else we should delete it from queues var currentWf = wfs.Where(wf => wf.Item1 == wfKey).ToList(); bool isWFFinished = false, isLaunchedNotInActive = false, isLaunchedNotInActiveAndEstimated = false; if (currentWf.Count == 0) { //logger.Info("DeleteFinishedTasksFromQueues(). Workflow " + wfId.ToString() + " (key " + wfKey + ") was not found in a list of workflows"); isWFFinished = true; } else { ulong globalTaskId = global.First().Key; var activeTasks = currentWf.First().Item2; var foundTask = activeTasks.Where(task => task.Parameters["id"] == taskId.ToString()).ToList(); isLaunchedNotInActive = (foundTask.Count == 0 && wasActive[globalTaskId] == true); isLaunchedNotInActiveAndEstimated = false; if (!isLaunchedNotInActive) { // second case - when task was not in active list // in this case wasActive status = false, but it is neither in active nor in estimated lists var estimatedTasks = currentWf.First().Item3; var foundEstimatedTask = estimatedTasks.Where(task => task.Parameters["id"] == taskId.ToString()).ToList(); if (foundTask.Count == 0 && foundEstimatedTask.Count == 0) isLaunchedNotInActiveAndEstimated = true; } } if (isLaunchedNotInActive || isLaunchedNotInActiveAndEstimated || isWFFinished)// && CheckTime()) { int nodeId = currentTask.Key; // remove current task from current node nodeCurrent[nodeId] = null; //logger.Info("Node current of " + nodeId.ToString() + " was nulled"); finishedTasks.Add(new Tuple<int, int>(wfId, taskId)); //taskIDs.Remove(taskToRemove.First().Key); logger.Info("DeleteFinishedTasksFromQueues(). Task " + taskId.ToString() + " of workflow " + wfId.ToString() + " was finished on " + currentTask.Key.ToString()); //logger.Info("DeleteFinishedTasksFromQueues(). Task " + taskId.ToString() + " was removed from taskIds"); } } } // PrintNodeQueues(); } catch (Exception ex) { logger.ErrorException("DeleteFinishedTasksFromQueues() exception. " + ex.Message, ex); } }
/// <summary>There's a dump on market, best time to SELL.</summary> private static bool runningSelloff(List<TradeResponse> tradeHistory) { //There's lot of activity in recent time and price is falling const double PRICE_DIFF = 3 * 0.001; //0.3% var endTime = tradeHistory.Last().TimeTyped; var startTime = endTime.AddSeconds(-90); //Trades of past 90 seconds var pastTrades = tradeHistory.Where(trade => trade.TimeTyped >= startTime).ToList(); if (pastTrades.Count < 10) //TODO: tune up return false; var startPrice = pastTrades.First().price; var endPrice = pastTrades.Last().price; return (startPrice > endPrice && startPrice - endPrice >= startPrice * PRICE_DIFF); }
public void PopulateCommissionBonusesChartXml() { // Establish our chart variables var xAxisLabels = new List<string>(); var seriesCollection = new List<ChartSeries>(); // Group our data to ensure that we show accurate data. var groupedData = CommissionBonusesDetails .GroupBy(c => new { c.BonusDescription, c.AcceptedDate }, (key, group) => new { key.BonusDescription, key.AcceptedDate, BonusAmount = group.Sum(a => a.BonusAmount) }); // Loop through each row and define our variables from the data foreach (var detail in groupedData) { // X-axis var monthDescription = detail.AcceptedDate.ToString("MMMM yyyy"); if (!xAxisLabels.Contains(monthDescription)) xAxisLabels.Add(monthDescription); // ConnectionStrings series var seriesName = detail.BonusDescription; var existingSeries = seriesCollection.Where(c => c.SeriesName == seriesName).Select(c => c).FirstOrDefault(); if (existingSeries == null) { var newSeries = new ChartSeries(); newSeries.SeriesName = seriesName; newSeries.Values.Add(detail.BonusAmount); seriesCollection.Add(newSeries); } else { existingSeries.Values.Add(detail.BonusAmount); } } // Compile the individual sections. Let's start with the categories. var categoriesXml = string.Empty; foreach (var label in xAxisLabels) { categoriesXml += string.Format(@"<category label='{0}' />", label); } categoriesXml = "<categories>" + categoriesXml + "</categories>"; // Next, compile the datasets var datasetXml = string.Empty; foreach (var series in seriesCollection) { // Dataset Values var datasetValuesJson = string.Empty; foreach (var value in series.Values) { datasetValuesJson += string.Format("<set value='{0}' />", value); } datasetXml += string.Format("<dataset seriesName='{0}'>", series.SeriesName) + datasetValuesJson + "</dataset>"; } // Compile the Json var json = new StringBuilder(); json.AppendFormat("<chart caption='' xAxisName='' yAxisName='Payouts' bgcolor='FFFFFF, FFFFFF' showBorder='0' showValues='0' labelDisplay='auto' showvalues='0' showSum='1' decimals='2' formatNumberScale='0' numberprefix='$'>{0}{1}</chart>", categoriesXml, datasetXml); // Set the Json to the corresponding property CommissionBonusesChartXml = json.ToString(); }
public CommissionSummaryViewModel(DataSet dataset) { // Divide our dataset into separate tables for easy reading var commissionEarningsData = dataset.Tables[0]; var commissionBonusesData = dataset.Tables[1]; // Populate our details collections CommissionEarningsDetails = new List<CommissionEarningsDetail>(); foreach (DataRow row in commissionEarningsData.Rows) { var detail = new CommissionEarningsDetail(); detail.CommissionRunID = Convert.ToInt32(row["CommissionRunID"]); detail.CommissionRunDescription = row["CommissionRunDescription"].ToString(); detail.AcceptedDate = Convert.ToDateTime(row["AcceptedDate"]); detail.PeriodTypeID = Convert.ToInt32(row["PeriodTypeID"]); detail.PaidRankID = Convert.ToInt32(row["PaidRankID"]); detail.PaidRankDescription = row["PaidRankDescription"].ToString(); detail.Earnings = Convert.ToDecimal(row["Earnings"]); detail.PaidAsRankCount = Convert.ToInt32(row["PaidAsRankCount"]); CommissionEarningsDetails.Add(detail); } CommissionBonusesDetails = new List<CommissionBonusDetail>(); foreach (DataRow row in commissionBonusesData.Rows) { var detail = new CommissionBonusDetail(); detail.CommissionRunID = Convert.ToInt32(row["CommissionRunID"]); detail.CommissionRunDescription = row["CommissionRunDescription"].ToString(); detail.AcceptedDate = Convert.ToDateTime(row["AcceptedDate"]); detail.PeriodTypeID = Convert.ToInt32(row["PeriodTypeID"]); detail.BonusID = Convert.ToInt32(row["BonusID"]); detail.BonusDescription = row["BonusDescription"].ToString(); detail.BonusAmount = Convert.ToDecimal(row["BonusAmount"]); CommissionBonusesDetails.Add(detail); } // Get the weekly totals var weeklyDetailsByRunID = CommissionEarningsDetails .Where(c => c.PeriodTypeID == (int)PeriodTypes.Weekly) .GroupBy(c => new { c.CommissionRunID, c.AcceptedDate }, (key, group) => new { CommissionRunID = key.CommissionRunID, AcceptedDate = key.AcceptedDate, Payout = group.Sum(a => a.Earnings) }); var orderedWeeklyPayouts = weeklyDetailsByRunID.OrderByDescending(c => c.Payout); if (orderedWeeklyPayouts.Count() > 0) { HighestWeeklyPayout = orderedWeeklyPayouts.First().Payout; HighestWeeklyPayoutDate = orderedWeeklyPayouts.First().AcceptedDate; LowestWeeklyPayout = orderedWeeklyPayouts.Last().Payout; LowestWeeklyPayoutDate = orderedWeeklyPayouts.Last().AcceptedDate; AverageWeeklyPayout = orderedWeeklyPayouts.Average(c => c.Payout); } // Get the monthly totals var monthlyDetailsByRunID = CommissionEarningsDetails .Where(c => c.PeriodTypeID == (int)PeriodTypes.Weekly) .GroupBy(c => new { c.CommissionRunID, c.AcceptedDate }, (key, group) => new { CommissionRunID = key.CommissionRunID, AcceptedDate = key.AcceptedDate, Payout = group.Sum(a => a.Earnings) }); var orderedMonthlyPayouts = monthlyDetailsByRunID.OrderByDescending(c => c.Payout); if (orderedMonthlyPayouts.Count() > 0) { HighestMonthlyPayout = orderedMonthlyPayouts.First().Payout; HighestMonthlyPayoutDate = orderedMonthlyPayouts.First().AcceptedDate; LowestMonthlyPayout = orderedMonthlyPayouts.Last().Payout; LowestMonthlyPayoutDate = orderedMonthlyPayouts.Last().AcceptedDate; AverageMonthlyPayout = orderedMonthlyPayouts.Average(c => c.Payout); } // Charts PopulateCommissionBonusesChartXml(); }
/// <summary> /// 记录筛选--可用于计算欠款的预付款记录 /// </summary> /// <param name="listFilter"></param> List<PreConsumeRecord_pcs> filterRecord_CanComputePreCost(List<PreConsumeRecord_pcs> listFilterPreCost) { //需要不为未确定结算款、待扣费款及对冲款 List<PreConsumeRecord_pcs> listFilterPreCostRv = listFilterPreCost.Where(x => x.pcs_cConsumeType != Common.DefineConstantValue.ConsumeMoneyFlowType.IndeterminateCost.ToString() && x.pcs_cConsumeType != Common.DefineConstantValue.ConsumeMoneyFlowType.AdvanceMealCost.ToString() && x.pcs_cConsumeType != Common.DefineConstantValue.ConsumeMoneyFlowType.HedgeFund.ToString() ).ToList(); return listFilterPreCostRv; }
public static ItemCategory GetItemCategory(int itemCategoryID) { var context = Exigo.OData(); // Get the nodes var categories = new List<ItemCategory>(); var rowcount = 50; var lastResultCount = rowcount; var callsMade = 0; while (lastResultCount == rowcount) { // Get the data var results = context.WebCategories .Where(c => c.WebID == 1) .OrderBy(c => c.ParentID) .OrderBy(c => c.SortOrder) .Skip(callsMade * rowcount) .Take(rowcount) .Select(c => c) .ToList(); results.ForEach(c => { categories.Add((ItemCategory)c); }); callsMade++; lastResultCount = results.Count; } // Recursively populate the children var category = categories.Where(c => c.ItemCategoryID == itemCategoryID).FirstOrDefault(); if (category == null) return null; category.Subcategories = GetItemCategorySubcategories(category, categories); return category; }
static void Main(string[] args) { List<Hand> all = new List<Hand>(); int result = 0; int a = 0; using (StreamReader r = new StreamReader("p054_poker.txt")) { while(!r.EndOfStream) { string line = r.ReadLine(); string hand1String = line.Substring(0, 14); string hand2String = line.Substring(15).Trim(); Hand h1 = Hand.Parse(hand1String); Hand h2 = Hand.Parse(hand2String); (a+1).Dump(); h1.ToConsole(); h2.ToConsole(); all.Add(h1); all.Add(h2); var ct = new CombinationTester(); if (ct.IsWin(h1, h2)) { result += 1; } a += 1; "---".Dump(); } } var ss = all.Where(h => h.SameSuit()).ToList(); var cs = all.Where(h => h.Consecutive()).ToList(); a.Dump("Total"); result.Dump("Answer"); }
/// <summary> /// 加載樹節點的所有子節點 /// </summary> /// <param name="nodeCurrent">當前樹節點</param> /// <param name="listForms">窗體記錄列表</param> /// <param name="iParentID">當前節點綁定的窗體ID</param> void GetFormList(TreeNode nodeCurrent, List<Sys_FormMaster_fom_Info> listForms, int iParentID) { List<Sys_FormMaster_fom_Info> listSubForms = listForms.Where(x => x.fom_iParentID == iParentID).ToList(); if (listForms == null) { return; } if (listForms.Count < 1) { return; } foreach (Sys_FormMaster_fom_Info formItem in listSubForms) { if (formItem == null) { continue; } TreeNode subNode = new TreeNode(formItem.fom_cFormDesc); subNode.Name = formItem.fom_iRecordID.ToString(); subNode.Tag = formItem.fom_cExePath.ToString(); nodeCurrent.Nodes.Add(subNode); GetFormList(subNode, listForms, formItem.fom_iRecordID); } }
private void BindMenuDropList(int parentId, int depth, List<DataRow> lDataRow) { List<DataRow> lChild = lDataRow.Where((dr) => int.Parse(dr["ParentId"].ToString()) == parentId).ToList(); lChild.ForEach((dr) => { int iMenuId = int.Parse(dr["Id"].ToString()); drpParentMenu.Items.Add(new ListItem(new string(' ', depth) + "|_" + dr["MenuName"].ToString(), iMenuId.ToString())); BindMenuDropList(iMenuId, depth + 1, lDataRow); }); }
protected override Task Execute() { return Task.Run(() => { var result = new List<AssetQuote>(); lock (_feed) { result.AddRange(from feedData in _feed.Values let assetName = _ourQuotes.ContainsKey(feedData.Id) ? _ourQuotes[feedData.Id] : feedData.Id select new AssetQuote { Id = assetName, Ask = feedData.Ask, Bid = feedData.Bid, DateTime = feedData.DateTime, }); _feed.Clear(); } if (result.Count > 0) _feedDatas?.Invoke(result.Where(itm => GlobalSettings.FinanceInstruments.ContainsKey(itm.Id)).ToArray()); }); }
public ActionResult StructPic(string id) { string path = Server.MapPath("~") + "/config/"; int pid = 0; int.TryParse(id, out pid); path = string.Format("{1}structPointConfig{0}.xml", pid, path); Plant plant = plantService.GetPlantInfoById(pid); List<StructPoint> points = new List<StructPoint>(); XmlHelper.DeserializerXML(path, ref points); List<StructPoint> tmppoints = new List<StructPoint>(); if (plant.isVirtualPlant) { foreach (Plant pnt in plant.childs) { StructPoint point = points.Where(m => m.id.Equals(pnt.id.ToString())).FirstOrDefault<StructPoint>(); if (point != null) tmppoints.Add(point); } points = tmppoints; XmlHelper.SerializerXML(path, points); } else { foreach (PlantUnit unit in plant.plantUnits) { StructPoint point = points.Where(m => m.id.Equals(unit.id.ToString())).FirstOrDefault<StructPoint>(); if (point != null) tmppoints.Add(point); } points = tmppoints; XmlHelper.SerializerXML(path, points); } foreach (StructPoint point in points) { if (plant.isVirtualPlant) { Plant tplant = PlantService.GetInstance().GetPlantInfoById(int.Parse(point.id)); point.displayName = tplant.name; } else { foreach (PlantUnit unit in plant.plantUnits) if (unit.id.Equals(int.Parse(point.id))) { point.displayName = unit.displayname; break; } } } ViewData["points"] = points; return View(plant); }
/// <summary> /// Обработчик приёма сообщения из сети /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected override void EventHandler_Connection_MessageReceived( object sender, EventArgs e) { IDataLinkPort port = (IDataLinkPort)sender; var messages = new List<MessageBase>(); // Читаем входящие сообщения из входного буфера порта while(port.MessagesToRead > 0) { var msg = port.Read(); messages.Add((MessageBase)msg); } // Обрабатываем сервисные сообщения var serviceErrorMessages = messages .Where(y => y.MessageType == MessageType.ServiceErrorMessage) .Select(z => (ServiceErrorMessage)z); foreach (var msg in serviceErrorMessages) { //запись в лог ошибок Logger.Error(String.Format("Controller Id={0} | Ошибка Code={1} | Description={2}", _Id, msg.Code, msg.Description)); //TODO: Сделать обработчик ошибок, если потребуется //switch (msg.SpecificErrorCode) //{ // case ErrorCode. //} } // TODO: сделать сервистные сообщения, если понадобятся //var serviceInfoMessages = messages // .Where(y => y.MessageType == MessageType.ServiceInfoMessage) // .Select(z => (....)); var dataMessages = messages .Where(y => y.MessageType == MessageType.IncomingMessage) .Select(z => (DataMessage)z).ToArray(); if (dataMessages.Length > 1) { throw new Exception( "Сетевой контроллер принял одновременно более одного сообщения из сети"); } if ((_currentNetworkRequest == null) || (_currentNetworkRequest.Status != NetworkRequestStatus.Running)) { throw new Exception("Принято сообщение в отсутствии запроса"); } // Обрабатывает сообщение _CurrentIncomingMessage = dataMessages[0]; _autoResetEventRequest.Set(); }
public ActionResult AssignArtifactList(ProjectDashboardPresenter presenter, string artifactType, string projectArtifactId, string nodeIndex) { var list = new List<ProcessComplianceListItem>(); if (presenter != null) { if (!string.IsNullOrEmpty(artifactType) && artifactType.Equals(Release, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(nodeIndex)) { list = presenter.ReleaseArtifactList.Where(a => a.NodeIndex == Convert.ToInt32(nodeIndex, CultureInfo.CurrentCulture)).SelectMany(a => a.Items).ToList(); list = list.Where(x => x.ProjectArtifactID != Convert.ToInt32(projectArtifactId, CultureInfo.CurrentCulture)).ToList(); } else if (!string.IsNullOrEmpty(artifactType) && artifactType.Equals(Project, StringComparison.OrdinalIgnoreCase)) { list = presenter.ProcessComplianceList.SelectMany(a => a.Items).ToList(); list = list.Where(x => x.ProjectArtifactID != Convert.ToInt32(projectArtifactId, CultureInfo.CurrentCulture)).ToList(); } } return this.Json(list, JsonRequestBehavior.AllowGet); }
/// <summary> /// Get result data and print to console out. /// </summary> /// <param name="groupId"></param> private static void GetResult(long groupId) { string[] unwantedStatuses = { "closed", "solved" }; string[] ticketTypes = {"problem", "incident"}; // Import first 100 tickets. var ticketPage = _api.Tickets.GetAllTickets(); _allTicketsInGroup = new List<Ticket>(); _allTicketsInGroup.AddRange(ticketPage.Tickets.Where(t => t.GroupId == groupId).ToList()); // If more than 100 exist, import the rest as well while (!string.IsNullOrEmpty(ticketPage.NextPage)) { ticketPage = _api.Tickets.GetByPageUrl<GroupTicketResponse>(ticketPage.NextPage); _allTicketsInGroup.AddRange(ticketPage.Tickets.Where(t => t.GroupId == groupId).ToList()); } _allOpenTicketsInGroup = _allTicketsInGroup.Where(t => t.Status != null && t.Type != null && !unwantedStatuses.Contains(t.Status.ToLower()) && ticketTypes.Contains(t.Type.ToLower())).ToList(); // Get number of open tickets GetNumOpenTicketsInGroup(); // Get number of unassigned tickets GetNumUnassignedTicketsInGroup(); // Get number of pending tickets GetNumPendingTicketsInGroup(); // Get number of "on-hold" tickets GetNumOnHOldTicketsInGroup(); // Get number of new tickets today GetNewTicketsToday(); // Get number of solved tickets today GetNumSolvedToday(); _xml.PrintXml(); }