public override IList<Data.Database.ColumnInfo> GetColumns(string tbl_name) { var ret = new List<ColumnInfo>(); var sql = "SELECT c.name 'name', t.name 'type', c.max_length 'length', c.precision, c.scale, c.is_nullable " + "FROM sys.columns c " + " INNER JOIN sys.types t " + " ON c.user_type_id = t.user_type_id " + "WHERE c.object_id = OBJECT_ID('"+tbl_name+"')"; var rows = this.ExecuteQuery( sql ); foreach( var row in rows ) { var ci = new ColumnInfo() { Name = (string)row["name"], DataType = (string)row["type"], MaxLength = (short)row["length"], Precision = (byte)row["precision"], Scale = (byte)row["scale"], IsNullable = (bool)row["is_nullable"] }; ret.Add( ci ); } return ret; }
/// <summary> /// Class constructor /// </summary> /// <param name="columnInfo">Columninfo</param> public DBInteraction(ColumnInfo columnInfo) { this.connectionString = columnInfo.dataMatrix.database.odbcConnectionString; this.columnSelectExpression = columnInfo.columnSelectExpression; this.dataMatrixName = columnInfo.dataMatrix.dataMatrixName; this.rowCount = columnInfo.dataMatrix.recordsCount; }
public AddColumnAction(ColumnInfo column) { if (column == null) throw new ArgumentNullException("column"); Column = column; }
CSVSheet(string filePath, TextLine textLine) { Assert.IsTrue(textLine != null); this.filePath = filePath; using (var lines = textLine.GetEnumerator()) { lines.MoveNext(); string colNames = lines.Current; lines.MoveNext(); string colTypes = lines.Current; this.columnInfo = new ColumnInfo(colNames, colTypes, filePath); List<RowData> tempList = new List<RowData>(); while (lines.MoveNext()) { string line = lines.Current; if (!string.IsNullOrEmpty(line)) { var tokens = line.Split(','); var newRow = new RowData(tokens); Assert.IsTrue(newRow.IsValidInLength(columnInfo), string.Format("tokens.Length={0}, columnInfo.Length={1} in \n{2}", tokens.Length, columnInfo.Length, line)); int errIndex; Assert.IsTrue(newRow.IsValidInType(columnInfo, out errIndex), errIndex < 0 ? string.Empty : string.Format("Converting error: [{0}] to {1} in {2}", tokens[errIndex], columnInfo[errIndex].Value, filePath)); tempList.Add(newRow); } } rows = tempList; } }
public StructuredParameterSchema(ISerializationTypeInfo typeInfo, ISerializationTypeMappingProvider typeMappingProvider) { SetupColumns(typeInfo.Type.Name, typeInfo.Type.Namespace); DataColumn columnName = Columns[SchemaTableColumn.ColumnName]; DataColumn allowDbNull = Columns[SchemaTableColumn.AllowDBNull]; DataColumn dataType = Columns[SchemaTableColumn.DataType]; /* DataColumn numericScale = Columns[SchemaTableColumn.NumericScale]; DataColumn numericPrecision = Columns[SchemaTableColumn.NumericPrecision]; DataColumn columnSize = Columns[SchemaTableColumn.ColumnSize]; */ DataColumn baseColumnName = Columns[SchemaTableColumn.BaseColumnName]; DataColumn providerType = Columns[SchemaTableColumn.ProviderType]; DataColumn nonVersionedProviderType = Columns[SchemaTableColumn.NonVersionedProviderType]; DataColumn columnOrdinal = Columns[SchemaTableColumn.ColumnOrdinal]; List<SqlColumnInfo> sqlColumnInfos = new List<SqlColumnInfo>(); List<ColumnInfo> columns = new List<ColumnInfo>(); Dictionary<SqlColumnInfo, int> columnIndices = new Dictionary<SqlColumnInfo, int>(); if (typeInfo.Mapping.IsNativeType) { DataRow row = NewRow(); row[columnName] = "value"; row[columnOrdinal] = 0; row[dataType] = typeInfo.Type; row[allowDbNull] = true; row[baseColumnName] = "value"; row[providerType] = (int)typeInfo.Mapping.DbType; Rows.Add(row); columns.Add(new ColumnInfo(0, "value", Enum.GetName(typeof(SqlDbType), typeInfo.Mapping.DbType), typeInfo.Type)); IMemberConverter memberConverter = MemberConverter.Get(typeInfo.Type, false, "value", 0, DateTimeKind.Unspecified); sqlColumnInfos.Add(new SqlColumnInfo(typeMappingProvider.GetMapping(typeInfo.Type), "value", memberConverter)); } else { foreach (MemberInfo memberInfo in typeInfo.Type.GetAllFieldsAndProperties()) { SqlColumnAttribute sqlColumn = SqlColumnAttributeBase.Get<SqlColumnAttribute>(memberInfo, false); if (sqlColumn != null) { Type memberType = memberInfo.GetMemberType(); SqlColumnInfo sqlColumnInfo = typeInfo.Mapping.Columns[sqlColumn.Name]; StructuredParameterAttribute parameterAttribute = StructuredParameterAttribute.GetStructuredParameterAttribute(memberInfo); Debug.Assert(parameterAttribute != null); ColumnInfo ci = new ColumnInfo(sqlColumnInfos.Count, sqlColumnInfo.Name, GetDataTypeName(sqlColumnInfo, memberType), memberType); DataRow row = NewRow(); row[columnName] = ci.ColumnName; row[columnOrdinal] = parameterAttribute.Position; row[dataType] = Nullable.GetUnderlyingType(ci.DataType) ?? ci.DataType; row[allowDbNull] = ci.DataType.IsNullableType(); row[baseColumnName] = ci.ColumnName; row[providerType] = (int)sqlColumnInfo.DbType; row[nonVersionedProviderType] = (int)sqlColumnInfo.DbType; Rows.Add(row); columnIndices.Add(sqlColumnInfo, parameterAttribute.Position); sqlColumnInfos.Add(sqlColumnInfo); columns.Add(ci); } } sqlColumnInfos = sqlColumnInfos.OrderBy(ci => columnIndices[ci]).ToList(); } MappedColumns = sqlColumnInfos.AsReadOnly(); ColumnsInfos = columns.ToArray(); if ((MappedColumns.Count != 1) ||(MappedColumns[0].MemberInfo != null)) { ExtractMembers = MembersMethods.Get(MappedColumns.Select(c => c.MemberInfo).ToArray()).ExtractMembers; } AcceptChanges(); }
protected override void DoRun() { var tables = Connection.GetSchema("Tables"); var columns = new List<DataRow>(); foreach (DataRow row in Connection.GetSchema("Columns").Rows) columns.Add(row); columns = new List<DataRow>(columns.SortedByKey<DataRow, int>(c => c.SafeInt("ORDINAL_POSITION"))); foreach (DataRow row in tables.Rows) { if (row.SafeString("TABLE_TYPE") != "BASE TABLE") continue; var table = new TableInfo(Result); table.FullName = new NameWithSchema(row.SafeString("TABLE_SCHEMA"), row.SafeString("TABLE_NAME")); Result.Tables.Add(table); _tables[table.FullName] = table; } foreach (DataRow row in columns) { if (row.SafeString("TABLE_TYPE") != "BASE TABLE") continue; var tname = new NameWithSchema(row.SafeString("TABLE_SCHEMA"), row.SafeString("TABLE_NAME")); var table = _tables[tname]; var col = new ColumnInfo(table); col.Name = row.SafeString("COLUMN_NAME"); col.NotNull = row.SafeString("IS_NULLABLE") == "NO"; col.DataType = row.SafeString("DATA_TYPE"); col.Length = row.SafeInt("CHARACTER_MAXIMUM_LENGTH"); col.Precision = row.SafeInt("NUMERIC_PRECISION"); col.Scale = row.SafeInt("NUMERIC_SCALE"); col.DefaultValue = row.SafeString("COLUMN_DEFAULT"); table.Columns.Add(col); } }
public TableInfo(string connectionString, string tableName, string schemaName, ColumnInfo[] columns) { ConnectionString = connectionString; TableName = tableName; SchemaName = schemaName; Columns = columns; }
public TableOperations(DbConnection connection, string tableName, ColumnInfo[] columnInfos, string[] primaryKeyColumns) { this.TableName = tableName; this.ColumnInfos = columnInfos; this.PrimaryKeyColumns = primaryKeyColumns; this.connection = connection; this.PrimaryKeyLocator = this.GetLocatorByPrimaryKey(); }
public static ColumnInfo CreateColumnInfo(object desc, object name, ConfigDataType dt) { ColumnInfo info = new ColumnInfo(); string sName = null == name ? string.Empty : name.ToString().Trim(); string sDesc = null == desc ? string.Empty : desc.ToString().Trim(); info.ColDesc = sDesc; info.ConfigName = sName; info.DataType = dt; return info; }
object IPreparable.Prepare(IExpressionPreparer preparer) { var newColumn = new ColumnInfo(Column.ColumnName, Column.ColumnType) { IsNotNull = Column.IsNotNull }; var defaultExp = Column.DefaultExpression; if (defaultExp != null) newColumn.DefaultExpression = defaultExp.Prepare(preparer); return new AddColumnAction(newColumn); }
public static ColumnInfo GetColumnInfoFrom(IDataReader reader) { string columnName = reader.IsDBNull(0) ? string.Empty : reader.GetString(0); string dataType = reader.IsDBNull(1) ? string.Empty : reader.GetString(1); int size = reader.IsDBNull(2) ? 0 : reader.GetInt32(2); ColumnInfo column = new ColumnInfo( columnName, dataType, size ); return column; }
public AlertExelForm(Type type,int sessionId, string fileNameSuffix) { InitializeComponent(); this.fileNameSuffix = fileNameSuffix; this.sessionId = sessionId; this.type = type; string[] columnTitles = new string[]{ "Name","Des","Group","Serial No","Phone Number","Router IP","Session Id", "Band","Lan IP","Wan IP","Device Status" ,"VPN","WIFI","SMS","Firmware","Ext Power", "Battery","Signal","Period","NMS version","Occuerrence Time", "Reset Time" }; this.columnInfos = new ColumnInfo[columnTitles.Length]; for (int i = 0; i < columnTitles.Length; i++) { columnInfos[i] = new ColumnInfo(columnTitles[i], true); } //그리드와 관련한 필요 object 생성 //Border border = new DevAge.Drawing.BorderLine(Color.Black, 1); cellBorder = new DevAge.Drawing.RectangleBorder(border, border); //Views viewNormal = new CellBackColorAlternate(Color.Khaki, Color.DarkKhaki); viewNormal.Border = cellBorder; viewNormal.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter; viewNormal.Font = new Font("돋음", 8, FontStyle.Regular); viewCheckBox = new CheckBoxBackColorAlternate(Color.Khaki, Color.DarkKhaki); viewCheckBox.Border = cellBorder; //ColumnHeader view viewColumnHeader = new SourceGrid.Cells.Views.ColumnHeader(); backHeader = new DevAge.Drawing.VisualElements.ColumnHeader(); backHeader.BackColor = Color.DimGray; //backHeader.Border = DevAge.Drawing.RectangleBorder.NoBorder; viewColumnHeader.Background = backHeader; viewColumnHeader.ForeColor = Color.White; viewColumnHeader.Font = new Font("맑은 고딕", 10, FontStyle.Bold); viewColumnHeader1 = new SourceGrid.Cells.Views.ColumnHeader(); backHeader1 = new DevAge.Drawing.VisualElements.ColumnHeader(); backHeader1.BackColor = Color.DarkSlateGray; viewColumnHeader1.Background = backHeader1; //viewColumnHeader1.Border = cellBorder; viewColumnHeader1.ForeColor = Color.White; viewColumnHeader1.Font = new Font("굴림", 8, FontStyle.Regular); viewColumnHeader1.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter; }
/// <summary> /// export excel file /// </summary> /// <param name="excelInfo">DataTable need to be export.</param> public void exportExcel(DataTable excelInfo) { var xls = new XlsDocument(); // set excel file xls.FileName = HttpContext.Current.Server.UrlEncode(excelInfo.TableName) + ".xls"; //;"Detail.xls"; // create excel sheet page Worksheet sheet = xls.Workbook.Worksheets.Add("Sheet1"); // set column width var ci = new ColumnInfo(xls, sheet); ci.ColumnIndexStart = 1; ci.ColumnIndexEnd = (ushort) (excelInfo.Columns.Count - 1); ci.Width = 13*256; sheet.AddColumnInfo(ci); // output content Cells cells = sheet.Cells; // set title style XF xf = xls.NewXF(); xf.HorizontalAlignment = HorizontalAlignments.Centered; xf.VerticalAlignment = VerticalAlignments.Centered; // output title cells.Merge(1, 1, 1, excelInfo.Columns.Count); cells.Add(1, 1, excelInfo.TableName, xf); // append cell style xf.UseBorder = true; xf.TopLineStyle = 1; xf.BottomLineStyle = 1; xf.LeftLineStyle = 1; xf.RightLineStyle = 1; // output data for (int i = 0; i < excelInfo.Columns.Count; i++) { // output output table header cells.Add(2, i + 1, excelInfo.Columns[i].ColumnName, xf); // output data for (int j = 0; j < excelInfo.Rows.Count; j++) { // check data type if (IsFloat(excelInfo.Rows[j][i].ToString())) { cells.Add(j + 3, i + 1, Convert.ToDecimal(excelInfo.Rows[j][i]), xf); } else { cells.Add(j + 3, i + 1, excelInfo.Rows[j][i].ToString(), xf); } } } xls.Send(); }
public List<ColumnInfo> GetColumnsInfo() { List<ColumnInfo> info = new List<ColumnInfo>(); GridView view = GetView(); foreach (MenuItem item in m_ConextMenu.Items){ GridViewColumn col = item.Tag as GridViewColumn; ColumnInfo i = new ColumnInfo() { Header = item.Header as string, Width = col.ActualWidth, IsVisible = item.IsChecked }; info.Add(i); } return info; }
public override void PreExecute() { // Prepare array of column information. Processing requires // lineageID so we can do this once in advance. IDTSInput100 input = ComponentMetaData.InputCollection[0]; _inputColumnInfos = new ColumnInfo[input.InputColumnCollection.Count]; for (int x = 0; x < input.InputColumnCollection.Count; x++) { IDTSInputColumn100 column = input.InputColumnCollection[x]; _inputColumnInfos[x] = new ColumnInfo(); _inputColumnInfos[x].bufferColumnIndex = BufferManager.FindColumnByLineageID(input.Buffer, column.LineageID); _inputColumnInfos[x].columnDisposition = column.ErrorRowDisposition; _inputColumnInfos[x].lineageID = column.LineageID; } }
protected override List<ColumnInfo> GetColumns(DataConnection dataConnection) { var sql = @" SELECT TABSCHEMA, TABNAME, COLNAME, LENGTH, SCALE, NULLS, IDENTITY, COLNO, TYPENAME, REMARKS, CODEPAGE FROM SYSCAT.COLUMNS WHERE " + GetSchemaFilter("TABSCHEMA"); return _columns = dataConnection.Query(rd => { var typeName = rd.ToString(8); var cp = Converter.ChangeTypeTo<int>(rd[10]); if (typeName == "CHARACTER" && cp == 0) typeName = "CHAR () FOR BIT DATA"; else if (typeName == "VARCHAR" && cp == 0) typeName = "VARCHAR () FOR BIT DATA"; var ci = new ColumnInfo { TableID = dataConnection.Connection.Database + "." + rd.GetString(0) + "." + rd.GetString(1), Name = rd.ToString(2), IsNullable = rd.ToString(5) == "Y", IsIdentity = rd.ToString(6) == "Y", Ordinal = Converter.ChangeTypeTo<int>(rd[7]), DataType = typeName, Description = rd.ToString(9), }; SetColumnParameters(ci, Converter.ChangeTypeTo<long?>(rd[3]), Converter.ChangeTypeTo<int?> (rd[4])); return ci; }, sql).ToList(); }
TableGenerator(string resPath, string className) { TextAsset csvFile = Resources.Load(resPath) as TextAsset; Assert.IsTrue(csvFile != null, "File not found: " + resPath); TextLine textLine = new TextLine(csvFile.text); Assert.IsTrue(textLine != null); using (var lines = textLine.GetEnumerator()) { lines.MoveNext(); string colNames = lines.Current; lines.MoveNext(); string colTypes = lines.Current; this.columnInfo = new ColumnInfo(colNames, colTypes, resPath); } this.className = className; }
public override ColumnInfo getColumnInfo(Ice.Current __current) { DataMatrixInfo dataMatrixInfo = this.getDataMatrixFunctionsPrx().getDataMatrixInfo(); string connectionString = dataMatrixInfo.database.odbcConnectionString; string dataMatrixName = dataMatrixInfo.dataMatrixName; string columnSelectExpression = this.columnSelectExpression; Ferda.Modules.Helpers.Data.Column.TestColumnSelectExpression( connectionString, dataMatrixName, columnSelectExpression, boxModule.StringIceIdentity); ColumnInfo result = new ColumnInfo(); result.statistics = getStatisticsStruct(dataMatrixInfo); result.dataMatrix = dataMatrixInfo; result.columnSelectExpression = columnSelectExpression; result.columnSubType = columnValueSubType; result.columnType = ColumnTypeEnum.Derived; return result; }
public ColumnSelection(Object obj, ColumnInfo[] columnInfos,string p) { InitializeComponent(); // TODO: Complete member initialization this.p = p; this.obj = obj; this.columnInfos = columnInfos; if (p.Equals("alert")) { this.grid = ((Alerts)this.obj).alertGrid; this.columnMap = ApplicationConfig.Instance().AlertColumnSetting; } if (p.Equals("device")){ this.grid = ((Device)this.obj).deviceGrid; this.columnMap = ApplicationConfig.Instance().DeviceColumnSetting; } }
public override Widget GetPropertyEditWidget(Widget parent, ColumnInfo column, IRecordList records) { switch (column.Name) { case "PayloadType": LabeledWidget<DropDown> dd = Context.Current.CreateWidget<LabeledWidget<DropDown>>(); dd.LabelText = "Task Type"; dd.Widget.Options = getTaskTypes(); dd.Widget.OnChanged += new EventHandler<EmergeTk.ChangedEventArgs>(delegate(object sender, ChangedEventArgs ea ) { string opt = dd.Widget.SelectedOption; this.payloadType = opt != "--SELECT--" ? opt : null; }); dd.Widget.SelectedOption = this.payloadType; return dd; default: return base.GetPropertyEditWidget(parent, column, records); } }
public void TestGetHashcode() { Tuple<string, string, string, string, string>[] tests = { Tuple.Create("", "", "", "", ""), Tuple.Create("name","", "", "", ""), Tuple.Create("name","db", "", "", ""), Tuple.Create("name","db", "table", "", ""), Tuple.Create("name","db", "table", "column", ""), Tuple.Create("name","db", "table", "column", "Variant"), }; foreach (var test in tests) { var fst = new ColumnInfo(test.Item1, test.Item2, test.Item3, test.Item4, test.Item5); var snd = new ColumnInfo(test.Item1, test.Item2, test.Item3, test.Item4, test.Item5); Assert.Equal(fst.GetHashCode(), snd.GetHashCode()); } }
public void TestEquality() { Tuple<string, string, string, string, string>[] tests = { Tuple.Create("", "", "", "", ""), Tuple.Create("name","", "","", ""), Tuple.Create("name","db", "", "", ""), Tuple.Create("name","db", "table", "", ""), Tuple.Create("name","db", "table", "column", ""), Tuple.Create("name","db", "table", "column", "Variant"), }; Assert.False(new ColumnInfo("", "", "", "", "").Equals(null)); Assert.False(new ColumnInfo("", "", "", "", "").Equals(new Object())); for (int i = 0; i < tests.Length; i++) { for (int j = 0; j < tests.Length; j++) { var fst = new ColumnInfo(tests[i].Item1, tests[i].Item2, tests[i].Item3, tests[i].Item4, tests[i].Item5); var snd = new ColumnInfo(tests[j].Item1, tests[j].Item2, tests[j].Item3, tests[j].Item4, tests[j].Item5); if (i == j) { Assert.True(fst.Equals(fst)); Assert.True(snd.Equals(snd)); Assert.Equal(fst, snd); Assert.True(fst == snd); Assert.False(fst != snd); } else { Assert.NotEqual(fst, snd); Assert.False(fst == snd); Assert.True(fst != snd); } } } }
public string Aspx() { string strResult = string.Empty; StringBuilder strbRecordField = new StringBuilder(); StringBuilder strbColumn = new StringBuilder(); StringBuilder strbTextField = new StringBuilder(); DataTable dt = GetProperty.DataTable; foreach (DataRow dr in dt.Rows) { ColumnInfo cols = new ColumnInfo(); cols = GetColumnInfo(dr); strbRecordField.AppendLine("<ext:RecordField Name=\"" + cols.ColumnName + "\" />"); strbColumn.AppendLine("<ext:Column ColumnID=\"" + cols.ColumnName + "\" DataIndex=\"" + cols.ColumnName + "\" Header=\"" + IsNull(cols.Remark, cols.ColumnName) + "\" />"); strbTextField.AppendLine("<ext:TextField ID=\"txt" + VarModel(cols.ColumnName) + "\" runat=\"server\" FieldLabel=\"" + cols.Remark + "\" Width=\"100\" DataIndex=\"" + cols.ColumnName + "\" />"); } //ģ������ strResult = GetProperty.ModuleCode; if (!string.IsNullOrEmpty(strResult)) { strResult = strResult.Replace("$RecordField$", strbRecordField.ToString()); strResult = strResult.Replace("$Column$", strbColumn.ToString()); strResult = strResult.Replace("$TextField$", strbTextField.ToString()); } else { strResult = strbRecordField.ToString(); strResult += strbColumn.ToString(); strResult += strbTextField.ToString(); } return strResult; }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="column"></param> /// <param name="databaseColumn"></param> protected virtual void AlterColumn(ColumnInfo column, ColumnInfo databaseColumn) { var alterColumnCommand = ColumnCommand <IAlterColumnCommand>(column); alterColumnCommand?.SetDatabaseColumn(databaseColumn); }
public Spreadsheet( string path ) { using ( StreamReader ip = new StreamReader( path ) ) { string[] types = ReadLine( ip ); string[] names = ReadLine( ip ); m_Columns = new ColumnInfo[types.Length]; for ( int i = 0; i < m_Columns.Length; ++i ) m_Columns[i] = new ColumnInfo( i, types[i], names[i] ); ArrayList records = new ArrayList(); string[] values; while ( ( values = ReadLine( ip ) ) != null ) { object[] data = new object[m_Columns.Length]; for ( int i = 0; i < m_Columns.Length; ++i ) { ColumnInfo ci = m_Columns[i]; switch ( ci.m_Type ) { case "int": { data[i] = Utility.ToInt32( values[ci.m_DataIndex] ); break; } case "string": { data[i] = values[ci.m_DataIndex]; break; } } } records.Add( new DataRecord( this, data ) ); } m_Records = (DataRecord[]) records.ToArray( typeof( DataRecord ) ); } }
public void AddNOTCondition(ColumnInfo parameter, string sqlOperator, object parameterValue) { AddNOTCondition("", "", parameter, sqlOperator, parameterValue, ""); }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="column"></param> protected virtual void DropColumn(ColumnInfo column) { ColumnCommand <IDropColumnCommand>(column); }
private bool AlreadyInCatalogue(ColumnInfo candidate) { return(_existingColumnInfos.Contains(candidate.ID)); }
private Size CreateColumnInfos() { int index = 0; Size minMax = new Size(); bool firstSeries = true; foreach (var series in Data.Series) { foreach (var item in series.Values) { if (item.Hidden) { continue; } ColumnInfo info = null; if (index < bars.Count) { info = bars[index]; } else { info = new ColumnInfo(); bars.Add(info); } info.Data = item; info.Color = item.Color.Value; if (firstSeries && !string.IsNullOrEmpty(item.Label)) { var block = info.Label; if (block == null) { block = new TextBlock() { Foreground = this.Foreground }; info.Label = block; } block.Text = item.Label; block.BeginAnimation(TextBlock.OpacityProperty, null); block.Opacity = 0; ChartCanvas.Children.Add(block); // so it measures properly. block.Measure(new Size(100, 100)); ChartCanvas.Children.Remove(block); var size = block.DesiredSize; minMax.Width = Math.Max(minMax.Width, size.Width); minMax.Height = Math.Max(minMax.Height, size.Height); } else { info.Label = null; } index++; } firstSeries = false; } bars.RemoveRange(index, bars.Count - index); return(minMax); }
private void dgvGridview_CellContentClick(object sender, DataGridViewCellEventArgs e) { DataGridView dgv = sender as DataGridView; if (dgv != null) { bool isFrmMain = dgv.FindForm() is FrmMain; if (e.RowIndex >= 0) { DataGridViewColumn column = dgv.Columns[e.ColumnIndex]; DataGridViewRow row = dgv.Rows[e.RowIndex]; if (isFrmMain && column.Name == "dgvColName" || column.Name == "dgvColView") { string pdgvColName = string.Concat(row.Cells["dgvColName"].Value); string dgvColValue = string.Concat(column.Name == "dgvColView" ? row.Cells["dgvColView"].Value : null); string viewTable = isFrmMain ? pdgvColName : row.Cells["dgvColView"].Tag.ToString(); string name = isFrmMain ? pdgvColName : dgv.Tag.ToString(); if (dgvColValue == "FK-x") { Lib.Msgbox("引用了外部项目,请直接生成后查看代码!"); return; } TableInfo table = _tables.Find(delegate(TableInfo table1) { return(viewTable == table1.FullName); }); if (table == null) { return; } FrmView frmView = new FrmView(); frmView.Text = isFrmMain ? (name + " - view") : (name + "." + pdgvColName + " - " + table.FullName + " - relation view"); frmView.dgvGridview.Tag = viewTable; foreach (ColumnInfo c1 in table.Columns) { string viewText = null; object image = c1.IsPrimaryKey ? this.imageList1.Images["PrimaryKey.ico"] : null; table.ForeignKeys.FindAll(delegate(ForeignKeyInfo fk) { ColumnInfo c2 = fk.Columns.Find(delegate(ColumnInfo c3) { return(c3.Name == c1.Name); }); if (c2 != null) { if (fk.ReferencedTable != null) { viewTable = fk.ReferencedTable.FullName; viewText = "View"; } else { viewTable = fk.ReferencedTableName; viewText = "FK-x"; } if (image == null) { image = imageList1.Images["Key.ico"]; } } return(c2 != null); }); frmView.dgvGridview.Rows.Add(new object[] { image, c1.Name, c1.SqlType, c1.IsNullable, viewText }); if (viewText != null) { frmView.dgvGridview.Rows[frmView.dgvGridview.Rows.Count - 1].Cells["dgvColView"].Tag = viewTable; } } frmView.dgvGridview.CellContentClick += dgvGridview_CellContentClick; frmView.ShowDialog(); frmView.Dispose(); } } } }
public override DbParameter AppendParamter(List <DbParameter> _params, string parameterName, ColumnInfo col, Type type, object value) { if (string.IsNullOrEmpty(parameterName)) { parameterName = $"p_{_params?.Count}"; } if (value?.Equals(DateTime.MinValue) == true) { value = new DateTime(1970, 1, 1); } var ret = new OdbcParameter { ParameterName = QuoteParamterName(parameterName), Value = value }; var tp = _orm.CodeFirst.GetDbInfo(type)?.type; if (tp != null) { ret.OdbcType = (OdbcType)tp.Value; } _params?.Add(ret); return(ret); }
/// <summary> /// It is strongly recommended to call this functions before calling any other function in this class. /// </summary> public GeneratedAttribute Value(string boxIdentity, BoxModuleI boxModule, ColumnInfo columnInfo) { lock (this) { Dictionary<string, IComparable> cacheSetting = new Dictionary<string, IComparable>(); cacheSetting.Add(Database.DatabaseBoxInfo.typeIdentifier + Database.DatabaseBoxInfo.OdbcConnectionStringPropertyName, columnInfo.dataMatrix.database.odbcConnectionString); cacheSetting.Add(DataMatrix.DataMatrixBoxInfo.typeIdentifier + DataMatrix.DataMatrixBoxInfo.DataMatrixNamePropertyName, columnInfo.dataMatrix.dataMatrixName); cacheSetting.Add(DataMatrix.DataMatrixBoxInfo.typeIdentifier + DataMatrix.DataMatrixBoxInfo.RecordCountPropertyName, columnInfo.dataMatrix.recordsCount); cacheSetting.Add(Column.ColumnBoxInfo.typeIdentifier + Column.ColumnBoxInfo.ColumnSelectExpressionPropertyName, columnInfo.columnSelectExpression); if (IsObsolete(columnInfo.dataMatrix.database.lastReloadInfo, cacheSetting)) { value = new GeneratedAttribute(); value = EachValueOneCategoryAlgorithm.Generate( columnInfo.dataMatrix.database.odbcConnectionString, columnInfo.dataMatrix.dataMatrixName, columnInfo.columnSelectExpression, boxIdentity); } if (value == null) value = new GeneratedAttribute(); return value; } }
/// <summary> /// It is strongly recommended to call this functions before calling any other function in this class. /// </summary> public GeneratedAttribute Value(string boxIdentity, BoxModuleI boxModule, ColumnInfo columnInfo, AttributeDomainEnum domainType, double from, double to, long countOfCategories) { lock (this) { Dictionary<string, IComparable> cacheSetting = new Dictionary<string, IComparable>(); cacheSetting.Add(Database.DatabaseBoxInfo.typeIdentifier + Database.DatabaseBoxInfo.OdbcConnectionStringPropertyName, columnInfo.dataMatrix.database.odbcConnectionString); cacheSetting.Add(DataMatrix.DataMatrixBoxInfo.typeIdentifier + DataMatrix.DataMatrixBoxInfo.DataMatrixNamePropertyName, columnInfo.dataMatrix.dataMatrixName); cacheSetting.Add(DataMatrix.DataMatrixBoxInfo.typeIdentifier + DataMatrix.DataMatrixBoxInfo.RecordCountPropertyName, columnInfo.dataMatrix.recordsCount); cacheSetting.Add(Column.ColumnBoxInfo.typeIdentifier + Column.ColumnBoxInfo.ColumnSelectExpressionPropertyName, columnInfo.columnSelectExpression); cacheSetting.Add("DomainType", domainType); cacheSetting.Add("From", from); cacheSetting.Add("To", to); cacheSetting.Add("CountOfCategories", countOfCategories); if (IsObsolete(columnInfo.dataMatrix.database.lastReloadInfo, cacheSetting)) { try { value = EquidistantAlgorithm.Generate( domainType, from, to, countOfCategories, columnInfo, boxIdentity); } catch (Ferda.Modules.BadParamsError ex) { value = new GeneratedAttribute(); if (ex.restrictionType == restrictionTypeEnum.DbColumnDataType) { boxModule.OutputMessage( Ferda.ModulesManager.MsgType.Info, "UnsupportedColumnDatatype", "NumericDatatypesSupportedOnly"); } else throw Ferda.Modules.Exceptions.BoxRuntimeError(ex, boxModule.StringIceIdentity, null); } } if (value == null) value = new GeneratedAttribute(); return value; } }
/// <summary> /// Initializes a new instance of the <see cref="ColumnInfoEventArgs"/> class. /// </summary> /// <param name="columnInfo">The column info.</param> public ColumnInfoEventArgs(ColumnInfo columnInfo) { this.columnInfo = columnInfo; }
/// <summary> /// Create new instance of <see cref="FieldPropertiesForm"/> /// </summary> /// <param name="columnData">Column data</param> public FieldPropertiesForm(ColumnInfo columnData) { if (columnData == null) { throw new ArgumentNullException("columnData"); } Contract.EndContractBlock(); _columnData = columnData; InitializeComponent(); if (this.IsDesignMode()) { return; } base.Text = string.Format("Column properties - {0}", _columnData.ColumnName); // Set bindings....... chApplySiteToAllCoumns.AddBinding <CheckBox, ColumnInfo>(c => c.Checked, _columnData, c => c.ApplySiteToAllColumns); chApplyVariableToAllColumns.AddBinding <CheckBox, ColumnInfo>(c => c.Checked, _columnData, c => c.ApplyVariableToAllColumns); chApplySourceToAllColumns.AddBinding <CheckBox, ColumnInfo>(c => c.Checked, _columnData, c => c.ApplySourceToAllColumns); chApplyMethodToAllColumns.AddBinding <CheckBox, ColumnInfo>(c => c.Checked, _columnData, c => c.ApplyMethodToAllColumns); chApplyQualityControlToAllColumns.AddBinding <CheckBox, ColumnInfo>(c => c.Checked, _columnData, c => c.ApplyQualityControlToAllColumns); chApplyOffsetToAllColumns.AddBinding <CheckBox, ColumnInfo>(c => c.Checked, _columnData, c => c.ApplyOffsetToAllColumns); // Site siteView1.ReadOnly = true; cmbSites.SelectedIndexChanged += CmbSitesOnSelectedIndexChanged; var sitesRepo = RepositoryFactory.Instance.Get <ISitesRepository>(); var sites = sitesRepo.GetAll(); if (_columnData.Site != null && !Array.Exists(sites, site => _columnData.Site == site)) { Array.Resize(ref sites, sites.Length + 1); sites[sites.Length - 1] = _columnData.Site; } sitesBindingSource.DataSource = sites; cmbSites.DataSource = sitesBindingSource; cmbSites.DisplayMember = NameHelper.Name <Site, object>(s => s.Name); if (_columnData.Site != null) { cmbSites.SelectedItem = _columnData.Site; } // Variable variableView1.ReadOnly = true; cmbVariables.SelectedIndexChanged += CmbVariablesOnSelectedIndexChanged; var variablesRepo = RepositoryFactory.Instance.Get <IVariablesRepository>(); var variables = variablesRepo.GetAll(); if (_columnData.Variable != null && !Array.Exists(variables, v => _columnData.Variable == v)) { Array.Resize(ref variables, variables.Length + 1); variables[variables.Length - 1] = _columnData.Variable; } variablesBindingSource.DataSource = variables; cmbVariables.DataSource = variablesBindingSource; cmbVariables.DisplayMember = NameHelper.Name <Variable, object>(s => s.Name); if (_columnData.Variable != null) { cmbVariables.SelectedItem = _columnData.Variable; } // Source sourceView1.Entity = _columnData.Source; // Method methodView1.Entity = _columnData.Method; // Quality Control qualityControlLevelView1.Entity = _columnData.QualityControlLevel; // Offset offsetTypeView1.Entity = _columnData.OffsetType; nudOffsetValue.AddBinding <NumericUpDown, ColumnInfo>(x => x.Value, _columnData, c => c.OffsetValue); }
private void AddColumnInfo_Click(TableInfo tableInfo) { var newColumnInfo = new ColumnInfo(RepositoryLocator.CatalogueRepository, Guid.NewGuid().ToString(), "fish", tableInfo); Publish(newColumnInfo); }
public void SetUp() { var types = new[] { typeof(User), typeof(ExtraUserInfo), typeof(UserWithExtraInfo), typeof(Usersss), typeof(House), typeof(Supervisor) }; var dbFactory = new DatabaseFactory(); var config = FluentMappingConfiguration.Scan(s => { s.Assembly(typeof(User).GetTypeInfo().Assembly); s.IncludeTypes(types.Contains); s.PrimaryKeysNamed(y => ToLowerIf(y.Name + "Id", false)); s.TablesNamed(y => ToLowerIf(Inflector.MakePlural(y.Name), false)); s.Columns.Named(x => ToLowerIf(x.Name, false)); s.Columns.ForceDateTimesToUtcWhere(x => x.GetMemberInfoType() == typeof(DateTime) || x.GetMemberInfoType() == typeof(DateTime?)); s.Columns.ResultWhere(y => ColumnInfo.FromMemberInfo(y).ResultColumn); s.OverrideMappingsWith(new FluentMappingOverrides()); s.OverrideMappingsWith(new OneToManyMappings()); }); dbFactory.Config().WithFluentConfig(config); var configuration = new ConfigurationBuilder() .AddJsonFile("config.json") .Build(); var testDBType = Convert.ToInt32(configuration.GetSection("TestDBType").Value); switch (testDBType) { case 1: // SQLite In-Memory TestDatabase = new InMemoryDatabase(); Database = dbFactory.Build(new Database(TestDatabase.Connection)); break; case 2: // SQL Local DB case 3: // SQL Server TestDatabase = new SQLLocalDatabase(); Database = dbFactory.Build(new Database(TestDatabase.Connection, new SqlServer2008DatabaseType())); break; case 4: // SQL CE case 5: // MySQL case 6: // Oracle case 7: // Postgres Assert.Fail("Database platform not supported for unit testing"); return; #if !DNXCORE50 case 8: // Firebird TestDatabase = new FirebirdDatabase(); var db = new Database(TestDatabase.Connection, new FirebirdDatabaseType()); db.Mappers.Insert(0, new FirebirdDefaultMapper()); Database = dbFactory.Build(db); break; #endif default: Assert.Fail("Unknown database platform specified"); return; } InsertData(); }
protected override ColumnInfo GetColumnInfo(MemberInfo mi, Type type) { if (!_mappings.Config.ContainsKey(type)) { return(base.GetColumnInfo(mi, type)); } var typeConfig = _mappings.Config[type]; var columnInfo = new ColumnInfo() { MemberInfo = mi }; var key = mi.Name; bool explicitColumns = typeConfig.ExplicitColumns ?? false; var isColumnDefined = typeConfig.ColumnConfiguration.ContainsKey(key); if (isColumnDefined && typeConfig.ColumnConfiguration[key].ValueObjectColumn.HasValue && typeConfig.ColumnConfiguration[key].ValueObjectColumn.Value) { columnInfo.ValueObjectColumn = true; } else if (isColumnDefined && typeConfig.ColumnConfiguration[key].IsComplexMapping.HasValue && typeConfig.ColumnConfiguration[key].IsComplexMapping.Value) { columnInfo.ComplexMapping = true; if (typeConfig.ColumnConfiguration[key].ComplexPrefix != null) { columnInfo.ComplexPrefix = typeConfig.ColumnConfiguration[key].ComplexPrefix; } } else if (isColumnDefined && typeConfig.ColumnConfiguration[key].IsReferenceMember.HasValue && typeConfig.ColumnConfiguration[key].IsReferenceMember.Value) { if (typeConfig.ColumnConfiguration[key].ReferenceType != null) { columnInfo.ReferenceType = typeConfig.ColumnConfiguration[key].ReferenceType.Value; } if (typeConfig.ColumnConfiguration[key].ReferenceMember != null) { columnInfo.ReferenceMemberName = typeConfig.ColumnConfiguration[key].ReferenceMember.Name; } } else if (isColumnDefined && typeConfig.ColumnConfiguration[key].Serialized.HasValue && typeConfig.ColumnConfiguration[key].Serialized.Value) { columnInfo.SerializedColumn = true; } if (explicitColumns && !isColumnDefined) { columnInfo.IgnoreColumn = true; } if (isColumnDefined && (typeConfig.ColumnConfiguration[key].IgnoreColumn.HasValue && typeConfig.ColumnConfiguration[key].IgnoreColumn.Value)) { columnInfo.IgnoreColumn = true; } // Work out the DB column name if (isColumnDefined) { var colattr = typeConfig.ColumnConfiguration[key]; columnInfo.ColumnName = colattr.DbColumnName; columnInfo.ColumnAlias = colattr.DbColumnAlias; if (colattr.ResultColumn.HasValue && colattr.ResultColumn.Value) { columnInfo.ResultColumn = true; } else if (colattr.VersionColumn.HasValue && colattr.VersionColumn.Value) { columnInfo.VersionColumn = true; columnInfo.VersionColumnType = colattr.VersionColumnType ?? VersionColumnType.Number; } else if (colattr.ComputedColumn.HasValue && colattr.ComputedColumn.Value) { columnInfo.ComputedColumn = true; columnInfo.ComputedColumnType = colattr.ComputedColumnType ?? ComputedColumnType.Always; } if (colattr.ForceUtc.HasValue) { columnInfo.ForceToUtc = colattr.ForceUtc.Value; } columnInfo.ColumnType = colattr.DbColumnType; } return(columnInfo); }
/// <summary> /// 直接导出Excel /// </summary> /// <param name="dataTable">数据</param> /// <param name="filePathName">文件保存路径(E:\\excelname.xls)</param> /// <param name="sheetName">表单名称(表单1)</param> /// <param name="headers">头部显示的文字(编号,名称,...),如果为空则取dataTable的头</param> /// <returns>返回成功与否</returns> public static bool Export(DataTable dataTable, string filePathName, string sheetName, params string[] headers) { try { if (dataTable == null) { return(false); } if (filePathName == null) { return(false); } if (sheetName == null || sheetName.Trim() == "") { sheetName = "Sheet"; } if (headers == null) { headers = new string[0]; } string path = Path.GetDirectoryName(filePathName); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } List <string> headerList = headers.ToList(); if (headers.Length < dataTable.Columns.Count) { for (int i = headers.Length; i < dataTable.Columns.Count; i++) { headerList.Add(dataTable.Columns[i].ColumnName); } } XlsDocument xls = new XlsDocument();//新建Excel int startIndex = 0; int endIndex = startIndex + 65533; if (dataTable.Rows.Count < endIndex + 1) { endIndex = dataTable.Rows.Count - 1; } string sheetText = sheetName; int count = 0; do { //新建一个表单 Worksheet ws = xls.Workbook.Worksheets.Add(sheetText); //开始到出数据 ColumnInfo columnInfo = new ColumnInfo(xls, ws);//头 columnInfo.ColumnIndexStart = 0; columnInfo.ColumnIndexEnd = (ushort)(headerList.Count - 1); columnInfo.Width = 21 * 256; ws.AddColumnInfo(columnInfo); for (ushort i = 1; i <= headerList.Count; i++) { ws.Cells.Add((ushort)1, i, headerList[i - 1]); ws.Rows[1].GetCell(i).Font.Bold = true; ws.Rows[1].GetCell(i).Font.Height = 13 * 20; ws.Rows[1].GetCell(i).TopLineStyle = 1; ws.Rows[1].GetCell(i).BottomLineStyle = 2; ws.Rows[1].GetCell(i).LeftLineStyle = 1; ws.Rows[1].GetCell(i).RightLineStyle = 1; ws.Rows[1].GetCell(i).Pattern = 1; ws.Rows[1].GetCell(i).PatternColor = org.in2bits.MyXls.Colors.Default1F; } for (int i = startIndex; i <= endIndex; i++) { object[] objs = dataTable.Rows[i].ItemArray; for (ushort j = 1; j <= objs.Length; j++) { if (objs[j - 1] == DBNull.Value) { objs[j - 1] = ""; } else if (objs[j - 1].GetType().Equals(typeof(DateTime))) { objs[j - 1] = ((DateTime)objs[j - 1]).ToString("yyyy-MM-dd HH:mm:ss"); } else { Type type = objs[j - 1].GetType(); if (type.Equals(typeof(int)) || type.Equals(typeof(Int64)) || type.Equals(typeof(float)) || type.Equals(typeof(double)) || type.Equals(typeof(decimal)) || type.Equals(typeof(byte)) || type.Equals(typeof(ushort)) || type.Equals(typeof(uint)) || type.Equals(typeof(ulong))) { objs[j - 1] = "'" + objs[j - 1]; } } ws.Cells.Add((ushort)(i + 2 - startIndex), j, objs[j - 1]); ws.Rows[(ushort)(i + 2 - startIndex)].GetCell(j).Font.Height = 13 * 20; ws.Rows[(ushort)(i + 2 - startIndex)].GetCell(j).TopLineStyle = 1; ws.Rows[(ushort)(i + 2 - startIndex)].GetCell(j).BottomLineStyle = 1; ws.Rows[(ushort)(i + 2 - startIndex)].GetCell(j).LeftLineStyle = 1; ws.Rows[(ushort)(i + 2 - startIndex)].GetCell(j).RightLineStyle = 1; } } //--结束导出数据 //下一个表单计算 startIndex = endIndex + 1; if (startIndex >= dataTable.Rows.Count) { break; } else { endIndex = startIndex + 65533; if (dataTable.Rows.Count < endIndex + 1) { endIndex = dataTable.Rows.Count - 1; } sheetText = sheetName + "-" + (++count); } } while (true); xls.Save(filePathName, true); xls = null; return(true); } catch { return(false); } }
void CellRendererEdited(CellRendererTextAdv sender, string pathStr, string newText, int colNum) { TreeModelSort model = (TreeModelSort)treeDebaters.Model; TreePath path = new TreePath(pathStr); TreeIter iter = TreeIter.Zero; model.GetIter(out iter, path); EditableDebater d = (EditableDebater)model.GetValue(iter, 0); try { ColumnInfo prop = columns[treeDebaters.Columns[colNum].Title]; // This parses the given new string, // and updates the data in store prop.parseAndSet(d, newText); // existing Debater: Update Data in (possibly) existing Rounds // tries to keep data consisting, but there's no guarantee // BlackList/WhiteList and ExtraInfo are not // used in RoundDebater, so skip this by condition colNum<4 if (newDebaterPath == null && colNum < 4) { var rd = new EditableDebater(d); var p = prop.get(d); // Only simple Renaming of Role is possible if Rounds exist if (colNum == 3 && Tournament.I.Rounds.Count > 0 && ((d.Role.IsTeamMember != rd.Role.IsTeamMember) || (d.Role.IsJudge != rd.Role.IsJudge))) { MiscHelpers.ShowMessage(this, "Changing Role from Judge to TeamMember (or vice versa)" + " is not possible since Rounds are already set.", MessageType.Error); // reset to old role... d.Role = rd.Role; return; } // check if new TeamName is already present if (colNum == 3 && d.Role.IsTeamMember) { int n = 0; foreach (object[] row in store) { EditableDebater d_ = (EditableDebater)row[0]; if (!d.Equals(d_) && d_.Role.TeamName == d.Role.TeamName) { n++; } } if (n == 3) { MiscHelpers.ShowMessage(this, "New TeamName is already present in three other Debaters.", MessageType.Error); // reset to old role... d.Role = rd.Role; return; } } // check for duplicate if (colNum < 3) { // need a temporary flag, throwing exceptions in delegates doesnt work... // the following flag stuff isn't elegant, but it should work bool flag = false; model.Foreach((model_, _, iter_) => { if (!iter.Equals(iter_)) { EditableDebater d_ = (EditableDebater)model_.GetValue(iter_, 0); if (d_.Equals(d)) { // reset to old value... prop.get(rd).Set(d); flag = true; return(true); } } return(false); }); if (flag) { throw new TargetInvocationException(new Exception("Debater exists.")); } } // keep data consistent in existing rounds foreach (RoundData round in Tournament.I.Rounds) { foreach (RoomData room in round.Rooms) { foreach (RoundDebater rd_ in room.GetRoomMembers()) { if (rd_ == null) { continue; } if (rd_.Equals(rd)) { p.UnsafeSetRoundDebater(rd_); } if (rd_.Role.TeamName == rd.Role.TeamName) { rd_.Role.TeamName = d.Role.TeamName; } } } if (rd.Role.IsTeamMember) { foreach (TeamData team in round.AllTeams) { foreach (RoundDebater rd_ in team) { if (rd_.Equals(rd)) { p.UnsafeSetRoundDebater(rd_); } if (rd_.Role.TeamName == rd.Role.TeamName) { rd_.Role.TeamName = d.Role.TeamName; } } } } else if (rd.Role.IsJudge) { foreach (RoundDebater rd_ in round.AllJudges) { if (rd_.Equals(rd)) { p.UnsafeSetRoundDebater(rd_); } } } } // Renaming TeamName needs extra Handling if (colNum == 3 && rd.Role.IsTeamMember && d.Role.IsTeamMember) { foreach (object[] row in store) { EditableDebater d_ = (EditableDebater)row[0]; if (d_.Role.TeamName == rd.Role.TeamName) { d_.Role.TeamName = d.Role.TeamName; } } } } // newDebater is entered... else if (newDebaterPath != null && colNum < 3) { // continue with entering data (goto next column) // as idle so that cells are resized GLib.Idle.Add(delegate { treeDebaters.SetCursor(ConvertStorePathToModelPath(newDebaterPath), treeDebaters.Columns[colNum + 1], true); return(false); }); } else if (newDebaterPath != null) { // new Debater entered completely (at least all necessary data) iter = TreeIter.Zero; if (store.GetIter(out iter, newDebaterPath)) { // as idle to prevent gtk critical (no idea why this happens) GLib.Idle.Add(delegate { store.Remove(ref iter); newDebaterPath = null; if (IsNotInStore(d)) { store.AppendValues(d); SaveDebaters(); } else { MiscHelpers.ShowMessage(this, "Debater exists.", MessageType.Error); } UpdateDebatersInfo(); btnDebaterAdd.GrabFocus(); return(false); }); } } // Gui stuff treeDebaters.ColumnsAutosize(); // ugly method of resorting the TreeSortModel... SortType st; int sortColumn; model.GetSortColumnId(out sortColumn, out st); if (st == SortType.Descending) { model.SetSortColumnId(sortColumn, SortType.Ascending); model.SetSortColumnId(sortColumn, SortType.Descending); } else { model.SetSortColumnId(sortColumn, SortType.Descending); model.SetSortColumnId(sortColumn, SortType.Ascending); } // save data from store if not adding new debater if (newDebaterPath == null) { SaveDebaters(); } } catch (TargetInvocationException e) { MessageDialog md = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.OkCancel, e.InnerException.Message + ". Try again?"); md.DefaultResponse = ResponseType.Ok; ResponseType r = (ResponseType)md.Run(); md.Destroy(); if (r == ResponseType.Ok) { // As Idle otherwise Editable isn't destroyed correctly GLib.Idle.Add(delegate { sender.TempEditString = newText; treeDebaters.SetCursor(path, treeDebaters.Columns[colNum], true); return(false); }); } else { if (newDebaterPath == null) { return; } iter = TreeIter.Zero; if (store.GetIter(out iter, newDebaterPath)) { // remove not finished new debater, // with idle call, // prevents Gtk critical filter model assertion. GLib.Idle.Add(delegate { newDebaterPath = null; store.Remove(ref iter); return(false); }); } } } }
public static ColumnInfoCollection GetColumnData(this SqlConnection connection, string tableName) { #region Testing //string oleConnectionString = connection.ConnectionString; //if (!oleConnectionString.Contains("Provider")) //{ // oleConnectionString = oleConnectionString.Prepend("Provider=SQLOLEDB;"); //} //using (OleDbConnection oleConnection = new OleDbConnection(oleConnectionString)) //{ // return oleConnection.GetColumnData(tableName); //} #endregion Testing const string CMD_COLUMN_INFO_FORMAT = @"SELECT COLUMN_NAME, COLUMN_DEFAULT, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE, ORDINAL_POSITION, NUMERIC_PRECISION, NUMERIC_SCALE, COLUMNPROPERTY(object_id(TABLE_SCHEMA + '.' + TABLE_NAME), COLUMN_NAME, 'IsIdentity') AS 'IsIdentity' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{0}'"; const string CMD_IS_PRIMARY_KEY_FORMAT = @"SELECT CU.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS T, INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CU WHERE CU.CONSTRAINT_NAME = T.Constraint_Name AND CU.TABLE_NAME = T.TABLE_NAME AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CU.TABLE_NAME = '{0}'"; var list = new ColumnInfoCollection(); bool alreadyOpen = (connection.State != ConnectionState.Closed); try { var foreignKeyColumns = connection.GetForeignKeyData(tableName); if (!alreadyOpen) { connection.Open(); } using (var command = new SqlCommand(string.Format(CMD_COLUMN_INFO_FORMAT, tableName), connection)) { command.CommandType = CommandType.Text; using (var reader = command.ExecuteReader()) { ColumnInfo columnInfo = null; while (reader.Read()) { columnInfo = new ColumnInfo(); if (!reader.IsDBNull(0)) { columnInfo.ColumnName = reader.GetString(0); } if (!reader.IsDBNull(1)) { columnInfo.DefaultValue = reader.GetString(1); } else { columnInfo.DefaultValue = string.Empty; } if (foreignKeyColumns.Contains(columnInfo.ColumnName)) { columnInfo.KeyType = KeyType.ForeignKey; } //else //{ try { columnInfo.DataType = DataTypeConvertor.GetDbType(reader.GetString(2).ToEnum <SqlDbType>(true)); } catch (ArgumentNullException) { columnInfo.DataType = DbType.Object; } catch (ArgumentException) { columnInfo.DataType = DbType.Object; } //} if (!reader.IsDBNull(3)) { columnInfo.MaximumLength = reader.GetInt32(3); } if (!reader.IsDBNull(4)) { if (reader.GetString(4).ToUpperInvariant().Equals("NO")) { columnInfo.IsNullable = false; } else { columnInfo.IsNullable = true; } } if (!reader.IsDBNull(5)) { columnInfo.OrdinalPosition = reader.GetInt32(5); } if (!reader.IsDBNull(6)) { columnInfo.Precision = reader.GetByte(6); } if (!reader.IsDBNull(7)) { columnInfo.Scale = reader.GetInt32(7); } if (!reader.IsDBNull(8)) { columnInfo.IsAutoIncremented = reader.GetInt32(8) == 1 ? true : false; } list.Add(columnInfo); } } } } finally { if (!alreadyOpen && connection.State != ConnectionState.Closed) { connection.Close(); } } #region Primary Keys using (var command = connection.CreateCommand()) { command.CommandText = string.Format(CMD_IS_PRIMARY_KEY_FORMAT, tableName); alreadyOpen = (connection.State != ConnectionState.Closed); if (!alreadyOpen) { connection.Open(); } using (var reader = command.ExecuteReader()) { while (reader.Read()) { string pkColumn = reader.GetString(0); ColumnInfo match = list[pkColumn]; if (match != null) { match.KeyType = KeyType.PrimaryKey; } } } if (!alreadyOpen) { connection.Close(); } } #endregion Primary Keys return(list); }
public List <ColumnInfo> GetColumnInfoList(string DbName, string TableName) { if (this.isdbosp) { return(this.GetColumnInfoListSP(DbName, TableName)); } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("SELECT "); stringBuilder.Append("colorder=a.colorder , "); stringBuilder.Append("ColumnName=a.name , "); stringBuilder.Append("TypeName=b.name , "); stringBuilder.Append("Length= CASE WHEN b.name='nchar' THEN a.length/2 WHEN b.name='nvarchar' THEN a.length/2 ELSE a.length END , "); stringBuilder.Append("Preci=COLUMNPROPERTY(a.id, a.name, 'PRECISION') , "); stringBuilder.Append("Scale=ISNULL(COLUMNPROPERTY(a.id, a.name, 'Scale'), 0) , "); stringBuilder.Append("IsIdentity=CASE WHEN COLUMNPROPERTY(a.id, a.name, 'IsIdentity') = 1 THEN '√' ELSE '' END , "); stringBuilder.Append("isPK=CASE WHEN EXISTS ( "); stringBuilder.Append(" SELECT 1 "); stringBuilder.Append(" FROM dbo.sysindexes si "); stringBuilder.Append(" INNER JOIN dbo.sysindexkeys sik ON si.id = sik.id AND si.indid = sik.indid "); stringBuilder.Append(" INNER JOIN dbo.syscolumns sc ON sc.id = sik.id AND sc.colid = sik.colid "); stringBuilder.Append(" INNER JOIN dbo.sysobjects so ON so.name = so.name AND so.xtype = 'PK' "); stringBuilder.Append(" WHERE sc.id = a.id AND sc.colid = a.colid) THEN '√' "); stringBuilder.Append(" ELSE '' "); stringBuilder.Append(" END , "); stringBuilder.Append(" isFK=CASE WHEN tony.fkey is not null and tony.fkey=a.colid THEN '√' ELSE '' END , "); stringBuilder.Append(" Create_Date=d.crdate, "); stringBuilder.Append(" Modify_Date=CASE WHEN a.colorder = 1 THEN d.refdate ELSE NULL END, "); stringBuilder.Append(" fkTab=CASE WHEN tony.fkey is not null and tony.fkey=a.colid "); stringBuilder.Append(" THEN object_name(tony.fkeyid) ELSE '' "); stringBuilder.Append(" END , "); stringBuilder.Append(" fkName=CASE WHEN tony.fkey is not null and tony.fkey=a.colid "); stringBuilder.Append(" THEN (SELECT name FROM syscolumns "); stringBuilder.Append(" WHERE colid=tony.fkey AND id=tony.fkeyid) "); stringBuilder.Append(" ELSE '' "); stringBuilder.Append(" END, "); stringBuilder.Append(" cisNull=CASE WHEN a.isnullable = 1 THEN '√' ELSE '' END , "); stringBuilder.Append(" defaultVal= ISNULL(e.text, ''), "); stringBuilder.Append(" deText=ISNULL(g.[value], '') "); stringBuilder.Append("FROM dbo.syscolumns a "); stringBuilder.Append("LEFT JOIN dbo.systypes b ON a.xtype = b.xusertype "); stringBuilder.Append("INNER JOIN dbo.sysobjects d ON a.id = d.id AND (d.xtype = 'U' or d.xtype = 'V') AND d.status >= 0 "); stringBuilder.Append("LEFT JOIN dbo.syscomments e ON a.cdefault = e.id "); stringBuilder.Append("LEFT JOIN sys.extended_properties g ON a.id = g.major_id AND a.colid = g.minor_id "); stringBuilder.Append("LEFT JOIN sys.extended_properties f ON d.id = f.major_id AND f.minor_id = 0 "); stringBuilder.Append("LEFT JOIN sysobjects htl ON htl.parent_obj=d.id AND htl.xtype='F' "); stringBuilder.Append("LEFT JOIN sysforeignkeys tony on htl.id=tony.constid "); stringBuilder.Append("WHERE d.name=N'" + TableName + "' "); stringBuilder.Append("ORDER BY d.id, a.colorder "); ArrayList arrayList = new ArrayList(); List <ColumnInfo> list = new List <ColumnInfo>(); using (SqlDataReader sqlDataReader = this.ExecuteReader(DbName, stringBuilder.ToString())) { while (sqlDataReader.Read()) { ColumnInfo columnInfo = new ColumnInfo(); columnInfo.ColumnOrder = sqlDataReader.GetValue(0).ToString(); columnInfo.ColumnName = sqlDataReader.GetString(1); columnInfo.TypeName = sqlDataReader.GetString(2); columnInfo.Length = sqlDataReader.GetValue(3).ToString(); columnInfo.Precision = sqlDataReader.GetValue(4).ToString(); columnInfo.Scale = sqlDataReader.GetValue(5).ToString(); columnInfo.IsIdentity = (sqlDataReader.GetString(6) == "√"); columnInfo.IsPrimaryKey = (sqlDataReader.GetString(7) == "√"); columnInfo.IsForeignKey = (sqlDataReader.GetString(8) == "√"); columnInfo.Nullable = (sqlDataReader.GetString(13) == "√"); columnInfo.DefaultVal = sqlDataReader.GetString(14).Replace("(", "").Replace(")", ""); columnInfo.Description = sqlDataReader.GetString(15); if (!arrayList.Contains(columnInfo.ColumnName)) { list.Add(columnInfo); arrayList.Add(columnInfo.ColumnName); } } sqlDataReader.Close(); } return(list); }
private void HorizontalLayout() { ChartCanvas.Children.Clear(); var duration = new Duration(TimeSpan.FromMilliseconds(this.AnimationGrowthMilliseconds)); int columns = GetVisibleColumns(); double w = this.ActualWidth; double h = this.ActualHeight; Size axisLabelSize = AddAxisLabels(out AxisTickSpacer scale); var min = scale.GetNiceMin(); var max = scale.GetNiceMax(); var spacing = scale.GetTickSpacing(); Size labelSize = CreateColumnInfos(); double labelGap = this.FontSize / 3; double labelMargin = labelSize.Height + labelGap + labelGap; if (-min > labelMargin) { labelMargin = 0; } h -= labelMargin; // allocate space at the bottom for column labels. double axisLabelGap = axisLabelSize.Width + labelGap + labelGap; w -= axisLabelGap; // allocate space for axis labels. int numSeries = Data.Series.Count; double seriesWidth = w / columns; double innerGap = numSeries > 1 ? 2 : 0; // gap between columns in a series double seriesGap = seriesWidth / (3 * numSeries); // gap between series seriesWidth -= seriesGap; double columnWidth = seriesWidth / numSeries; columnWidth -= innerGap; double range = (max - min); double zero = 0; if (min < 0) { zero = (Math.Abs(min) * h / range); } // layout the axis labels and lines int i = 0; for (var r = min; r <= max; r += spacing) { double ypos = (h - zero) - (r * h / range); var label = axisLabels[i]; var line = axisLines[i]; var mid = label.DesiredSize.Height / 2; Canvas.SetLeft(label, labelGap); Canvas.SetTop(label, ypos - mid); PointCollection poly = new PointCollection(); poly.Add(new Point() { X = axisLabelGap, Y = ypos }); poly.Add(new Point() { X = w, Y = ypos }); line.BeginAnimation(Polygon.PointsProperty, new PointCollectionAnimation() { To = poly, Duration = duration }); label.BeginAnimation(TextBlock.OpacityProperty, new DoubleAnimation() { From = 0, To = 1, Duration = duration }); i++; } Rect previousLabel = new Rect() { X = -1000, Y = 0, Width = 0, Height = 0 }; double x = axisLabelGap; double y = h - zero; // layout the columns. for (int col = 0; col < columns; col++) { int index = 0; foreach (var series in this.Data.Series) { var dataValue = series.Values[col]; if (dataValue.Hidden) { continue; } double s = (dataValue.Value * h / range); Color color = dataValue.Color.Value; var start = TimeSpan.FromMilliseconds(index * AnimationRippleMilliseconds); ColumnInfo info = this.bars[col + (index * columns)]; Polygon polygon = info.Shape; SolidColorBrush brush = null; if (polygon != null) { brush = polygon.Fill as SolidColorBrush; } else { // make initial bars grow from zero. PointCollection initial = new PointCollection(); initial.Add(new Point() { X = x, Y = y }); initial.Add(new Point() { X = x, Y = y, }); initial.Add(new Point() { X = x + columnWidth, Y = y }); initial.Add(new Point() { X = x + columnWidth, Y = y }); brush = new SolidColorBrush() { Color = Colors.Transparent }; polygon = new Polygon() { Fill = brush, Points = initial }; info.Shape = polygon; } if (info.Label != null) { var block = info.Label; var size = block.DesiredSize; double ypos = 0; if (s < 0) { // above the downward pointing column then. ypos = y - labelGap - size.Height; } else { ypos = y + labelGap; } Rect bounds = new Rect() { X = x + (seriesWidth - size.Width) / 2, Y = ypos, Width = size.Width, Height = size.Height }; Rect inflated = bounds; inflated.Inflate(this.FontSize / 2, 0); if (inflated.IntersectsWith(previousLabel)) { // skip it! } else { previousLabel = inflated; Canvas.SetLeft(block, bounds.X); Canvas.SetTop(block, bounds.Y); block.BeginAnimation(TextBlock.OpacityProperty, new DoubleAnimation() { From = 0, To = 1, Duration = duration, BeginTime = start }); ChartCanvas.Children.Add(block); } } if (s < 0) { info.Bounds = new Rect() { X = x, Y = y, Width = columnWidth, Height = -s }; } else { info.Bounds = new Rect() { X = x, Y = y - s, Width = columnWidth, Height = s }; } PointCollection poly = new PointCollection(); poly.Add(new Point() { X = x, Y = y }); poly.Add(new Point() { X = x, Y = y - s }); x += columnWidth; poly.Add(new Point() { X = x, Y = y - s }); poly.Add(new Point() { X = x, Y = y }); ChartCanvas.Children.Add(polygon); polygon.BeginAnimation(Polygon.PointsProperty, new PointCollectionAnimation() { To = poly, Duration = duration, BeginTime = start }); brush.BeginAnimation(SolidColorBrush.ColorProperty, new ColorAnimation() { To = color, Duration = duration, BeginTime = start }); index++; x += innerGap; } x += seriesGap; } }
public override DbParameter AppendParamter(List <DbParameter> _params, string parameterName, ColumnInfo col, Type type, object value) { if (string.IsNullOrEmpty(parameterName)) { parameterName = $"p_{_params?.Count}"; } var ret = new MySqlParameter { ParameterName = QuoteParamterName(parameterName), Value = value }; var dbtype = (MySqlDbType)_orm.CodeFirst.GetDbInfo(type)?.type; if (col != null) { var dbtype2 = (MySqlDbType)_orm.DbFirst.GetDbType(new DatabaseModel.DbColumnInfo { DbTypeText = col.DbTypeText, DbTypeTextFull = col.Attribute.DbType, MaxLength = col.DbSize }); switch (dbtype2) { //case MySqlDbType.Binary: //case MySqlDbType.VarBinary: // break; default: dbtype = dbtype2; if (col.DbSize != 0) { ret.Size = col.DbSize; } if (col.DbPrecision != 0) { ret.Precision = col.DbPrecision; } if (col.DbScale != 0) { ret.Scale = col.DbScale; } break; } } if (dbtype == MySqlDbType.Geometry) { ret.MySqlDbType = MySqlDbType.Text; if (value != null) { ret.Value = (value as MygisGeometry).AsText(); } } else { ret.MySqlDbType = dbtype; if (ret.MySqlDbType == MySqlDbType.Enum && value != null) { ret.Value = (long)Convert.ChangeType(value, typeof(long)) + 1; } } _params?.Add(ret); return(ret); }
public void AddNOTCondition(ColumnInfo parameter, object parameterValue) { AddNOTCondition("", "", parameter, "=", parameterValue, ""); }
public override object AddslashesProcessParam(object param, Type mapType, ColumnInfo mapColumn) { if (param == null) { return("NULL"); } if (mapType != null && mapType != param.GetType() && (param is IEnumerable == false)) { param = Utils.GetDataReaderValue(mapType, param); } if (param is bool || param is bool?) { return((bool)param ? 1 : 0); } else if (param is string) { if (mapColumn != null && mapColumn.CsType.NullableTypeOrThis() == typeof(string) && ncharDbTypes.Any(a => mapColumn.Attribute.DbType.Contains(a)) == false) { return(string.Concat("'", param.ToString().Replace("'", "''"), "'")); } return(string.Concat("N'", param.ToString().Replace("'", "''"), "'")); } else if (param is char) { return(string.Concat("'", param.ToString().Replace("'", "''").Replace('\0', ' '), "'")); } else if (param is Enum) { return(((Enum)param).ToInt64()); } else if (decimal.TryParse(string.Concat(param), out var trydec)) { return(param); } else if (param is DateTime || param is DateTime?) { if (param.Equals(DateTime.MinValue) == true) { param = new DateTime(1970, 1, 1); } return(string.Concat("'", ((DateTime)param).ToString("yyyy-MM-dd HH:mm:ss.fff"), "'")); } else if (param is DateTimeOffset || param is DateTimeOffset?) { if (param.Equals(DateTimeOffset.MinValue) == true) { param = new DateTimeOffset(new DateTime(1970, 1, 1), TimeSpan.Zero); } return(string.Concat("'", ((DateTimeOffset)param).ToString("yyyy-MM-dd HH:mm:ss.fff zzzz"), "'")); } else if (param is TimeSpan || param is TimeSpan?) { return(((TimeSpan)param).TotalSeconds); } else if (param is byte[]) { return($"0x{CommonUtils.BytesSqlRaw(param as byte[])}"); } else if (param is IEnumerable) { return(AddslashesIEnumerable(param, mapType, mapColumn)); } return(string.Concat("'", param.ToString().Replace("'", "''"), "'")); }
public void AddNOTCondition(string left, string preParameter, ColumnInfo parameter, string sqlOperator, object parameterValue, string right) { AddCondition(LogicalOperator.NOT, left, preParameter, parameter, sqlOperator, parameterValue, right); }
private void UpdateValidityAssesment(bool actuallyDoIt = false) { ragSmiley1.Reset(); try { var fks = new ColumnInfo[] { fk1.SelectedColumn, fk2.SelectedColumn, fk3.SelectedColumn }.Where(f => f != null).ToArray(); var pks = new ColumnInfo[] { pk1.SelectedColumn, pk2.SelectedColumn, pk3.SelectedColumn }.Where(p => p != null).ToArray(); if (fk1.SelectedColumn == null || pk1.SelectedColumn == null) { throw new Exception("You must specify at least one pair of keys to join on, do this by dragging columns out of the collection into the key boxes"); } if ( ((pk2.SelectedColumn == null) != (fk2.SelectedColumn == null)) || ((pk3.SelectedColumn == null) != (fk3.SelectedColumn == null))) { throw new Exception("You must have the same number of primary and foregin keys (they must come in pairs)"); } if (pks.Any(p => p.TableInfo_ID != _leftTableInfo.ID)) { throw new Exception("All Primary Keys must come from the Left hand TableInfo"); } if (fks.Any(f => f.TableInfo_ID != _rightTableInfo.ID)) { throw new Exception("All Foreign Keys must come from the Right hand TableInfo"); } ExtractionJoinType joinType; if (rbAllLeftHandTableRecords.Checked) { joinType = ExtractionJoinType.Right; //confusing I know, basically JoinInfo database record has fk,pk and direction field assuming fk joins via that direction to pk which is the opposite to the layout of this form } else if (rbAllRightHandTableRecords.Checked) { joinType = ExtractionJoinType.Left; } else if (rbJoinInner.Checked) { joinType = ExtractionJoinType.Inner; } else { throw new Exception("You must select an Extraction Join direction"); } var cataRepo = _leftTableInfo.CatalogueRepository; for (int i = 0; i < pks.Length; i++) { if (cataRepo.GetAllObjects <JoinInfo>().Any(j => j.PrimaryKey_ID == pks[i].ID && j.ForeignKey_ID == fks[i].ID)) { throw new Exception("Join already exists between " + fks[i] + " and " + pks[i].ID); } } if (actuallyDoIt) { for (int i = 0; i < pks.Length; i++) { new JoinInfo(cataRepo, fks[i], pks[i], joinType, tbCollation.Text); } MessageBox.Show("Successfully Created Joins"); Activator.RefreshBus.Publish(this, new RefreshObjectEventArgs(_leftTableInfo)); foreach (KeyDropLocationUI ui in new[] { pk1, pk2, pk3, fk1, fk2, fk3 }) { ui.Clear(); } } else { btnCreateJoinInfo.Enabled = true; } } catch (Exception ex) { btnCreateJoinInfo.Enabled = false; ragSmiley1.Fatal(ex); } }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="column"></param> protected virtual void RenameColumn(ColumnInfo column) { ColumnCommand <IRenameColumnCommand>(column); }
internal void CreateColumn(string schema, string tabla, ColumnInfo col) { var add = $"{col.Name} {col.Type}{col.LengthToShow} {(col.Nullable ? "NULL" : "NOT NULL")}"; con.Get <object>($"ALTER TABLE {schema}.{tabla} ADD {add}"); }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="column"></param> protected virtual void CreateColumn(ColumnInfo column) { ColumnCommand <ICreateColumnCommand>(column); }
public override List <ColumnInfo> GetColumnInfos() { //增加模具组长、项目负责人信息列 var columnInfos = new List <ColumnInfo>(); var projectChargerColumnInfo = new ColumnInfo() { ColumnKey = "ProjectCharger", ColumnName = "模具组长", ColumnType = ColumnTypes.Text, IsInterColumn = true, ValuePath = "Property", Sort = 7, }; columnInfos.Add(projectChargerColumnInfo); var projectTrackerColumnInfo = new ColumnInfo() { ColumnKey = "ProjectTracker", ColumnName = "项目负责", ColumnType = ColumnTypes.Text, IsInterColumn = true, ValuePath = "Property", Sort = 8, }; columnInfos.Add(projectTrackerColumnInfo); var productDesignColumnInfo = new ColumnInfo() { ColumnKey = "ProductDesign", ColumnName = "产品设计", ColumnType = ColumnTypes.Text, IsInterColumn = true, ValuePath = "Property", Sort = 9, }; columnInfos.Add(productDesignColumnInfo); var mouldDesignColumnInfo = new ColumnInfo() { ColumnKey = "MouldDesign", ColumnName = "模具设计", ColumnType = ColumnTypes.Text, IsInterColumn = true, ValuePath = "Property", Sort = 10, }; columnInfos.Add(mouldDesignColumnInfo); var salesmanColumnInfo = new ColumnInfo() { ColumnKey = "Salesman", ColumnName = "业务员", ColumnType = ColumnTypes.Text, IsInterColumn = true, ValuePath = "Property", Sort = 11, }; columnInfos.Add(salesmanColumnInfo); var t0ColumnInfo = new ColumnInfo() { ColumnKey = "T0Date", ColumnName = "T0日期", ColumnType = ColumnTypes.DateTime, IsInterColumn = true, ValuePath = "Property", Sort = 6 }; columnInfos.Add(t0ColumnInfo); return(columnInfos); }
public override string GetNoneParamaterSqlValue(List <DbParameter> specialParams, string specialParamFlag, ColumnInfo col, Type type, object value) { if (value == null) { return("NULL"); } if (type.IsNumberType()) { return(string.Format(CultureInfo.InvariantCulture, "{0}", value)); } value = getParamterValue(type, value); var type2 = value.GetType(); if (type2 == typeof(byte[])) { return($"0x{CommonUtils.BytesSqlRaw(value as byte[])}"); } if (type2 == typeof(TimeSpan) || type2 == typeof(TimeSpan?)) { var ts = (TimeSpan)value; var hh = Math.Min(24, (int)Math.Floor(ts.TotalHours)); if (hh >= 24) { hh = 0; } value = $"{hh}:{ts.Minutes}:{ts.Seconds}.{ts.Milliseconds}"; } else if (value is Array) { var valueArr = value as Array; var eleType = type2.GetElementType(); var len = valueArr.GetLength(0); var sb = new StringBuilder().Append("ARRAY["); for (var a = 0; a < len; a++) { var item = valueArr.GetValue(a); if (a > 0) { sb.Append(","); } sb.Append(GetNoneParamaterSqlValue(specialParams, specialParamFlag, col, eleType, item)); } sb.Append("]"); var dbinfo = _orm.CodeFirst.GetDbInfo(type); if (dbinfo != null) { sb.Append("::").Append(dbinfo.dbtype); } return(sb.ToString()); } return(FormatSql("{0}", value, 1)); }
internal static NpgsqlDbType GetNpgsqlType(ColumnInfo info) { switch (info.ColumnType) { case "interval": return NpgsqlDbType.Interval; case "integer": case "int": case "int4": return NpgsqlDbType.Integer; case "bool": case "boolean": return NpgsqlDbType.Boolean; case "box": return NpgsqlDbType.Box; case "circle": return NpgsqlDbType.Circle; case "line": return NpgsqlDbType.Line; case "lseg": return NpgsqlDbType.LSeg; case "money": return NpgsqlDbType.Money; case "path": return NpgsqlDbType.Path; case "point": return NpgsqlDbType.Point; case "polygon": return NpgsqlDbType.Polygon; case "inet": return NpgsqlDbType.Inet; case "bit": return NpgsqlDbType.Bit; case "varchar": return NpgsqlDbType.Varchar; case "char": return NpgsqlDbType.Char; case "real": case "float4": return NpgsqlDbType.Real; case "float8": case "double": case "double precision": return NpgsqlDbType.Double; case "numeric": case "decimal": return NpgsqlDbType.Numeric; case "citext": return NpgsqlDbType.Citext; case "text": return NpgsqlDbType.Text; case "int8": case "bigint": return NpgsqlDbType.Bigint; case "timetz": return NpgsqlDbType.TimeTz; case "time": return NpgsqlDbType.Time; case "date": return NpgsqlDbType.Date; case "int2": case "smallint": return NpgsqlDbType.Smallint; case "uuid": return NpgsqlDbType.Uuid; case "timestamp": return NpgsqlDbType.Timestamp; case "timestamptz": return NpgsqlDbType.TimestampTz; case "bpchar": return NpgsqlDbType.Char; case "hstore": return NpgsqlDbType.Hstore; case "json": return NpgsqlDbType.Json; case "jsonb": return NpgsqlDbType.Jsonb; case "_text": return NpgsqlDbType.Array; case "bytea": return NpgsqlDbType.Bytea; case "tsrange": case "int4range": case "int8range": case "numrange": case "tstzrange": case "daterange": return NpgsqlDbType.Range; default: if (Enum.TryParse<NpgsqlDbType>(info.ColumnType, true, out var npgsqlDbType)) return npgsqlDbType; if (string.Equals(info?.ColumnTypeExtra, "array", StringComparison.OrdinalIgnoreCase) || info.ColumnType.StartsWith("_")) return NpgsqlDbType.Array; throw new NotImplementedException($"Column type '{info.ColumnType}' is not supported"); } }
private GeneratedAttribute getCategoriesInfo(ColumnInfo columnInfo) { return categoriesCached.Value(boxModule.StringIceIdentity, this.boxModule, columnInfo); }
public override DbParameter AppendParamter(List <DbParameter> _params, string parameterName, ColumnInfo col, Type type, object value) { if (string.IsNullOrEmpty(parameterName)) { parameterName = $"p_{_params?.Count}"; } if (value != null) { value = getParamterValue(type, value); } var ret = new OscarParameter { ParameterName = QuoteParamterName(parameterName), Value = value }; //if (value.GetType().IsEnum || value.GetType().GenericTypeArguments.FirstOrDefault()?.IsEnum == true) { // ret.DataTypeName = ""; //} else { var tp = _orm.CodeFirst.GetDbInfo(type)?.type; if (tp != null) { ret.OscarDbType = (OscarDbType)tp.Value; } if (col != null) { var dbtype = (OscarDbType)_orm.DbFirst.GetDbType(new DatabaseModel.DbColumnInfo { DbTypeText = col.DbTypeText }); if (dbtype != OscarDbType.Oidvector) { ret.OscarDbType = dbtype; //if (col.DbSize != 0) ret.Size = col.DbSize; if (col.DbPrecision != 0) { ret.Precision = col.DbPrecision; } if (col.DbScale != 0) { ret.Scale = col.DbScale; } } } //} _params?.Add(ret); return(ret); }
private GeneratedAttribute getCategoriesInfo(ColumnInfo columnInfo) { return categoriesCached.Value(boxModule.StringIceIdentity, this.boxModule, columnInfo, Domain, From, To, CountOfCategories); }
internal void InternalToSqlCaseWhenEnd(StringBuilder sb, ColumnInfo col) => ToSqlCaseWhenEnd(sb, col);
private ColumnInfo GetColumnInfo(Property p) { ColumnInfo columnInfo; if (!m_columnInfo.TryGetValue(p.Descriptor, out columnInfo)) { columnInfo = new ColumnInfo(); columnInfo.Width = DefaultColumnWidth; if (p.Control != null && p.Control.Width > 0) columnInfo.Width = p.Control.Width; else { // try persisted settings int width; if (m_savedColumnWidths.TryGetValue(p.Descriptor.Name + p.Descriptor.PropertyType, out width)) { columnInfo.Width = width; } else if (p.DefaultWidth != 0) { columnInfo.Width = p.DefaultWidth; } } m_columnInfo.Add(p.Descriptor, columnInfo); } return columnInfo; }
public abstract DbParameter AppendParamter(List <DbParameter> _params, string parameterName, ColumnInfo col, Type type, object value);