public void ShowTrTimesReport() { if (bigShadow.Shadow == null) { bigShadow.ShowThis(new LoadingControl("Generating...")); bigShadow.ShadowUp(); } var dt = new DataTableEx(); ThreadPool.QueueUserWorkItem(o => { aex.Protect(() => { dt = OnGenerateTrTimesReport(dt); MasterModel.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate() { var cReport = new CountersReportControl("Tr. Times Report", manager, dt.Items); cReport.datagrid.ItemsSource = CollectionViewSource.GetDefaultView(dt.dt); cReport.btnClose.Click += (s_, e_) => bigShadow.ShadowDown(); bigShadow.ShowThis(cReport); })); }); }); }
public override DataTableEx getSubTable(int FromId, int lng) { //DataTableEx ret = null; DataTableEx DataCopy = CarTable.Copy(); if (lng * 2 > DataCopy.Rows.Count) { for (int i = FromId + lng; i < DataCopy.Rows.Count; i++) { DataCopy.Rows.RemoveAt(i); } for (int i = FromId - 1; i >= 0; i--) { DataCopy.Rows.RemoveAt(i); } return(DataCopy); } DataTableEx ret = DataCopy.Clone() as DataTableEx; for (int i = FromId; i < FromId + lng; i++) { ret.Rows.Add(DataCopy.Rows[i].ItemArray); } return(ret); }
public DataTable GetDataTable(string tblname) { tblname = ToLower(tblname); if (ExistRemotingTable(tblname)) { DataTableEx table = null; try { table = mDataTableRemoting.GetDataTable(tblname) as DataTableEx; table.SetCanWrite(true); } catch (Exception ex) { throw ex; } return(table); } else { string sql = "select * from " + tblname; sql = ConvertSqlString(tblname, sql); DataTable table = GetTableNotRemote(sql); return(table); } }
private void showReal() { var dr = DataTableEx.FindRowInTable(dataTable, unitCode, "КодЕИ"); if (dr != null) { showReal(dr); } }
private DataTableEx OnGenerateTrTimesReport(DataTableEx dt) { if (GenerateTrTimesReport != null) { var e = new EventArgs <DataTableEx, Dispatcher>(dt, MasterModel.Dispatcher); GenerateTrTimesReport(this, e); } return(dt); }
/// <summary> /// 加载数据表 /// </summary> /// <param name="conn">SQL连接</param> /// <param name="sql">SQL查询语句</param> private void LoadDataTable(SqlConnection conn, string sql) { mAdapter = new SqlDataAdapter(sql, conn); mAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey; mTable = new DataTableEx(); mAdapter.Fill(mTable); mTable.TableName = mTableName; mTableChanged = false; foreach (DataColumn column in mTable.Columns) { column.ReadOnly = false; } }
private void OnEnterToActTextbox(object obj, EventArgs e) { if (!actedLabel.Visible) { return; } bool cancel = false; if (!Number.IsNumber(actedTextBox.Text)) { cancel = true; } int count = Convert.ToInt32(actedTextBox.Text); var dr = DataTableEx.FindRowInTable(dataTable, unitCode, "КодЕИ"); if (((double)(dr["КоличествоЕдиницПоУмолчанию"])) <= count) { ShowMessage(string.Format("Введенное значение - {0} превышает допустимое - {1}", count, ((double)(dr["КоличествоЕдиницПоУмолчанию"])) - 1)); return; } cancel = count == 0; actedLabel.Hide(); actedTextBox.Hide(); uniqueCodeText = 0; if (cancel) { return; } var newR = dataTable.NewRow(); newR["КодЕИ"] = dr["КодЕИПоУмолчанию"]; newR["КодЕИПоУмолчанию"] = 0; newR["План"] = dr["КоличествоЕдиницПоУмолчанию"]; newR["Факт"] = System.Convert.ToInt32(newR["План"]) - count; newR["УникальныйНомер"] = unqueCode; newR["КоличествоЕдиницПоУмолчанию"] = 1; dataTable.Rows.InsertAt(newR, dataTable.Rows.IndexOf(dr) + 1); showReal(dr); }
public static void ConfigureGrid(XamDataGrid dataGrid, DataTableEx userTable, enumTimeDiscreteType discreteType, enumTypeInformation typeInformation, string format, bool isHalfhours, bool isCumulateDrums = false, bool isDateTimeGroupingGridControlXam = true, bool useBindedConverter = true) { if (dataGrid == null || userTable == null) { return; } var view = userTable.DefaultView; try { dataGrid.BeginInit(); dataGrid.FieldSettings.AllowEdit = false; view.AllowDelete = view.AllowEdit = view.AllowNew = false; //var style = new Style(typeof(XamNumericEditor)); //style.Setters.Add(new Setter(ValueEditor.FormatProperty, format)); if (isHalfhours) { SetHalfhoursColumnsForXamDataGrid(dataGrid, userTable, discreteType, typeInformation, format, isCumulateDrums, isDateTimeGroupingGridControlXam, useBindedConverter); } else { SetValidateColumnsForXamDataGrid(dataGrid, userTable); } //view.Table = null; } finally { dataGrid.DataSource = view; dataGrid.EndInit(); } //dataGrid.Dispatcher.BeginInvoke((System.Action) (() => //{ //}), DispatcherPriority.Background); }
public override List <ChanceClass> getChances(BaseCollection sc, ExpectData ed) { List <ChanceClass> ret = new List <ChanceClass>(); if (sc == null || sc.Table == null || sc.Table.Rows.Count < this.ReviewExpectCnt) { return(ret); } DataTableEx dt = sc.CarTable; if (dt == null) { throw new Exception("无法获得概率分布表!"); } //Log("最后一期数据", string.Join(",", dt.Rows[0].ItemArray)); //Log("最后二期数据", string.Join(",", dt.Rows[1].ItemArray)); string val = dt.Rows[dt.Rows.Count - 1][string.Format("{0}", InputMinTimes)].ToString(); OnceChance cc = new OnceChance(); cc.SignExpectNo = ed.Expect; cc.ChanceType = 1; string code_model = "{0}/{1}"; HoldCnt++; cc.ChanceCode = BySer ? string.Format(code_model, InputMaxTimes, val) : string.Format(code_model, val, InputMaxTimes); cc.ChipCount = 1;//码数必须是实际码数,使用的金额队列必须是1码的队列 cc.InputTimes = HoldCnt; cc.strInputTimes = string.Format("{0}", cc.InputTimes); cc.AllowMaxHoldTimeCnt = 1; cc.InputExpect = ed; cc.StragId = this.GUID; cc.NeedConditionEnd = true;//这是必须的,才能在整体回测中触发CheckNeedEndTheChance //cc.MinWinRate = this.CommSetting.GetGlobalSetting().DefaultHoldAmtSerials.MaxRates[cc.ChipCount - 1]; cc.IsTracer = 0; cc.Odds = this.CommSetting.GetGlobalSetting().Odds; //cc.UnitCost = this.getChipAmount(0,cc,); ret.Add(cc); return(ret); }
DataTableEx GetDistribTable() { DataTableEx ret = new DataTableEx(); ret.Columns.Add("Id", typeof(int)); if (true) { //ret = new DataTable(); if (isByNo) { for (int i = 0; i < 10; i++) { ret.Columns.Add(string.Format("{0}", (i + 1) % 10)); } } else { for (int i = 1; i < 10; i++) { ret.Columns.Add(i.ToString()); } ret.Columns.Add("0"); } for (int i = 0; i < 10; i++) //10*10的表 { DataRow dr = ret.NewRow(); dr["Id"] = (i + 1) % 10; ret.Rows.Add(dr); } for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { ret.Rows[(i + 1) % 10][j.ToString()] = this.CarTable.Select(string.Format("[{0}]={1}", (i + 1) % 10, j)).Length; } } return(ret); } }
private void OnUniqueCode() { var existDr = DataTableEx.FindRowInTable(dataTable, unqueCode, "УникальныйНомер"); if (existDr != null) { if (ShowQuery(string.Format("Удалить паллету из прихода (уникальный код = {0})?", unqueCode))) { var dr = DataTableEx.FindRowInTable(dataTable, unitCode, "КодЕИ"); dataTable.Rows.Remove(existDr); showReal(dr); } return; } uniqueCodeText = unqueCode; actedLabel.Show(); actedTextBox.Text = "1"; actedTextBox.Show(); actedTextBox.SelectionStart = 0; actedTextBox.SelectionLength = 1; actedTextBox.Focus(); }
public DataTable GetDataTableWithSql(string[] tblnames, string sql) { tblnames = ToLower(tblnames); sql = ToLower(sql); if (ExistRemotingTable(tblnames[0])) { DataTableEx table = null; try { table = mDataTableRemoting.GetDataTableWithSql(tblnames, sql) as DataTableEx; table.SetCanWrite(false); } catch (Exception ex) { throw ex; } return(table); } else { DataTable table = GetTableNotRemote(sql); return(table); } }
public static void ConfigureGridDailyIntegrals(XamDataGrid dataGrid, DataTableEx userTable, bool useLossesCoefficient) { if (dataGrid == null || userTable == null) { return; } try { var labelStyle = dataGrid.FindResource("LabelObjectStyle") as Style; dataGrid.FieldSettings.LabelPresenterStyle = labelStyle; } catch { } var view = userTable.DefaultView; #if DEBUG var sw = new System.Diagnostics.Stopwatch(); sw.Start(); #endif try { var hierObjectStyle = dataGrid.FindResource("HierObjectStyle") as Style; var chTemplate = dataGrid.FindResource("ChannelTemplate") as DataTemplate; var fValueStyle = dataGrid.FindResource("FValueStyle") as Style; var fValueNoFlagStyle = dataGrid.FindResource("FValueNoFlagStyle") as Style; var widthValue = new FieldLength(105); dataGrid.BeginInit(); var fieldLayout = dataGrid.FieldLayouts[0]; var fields = fieldLayout.Fields; try { fields.BeginUpdate(); #region Создаем основные колонки var comparer = new IFreeHierarchyObjectComparer(); fields.Add(new Field { Name = "Parent", DataType = typeof(IFreeHierarchyObject), Label = "Объект", Width = new FieldLength(160), AllowFixing = AllowFieldFixing.Near, //FixedLocation = FixedFieldLocation.FixedToNearEdge, Settings = { //GroupByMode = FieldGroupByMode.Value, AllowGroupBy = true, GroupByComparer = comparer, SortComparer = comparer, FilterComparer = comparer, CellVisibilityWhenGrouped = Visibility.Collapsed, FilterOperandUIType = FilterOperandUIType.DropDownList, AllowFixing = AllowFieldFixing.Near, AllowEdit = false, EditorStyle = null, AllowRecordFiltering = true, CellValuePresenterStyle = hierObjectStyle, }, HorizontalContentAlignment = HorizontalAlignment.Left, VerticalContentAlignment = VerticalAlignment.Center, }); fields.Add(new Field { Name = "NameTI", DataType = typeof(IFreeHierarchyObject), Label = "ТИ", Width = new FieldLength(200), AllowFixing = AllowFieldFixing.Near, //FixedLocation = FixedFieldLocation.FixedToNearEdge, Settings = { AllowGroupBy = true, GroupByComparer = comparer, SortComparer = comparer, FilterComparer = comparer, CellVisibilityWhenGrouped = Visibility.Collapsed, FilterOperandUIType = FilterOperandUIType.DropDownList, AllowFixing = AllowFieldFixing.Near, AllowEdit = false, EditorStyle = null, AllowRecordFiltering = true, CellValuePresenterStyle = hierObjectStyle, }, HorizontalContentAlignment = HorizontalAlignment.Left, VerticalContentAlignment = VerticalAlignment.Center, }); fields.Add(new TemplateField { Name = "Channel", Label = "К", DataType = typeof(object), DisplayTemplate = chTemplate, Width = new FieldLength(40), AllowFixing = AllowFieldFixing.Near, //FixedLocation = FixedFieldLocation.FixedToNearEdge, Settings = { AllowGroupBy = true, FilterOperandUIType = FilterOperandUIType.DropDownList, AllowFixing = AllowFieldFixing.Near, AllowEdit = false, EditorStyle = null, AllowRecordFiltering = true, }, }); fieldLayout.Fields.Add(new Field { Name = "DataSource", Label = "Источник данных", Width = new FieldLength(100), AllowFixing = AllowFieldFixing.Near, Settings = { AllowGroupBy = true, FilterOperandUIType = FilterOperandUIType.DropDownList, AllowFixing = AllowFieldFixing.Near, AllowEdit = false, EditorStyle = null, AllowRecordFiltering = true, }, }); fields.Add(new Field { Name = "Coeff", DataType = typeof(double), Width = widthValue, Label = "Коэфф. тр.", Format = "#0", AllowFixing = AllowFieldFixing.Near, Settings = { AllowGroupBy = true, AutoSizeOptions = FieldAutoSizeOptions.None, Width = widthValue, SummaryUIType = SummaryUIType.MultiSelect, AllowEdit = false, EditorStyle = null, FilterOperandUIType = FilterOperandUIType.Combo, AllowRecordFiltering = true, }, HorizontalContentAlignment = HorizontalAlignment.Right, VerticalContentAlignment = VerticalAlignment.Center, }); if (useLossesCoefficient) { fields.Add(new Field { Name = "CoeffLosses", DataType = typeof(double), Width = widthValue, Label = "Коэфф. потерь", Format = "#0.###", AllowFixing = AllowFieldFixing.Near, Settings = { AllowGroupBy = true, AutoSizeOptions = FieldAutoSizeOptions.None, Width = widthValue, SummaryUIType = SummaryUIType.MultiSelect, AllowEdit = false, EditorStyle = null, FilterOperandUIType = FilterOperandUIType.Combo, AllowRecordFiltering = true, }, HorizontalContentAlignment = HorizontalAlignment.Right, VerticalContentAlignment = VerticalAlignment.Center, }); } #endregion #region Посуточные колонки var counter = 0; FieldGroup fieldGroup = null; foreach (var col in userTable.Columns.OfType <DataColumnEx>()) { if (col == null) { continue; } if (counter == 0) { fieldGroup = new FieldGroup { Label = col.GroupName, }; fieldLayout.FieldItems.Add(fieldGroup); } var fld = AddFValueField(col.ColumnName, col.DataType, widthValue, col.IsFValue ? fValueStyle : fValueNoFlagStyle, null); fld.Label = col.Caption; //if (!col.IsFValue) //{ // fld.Format = "##0.######"; //} fieldGroup.Children.Add(fld); if (++counter == 3) { counter = 0; } } #endregion } finally { fieldLayout.Fields.EndUpdate(); } dataGrid.RecordsInViewChanged += ExpandFirstRecord; } finally { dataGrid.DataSource = view; dataGrid.EndInit(); } #if DEBUG sw.Stop(); Console.WriteLine("ConfigureGridDailyIntegrals - > {0} млс", sw.ElapsedMilliseconds); #endif }
public override List <ChanceClass> getChances(BaseCollection sc, ExpectData ed) { List <ChanceClass> ret = new List <ChanceClass>(); DataTableEx dt = null; if (this.BySer) { dt = sc.SerialDistributionTable; } else { dt = sc.CarDistributionTable; } if (dt == null) { throw new Exception("无法获得概率分布表!"); } int MatchCnt = 0; string strAllCodes = ""; double MinSucRate = 0; if (this.FixChipCnt) { MinSucRate = this.CommSetting.Odds / this.ChipCount; //指定注数需要的最小胜率 } for (int i = 0; i < 10; i++) { //获得各项的最小的 List <double> coldata = null; string strCol = string.Format("{0}", (i + 1) % 10); string strVal = ed.ValueList[i]; int ExistCnt = sc.FindLastDataExistCount(this.InputMinTimes, strCol, strVal); if (ExistCnt > 1)//前n次不是最后一次才出现 { continue; } dt.getColumnData(strCol, ref coldata); double avgval = coldata.Average(); double stdval = ProbMath.CalculateStdDev(coldata); string strSql = string.Format("[{0}]={1}", "Id", strVal); string strSort = string.Format("[{0}] asc", "Id"); DataRow[] drs = dt.Select(strSql, ""); if (drs.Length != 1) { throw new Exception("概率数据表错乱!"); } int InAllViewExistCnt = int.Parse(drs[0][strCol].ToString()); //前100(指定的viewcnt)期出现的次数 if (InAllViewExistCnt > avgval - stdval * this.StdvCnt) //如果前100期内出现的概率大于指定的标准差数,跳过 { continue; } if (InAllViewExistCnt > this.ReviewExpectCnt * (1 - MinSucRate))//如果成功数小于对应注数的失败数 { continue; } string strCode = string.Format("{0}/{1}", BySer ? strCol : strVal, BySer ? strVal : strCol); MatchCnt++; strAllCodes = string.Format("{0}{1}{2}", strAllCodes, MatchCnt > 1 ? "+" : "", strCode); } if (MatchCnt < this.ChipCount) { return(ret); } ChanceClass cc = new ChanceClass(); cc.SignExpectNo = ed.Expect; cc.ChanceType = 3; cc.InputTimes = 1; cc.strInputTimes = "1"; cc.AllowMaxHoldTimeCnt = 1; cc.InputExpect = ed; cc.ChipCount = MatchCnt; cc.ChanceCode = strAllCodes; cc.CreateTime = ed.OpenTime; cc.NeedConditionEnd = true; cc.OnCheckTheChance += CheckNeedEndTheChance; cc.Closed = false; ret.Add(cc); return(ret); }
static void SetValidateColumnsForXamDataGrid(XamDataGrid dataGrid, DataTableEx userTable) { var hierObjectStyle = dataGrid.FindResource("HierObjectStyle") as Style; var hTemplate = dataGrid.FindResource("HierarchyObjectTemplate") as DataTemplate; var chTemplate = dataGrid.FindResource("ChannelTemplate") as DataTemplate; var fFlagStyle = dataGrid.FindResource("FFlagStyle") as Style; dataGrid.FieldSettings.LabelPresenterStyle = dataGrid.FindResource("ValidLabelStyle") as Style; // dataGrid.BeginInit(); //var leftHorizontalStyle = dataGrid.FindResource("FastHorizontalLeftCellValuePresenterStyle") as Style; var fieldLayout = dataGrid.FieldLayouts[0]; var fields = fieldLayout.Fields; //var field = fieldLayout.Fields["NameTI"] as TemplateField; try { fields.BeginUpdate(); #region Вспомогательные поля var comparer = new IFreeHierarchyObjectComparer(); var tiFld = new Field { Name = "NameTI", DataType = typeof(IFreeHierarchyObject), Label = "Объект", Width = new FieldLength(200), FixedLocation = FixedFieldLocation.FixedToNearEdge, //FixedLocation = FixedFieldLocation.FixedToNearEdge, Settings = { AllowGroupBy = true, GroupByComparer = comparer, SortComparer = comparer, FilterComparer = comparer, CellVisibilityWhenGrouped = Visibility.Collapsed, FilterOperandUIType = FilterOperandUIType.DropDownList, AllowFixing = AllowFieldFixing.Near, AllowEdit = false, EditorStyle = null, AllowRecordFiltering = true, CellValuePresenterStyle = hierObjectStyle, }, HorizontalContentAlignment = System.Windows.HorizontalAlignment.Left, VerticalContentAlignment = VerticalAlignment.Center, }; //if (leftHorizontalStyle != null) //{ // //Это // tiFld.Settings.CellValuePresenterStyle = leftHorizontalStyle; //} fields.Add(tiFld); fields.Add(new TemplateField { Name = "Channel", Label = "К", DataType = typeof(object), DisplayTemplate = chTemplate, Width = new FieldLength(30), FixedLocation = FixedFieldLocation.FixedToNearEdge, Settings = { FilterOperandUIType = FilterOperandUIType.None, AllowFixing = AllowFieldFixing.Near, AllowEdit = false, EditorStyle = null, }, }); //fieldLayout.Fields.Add(new TemplateField //{ // Name = "DataSource", // Label = "Источник данных", // Width = new FieldLength(130), //}); var fld = new Field { Name = "Parent", DataType = typeof(IFreeHierarchyObject), Label = "Родитель", Width = new FieldLength(160), AllowFixing = AllowFieldFixing.Near, //FixedLocation = FixedFieldLocation.FixedToNearEdge, Settings = { //GroupByMode = FieldGroupByMode.Value, AllowGroupBy = true, GroupByComparer = comparer, SortComparer = comparer, FilterComparer = comparer, CellVisibilityWhenGrouped = Visibility.Collapsed, FilterOperandUIType = FilterOperandUIType.DropDownList, AllowFixing = AllowFieldFixing.Near, AllowEdit = false, EditorStyle = null, AllowRecordFiltering = true, CellValuePresenterStyle = hierObjectStyle, }, HorizontalContentAlignment = System.Windows.HorizontalAlignment.Left, VerticalContentAlignment = VerticalAlignment.Center, }; fields.Add(fld); var fsd = new FieldSortDescription("Parent", ListSortDirection.Ascending, true); fieldLayout.SortedFields.Add(fsd); #endregion // var flagStyle = XamDataGridHelper.DataTemplateSelectorToCellEditorStyle(flagTemplateSelector, null); var width = new FieldLength(32); var height = new FieldLength(20); foreach (DataColumn col in userTable.Columns) { //var column = fieldLayout.Fields.FirstOrDefault(c => string.Equals(c.Name, "Valid" + i)) as TemplateField; //if (column == null) return; var isValid = col.ColumnName.IndexOf("Valid") >= 0; if (isValid || col.ColumnName.IndexOf("TotalFlag") >= 0) { fields.Add(new Field { Name = col.ColumnName, DataType = col.DataType, ToolTip = col.Caption, Label = col.Caption, Visibility = isValid ? Visibility.Visible : Visibility.Collapsed, Width = width, Height = height, AllowFixing = AllowFieldFixing.No, AllowResize = false, Settings = { SummaryUIType = SummaryUIType.MultiSelect, FilterOperandUIType = FilterOperandUIType.Combo, FilterOperatorDropDownItems = ComparisonOperatorFlags.None, CellValuePresenterStyle = fFlagStyle, AllowEdit = false, AllowRecordFiltering = true, //CellValuePresenterStyle = fFlagStyle, }, }); } } } finally { fieldLayout.Fields.EndUpdate(); } //XamDataGridHelper.ConfigureGrid(dataGrid, false, true, false, true, false); // раскрываем первую группу dataGrid.RecordsInViewChanged += ExpandFirstRecord; }
static void SetHalfhoursColumnsForXamDataGrid(XamDataGrid dataGrid, DataTableEx userTable, enumTimeDiscreteType discreteType, enumTypeInformation typeInformation, string format, bool isCumulateDrums , bool isDateTimeGroupingGridControlXam, bool useBindedConverter) { //var nameStyle = dataGrid.FindResource("TIChanelName") as Style; ////Style labelStyle = null; try { var labelStyle = dataGrid.FindResource("LabelObjectStyle") as Style; dataGrid.FieldSettings.LabelPresenterStyle = labelStyle; } catch { } //var vTemplate = dataGrid.FindResource("FValueTemplate") as DataTemplate; var fValueNoBindMeasureStyle = dataGrid.FindResource("FValueNoBindMeasureStyle") as Style; var vFreeHierarchyObjectTemplate = Application.Current.FindResource("FreeHierarchyObjectTemlate") as DataTemplate; var fValueStyle = useBindedConverter ? dataGrid.FindResource("FValueStyle") as Style : fValueNoBindMeasureStyle; var widthValue = new FieldLength(105); var widthFreeHier = new FieldLength(270); var comparer = new IFValueComparer(); var measure = dataGrid.FindParent <IMeasure>(); dataGrid.Resources["IMeasure"] = measure; //var fConverter = new FValueConverter //{ // FParameter = new FValueParameter // { // Measure = measure, // } //}; var fieldLayout = dataGrid.FieldLayouts[0]; var fields = fieldLayout.Fields; try { fields.BeginUpdate(); //fieldLayout.SortedFields.BeginUpdate(); var dtCol = userTable.Columns["EventDateTime"]; var dtField = new TemplateField { Name = dtCol.ColumnName, DataType = dtCol.DataType, Label = dtCol.Caption, Width = new FieldLength(95), AllowFixing = AllowFieldFixing.Default, FixedLocation = FixedFieldLocation.FixedToNearEdge, Settings = { LabelPresenterStyle = dataGrid.FindResource("TimeStyle") as Style } }; fields.Add(dtField); if (isCumulateDrums) { //dtField.Settings.CellValuePresenterStyle = // XamDataGridHelper.DataTemplateToCellValuePresenterStyle(ConstantHelper.DateTimeTemplateName); dtField.DisplayTemplate = Application.Current.Resources[ConstantHelper.DateTimeTemplateName] as DataTemplate; } else { string dataTemplateToCellValuePresenterStyleName; //------------------------------- switch (discreteType) { case enumTimeDiscreteType.DBHalfHours: dataTemplateToCellValuePresenterStyleName = ConstantHelper.HalfHourstoRangeTimeTemplateName; break; case enumTimeDiscreteType.DBHours: dataTemplateToCellValuePresenterStyleName = ConstantHelper.HourstoRangeTimeTemplateName; break; case enumTimeDiscreteType.DB24Hour: dataTemplateToCellValuePresenterStyleName = ConstantHelper.DateTemplateName; break; case enumTimeDiscreteType.DBMonth: dataTemplateToCellValuePresenterStyleName = ConstantHelper.MonthName; break; default: dataTemplateToCellValuePresenterStyleName = ConstantHelper.DateTimeTemplateName; break; } dtField.Tag = dataTemplateToCellValuePresenterStyleName; //Это нужно для форматирования при выгрузке в Excel dtField.DisplayTemplate = Application.Current.Resources[dataTemplateToCellValuePresenterStyleName] as DataTemplate; //dtField.Settings.CellValuePresenterStyle = // XamDataGridHelper.DataTemplateToCellValuePresenterStyle( // dataTemplateToCellValuePresenterStyleName); } dtField.Label = "Время"; if (discreteType == enumTimeDiscreteType.DB24Hour) { dtField.Settings.GroupByMode = FieldGroupByMode.Month; dtField.Settings.GroupByRecordPresenterStyle = Application.Current.FindResource("MonthYearXamDataGridStyle") as Style; } else { dtField.Settings.GroupByMode = FieldGroupByMode.Date; } SummaryCalculator statType; string prefix; if (typeInformation == enumTypeInformation.Power) { statType = new FValueAvgCalculator(format); prefix = "Сред:"; } else { statType = new FValueSumCalculator(format); prefix = "Сум:"; } var stringFormat = prefix + " {0:" + format + "}"; var dfc = new DetailFieldInfoEqualityComparer(); //FieldGroup fieldGroupByObject = null; //FieldGroup fieldGroupByMeasureCategory = null; //EnumMeasureUnitCategory? previousMeasureCategory = null; //Для определения групповать или нет по категории foreach (var colGroupByObject in userTable.Columns .Cast <DataColumn>() .Where(c => c.ColumnName != "EventDateTime") .Select(c => { DetailFieldInfo fieldInfo; userTable.TryGetIndexByItemName(c.ColumnName, out fieldInfo); return(new Tuple <DetailFieldInfo, DataColumn>(fieldInfo, c)); }) .GroupBy(c => c.Item1, dfc)) { if (colGroupByObject.Key == null || (colGroupByObject.Key.ChannelType == 0 && colGroupByObject.Key.ColumnType == EnumColumnType.None)) { //Группировать не нужно foreach (var colByObject in colGroupByObject) { DetailFieldInfo fieldInfo; userTable.ItemsIndexesDict.TryGetValue(colByObject.Item2.ColumnName, out fieldInfo); SummaryDefinition summaryDefinition; var fld = AddFieldAndSummary(colByObject.Item2, widthValue, comparer, fieldInfo != null && fieldInfo.UseMeasureModule, isCumulateDrums, statType, stringFormat, out summaryDefinition, fValueStyle); fld.Label = fieldInfo == null ? colByObject.Item2.Caption : (object)colByObject.Item1; fields.Add(fld); if (summaryDefinition != null) { fieldLayout.SummaryDefinitions.Add(summaryDefinition); } } } //else if () //{ // //Группируем по типу // foreach (var colByObjectByColumnType in colGroupByObject.GroupBy(c => c.Item1.ColumnType)) // { // foreach (var colByObject in colByObjectByColumnType) // { // DetailFieldInfo fieldInfo; // if (!userTable.ItemsIndexesDict.TryGetValue(colByObject.Item2.ColumnName, out fieldInfo)) continue; // FValueSummaryDefinition summaryDefinition; // var fld = AddFieldAndSummary(colByObject.Item2, widthValue, comparer, fieldInfo != null && fieldInfo.UseMeasureModule, // isCumulateDrums, statType, stringFormat, out summaryDefinition, fValueStyle); // fld.Label = fieldInfo == null ? colByObject.Item2.Caption : (object)colByObject.Item1; // fields.Add(fld); // if (summaryDefinition != null) // { // fieldLayout.SummaryDefinitions.Add(summaryDefinition); // } // } // } //} else { var fieldInfo = colGroupByObject.Key; var fieldGroupByObject = new FieldGroup { Label = fieldInfo.Id, }; fieldLayout.FieldItems.Add(fieldGroupByObject); //Группируем по ед.измерения foreach (var colGroupByMeasureCategory in colGroupByObject.GroupBy(c => c.Item1.MeasureUnitUn.SubstringQuantityUn())) { var colGroupByMeasureCategoryList = colGroupByMeasureCategory.ToList(); if (!string.IsNullOrEmpty(colGroupByMeasureCategory.Key) && colGroupByMeasureCategoryList.Count > 1) { //Есть категории ед. измерения и их несколько var fieldGroupByMeasureCategory = new FieldGroup { Label = new LabelMeasureQuantity { MeasureQuantityType_UN = colGroupByMeasureCategory.Key, }, }; fieldGroupByObject.Children.Add(fieldGroupByMeasureCategory); foreach (var colByMeasure in colGroupByMeasureCategoryList) { SummaryDefinition summaryDefinition; var fld = AddFieldAndSummary(colByMeasure.Item2, widthValue, comparer, fieldInfo.UseMeasureModule, isCumulateDrums, statType, stringFormat, out summaryDefinition, fValueStyle); fld.Label = colByMeasure.Item1; fieldGroupByMeasureCategory.Children.Add(fld); if (summaryDefinition != null) { fieldLayout.SummaryDefinitions.Add(summaryDefinition); } } } else { var fielgGroupByReplacedTiDict = new Dictionary <string, FieldGroup>(); //Нет категорий, или она одна foreach (var colByMeasure in colGroupByMeasureCategoryList) { if (colByMeasure.Item2.ColumnName.StartsWith("ovInfo")) { var hoc = new HierObjectsConverterComparer(); //var fld = AddField(colByMeasure.Item2, widthFreeHier, hoc, fieldInfo.UseMeasureModule, // vFreeHierarchyObjectTemplate, // vFreeHierarchyObjectTemplate, new HierObjectsConverter(), null); var fld = new TemplateField { Name = colByMeasure.Item2.ColumnName, DataType = colByMeasure.Item2.DataType, Width = widthFreeHier, AllowFixing = AllowFieldFixing.No, DisplayTemplate = vFreeHierarchyObjectTemplate, Settings = { AutoSizeOptions = FieldAutoSizeOptions.None, Width = widthFreeHier, SummaryUIType = SummaryUIType.MultiSelect, FilterComparer = hoc, FilterOperandUIType = FilterOperandUIType.Combo, AllowRecordFiltering = true, }, HorizontalContentAlignment = HorizontalAlignment.Stretch, VerticalContentAlignment = VerticalAlignment.Stretch, }; fld.Label = "Замещаемые ТИ"; fld.Settings.FilterOperandUIType = FilterOperandUIType.DropDownList; fld.Settings.FilterLabelIconDropDownType = FilterLabelIconDropDownType.MultiSelectExcelStyle; fld.Settings.GroupByComparer = hoc; //fld.ValueToTextConverter = new HierObjectsConverter(); fld.Settings.FilterComparer = new HierObjectsConverterComparer(); fieldGroupByObject.Children.Add(fld); } else { FieldGroup fielgGroupByReplacedTi = null; //Группируем по замещаемой ТИ if (colByMeasure.Item2.ColumnName.StartsWith("ovValue") && !fielgGroupByReplacedTiDict.TryGetValue( colByMeasure.Item1.GroupByReplacedTiName, out fielgGroupByReplacedTi)) { fielgGroupByReplacedTi = new FieldGroup { Label = colByMeasure.Item1.ReplacedId, }; fielgGroupByReplacedTiDict[colByMeasure.Item1.GroupByReplacedTiName] = fielgGroupByReplacedTi; } SummaryDefinition summaryDefinition; Field fld; if (!string.IsNullOrEmpty(colByMeasure.Item1.MeasureUnitUn) && colByMeasure.Item1.MeasureUnitUn.IndexOf("RatioUnit") > -1) { //Это %, нужно усреднять fld = AddFieldAndSummary(colByMeasure.Item2, widthValue, comparer, colByMeasure.Item1.UseMeasureModule, isCumulateDrums, new FValueAvgCalculator(format), "Сред: {0:" + format + "}", out summaryDefinition, fValueNoBindMeasureStyle); } else { fld = AddFieldAndSummary(colByMeasure.Item2, widthValue, comparer, useBindedConverter && colByMeasure.Item1.UseMeasureModule, isCumulateDrums, statType, stringFormat, out summaryDefinition, fValueStyle); } fld.Label = colByMeasure.Item1; if (fielgGroupByReplacedTi != null) { fielgGroupByReplacedTi.Children.Add(fld); } else { fieldGroupByObject.Children.Add(fld); } if (summaryDefinition != null) { fieldLayout.SummaryDefinitions.Add(summaryDefinition); } if (colByMeasure.Item1.IsOv) { //Если это ОВ, добавляем суммарную информацию о неразнесенных значениях var unWritedOvs = new FValueSummaryDefinition { SourceFieldName = colByMeasure.Item2.ColumnName, Calculator = new FValueSumUnreplacedCalculator(format), StringFormat = stringFormat, UseMeasureModule = fieldInfo.UseMeasureModule, }; fieldLayout.SummaryDefinitions.Add(unWritedOvs); } } } if (fielgGroupByReplacedTiDict.Count > 0) { fieldGroupByObject.Children.AddRange(fielgGroupByReplacedTiDict.Values); } } } } } if (isDateTimeGroupingGridControlXam) { //dtField.Settings.AllowSummaries = false; dtField.Settings.AllowGroupBy = true; fieldLayout.SortedFields.Add(new FieldSortDescription("EventDateTime", ListSortDirection.Ascending, true)); } else if (discreteType != enumTimeDiscreteType.DBMonth && discreteType != enumTimeDiscreteType.DB24Hour) { dtField.DisplayTemplate = Application.Current.Resources[ConstantHelper.DateTimeTemplateName] as DataTemplate; } //var consumptionScheduleField = fields.FirstOrDefault(ff => ff.Name == "ConsumptionSchedule"); //if (consumptionScheduleField != null) //{ // consumptionScheduleField.Label = "Тип. потр."; //} //var consumptionSchedulePercentField = fields.FirstOrDefault(ff => ff.Name == "ConsumptionSchedulePercent"); //if (consumptionSchedulePercentField != null) //{ // consumptionSchedulePercentField.Label = "Тип. потр. %"; //} } finally { // fieldLayout.SortedFields.EndUpdate(); fields.EndUpdate(); } //XamDataGridHelper.ConfigureGrid(dataGrid, true, false, true, true, true); dataGrid.FieldLayoutSettings.FixedFieldUIType = FixedFieldUIType.Splitter; dataGrid.FieldSettings.SummaryDisplayArea = SummaryDisplayAreas.BottomFixed; if (userTable.Columns.Count < 20) { //из-за того что тормоза ограничиваем //dataGrid.FieldSettings.SummaryDisplayArea = dataGrid.FieldSettings.SummaryDisplayArea | SummaryDisplayAreas.InGroupByRecords; } if (userTable.Columns.Count < 1000) { dataGrid.RecordsInViewChanged += ExpandFirstRecord; } }
public override List <ChanceClass> getChances(BaseCollection sc, ExpectData ed) { List <ChanceClass> ret = new List <ChanceClass>(); CurrChancesCnt = 0;//置零,防止后面留存 ExpectList LastDataList = this.LastUseData(); if (LastDataList == null) { Log(this.StragClassName, "数据为空!"); return(ret); } if (LastDataList.Count < ReviewExpectCnt) { Log("基础数据数量不足", string.Format("小于回览期数:{0}", ReviewExpectCnt)); return(ret); } //ExpectList LastDataList = datas; ExpectData PreData = LastDataList[LastDataList.Count - 2]; //Log(string.Format("前期{0}:{1}", PreData.Expect, PreData.OpenCode), string.Format("当期{0}:{1}", LastDataList.LastData.Expect, LastDataList.LastData.OpenCode)); //Log(string.Format("el数据长度:{0},First:{1};Last{2}", LastDataList.Count,LastDataList.FirstData.Expect,LastDataList.LastData.Expect), string.Format("原始数据长度:{0};First:{1};Last:{2}", sc.orgData.Count,sc.orgData.FirstData.Expect,sc.orgData.LastData.Expect)); DataTableEx dt = sc.getSubTable(sc.orgData.Count - this.ReviewExpectCnt, this.ReviewExpectCnt); List <string> strCodes = new List <string>(); for (int i = 0; i < 10; i++)//遍历每个车号/名次 { List <int> coldata = null; string strCol = string.Format("{0}", (i + 1) % 10); dt.getColumnData(strCol, ref coldata); //Log(string.Format("车/次:{0}",strCol), string.Format("取得的数据:{0}",string.Join(",",coldata))); int RepeatCnt = 0; for (int j = 1; j < ReviewExpectCnt; j++) { if (coldata[j] == coldata[j - 1]) { RepeatCnt++; } } if (RepeatCnt < this.ReviewExpectCnt - 1)//如果重复次数小于回顾次数减一,表示重复次数不够,跳过 { continue; } string strCode = "";//其实无需比较,对单个车/名次来说,矩阵都一样,策略只需建立一个即可 strCode = string.Format("{0}/{1}", strCol, coldata[0]); //Log(string.Format("车/次:{0}", strCol), strCode); strCodes.Add(strCode); if (HoldCnt >= 0) //当持有次数超过指定次数后,不再增加 { HoldCnt++; //持有次数加1 } //Log("获得机会处理", string.Format("当前持有次数:{0}", HoldCnt)); RealCnt++; } if (strCodes.Count == 0)//机会数为0 { return(ret); } if (!GetRev) { OnceChance cc = new OnceChance(); cc.SignExpectNo = ed.Expect; cc.ChanceType = 1; cc.ChanceCode = string.Join("+", strCodes); cc.ChipCount = strCodes.Count;//码数必须是实际码数,使用的金额队列必须是1码的队列 cc.InputTimes = RealCnt; cc.strInputTimes = string.Format("{0}", cc.InputTimes); cc.AllowMaxHoldTimeCnt = 1; cc.InputExpect = ed; cc.NeedConditionEnd = true; cc.StragId = this.GUID; //cc.MinWinRate = this.CommSetting.GetGlobalSetting().DefaultHoldAmtSerials.MaxRates[cc.ChipCount - 1]; cc.IsTracer = 0; cc.Odds = this.CommSetting.GetGlobalSetting().Odds; CurrChancesCnt = strCodes.Count; //cc.UnitCost = this.getChipAmount(0,cc,); ret.Add(cc); //获得所有机会后,统一为本次机会分配资金 return(ret); } else { for (int i = 0; i < strCodes.Count; i++) { NolimitTraceChance cc = new NolimitTraceChance(); cc.SignExpectNo = ed.Expect; cc.ChanceType = 1; cc.ChanceCode = ChanceClass.getRevChance(strCodes[i]); cc.ChipCount = 9;//码数必须是实际码数,使用的金额队列必须是1码的队列 cc.InputTimes = RealCnt; cc.strInputTimes = string.Format("{0}", cc.InputTimes); cc.AllowMaxHoldTimeCnt = 1; cc.InputExpect = ed; cc.StragId = this.GUID; //cc.MinWinRate = this.CommSetting.GetGlobalSetting().DefaultHoldAmtSerials.MaxRates[cc.ChipCount - 1]; cc.IsTracer = 1; cc.Odds = this.CommSetting.GetGlobalSetting().Odds; CurrChancesCnt = strCodes.Count; //cc.UnitCost = this.getChipAmount(0,cc,); ret.Add(cc); } return(ret); } }
static void SetHalfhoursColumnsForXamDataGrid(XamGrid dataGrid, DataTableEx userTable, enumTimeDiscreteType discreteType, enumTypeInformation typeInformation, string format, bool isCumulateDrums, bool isDateTimeGroupingGridControlXam) { //var nameStyle = dataGrid.FindResource("TIChanelName") as Style; Style labelStyle = null; //try //{ // labelStyle = dataGrid.FindResource("LabelObjectStyle") as Style; // dataGrid.FieldSettings.LabelPresenterStyle = labelStyle; //} //catch //{ //} var groupLabelTemplate = dataGrid.FindResource("GroupLabelObjectTemplate") as DataTemplate; var channelLabelTemplate = dataGrid.FindResource("ChannelLabelObjectTemplate") as DataTemplate; var unchannelLabelTemplate = dataGrid.FindResource("LabelUnchannelTemplate") as DataTemplate; var vTemplate = dataGrid.FindResource("FValueTemplate") as DataTemplate; var vTemplateNoBindMeasure = Application.Current.FindResource("FValueTemplateNoBindMeasureFormTemplate") as DataTemplate; var vFreeHierarchyObjectTemplate = Application.Current.FindResource("FreeHierarchyObjectTemlate") as DataTemplate; var columnWidth = new ColumnWidth(105, false); //var widthValue = new FieldLength(105); //var widthFreeHier = new FieldLength(270); var comparer = new IFValueComparer(); var dtConverter = new DateTimeConverter(); var dtToolTiptemplate = Application.Current.Resources[ConstantHelper.DateTimeTemplateName] as DataTemplate; var measure = dataGrid.FindParent <IMeasure>(); dataGrid.Resources["IMeasure"] = measure; //var fieldLayout = dataGrid.ColumnLayouts[0]; //TemplateField dtField; try { //fieldLayout.Fields.BeginUpdate(); //fieldLayout.SortedFields.BeginUpdate(); var dtCol = userTable.Columns["EventDateTime"]; var dtField = new TextColumn { Key = dtCol.ColumnName, IsReadOnly = true, //DataType = dtCol.DataType, HeaderText = dtCol.Caption, //Width = new FieldLength(95), Width = new ColumnWidth(90, false), ValueConverter = dtConverter, HorizontalContentAlignment = HorizontalAlignment.Center, VerticalContentAlignment = VerticalAlignment.Center, AllowToolTips = AllowToolTips.Always, ToolTipContentTemplate = dtToolTiptemplate, DataViewType = typeof(DateTime), IsSortable = true, IsSorted = SortDirection.Ascending, GroupByComparer = new ByDayComparer(), //Settings = { LabelPresenterStyle = dataGrid.FindResource("TimeStyle") as Style } }; dataGrid.Columns.Add(dtField); if (isCumulateDrums) { //dtField.Settings.CellValuePresenterStyle = // XamDataGridHelper.DataTemplateToCellValuePresenterStyle(ConstantHelper.DateTimeTemplateName); dtConverter.Parametr = ConstantHelper.DateTimeTemplateName; //dtField.ItemTemplate = Application.Current.Resources[ConstantHelper.DateTimeTemplateName] as DataTemplate; } else { string dataTemplateToCellValuePresenterStyleName; //------------------------------- switch (discreteType) { case enumTimeDiscreteType.DB24Hour: dataTemplateToCellValuePresenterStyleName = ConstantHelper.DateTemplateName; break; case enumTimeDiscreteType.DBMonth: dataTemplateToCellValuePresenterStyleName = ConstantHelper.MonthName; break; default: dataTemplateToCellValuePresenterStyleName = ConstantHelper.DateTimeTemplateName; break; } dtConverter.Parametr = dataTemplateToCellValuePresenterStyleName; } dtField.HeaderText = "Время"; //dataGrid.GroupBySettings.GroupByColumns.Add(dtField); //if (discreteType == enumTimeDiscreteType.DB24Hour) //{ //dtField.Settings.GroupByMode = FieldGroupByMode.Month; //dtField.Settings.GroupByRecordPresenterStyle = //Application.Current.FindResource("MonthYearXamDataGridStyle") as Style; //} //else //{ //dtField.Settings.GroupByMode = FieldGroupByMode.Date; //} //SummaryCalculator statType; //string prefix; //if (typeInformation == enumTypeInformation.Power) //{ // statType = new FValueAvgCalculator(format); // prefix = "Сред:"; //} //else //{ // statType = new FValueSumCalculator(format); // prefix = "Сум:"; //} //var stringFormat = prefix + " {0:" + format + "}"; var stringFormat = " {0:" + format + "}"; var dfc = new DetailFieldInfoEqualityComparer(); //FieldGroup fieldGroupByObject = null; //FieldGroup fieldGroupByMeasureCategory = null; //EnumMeasureUnitCategory? previousMeasureCategory = null; //Для определения групповать или нет по категории foreach (var colGroupByObject in userTable.Columns .Cast <DataColumn>() .Where(c => c.ColumnName != "EventDateTime") .Select(c => { DetailFieldInfo fieldInfo; userTable.TryGetIndexByItemName(c.ColumnName, out fieldInfo); return(new Tuple <DetailFieldInfo, DataColumn>(fieldInfo, c)); }) .GroupBy(c => c.Item1, dfc)) { var fieldInfo = colGroupByObject.Key; if (fieldInfo == null || fieldInfo.ChannelType == 0) { //Группировать не нужно foreach (var colByObject in colGroupByObject) { FValueSummaryDefinition summaryDefinition; var fld = AddFieldAndSummary(colByObject.Item2, comparer, fieldInfo != null && fieldInfo.UseMeasureModule, vTemplate, vTemplateNoBindMeasure, columnWidth); if (fieldInfo != null && fieldInfo.Id != null) { fld.HeaderTemplate = groupLabelTemplate; fld.Label = colByObject.Item1.Id; } else { fld.HeaderText = colByObject.Item2.Caption; } //fld.HeaderText = (fieldInfo == null ? colByObject.Item2.Caption : (object)colByObject.Item1).ToString(); dataGrid.Columns.Add(fld); //if (summaryDefinition != null) //{ // fieldLayout.SummaryDefinitions.Add(summaryDefinition); //} } } else { var fieldGroupByObject = new GroupColumn { //Label = fieldInfo.Id, Key = fieldInfo.ColumnName + "___", Label = fieldInfo.Id, //HeaderText = fieldInfo.Id.ToString(), HeaderTemplate = groupLabelTemplate, }; dataGrid.Columns.Add(fieldGroupByObject); //Группируем по объектам foreach (var colGroupByMeasureCategory in colGroupByObject.GroupBy(c => c.Item1.MeasureUnitUn.SubstringQuantityUn())) { var colGroupByMeasureCategoryList = colGroupByMeasureCategory.ToList(); if (!string.IsNullOrEmpty(colGroupByMeasureCategory.Key) && colGroupByMeasureCategoryList.Count > 1) { //Есть категории ед. измерения и их несколько var fieldGroupByMeasureCategory = new GroupColumn { Label = new LabelMeasureQuantity { MeasureQuantityType_UN = colGroupByMeasureCategory.Key, }, Key = fieldInfo.Id + "_" + colGroupByMeasureCategory.Key, }; fieldGroupByObject.Columns.Add(fieldGroupByMeasureCategory); foreach (var colByMeasure in colGroupByMeasureCategoryList) { FValueSummaryDefinition summaryDefinition; var fld = AddFieldAndSummary(colByMeasure.Item2, comparer, fieldInfo.UseMeasureModule, vTemplate, vTemplateNoBindMeasure, columnWidth); //isCumulateDrums, statType, stringFormat, fieldLayout, out summaryDefinition); //fld.Label = colByMeasure.Item1; fld.HeaderTemplate = colByMeasure.Item1.ChannelType == 0 ? unchannelLabelTemplate : channelLabelTemplate; fld.Label = colByMeasure.Item1; fieldGroupByMeasureCategory.Columns.Add(fld); //if (summaryDefinition != null) //{ // fieldLayout.SummaryDefinitions.Add(summaryDefinition); //} } } else { //Нет категорий, или она одна var fielgGroupByReplacedTiDict = new Dictionary <string, GroupColumn>(); foreach (var colByMeasure in colGroupByMeasureCategoryList) { if (colByMeasure.Item2.ColumnName.StartsWith("ovInfo")) { //Это информация об ОВ //var hoc = new HierObjectsConverterComparer(); var fld = AddField(colByMeasure.Item2, fieldInfo.UseMeasureModule, vFreeHierarchyObjectTemplate, vFreeHierarchyObjectTemplate, columnWidth); //widthFreeHier fld.Label = "Замещаемые ТИ"; //fld.Settings.FilterOperandUIType = FilterOperandUIType.DropDownList; //fld.Settings.FilterLabelIconDropDownType = FilterLabelIconDropDownType.MultiSelectExcelStyle; //fld.Settings.GroupByComparer = hoc; //fld.ValueToTextConverter = new HierObjectsConverter(); //fld.Settings.FilterComparer = new HierObjectsConverterComparer(); fieldGroupByObject.Columns.Add(fld); } else { GroupColumn fielgGroupByReplacedTi = null; //Группируем по замещаемой ТИ if (colByMeasure.Item2.ColumnName.StartsWith("ovValue") && !fielgGroupByReplacedTiDict.TryGetValue( colByMeasure.Item1.GroupByReplacedTiName, out fielgGroupByReplacedTi)) { fielgGroupByReplacedTi = new GroupColumn { Label = colByMeasure.Item1.ReplacedId, Key = colByMeasure.Item1.ColumnName + "_", HeaderText = colByMeasure.Item1.ReplacedId.ToString(), }; fielgGroupByReplacedTiDict[colByMeasure.Item1.GroupByReplacedTiName] = fielgGroupByReplacedTi; } //FValueSummaryDefinition summaryDefinition; var fld = AddFieldAndSummary(colByMeasure.Item2, comparer, fieldInfo.UseMeasureModule, vTemplate, vTemplateNoBindMeasure, columnWidth); //isCumulateDrums, statType, stringFormat, fieldLayout, out summaryDefinition); fld.Label = colByMeasure.Item1; fld.HeaderTemplate = colByMeasure.Item1.ChannelType == 0 ? unchannelLabelTemplate : channelLabelTemplate; if (fielgGroupByReplacedTi != null) { fielgGroupByReplacedTi.Columns.Add(fld); } else { fieldGroupByObject.Columns.Add(fld); } //if (summaryDefinition != null) //{ // fieldLayout.SummaryDefinitions.Add(summaryDefinition); //} //if (colByMeasure.Item1.IsOv) //{ // //Если это ОВ, добавляем суммарную информацию о неразнесенных значениях // var unWritedOvs = new FValueSummaryDefinition // { // SourceFieldName = colByMeasure.Item2.ColumnName, // Calculator = new FValueSumUnreplacedCalculator(format), // StringFormat = stringFormat, // UseMeasureModule = fieldInfo.UseMeasureModule, // }; // fieldLayout.SummaryDefinitions.Add(unWritedOvs); //} } } if (fielgGroupByReplacedTiDict.Count > 0) { foreach (var c in fielgGroupByReplacedTiDict.Values) { fieldGroupByObject.Columns.Add(c); } } } } } } //if (isDateTimeGroupingGridControlXam && // (discreteType == enumTimeDiscreteType.DBHalfHours || discreteType == enumTimeDiscreteType.DBHours || // discreteType == enumTimeDiscreteType.DB24Hour)) //{ // //dtField.Settings.AllowSummaries = false; // dtField.Settings.AllowGroupBy = true; // fieldLayout.SortedFields.Add(new FieldSortDescription("EventDateTime", ListSortDirection.Ascending, // true)); //} //else //{ // dtField.DisplayTemplate = Application.Current.Resources[ConstantHelper.DateTimeTemplateName] as DataTemplate; // //dtField.Settings.CellValuePresenterStyle = // // XamDataGridHelper.DataTemplateToCellValuePresenterStyle(ConstantHelper.DateTimeTemplateName); //} //var consumptionScheduleField = fieldLayout.Fields.FirstOrDefault(ff => ff.Name == "ConsumptionSchedule"); //if (consumptionScheduleField != null) //{ // consumptionScheduleField.Label = "Тип. потр."; //} //var consumptionSchedulePercentField = fieldLayout.Fields.FirstOrDefault(ff => ff.Name == "ConsumptionSchedulePercent"); //if (consumptionSchedulePercentField != null) //{ // consumptionSchedulePercentField.Label = "Тип. потр. %"; //} } finally { // fieldLayout.SortedFields.EndUpdate(); //fieldLayout.Fields.EndUpdate(); } //dataGrid.FieldLayoutSettings.FixedFieldUIType = FixedFieldUIType.Splitter; //dataGrid.FieldSettings.SummaryDisplayArea = SummaryDisplayAreas.BottomFixed; if (userTable.Columns.Count < 20) { //из-за того что тормоза ограничиваем //dataGrid.FieldSettings.SummaryDisplayArea = dataGrid.FieldSettings.SummaryDisplayArea | SummaryDisplayAreas.InGroupByRecords; } //if (userTable.Columns.Count < 1000) //{ // dataGrid.RecordsInViewChanged += ExpandFirstRecord; //} }
public static DataTableEx ExecuteValidateValue(FormulasResult formulasResult, ArchivesValidate_List archivesList, ArchivesTPValueAllChannels archivesTpList, IVisualDataRequestObjectsNames getNameInterface, List <DateTime> dts) { if ((archivesList == null || archivesList.Result_Values == null) && (formulasResult == null || formulasResult.Result_Values == null) && (archivesTpList == null || archivesTpList.Result_Values == null)) { return(null); } int countColumn; DateTime dtStart, dtEnd; enumTimeDiscreteType discreteType; if (archivesList != null && archivesList.Result_Values != null && archivesList.Result_Values.Count > 0) { dtStart = archivesList.DTStart; dtEnd = archivesList.DTEnd; countColumn = archivesList.NumbersValues; discreteType = archivesList.DiscreteType; } else if (formulasResult != null && formulasResult.Result_Values != null && formulasResult.Result_Values.Count > 0 && formulasResult.Result_Values[0].Result_Values != null && formulasResult.Result_Values[0].Result_Values.Count > 0) { dtStart = formulasResult.DTStart; dtEnd = formulasResult.DTEnd; countColumn = formulasResult.NumbersValues; discreteType = formulasResult.DiscreteType; } else if (archivesTpList != null && archivesTpList.Result_Values != null) { dtStart = archivesTpList.DTStart; dtEnd = archivesTpList.DTEnd; countColumn = archivesTpList.NumbersValues; discreteType = archivesTpList.DiscreteType; } else { return(null); } string labelFormat; if (discreteType == enumTimeDiscreteType.DBHours || discreteType == enumTimeDiscreteType.DBHalfHours) { labelFormat = "dd.MM.yy\nHH:mm"; } else { labelFormat = "dd.MM.yy"; } var userTable = new DataTableEx() { FieldForSearch = "NameTI", }; userTable.BeginLoadData(); try { #region -------------Таблица для представления данных---------------------------- userTable.Columns.Add("NameTI", typeof(IFreeHierarchyObject)); userTable.Columns.Add("Channel", typeof(object)); userTable.Columns.Add("Parent", typeof(IFreeHierarchyObject)); userTable.Columns.Add("DataSource", typeof(string)); var fType = typeof(VALUES_FLAG_DB); userTable.Columns.Add(new DataColumn("TotalFlag", fType) { Caption = "Итого", }); var i = 0; foreach (var dt in dts) { userTable.Columns.Add(new DataColumn("Valid" + i, fType) { Caption = dt.ToString(labelFormat), }); i++; } #endregion #region ------------Перебираем ТИ в архиве--------------------------------------- if (archivesList != null && archivesList.Result_Values != null) { userTable.Description = new DataTableDescription { DtStart = archivesList.DTStart, DiscreteType = archivesList.DiscreteType, TimeZoneId = archivesList.TimeZoneId, }; //сортировка foreach (var pair in archivesList.Result_Values .Select(v => new Tuple <TPSHierarchy, TArchivesValidate, TInfo_TI>( EnumClientServiceDictionary.DetailPSList[v.TI_Validate.PS_ID], v, v.TI_Validate.TI_Ch_ID.IsCA ? EnumClientServiceDictionary.TICAList[v.TI_Validate.TI_Ch_ID.TI_ID] : EnumClientServiceDictionary.TIHierarchyList[v.TI_Validate.TI_Ch_ID.TI_ID])) .Where(v => v.Item1 != null && v.Item3 != null && v.Item2.TI_Validate != null) .OrderBy(v => v.Item2.TI_Validate.TI_Ch_ID.IsCA) .ThenBy(v => v.Item1.Name) .ThenBy(v => v.Item2.TI_Validate.PS_ID) .ThenBy(v => v.Item3.Name) .ThenBy(v => v.Item2.TI_Validate.TI_Ch_ID.TI_ID) .ThenBy(v => v.Item2.TI_Validate.TI_Ch_ID.ChannelType % 10) .ThenBy(v => v.Item2.TI_Validate.TI_Ch_ID.ChannelType)) { var archiveValidateValue = pair.Item2; var validate = archiveValidateValue.TI_Validate; //--------колонки в промежуточную таблицу----------- var row = userTable.NewRow() as DataRowEx; if (validate != null) { row["NameTI"] = pair.Item3; row["Channel"] = new TTariffPeriodID { ChannelType = validate.TI_Ch_ID.ChannelType, IsOV = false, TI_ID = validate.TI_Ch_ID.TI_ID, StartDateTime = dtStart, FinishDateTime = dtEnd, }; row["Parent"] = pair.Item1; row["DataSource"] = EnumClientServiceDictionary .DataSourceTypeList .FirstOrDefault(v => EqualityComparer <EnumDataSourceType?> .Default.Equals(validate.TI_Ch_ID.DataSourceType, v.Key)) .Value; var id = new ID_Hierarchy { ID = validate.TI_Ch_ID.TI_ID.ToString(), TypeHierarchy = validate.TI_Ch_ID.IsCA ? enumTypeHierarchy.Info_ContrTI : enumTypeHierarchy.Info_TI }; row["TotalFlag"] = validate.Total_Flag; if (validate.F_FLAG_List != null) { for (var j = 0; j < countColumn; j++) { var flag = validate.F_FLAG_List.ElementAtOrDefault(j); row.SetValue("Valid" + j, j, validate.TI_Ch_ID.ChannelType, id, validate.TI_Ch_ID.DataSourceType, null, flag); } } } userTable.Rows.Add(row); validate = archiveValidateValue.ContrTI_Validate; if (validate != null) { row = userTable.NewRow() as DataRowEx; row["NameTI"] = "ТИ КА -" + getNameInterface.GetHierarchyDbTreeObject( validate.TI_Ch_ID.TI_ID.ToString(), validate.TI_Ch_ID.IsCA ? enumTypeHierarchy.Info_ContrTI : enumTypeHierarchy.Info_TI); row["Parent"] = EnumClientServiceDictionary.DetailContrPSList[validate.PS_ID]; row["Channel"] = validate.TI_Ch_ID.ChannelType; if (validate.F_FLAG_List != null) { for (var j = 0; j < countColumn; j++) { var flag = validate.F_FLAG_List.ElementAtOrDefault(j); row["Valid" + j] = flag; } } row["TotalFlag"] = validate.Total_Flag; userTable.Rows.Add(row); } } } #endregion #region ------------Перебираем формулы--------------------------------------------- var tps = EnumClientServiceDictionary.GetTps(); if (tps == null) { return(userTable); } if (formulasResult != null && formulasResult.Result_Values != null) { if (userTable.Description == null) { userTable.Description = new DataTableDescription { DtStart = formulasResult.DTStart, DiscreteType = formulasResult.DiscreteType, TimeZoneId = formulasResult.TimeZoneId, }; } foreach (var pair in formulasResult.Result_Values .Where(fr => fr.Result_Values != null && fr.Result_Values.Count > 0) .Select(fr => new Tuple <IFreeHierarchyObject, IFormulaInfo, TFormulaResultsList>(fr.TP_CH_ID != null ? (IFreeHierarchyObject)tps[fr.TP_CH_ID.TP_ID] : EnumClientServiceDictionary.DetailPSList[fr.PS_ID], fr.GetFormulaInfo(getNameInterface), fr)) .OrderBy(p => p.Item1 == null ? "Формулы" : p.Item1.Name) .ThenBy(p => p.Item2 == null ? string.Empty : p.Item2.FormulaName)) { var formula = pair.Item3; var formulaResult = formula.Result_Values[0]; var row = userTable.NewRow() as DataRowEx; row["NameTI"] = pair.Item2; row["Channel"] = null; row["Parent"] = pair.Item1; var totalFlag = VALUES_FLAG_DB.None; enumTypeHierarchy typeHierarchy; switch (pair.Item2.FormulasTable) { case enumFormulasTable.Info_Formula_Description: typeHierarchy = enumTypeHierarchy.Formula; break; case enumFormulasTable.Info_TP2_OurSide_Formula_Description: typeHierarchy = enumTypeHierarchy.Formula_TP_OurSide; break; case enumFormulasTable.Info_TP2_Contr_Formula_Description: typeHierarchy = enumTypeHierarchy.Formula_TP_CA; break; default: typeHierarchy = enumTypeHierarchy.Unknown; break; } var id = new ID_Hierarchy { ID = formulaResult.FormulaId, TypeHierarchy = typeHierarchy, }; if (formulaResult.Val_List != null && formulaResult.Val_List.Count > 0) { for (int j = 0; j < countColumn; j++) { var v = formulaResult.Val_List.ElementAt(j); if (v != null) { var flag = v.F_FLAG; row.SetValue("Valid" + j, j, 0, id, null, null, flag); totalFlag = totalFlag.CompareAndReturnMostBadStatus(flag); } //row.SetIndex(description, j); } } row["TotalFlag"] = totalFlag.AccomulateTotalStatistic(); userTable.Rows.Add(row); } } #endregion #region ------------Перебираем ТП в архиве--------------------------------------- if (archivesTpList == null || archivesTpList.Result_Values == null) { return(userTable); } var sections = EnumClientServiceDictionary.GetSections(); if (sections == null) { return(userTable); } if (userTable.Description == null) { userTable.Description = new DataTableDescription { DtStart = archivesTpList.DTStart, DiscreteType = archivesTpList.DiscreteType, TimeZoneId = archivesTpList.TimeZoneId, }; } foreach (var pair in archivesTpList.Result_Values .Select(a => { TPoint tp; tps.TryGetValue(a.Key, out tp); TSection section; sections.TryGetValue(tp.Section_ID, out section); return(new Tuple <TSection, TPoint, List <TArchivesTPValueAllChannels> >(section, tp, a.Value)); }) .Where(p => p.Item1 != null && p.Item2 != null && p.Item3 != null) .OrderBy(p => p.Item1.SectionName) .ThenBy(p => p.Item2.StringName)) { foreach (var tpArchive in pair.Item3) { if (tpArchive.Val_List == null) { continue; } Dictionary <byte, List <TPointValue> > tpVals; if (!tpArchive.Val_List.TryGetValue(tpArchive.IsMoneyOurSide, out tpVals) || tpVals == null || tpVals.Count <= 0) { continue; } foreach (var valueByChannel in tpVals) { var row = userTable.NewRow() as DataRowEx; row["NameTI"] = pair.Item2; row["Channel"] = valueByChannel.Key; row["Parent"] = pair.Item1; var totalFlag = VALUES_FLAG_DB.None; var id = new ID_Hierarchy { ID = pair.Item2.TP_ID.ToString(), TypeHierarchy = enumTypeHierarchy.Info_TP, }; if (valueByChannel.Value != null && valueByChannel.Value.Count > 0) { for (var j = 0; j < countColumn; j++) { var v = valueByChannel.Value.ElementAtOrDefault(j); if (v != null) { var flag = v.F_FLAG; row.SetValue("Valid" + j, j, valueByChannel.Key, id, null, null, flag); totalFlag = totalFlag.CompareAndReturnMostBadStatus(flag); //row.SetIndex(description, j); } } } row["TotalFlag"] = totalFlag.AccomulateTotalStatistic(); userTable.Rows.Add(row); } } } #endregion } finally { userTable.EndLoadData(); userTable.AcceptChanges(); } return(userTable); }
/// <summary> /// 加载数据表 /// </summary> /// <param name="conn">SQL连接</param> /// <param name="sql">SQL查询语句</param> private void LoadDataTable(SqlConnection conn, string sql) { mAdapter = new SqlDataAdapter(sql, conn); mAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey; mTable = new DataTableEx(); mAdapter.Fill(mTable); mTable.TableName = mTableName; mTableChanged = false; foreach (DataColumn column in mTable.Columns) { column.ReadOnly = false; } }
public static DataTableEx ExecuteFormulasValueExpand(FormulasResult formulasResult, ArchivesValues_List2 archivesList, IVisualDataRequestObjectsNames getNameInterface, int doublePrecision, DateTime dtStart, DateTime dtEnd, enumTimeDiscreteType discreteType, string timeZoneId, ArchivesTPValueAllChannels archivesTpList = null, SectionIntegralActsTotalResults?archivesSection = null, bool isSumTiForChart = false, FormulaConstantArchives constantArchives = null, ArchTariffIntegralsTIs cumulativeIntegrals = null, ForecastConsumptionResult fResult = null, List <TRowObjectForGrid> listTiViewModel = null, bool isDetailOv = true, BalanceFreeHierarchyResults balanceFreeHierarchy = null) { if (archivesList == null && formulasResult == null && archivesTpList == null && archivesSection == null && constantArchives == null && cumulativeIntegrals == null && fResult == null && balanceFreeHierarchy == null) { return(null); } #if DEBUG var sw = new System.Diagnostics.Stopwatch(); sw.Start(); #endif var dts = getNameInterface.GetDateTimeListForPeriod(dtStart, dtEnd, discreteType, timeZoneId.GeTimeZoneInfoById()); var numbersValues = dts.Count; //Расчетный ли это профиль var deltaDiscrete = (int)discreteType + 1; //-------------Таблица для представления данных---------------------------- var userTable = new DataTableEx(); userTable.BeginLoadData(); try { userTable.Columns.Add("EventDateTime", typeof(DateTime)); #region Создаем колонки в пользовательском представлениее var vType = typeof(IFValue); var k = 0; #region ------------Перебираем точки--------------------------------------------- var tiColumnValues = userTable.AddColumnsTi(ref k, archivesList, isSumTiForChart, isDetailOv); #endregion #region ------------ТП--------------------------------------------- var tpColumnValues = userTable.AddColumnsTp(ref k, archivesTpList, listTiViewModel); // var tpArchives = new List<Tuple<TPoint, Dictionary<byte, List<TPointValue>>>>(); //if (archivesTpList != null) //{ //} #endregion #region ------------Перебираем формулы--------------------------------------------- var formulaArchives = new List <Tuple <IFormulaInfo, TFormulasResult, List <TFormulaConsist> > >(); if (formulasResult != null && formulasResult.Result_Values != null) { foreach (var formulas in formulasResult.Result_Values .Select(f => new Tuple <IFormulaInfo, TFormulasResult, List <TFormulaConsist> >(f.GetFormulaInfo(getNameInterface), f.Result_Values.FirstOrDefault(), f.FormulaConsist)) .Where(f => f.Item1 != null) .OrderBy(f => f.Item1.FormulaName)) { var fVal = formulas.Item2; if (fVal != null && fVal.Val_List != null && fVal.Val_List.Count > 0) { var col = new DataColumn("F_VALUE" + k, vType) { ReadOnly = true, }; userTable.Columns.Add(col); k++; } //------------ТИ которые входят в формулу------------------------------------------------------- if (formulasResult.IsValuesAllTIEnabled && formulas.Item3 != null) { foreach (var archivesValue in formulas.Item3) { if (archivesValue.Val_List == null) { continue; } //var hierObj = // getNameInterface.GetHierarchyDbTreeObject(archivesValue.TI_Ch_ID.TI_ID.ToString(), // archivesValue.TypeTIinFormula); var col = new DataColumn("F_VALUE" + k, vType) { ReadOnly = true, }; userTable.Columns.Add(col); k++; } } formulaArchives.Add(formulas); } } #endregion #region ------------Перебираем константы--------------------------------------------- if (constantArchives != null && constantArchives.FormulaConstantDict != null) { foreach (var formulaConstant in constantArchives.FormulaConstantDict.Values) { if (formulaConstant.ArchiveValues != null && formulaConstant.ArchiveValues.Count > 0) { var col = new DataColumn("F_VALUE" + k, vType) { //Caption = "Конст. -" + formulaConstant.ConstantaParams.FormulaConstantName, ReadOnly = true, }; userTable.Columns.Add(col); //namesFormulas.Add(new GridTitle //{ // //TitleString = "Конст. -" + formulaConstant.ConstantaParams.FormulaConstantName, // TitleString = "Конст. -" + formulaConstant.ConstantaParams.FormulaConstantName //}); k++; } } } #endregion #region ------------Перебираем сечения--------------------------------------------- if (archivesSection != null && archivesSection.Value.Total_Result != null && archivesSection.Value.Total_Result.Count > 0) { foreach (var sectionPair in archivesSection.Value.Total_Result) { var section = sectionPair.Value; if (section.TotalVals != null && section.TotalVals.Count > 0) { var sectionName = getNameInterface.GetSectionName(sectionPair.Key); var col = new DataColumn("F_VALUE" + k, vType) { //Caption = "Сеч. -" + sectionName, ReadOnly = true, }; userTable.Columns.Add(col); //namesFormulas.Add(new GridTitle //{ // //TitleString = "Сеч. -" + sectionName, // TitleString = "Сеч. -" + sectionName //}); k++; } } } #endregion #region ------------Перебираем накопительные интегралы------------------------------ if (cumulativeIntegrals != null && cumulativeIntegrals.IntegralsValue30orHour != null) { var nType = typeof(IConvertible); foreach (var integral in cumulativeIntegrals.IntegralsValue30orHour) { if (integral.Cumulate_Val_List == null || integral.Cumulate_Val_List.Count == 0) { continue; } //var tiName = getNameInterface.GetTIName(integral.TI_Ch_ID.TI_ID, integral.TI_Ch_ID.IsCA); //var psName = getNameInterface.GetPSName(integral.PS_ID, integral.TI_Ch_ID.IsCA); var col = new DataColumn("F_VALUE" + k, nType) { //Caption = tiName + // getNameInterface.GetChanelTypeNameByID(integral.TI_Ch_ID.TI_ID, // integral.TI_Ch_ID.ChannelType, false, // cumulativeIntegrals.DTStart, cumulativeIntegrals.DTEnd) + " \n" + // psName, ReadOnly = true, }; userTable.Columns.Add(col); k++; } } #endregion #region ------------Прогнозирование------------------------------ if (fResult != null && fResult.Result_Values != null) { var hierarchyObject = getNameInterface.GetHierarchyDbTreeObject(fResult.ID.ID, fResult.ID.TypeHierarchy); if (hierarchyObject != null) { foreach (var archive in fResult.Result_Values) { if (archive.Value == null) { continue; } var col = new DataColumn("F_VALUE" + k, vType) { Caption = hierarchyObject.Name + " " + getNameInterface.GetChanelTypeNameByID(archive.Key.Channel, false), ReadOnly = true, }; userTable.Columns.Add(col); k++; } } } #endregion #region ------------Перебираем балансы--------------------------------------------- var balanceColumnValues = userTable.AddColumnsBalances(ref k, balanceFreeHierarchy); #endregion #endregion #if DEBUG sw.Stop(); Console.WriteLine("Создаем колонки в пользовательском представлениее - > {0} млс", sw.ElapsedMilliseconds); sw.Restart(); #endif #region Наполняем поставщик if (archivesList != null) { userTable.Description = new DataTableDescription { DtStart = archivesList.DTStart, DiscreteType = archivesList.DiscreteType, TimeZoneId = archivesList.TimeZoneId, }; } else { userTable.Description = null; } for (var i = 0; i < numbersValues; i++) { k = 0; //--------колонки в промежуточную таблицу----------- var row = userTable.NewRow() as DataRowEx; var dt = dts[i]; row["EventDateTime"] = dt; //row["Time"] = dt.TimeOfDay; //-------пишем в промежуточную таблицу значения-------- //TVALUES_DB mainChannelVal = null; #region ТИ userTable.PopulateRowsTi(ref k, tiColumnValues, numbersValues, isSumTiForChart, row, i); #endregion #region ТП userTable.PopulateRowsTp(ref k, tpColumnValues, row, i); #endregion #region Формулы if (formulasResult != null && formulasResult.Result_Values != null) { foreach (var formulas in formulaArchives) { enumTypeHierarchy typeHierarchy; switch (formulas.Item1.FormulasTable) { case enumFormulasTable.Info_Formula_Description: typeHierarchy = enumTypeHierarchy.Formula; break; case enumFormulasTable.Info_TP2_OurSide_Formula_Description: typeHierarchy = enumTypeHierarchy.Formula_TP_OurSide; break; case enumFormulasTable.Info_TP2_Contr_Formula_Description: typeHierarchy = enumTypeHierarchy.Formula_TP_CA; break; default: typeHierarchy = enumTypeHierarchy.Unknown; break; } var id = new ID_Hierarchy { ID = formulas.Item1.Formula_UN, TypeHierarchy = typeHierarchy }; var fVal = formulas.Item2; if (fVal != null && fVal.Val_List != null && fVal.Val_List.Count > 0) { var v = fVal.Val_List.ElementAtOrDefault(i); if (v != null) { var useMeasureModule = string.IsNullOrEmpty(fVal.MeasureUnit_UN) && (string.Equals(fVal.MeasureQuantityType_UN, "EnergyUnit") || string.Equals(fVal.MeasureQuantityType_UN, "PowerUnit")); //row["F_VALUE" + k] = v; row.SetValue("F_VALUE" + k, i, 0, id, null, fVal.MeasureUnit_UN, v, useMeasureModule); } k++; } if (formulasResult.IsValuesAllTIEnabled && formulas.Item3 != null) { foreach (var archivesValue in formulas.Item3) { if (archivesValue.Val_List == null) { continue; } var v = archivesValue.Val_List.ElementAtOrDefault(i); if (v != null) { if (archivesValue.Id == null) { row["F_VALUE" + k] = new TVALUES_DB { F_VALUE = v.F_VALUE, F_FLAG = v.F_FLAG, }; } else { row.SetValue("F_VALUE" + k, i, archivesValue.ChannelType, archivesValue.Id, null, null, v); } } k++; } } } } #endregion #region Константы if (constantArchives != null && constantArchives.FormulaConstantDict != null) { foreach (var formulaConstant in constantArchives.FormulaConstantDict.Values) { if (formulaConstant.ArchiveValues != null) { var v = formulaConstant.ArchiveValues.ElementAtOrDefault(i); if (v != null) { row.SetValue("F_VALUE" + k, i, 0, new ID_Hierarchy { ID = formulaConstant.ConstantaParams.FormulaConstant_UN, TypeHierarchy = enumTypeHierarchy.FormulaConstant }, null, null, v); } k++; } } } #endregion #region Сечения if (archivesSection != null && archivesSection.Value.Total_Result != null && archivesSection.Value.Total_Result.Count > 0) { foreach (var sectionPair in archivesSection.Value.Total_Result) { var section = sectionPair.Value; List <TVALUES_DB> values; if (section.TotalVals != null && section.TotalVals.Count > 0 && section.TotalVals.TryGetValue(enumInputType.Saldo, out values)) { var v = values.ElementAtOrDefault(i); if (v != null) { //row["F_VALUE" + k] = v; row.SetValue("F_VALUE" + k, i, 0, new ID_Hierarchy { ID = sectionPair.Key.ToString(), TypeHierarchy = enumTypeHierarchy.Section }, null, null, v); } k++; } } } #endregion #region ------------Перебираем накопительные интегралы------------------------------ if (cumulativeIntegrals != null && cumulativeIntegrals.IntegralsValue30orHour != null) { var unitDigitCoeff = (double)cumulativeIntegrals.UnitDigit; foreach (var integral in cumulativeIntegrals.IntegralsValue30orHour) { if (integral.Cumulate_Val_List == null || integral.Cumulate_Val_List.Count == 0) { continue; } var val = integral.Cumulate_Val_List.ElementAtOrDefault(i); if (val != null) { var v = new TVal { F_FLAG = val.F_FLAG, F_VALUE = val.Value / unitDigitCoeff, }; //var v = val.Value / unitDigitCoeff; //------------ТИ ФСК----------------------------- row.SetValue("F_VALUE" + k, i, integral.TI_Ch_ID.ChannelType, new ID_Hierarchy { ID = integral.TI_Ch_ID.TI_ID.ToString(), TypeHierarchy = enumTypeHierarchy.Info_TI }, integral.TI_Ch_ID.DataSourceType, null, v); //row["F_VALUE" + k] = v; //if (integral.TI_Ch_ID.ChannelType < 3 && v > 0) //{ // mainChannelVal = v; //} } k++; } } #endregion #region ------------Прогнозирование------------------------------ if (fResult != null && fResult.Result_Values != null) { var hierarchyObject = getNameInterface.GetHierarchyDbTreeObject(fResult.ID.ID, fResult.ID.TypeHierarchy); if (hierarchyObject != null) { var unitDigitCoeff = (double)fResult.UnitDigit; foreach (var archive in fResult.Result_Values) { if (archive.Value == null) { continue; } var val = archive.Value.ElementAtOrDefault(i); if (val != null) { var v = new TVALUES_DB { F_FLAG = val.F_FLAG, F_VALUE = val.F_VALUE / unitDigitCoeff, }; //------------ТИ ФСК----------------------------- //row["F_VALUE" + k] = v; row.SetValue("F_VALUE" + k, i, archive.Key.Channel, new ID_Hierarchy { ID = archive.Key.ID, TypeHierarchy = archive.Key.TypeHierarchy, }, null, null, v); } k++; } } } #endregion #region Балансы userTable.PopulateRowsBalances(ref k, balanceColumnValues, row, i); #endregion // if (consumptionSchedule != null && mainChannelVal != null && mainChannelVal.F_VALUE != null && // mainChannelVal.F_FLAG.HasFlag(VALUES_FLAG_DB.ConsumptionScheduleOverflow)) //{ // //Ищем значение типового графика для данной получасовки // var cs_val = // consumptionSchedule.ConsumptionScheduleValues.FirstOrDefault( // cs => cs.TotalDay == (dt.Date - dtStart.Date).TotalDays && cs.TotalNumberPerDay == // dt.TimeOfDay.TotalMinutes / (30 * deltaDiscrete)); // if (cs_val != null && cs_val.F_VALUE.HasValue) // { // double delta = 0; // if (mainChannelVal.F_VALUE > cs_val.MAX_VALUE) // { // delta = mainChannelVal.F_VALUE - cs_val.F_VALUE.Value; // } // else // { // delta = mainChannelVal.F_VALUE - cs_val.F_VALUE.Value; // } // row["ConsumptionSchedule"] = delta; // row["ConsumptionSchedulePercent"] = delta / mainChannelVal.F_VALUE * 100; // } //} userTable.Rows.Add(row); } #endregion } finally { userTable.EndLoadData(); userTable.AcceptChanges(); } #if DEBUG sw.Stop(); Console.WriteLine("ExecuteFormulasValueExpand - > {0} млс", sw.ElapsedMilliseconds); #endif return(userTable); }
public void Database(string type) { if (CheckAjax()) { if (CheckRight()) { if (CheckPost(string.Concat("db_", type), new Action(() => { this["Conns"] = WebConfigurationManager.ConnectionStrings; }))) { switch (type) { case "excute": { try { DataTableEx table = new DataTableEx(); using (DataSource ds = new DataSource(Request.Form["Conn"])) ds.ExecuteReader(table, Request.Form["sql"]); SetResult(true, () => { WritePostLog("EXE"); }, table); } catch (Exception ex) { SetResult(false, ex.Message); } } break; case "vacuum": { try { using (DataSource ds = new DataSource(Request.Form["Conn"])) { if (DbTable.Vacuum(ds)) { SetResult(() => { WritePostLog("SUB"); }); } else { SetResult(-1); } } } catch (Exception ex) { SetResult(false, ex.Message); } } break; case "backup": { SetResult(-1); } break; case "reduce": { SetResult(-1); } break; } } } } }
public override List <ChanceClass> getChances(CommCollection sc, ExpectData ed) { List <ChanceClass> ret = new List <ChanceClass>(); DataTableEx dt = null; if (this.BySer) { dt = sc.SerialDistributionTable; } else { dt = sc.CarDistributionTable; } if (dt == null) { throw new Exception("无法获得概率分布表!"); } string strCodes = ""; int AllChipCnt = 0; for (int i = 0; i < 10; i++) { //获得各项的最小的 List <double> coldata = null; string strCol = string.Format("{0}", (i + 1) % 10); dt.getColumnData(strCol, ref coldata); double avgval = coldata.Average(); double stdval = ProbMath.CalculateStdDev(coldata); string strSql = string.Format("[{0}]<{1}", strCol, avgval - this.StdvCnt * stdval); string strSort = string.Format("[{0}] asc", "Id"); DataRow[] drs = dt.Select(strSql, strSort); if (drs.Length < this.ChipCount) { continue; } string strCode = ""; StringBuilder sb = new StringBuilder(); bool Matched = false; for (int j = 0; j < drs.Length; j++) { string strId = drs[j]["Id"].ToString(); int RowCnt = sc.FindLastDataExistCount(this.InputMinTimes, strCol, strId); if (RowCnt > 0)//任何一个不匹配最近5期内出现,不满足条件 { Matched = false; break; } sb.Append(drs[j]["Id"].ToString()); Matched = true; } if (!Matched) { continue; } AllChipCnt += drs.Length; if (BySer) { strCode = string.Format("{0}/{1}", strCol, sb.ToString()); } else { strCode = string.Format("{0}/{1}", sb.ToString(), strCol); } if (strCode.Length > 0) { strCodes = string.Format("{0}{1}{2}", strCodes, strCodes.Length > 0?"+":"", strCode); } } if (strCodes.Length < 2 * (this.ChipCount + 2)) { return(ret); } ChanceClass cc = new ChanceClass(); cc.SignExpectNo = ed.Expect; cc.ChanceType = 3; cc.InputTimes = 1; cc.strInputTimes = "1"; cc.AllowMaxHoldTimeCnt = 1; cc.InputExpect = ed; cc.ChipCount = AllChipCnt; cc.ChanceCode = strCodes; cc.CreateTime = ed.OpenTime; cc.Closed = false; ret.Add(cc); return(ret); }
public override void OnBarcode(string Barcode) { if (processStep == Steps.DocumentSelecting) { return; } bool isUniqueCode = false; int asterixIndex = 0; #region Получение кода единицы измерения, уник. кода if (Barcode.Length > 8 && Barcode.Substring(0, 3) == "SB_" && Barcode.IndexOf('.') > 0) { bool isWrongFormat = false; if (Barcode.Substring(3, 5) != "UNIT.") { isWrongFormat = true; } else { string barBody = Barcode.Substring(8, Barcode.Length - 8); asterixIndex = barBody.IndexOf('*'); if (asterixIndex == -1) { if (!Number.IsNumber(barBody)) { isWrongFormat = true; } else { unitCode = Convert.ToUInt64(barBody); } } else { isUniqueCode = true; string unitCodeStr = barBody.Substring(0, asterixIndex); string uniqueCodeStr = barBody.Substring(asterixIndex + 1, barBody.Length - asterixIndex - 1); if (!Number.IsNumber(unitCodeStr) || !Number.IsNumber(uniqueCodeStr)) { isWrongFormat = true; } else { unitCode = Convert.ToUInt64(unitCodeStr); unqueCode = Convert.ToUInt64(uniqueCodeStr); } } } if (isWrongFormat) { ShowMessage("Неверный тип штрих-кода, ожидается единица измерения расх. мат."); return; } } else { PerformQuery("НайтиКодЕдИзм", Barcode); if (ResultParameters == null || ResultParameters[0] == null) { return; } unitCode = Convert.ToUInt64(ResultParameters[0] as string); if (unitCode == 0) { ShowMessage("Штрих-код не найден среди единиц измерения расходных материалов."); return; } } #endregion var dr = DataTableEx.FindRowInTable(dataTable, unitCode, "КодЕИ"); if (dr == null) { ShowMessage("Данного товара нет в плане прихода!"); return; } if (isUniqueCode) { OnUniqueCode(); } else { dr["Факт"] = ((int)(dr["Факт"])) + 1; } currentRow = dr; showReal(dr); }
/// <summary> /// Строим суточные интегралы /// </summary> /// <param name="archiveIntegrals">Интегралы</param> /// <param name="getNameInterface"></param> /// <param name="dts">Даты/время</param> /// <returns></returns> public static DataTableEx ExecuteDailyIntegrals(ArchTariffIntegralsTIs archiveIntegrals, enumTimeDiscreteType discreteType) { if (archiveIntegrals == null || archiveIntegrals.IntegralsValue30orHour == null) { return(null); } if (discreteType < enumTimeDiscreteType.DB24Hour) { //Допускается только 3 периода дискретизации discreteType = enumTimeDiscreteType.DB24Hour; } var unitDigitCoeff = (double)archiveIntegrals.UnitDigit; var dtStart = archiveIntegrals.DTStart; var dtEnd = archiveIntegrals.DTEnd; //Округляем до суток var dts = Extention.GetDateTimeListForPeriod(dtStart, dtEnd, discreteType, archiveIntegrals.TimeZoneId.GeTimeZoneInfoById()); #if DEBUG var sw = new System.Diagnostics.Stopwatch(); sw.Start(); #endif var userTable = new DataTableEx() { FieldForSearch = "NameTI", }; userTable.BeginLoadData(); try { #region Создаем основные колонки userTable.Columns.Add("Parent", typeof(IFreeHierarchyObject)); userTable.Columns.Add("NameTI", typeof(IFreeHierarchyObject)); userTable.Columns.Add("Coeff", typeof(double)); userTable.Columns.Add("CoeffLosses", typeof(double)); userTable.Columns.Add("Channel", typeof(object)); userTable.Columns.Add("DataSource", typeof(string)); #endregion #region Посуточные колонки var sufixFormat = "dd.MM.yyyy"; var prefixs = new List <string> { "_OnStart", "_OnEnd", "_Delta", }; //Строим 3 колонки по каждой дате foreach (var d in dts) { var startCaption = d.ToString(sufixFormat); var endCaption = ""; string groupLabel; switch (discreteType) { case enumTimeDiscreteType.DB24Hour: groupLabel = "За " + startCaption; endCaption = d.AddDays(1).ToString(sufixFormat); break; case enumTimeDiscreteType.DBMonth: groupLabel = "За " + d.ToString("MMMM yyyy"); endCaption = d.AddMonths(1).ToString(sufixFormat); break; default: groupLabel = "За период c " + dtStart.ToString("dd.MM.yyyy HH:mm") + " по " + dtEnd.ToString("dd.MM.yyyy HH:mm"); endCaption = dtEnd.Date.AddDays(1).ToString(sufixFormat); break; } foreach (var prefix in prefixs) { var col = new DataColumnEx(prefix + startCaption, typeof(IConvertible)); switch (prefix) { case "_OnStart": col.Caption = startCaption; break; case "_OnEnd": col.Caption = endCaption; break; default: col.Caption = "Расход"; col.IsFValue = true; break; } col.GroupName = groupLabel; userTable.Columns.Add(col); } } #endregion #region Наполняем содержимым var rd = TimeSpan.FromDays(1); foreach (var tiVal in archiveIntegrals.IntegralsValue30orHour) { if (tiVal.Val_List == null) { continue; } var row = userTable.NewRow() as DataRowEx; TPSHierarchy ps; if (EnumClientServiceDictionary.DetailPSList.TryGetValue(tiVal.PS_ID, out ps)) { row["Parent"] = ps; } TInfo_TI ti; if (EnumClientServiceDictionary.TIHierarchyList.TryGetValue(tiVal.TI_Ch_ID.TI_ID, out ti)) { row["NameTI"] = ti; } row["Coeff"] = tiVal.CoeffTransformation; row["Channel"] = new TTariffPeriodID { ChannelType = tiVal.TI_Ch_ID.ChannelType, IsOV = false, TI_ID = tiVal.TI_Ch_ID.TI_ID, StartDateTime = dtStart, FinishDateTime = dtEnd, }; row["DataSource"] = EnumClientServiceDictionary .DataSourceTypeList .FirstOrDefault(v => EqualityComparer <EnumDataSourceType?> .Default.Equals(tiVal.TI_Ch_ID.DataSourceType, v.Key)) .Value; DateTime?startRangeDt = null, endRangeDt = null; //Обрабатываемый диапазон var rangeDiff = 0.0; //накопленный расход за диапазон var ranfeFlag = VALUES_FLAG_DB.None; //Состояние интегралов за диапазон var isFirst = true; //Перебираем интегралы foreach (var iVal in tiVal.Val_List.OrderBy(d => d.EventDateTime)) { if (isFirst) { row["CoeffLosses"] = iVal.CoeffLosses ?? 1; isFirst = false; } var roundedDt = iVal.EventDateTime.Round(rd); //Это новая запись или переход на следующую дату/время if (!startRangeDt.HasValue || roundedDt >= endRangeDt) { if (iVal.IsIntegralType) { //Эта дата осталась от предыдущего диапазона, надо закрыть диапазона if (startRangeDt.HasValue) { row["_OnEnd" + startRangeDt.Value.ToString(sufixFormat)] = iVal.F_VALUE / unitDigitCoeff; row["_Delta" + startRangeDt.Value.ToString(sufixFormat)] = new TVALUES_DB { F_VALUE = rangeDiff, F_FLAG = ranfeFlag, }; } if (roundedDt > dtEnd) { break; } //Теперь новый диапазон switch (discreteType) { case enumTimeDiscreteType.DB24Hour: //Первая дата/время нового диапазона startRangeDt = new DateTime(roundedDt.Year, roundedDt.Month, roundedDt.Day); //Последняя дата/время нового диапазона endRangeDt = startRangeDt.Value.AddDays(1); break; case enumTimeDiscreteType.DBMonth: //Первая дата/время нового диапазона startRangeDt = new DateTime(roundedDt.Year, roundedDt.Month, 1); //Последняя дата/время нового диапазона endRangeDt = startRangeDt.Value.AddMonths(1); break; default: //Первая дата/время нового диапазона startRangeDt = dtStart.Date; //Последняя дата/время нового диапазона endRangeDt = dtEnd.Date.AddDays(1); break; } row["_OnStart" + startRangeDt.Value.ToString(sufixFormat)] = iVal.F_VALUE / unitDigitCoeff; rangeDiff = 0; ranfeFlag = VALUES_FLAG_DB.None; } } rangeDiff += iVal.F_VALUE_DIFF / unitDigitCoeff; ranfeFlag = ranfeFlag.CompareAndReturnMostBadStatus(iVal.F_FLAG); } userTable.Rows.Add(row); } #endregion } finally { userTable.EndLoadData(); userTable.AcceptChanges(); } #if DEBUG sw.Stop(); Console.WriteLine("ExecuteDailyIntegralsExpand - > {0} млс", sw.ElapsedMilliseconds); #endif return(userTable); }