//private int displaylist; public RMViewer(ColData data) { //initialize variables here dlist_col = dlist_trg = -1; k_t = false; this.data = data; }
/// <summary> /// Insert the current into the table. /// </summary> /// <returns></returns> protected bool InsertRow() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("Insert Into \"{0}\" (", TableName); StringBuilder sbValues = new StringBuilder(); sbValues.Append("Values("); ArrayList parms = new ArrayList(); int count = 0; int i = 0; for (i = 0; i <= panelBody.Controls.Count; i++) { if (i == RowIdIndex) { continue; } TextBox t = FindTextBox(string.Format("txt{0}", i.ToString().PadLeft(4, '0'))); if (t == null) { break; } if (!string.IsNullOrEmpty(t.Text)) { count++; ColData cd = (ColData)t.Tag; sb.Append(count > 1 ? "," : string.Empty).AppendFormat(" \"{0}\"", cd.colname); sbValues.Append(count > 1 ? "," : string.Empty).Append("?"); if (!ValidateData(t, out string szData)) { return(false); } parms.Add(szData); } } if (count == 0) { DialogResult dgResult = Common.ShowMsg("No data to insert. Please enter data to insert or press the 'Undo' button to cancel insert."); return(false); } sb.Append(")"); sbValues.Append(")"); int recsupdated = DataAccess.ExecuteNonQuery(DatabaseName, string.Format("{0} {1}", sb.ToString(), sbValues.ToString()), parms, out SQLiteErrorCode returnCode); if (recsupdated == -1 || returnCode != SQLiteErrorCode.Ok) { DialogResult dgResult = Common.ShowMsg(string.Format(Common.ERR_SQL, DataAccess.LastError, returnCode)); return(false); } toolStripLabelStatus.Text = string.Format("{0} Record(s) added.", recsupdated.ToString()); AddingRow = false; RowCount++; CurrentRow = RowCount; return(true); }
public ColDataController(MainForm topform, ColData item) : base(topform, item) { Data = item; AddMenu("Open RMViewer", Menu_OpenRMViewer); AddMenu("Open collision tree viewer", Menu_OpenColDataViewer); AddMenu("Export Collision Model", Menu_Export); AddMenu("Import Collision Model", Menu_Import); }
public ColDataEditor(ColData col) { this.col = col; InitializeComponent(); splitContainer1.IsSplitterFixed = true; splitContainer1.SplitterDistance = (int)(splitContainer1.Width * 1F); splitContainer1.SizeChanged += SplitContainer1_SizeChanged; PopulateTree(treeView1); }
public void Push(int iRow, object value) { var cd = new ColData() { iRow = iRow, Value = value }; if (values.Count == 0) { first = cd; } values.Push(cd); }
//取得本账户所有的收藏数据 public static List <ColData> GetAllCols() { CheckAndReconnect(); colDatas = new List <ColData>(); string sql = $"select * from t_collect where user_id='{currentUser.id}';"; try { //查询 MySqlCommand cmd = new MySqlCommand(sql, mysql); MySqlDataReader dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { //判断游标位置 if (!dataReader.HasRows) { dataReader.Close(); } ColData cd = new ColData(); cd.id = dataReader.GetString("id"); cd.question_id = dataReader.GetString("question_id"); cd.user_id = dataReader.GetString("user_id"); colDatas.Add(cd); } dataReader.Close(); return(colDatas); } catch (Exception e) { PanelManager.Open <TipPanel> ("[DBManager.GetAllCols()]获取当前用户所有的收藏问题失败,异常为" + e.Message); return(null); } }
/// <summary> /// Determine how many resords are in the table and point the editor to the first row. If the table /// is empty, go into insert mode and dispaly a blank page. /// </summary> protected void InitializePage() { lblTable.Text = TableName; tableHasRowID = DataAccess.CheckForRowID(DatabaseName, TableName, out RowIDColName, out PrimaryKeyName); BaseSQL = string.Format("Select Count(*) From \"{0}\"", TableName); searchWhereClause = string.IsNullOrEmpty(richTextWhere.Text) ? string.Empty : string.Format("Where {0}", richTextWhere.Text.Trim()); RowIdIndex = -1; searchSQL = string.Format("{0} {1}", BaseSQL, searchWhereClause); int iRowCount = Convert.ToInt32(DataAccess.ExecuteScalar(DatabaseName, searchSQL, out SQLiteErrorCode returnCode)); if (iRowCount == -1 || returnCode != SQLiteErrorCode.Ok) { Common.ShowMsg(string.Format("Error processing SQL. Please review your WHERE clause.\r\n{0}", DataAccess.LastError)); searchSQL = BaseSQL; searchWhereClause = string.Empty; RowCount = 0; LoadRecord(0); return; } RowCount = iRowCount; BaseSQL = tableHasRowID ? string.Format("Select {0}, * From \"{1}\"", RowIDColName, TableName) : BaseSQL = string.Format("Select * From \"{0}\"", TableName); searchSQL = string.Format("{0} {1}", BaseSQL, searchWhereClause); SQLiteConnection conn = new SQLiteConnection(); SQLiteCommand cmd = new SQLiteCommand(); DataAccess.OpenDB(DatabaseName, ref conn, ref cmd, out returnCode, false); SQLiteDataReader dr; cmd.CommandText = searchSQL; try { dr = cmd.ExecuteReader(CommandBehavior.SchemaOnly); } catch (Exception ex) { Common.ShowMsg(string.Format("Error processing SQL. Please review your WHERE clause.\r\n{0}", ex.Message)); searchSQL = BaseSQL; searchWhereClause = string.Empty; DataAccess.CloseDB(conn); RowCount = 0; LoadRecord(0); return; } int start = 50; int lablen = 180; int height = 30; // draw a textbox for each column in the row except rowid. for (int i = 0; i < dr.FieldCount; i++) { string colname = dr.GetName(i); if (RowIdIndex < 0) { if (tableHasRowID) { if (RowIDColName == colname) { RowIdIndex = i; } } } if (i == RowIdIndex) { continue; } if (colname == PrimaryKeyName) { PKIndex = i; } Label lbl = new Label { Text = string.Format("{0}:", colname), Top = start, Left = 50, Width = lablen - 10 }; panelBody.Controls.Add(lbl); TextBox txt = new TextBox { Name = string.Format("txt{0}", i.ToString().PadLeft(4, '0')) }; ColData cd = new ColData() { colname = colname, coltype = dr.GetDataTypeName(i) }; txt.Tag = cd; txt.Top = start; txt.Left = lbl.Left + lablen; txt.Width = 300; panelBody.Controls.Add(txt); if (dr.GetFieldType(i).Equals(typeof(byte[]))) { txt.ReadOnly = true; Button btn = new Button { Name = string.Format("btn{0}", i.ToString().PadLeft(4, '0')), Text = "View", Left = txt.Left + 320, Top = txt.Top - 2, Height = 24, Width = 60, BackColor = SystemColors.Control, Tag = colname }; btn.Click += button_clicked; panelBody.Controls.Add(btn); } start += height; } dr.Close(); DataAccess.CloseDB(conn); }
/// <summary> /// Validate entered data and convert it to SQLite acceptablr value /// </summary> /// <param name="t"></param> /// <param name="szValue"></param> /// <returns></returns> protected bool ValidateData(TextBox t, out string szValue) { szValue = ""; ColData cd = (ColData)t.Tag; switch (cd.coltype.ToLower()) { case "boolean": if (boolvalues.Contains(t.Text.ToLower().Trim())) { szValue = t.Text; return(true); } Common.ShowMsg("Please enter 'true' or 'false'"); t.Focus(); break; case "datetime": case "date": case "timestamp": if (DateTime.TryParse(t.Text, out DateTime newdate)) { szValue = newdate.ToString("yyyy-MM-dd HH:mm:ss"); return(true); } Common.ShowMsg("Please enter a valid Date"); t.Focus(); break; case "time": if (DateTime.TryParse(t.Text, out DateTime newtime)) { szValue = newtime.ToString("HH:mm:ss"); return(true); } Common.ShowMsg("Please enter a valid Time"); t.Focus(); break; case "integer": case "int": case "tinyint": case "smallint": case "mediumint": case "bigint": case "unsigned big int": case "int2": case "int4": case "int8": if (int.TryParse(t.Text, out int newint)) { szValue = t.Text; return(true); } Common.ShowMsg("Please enter a valid Integer"); t.Focus(); break; case "float": case "numeric": case "real": case "double": case "double precision": case "single": case "single precision": if (double.TryParse(t.Text, out double newdbl)) { szValue = newdbl.ToString(); return(true); } Common.ShowMsg("Please enter a valid value"); t.Focus(); break; default: if (cd.coltype.ToLower().StartsWith("decimal")) { if (decimal.TryParse(t.Text, out decimal newdec)) { szValue = newdec.ToString(); return(true); } Common.ShowMsg("Please enter a valid Decimal value"); t.Focus(); break; } szValue = t.Text; return(true); } return(false); }
/// <summary> /// Determine if any changes have been made and update any changed columns. Make /// sure the underlying row has not been updated in the meantime. /// </summary> /// <returns></returns> protected bool UpdateRow() { toolStripLabelStatus.Text = string.Empty; if (AddingRow) { return(InsertRow()); } if (RowCount == 0) { return(false); } // Iterate through all the rows to determine if any data chas changed. StringBuilder sb = new StringBuilder(); sb.AppendFormat("Update \"{0}\" Set", TableName); int count = 0; int i = 0; ArrayList parms = new ArrayList(); DataRow dr = dt.Rows[0]; for (i = 0; i < dr.ItemArray.Count(); i++) { if (i == RowIdIndex) { continue; } TextBox t = FindTextBox(string.Format("txt{0}", i.ToString().PadLeft(4, '0'))); if (dr[i].ToString() != t.Text) { ColData cd = (ColData)t.Tag; count++; sb.Append(count > 1 ? "," : string.Empty).AppendFormat(" \"{0}\" = ?", cd.colname); if (!ValidateData(t, out string szData)) { return(false); } parms.Add(szData); } } // If no data has changed, just return if (count == 0) { return(true); } //Let's see if the row was updated through another process RowStatus rowStat = RecordUpdated(out DataRow currDataRow); DialogResult dgResult; switch (rowStat) { case RowStatus.Updated: dgResult = Common.ShowMsg("The Row has changed since it was retrieved. Click 'Yes' to save your changes anyway or click 'No' to discard your change and retrieve current data for this row.", MessageBoxButtons.YesNo); if (dgResult == DialogResult.No) { LoadRecord(CurrentRow); return(false); } break; case RowStatus.Inconsistent: dgResult = Common.ShowMsg("The Row has changed since it was retrieved. Please read the Row again before updating it."); return(false); case RowStatus.NotFound: dgResult = Common.ShowMsg("The Row cannot be found."); return(false); default: break; } if (!BuildWhereClause(currDataRow, out string whereClause)) { return(false); } sb.AppendFormat(" {0}", whereClause); int recsupdated = DataAccess.ExecuteNonQuery(DatabaseName, sb.ToString(), parms, out SQLiteErrorCode returnCode); toolStripLabelStatus.Text = string.Format("{0} Record(s) updated.", recsupdated.ToString()); return(true); }
private static string genDatasList(ISheet sheet, List <ColData> members, int rowCount) { string ret = ""; ColData cd = null; for (int i = Generater.headerRowCount; i < rowCount; i++) { IRow r = sheet.GetRow(i); for (int j = 0; j < members.Count; j++) { cd = members[j]; string v = r.GetCell(cd.column).StringCellValue; #if WRITE_WITH_FORMAT //格式化排版 if (j == 0) { ret += _tab + string.Format("\"{0}\" : {{\n", v); } ret += _tab + _tab + cd.vname + " : "; if (cd.isCommaArr) { string[] arr = v.Split(','); ret += "{\n"; int idx = 0; foreach (string e in arr) { ret += _tab + _tab + _tab; if (cd.vtype == "str") { ret += "\"" + e + "\""; } else { ret += e; } if (idx == arr.Count() - 1) { ret += "\n"; } else { ret += ",\n"; } idx++; } ret += _tab + _tab + "}"; } else if (cd.isCombineArr) { ret += "{\n"; for (int k = cd.column; k < cd.column + cd.arrLen; k++) { v = r.GetCell(k).StringCellValue; ret += _tab + _tab + _tab; if (cd.vtype == "str") { ret += "\"" + v + "\""; } else { ret += v; } if (k == cd.column + cd.arrLen - 1) { ret += "\n"; } else { ret += ",\n"; } } ret += _tab + _tab + "}"; } else { if (cd.vtype == "str") { ret += "\"" + v + "\""; } else { ret += v; } } if (j == members.Count - 1) { ret += "\n"; } else { ret += ",\n"; } } ret += _tab + "}"; #else //内容排版紧缩 if (j == 0) { ret += _tab + string.Format("\"{0}\" : {{", v); } ret += cd.vname + ":"; if (cd.isCommaArr) { string[] arr = v.Split(','); ret += "{"; int idx = 0; foreach (string e in arr) { if (cd.vtype == "str") { ret += "\"" + e + "\""; } else { ret += e; } if (idx < arr.Count() - 1) { ret += ","; } idx++; } ret += "}"; } else if (cd.isCombineArr) { ret += "{"; for (int k = cd.column; k < cd.column + cd.arrLen; k++) { v = r.GetCell(k).StringCellValue; if (cd.vtype == "str") { ret += "\"" + v + "\""; } else { ret += v; } if (k < cd.column + cd.arrLen - 1) { ret += ","; } } ret += "}"; } else { if (cd.vtype == "str") { ret += "\"" + v + "\""; } else { ret += v; } } if (j < members.Count - 1) { ret += ", "; } } ret += "}"; #endif if (i == rowCount - 1) { ret += "\n"; } else { ret += ",\n"; } }
public AddAction(ColData d) { data = d; }
public static void TextToXml(string inDirectory, string inFile, string outDirectory, string outFileName) { List <string> electrodeNames = new List <string>(); List <double> timeSlices = new List <double>(); List <ColData> colDataSet = new List <ColData>(); string directory = inDirectory; string fileName = inFile; StreamReader reader = new StreamReader(directory + fileName); // Header line looks like "T[s]\tName\tName\tName" // Read the header, skip over the T[s] portion. Then put the names into a list // At the same time, use the header electrode names to determine the number // of columns in the file int columnCount = 0; foreach (string name in reader.ReadLine().Split('\t')) { if (name == "T[s]") { continue; } electrodeNames.Add(name); columnCount++; } // Empty line between header and data. Skip over empty line reader.ReadLine(); /** * For every column in the file (found by counting header names), * generate a new ColData object to put into the overall data set **/ for (int i = 0; i < columnCount; i++) { ColData column = new ColData(); column.index = i; column.colElements = new List <DataElement>(); colDataSet.Add(column); } /** * Each data row looks like "Time\tValue\tValue\tValue" * Pull out time, then get data **/ // RowIndex quite simply keeps track of what row is being read in the file. We need // this to determine where to place the data within the column element list. int rowIndex = 0; // Loop through all of the rows in the file while (!reader.EndOfStream) { // read in the row string row = reader.ReadLine(); // find where the time value ends and data entries begin int indexOfFirstTab = row.IndexOf('\t'); // store the time, from front of row double time = Convert.ToDouble(row.Substring(0, indexOfFirstTab)); timeSlices.Add(time); // All of the row's data go into rowValues. List <string> rowValues = new List <string>(); // Just need to separate the different values from the string cluster // holding all of the data foreach (string reading in row.Substring(indexOfFirstTab + 1).Split('\t')) { rowValues.Add(reading); } // Place one piece of data in each column for this particular row for (int i = 0; i < columnCount; i++) { colDataSet[i].colElements.Add(new DataElement()); colDataSet[i].colElements[rowIndex].value = Convert.ToDouble(rowValues[i]); } rowIndex++; } //write xml data XmlDocument doc = new XmlDocument(); XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null); doc.AppendChild(docNode); XmlNode fileNameNode = doc.CreateElement("File_Name"); XmlAttribute fileNameAttribute = doc.CreateAttribute("value"); fileNameAttribute.Value = fileName; fileNameNode.Attributes.Append(fileNameAttribute); doc.AppendChild(fileNameNode); /** * int electrodeIndex = 0; * int timeSliceIndex = 0; * foreach(column in colDataSet) * add electrode name node * foreach(dataelement in column) * add time in to file * value = dataelement.value **/ int electrodeIndex = 0; foreach (ColData column in colDataSet) { int timeSliceIndex = 0; // electrode node XmlNode electrodeNode = doc.CreateElement("Electrode"); XmlAttribute electrodeAttribute = doc.CreateAttribute("id"); electrodeAttribute.Value = electrodeNames[electrodeIndex]; electrodeNode.Attributes.Append(electrodeAttribute); fileNameNode.AppendChild(electrodeNode); foreach (DataElement element in column.colElements) { XmlNode timeSliceNode = doc.CreateElement("Time"); XmlAttribute timeSliceAttribute = doc.CreateAttribute("id"); timeSliceAttribute.Value = timeSlices[timeSliceIndex].ToString(); timeSliceNode.Attributes.Append(timeSliceAttribute); timeSliceNode.AppendChild(doc.CreateTextNode(element.value.ToString())); electrodeNode.AppendChild(timeSliceNode); timeSliceIndex++; } electrodeIndex++; } outFileName = fileName.Substring(0, fileName.LastIndexOf(".")); doc.Save(outDirectory + outFileName + ".xml"); }
public static void TextToXml(string inDirectory, string inFile, string outDirectory, string outFileName) { List<string> electrodeNames = new List<string>(); List<double> timeSlices = new List<double>(); List<ColData> colDataSet = new List<ColData>(); string directory = inDirectory; string fileName = inFile; StreamReader reader = new StreamReader(directory + fileName); // Header line looks like "T[s]\tName\tName\tName" // Read the header, skip over the T[s] portion. Then put the names into a list // At the same time, use the header electrode names to determine the number // of columns in the file int columnCount = 0; foreach (string name in reader.ReadLine().Split('\t')) { if (name == "T[s]") continue; electrodeNames.Add(name); columnCount++; } // Empty line between header and data. Skip over empty line reader.ReadLine(); /** * For every column in the file (found by counting header names), * generate a new ColData object to put into the overall data set **/ for (int i = 0; i < columnCount; i++) { ColData column = new ColData(); column.index = i; column.colElements = new List<DataElement>(); colDataSet.Add(column); } /** * Each data row looks like "Time\tValue\tValue\tValue" * Pull out time, then get data **/ // RowIndex quite simply keeps track of what row is being read in the file. We need // this to determine where to place the data within the column element list. int rowIndex = 0; // Loop through all of the rows in the file while (!reader.EndOfStream) { // read in the row string row = reader.ReadLine(); // find where the time value ends and data entries begin int indexOfFirstTab = row.IndexOf('\t'); // store the time, from front of row double time = Convert.ToDouble(row.Substring(0, indexOfFirstTab)); timeSlices.Add(time); // All of the row's data go into rowValues. List<string> rowValues = new List<string>(); // Just need to separate the different values from the string cluster // holding all of the data foreach (string reading in row.Substring(indexOfFirstTab + 1).Split('\t')) { rowValues.Add(reading); } // Place one piece of data in each column for this particular row for (int i = 0; i < columnCount; i++) { colDataSet[i].colElements.Add(new DataElement()); colDataSet[i].colElements[rowIndex].value = Convert.ToDouble(rowValues[i]); } rowIndex++; } //write xml data XmlDocument doc = new XmlDocument(); XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null); doc.AppendChild(docNode); XmlNode fileNameNode = doc.CreateElement("File_Name"); XmlAttribute fileNameAttribute = doc.CreateAttribute("value"); fileNameAttribute.Value = fileName; fileNameNode.Attributes.Append(fileNameAttribute); doc.AppendChild(fileNameNode); /** * int electrodeIndex = 0; * int timeSliceIndex = 0; * foreach(column in colDataSet) * add electrode name node * foreach(dataelement in column) * add time in to file * value = dataelement.value **/ int electrodeIndex = 0; foreach (ColData column in colDataSet) { int timeSliceIndex = 0; // electrode node XmlNode electrodeNode = doc.CreateElement("Electrode"); XmlAttribute electrodeAttribute = doc.CreateAttribute("id"); electrodeAttribute.Value = electrodeNames[electrodeIndex]; electrodeNode.Attributes.Append(electrodeAttribute); fileNameNode.AppendChild(electrodeNode); foreach (DataElement element in column.colElements) { XmlNode timeSliceNode = doc.CreateElement("Time"); XmlAttribute timeSliceAttribute = doc.CreateAttribute("id"); timeSliceAttribute.Value = timeSlices[timeSliceIndex].ToString(); timeSliceNode.Attributes.Append(timeSliceAttribute); timeSliceNode.AppendChild(doc.CreateTextNode(element.value.ToString())); electrodeNode.AppendChild(timeSliceNode); timeSliceIndex++; } electrodeIndex++; } outFileName = fileName.Substring(0, fileName.LastIndexOf(".")); doc.Save(outDirectory + outFileName + ".xml"); }
public static void generater(ISheet sheet, List <ColData> members) { string filename = Path.Combine(Properties.Settings.Default.cdataPath, sheet.SheetName + "Config.bin"); EndianBinaryWriter bw = new EndianBinaryWriter(EndianBitConverter.Big, new FileStream(filename, FileMode.Create), Encoding.UTF8); //BinaryWriter bw = new BinaryWriter(new FileStream(filename, FileMode.Create), System.Text.Encoding.BigEndianUnicode); ColData cd = null; int rowCount = convertCellType(sheet); bw.Write(rowCount - Generater.headerRowCount); for (int i = Generater.headerRowCount; i < rowCount; i++) { IRow r = sheet.GetRow(i); for (int j = 0; j < members.Count; j++) { cd = members[j]; string v = r.GetCell(cd.column).StringCellValue; if (cd.isCommaArr) { string[] arr = v.Split(','); bw.Write((int)arr.Length); foreach (string e in arr) { string errmsg = string.Format("单元格({0},{1})内容错误, 要求类型 {2}: [{3}]", i + 1, Char.ConvertFromUtf32('A' + cd.column), cd.vtype, e); writeMember(bw, cd.vtype, e, errmsg); } } else if (cd.isCombineArr) { bw.Write(cd.arrLen); for (int k = cd.column; k < cd.column + cd.arrLen; k++) { v = r.GetCell(k).StringCellValue; string errmsg = string.Format("单元格({0},{1})内容错误, 要求类型 {2}: [{3}]", i + 1, Char.ConvertFromUtf32('A' + cd.column), cd.vtype, v); writeMember(bw, cd.vtype, v, errmsg); } } else { string errmsg = string.Format("单元格({0},{1})内容错误, 要求类型 {2}: [{3}]", i + 1, Char.ConvertFromUtf32('A' + cd.column), cd.vtype, v); writeMember(bw, cd.vtype, v, errmsg); } } } bw.Close(); //debug read bin //BinaryReader br = new BinaryReader(new FileStream(filename, FileMode.Open)); //int len = br.ReadInt32(); //Console.WriteLine(len); //for (int i = 0; i < len; i++) //{ //foreach (ColData d in members) //{ // if (d.isCommaArr || d.isCombineArr) // { // len = br.ReadInt32(); // Console.WriteLine(len); // for (int j = 0; j < len; j++) // { // readMember(br, d.vtype); // } // } // else // { // readMember(br, d.vtype); // } //} // Console.Write("\n"); //} //br.Close(); }