/// <summary> /// Tgastab kogu info kui kasutaja eksisteerib (PIN, jäägi jne) /// </summary> /// <param name="kasutaja"></param> /// <returns></returns> public List <string> KasutajaInfo(string kasutaja) { using (CsvFileReader lugeja = new CsvFileReader(failiNimi)) { CsvRow rida = new CsvRow(); int i = 0; while (lugeja.ReadRow(rida)) { if (i > 0 && rida[0] == kasutaja) { lugeja.Close(); return(rida); } i++; } lugeja.Close(); } List <string> vastus = new List <string>(); vastus.Add(""); vastus.Add(""); vastus.Add(""); vastus.Add(""); return(vastus); }
public static string kToSqlCreateTable(string tblFileName, string csvFilePath) { string cmdText = string.Empty; using (CsvFileReader reader = new CsvFileReader(csvFilePath)) { CsvRow row = new CsvRow(); bool isHeader = true; string tTblFile = tblFileName.Substring(0, tblFileName.IndexOf("_")); Console.WriteLine("c o d i n g . . . t r a n s c o d i n g . . . t r a n s . . . . . "); cmdText += string.Format("DROP TABLE IF EXISTS `{0}`;", tTblFile) + Environment.NewLine; cmdText += string.Format("CREATE TABLE IF NOT EXISTS `{0}` (", tTblFile) + Environment.NewLine; while (reader.ReadRow(row)) { if (isHeader) { isHeader = false; continue; } string tRowType = kToMySQLTypeStatement(row); cmdText += "\t" + (tRowType.Equals(",") ? "" : tRowType) + Environment.NewLine; } cmdText = cmdText.Remove(cmdText.LastIndexOf(","), 1); cmdText += ") ENGINE=InnoDB DEFAULT CHARSET=utf8;" + Environment.NewLine; Console.WriteLine(cmdText); Console.WriteLine("DONE !!!"); reader.Close(); } return(cmdText); }
private void loadSNPSPToolStripMenuItem_Click(object sender, EventArgs e) { _openFileDialog.FileName = "SNPCC.csv"; _openFileDialog.Filter = "csv files (*.csv)|*.csv"; _openFileDialog.DefaultExt = "txt"; _openFileDialog.FilterIndex = 2; _openFileDialog.AddExtension = true; if (_openFileDialog.ShowDialog() == DialogResult.OK) { string fileName = _openFileDialog.FileName; CsvFileReader csv = new CsvFileReader(fileName); char[] _separators = new char[] { '\n', '"', ',' }; CsvRow row = new CsvRow(); bool entering = true; while (entering == true) { entering = csv.ReadRow(row); staters.Add(new Stater(row[1], row[0])); char[] bar = row[2].ToCharArray(); string bs = Convert.ToString(bar[0]) + Convert.ToString(bar[1]) + Convert.ToString(bar[2]) + Convert.ToString(bar[3]); staters[staters.Count - 1].Barcode = Convert.ToInt32(bs); staters[staters.Count - 1].City = row[3]; staters[staters.Count - 1].County = row[4]; } csv.Close(); staters.RemoveAt(staters.Count - 1); List<Stater> testing = staters; } }
/// <summary> /// 读取CSV文件到DataTable中 /// </summary> /// <param name="filePath">CSV的文件路径</param> /// <returns></returns> public static DataTable ReadCSV(string filePath) { DataTable dt = new DataTable(); int lineNumber = 0; using (CsvFileReader reader = new CsvFileReader(filePath)) { CsvRow row = new CsvRow(); while (reader.ReadRow(row)) { if (0 == lineNumber) { foreach (string s in row) { dt.Columns.Add(s.Replace("\"", "")); } } else { int index = 0; DataRow dr = dt.NewRow(); foreach (string s in row) { dr[index] = s.Replace("\"", ""); index++; } dt.Rows.Add(dr); } lineNumber++; } reader.Close(); } return(dt); }
/// <summary> /// Leiab antud kasutaja txt failist. /// Kui kasutajat pole siis tagasta tühjus. /// </summary> /// <param name="kasutaja"></param> /// <returns></returns> public string KasutajaKonto(string kasutaja) { using (CsvFileReader lugeja = new CsvFileReader(failiNimi)) { CsvRow rida = new CsvRow(); int i = 0; while (lugeja.ReadRow(rida)) { if (i > 0 && rida[0] == kasutaja) { lugeja.Close(); return(rida[2]); } i++; } lugeja.Close(); } return(""); }
/// <summary> /// Kontrollime, kas kasutaja info on olemas CSV failis /// </summary> /// <param name="kasutaja"></param> /// <returns></returns> public bool KasutajaOlemas(string kasutaja) { using (CsvFileReader lugeja = new CsvFileReader(failiNimi)) { CsvRow rida = new CsvRow(); int i = 0; while (lugeja.ReadRow(rida)) { if (i > 0 && rida[0] == kasutaja) { lugeja.Close(); return(true); } i++; } lugeja.Close(); } return(false); }
public void CsvDataReaderReadAfterClose() { using (var test = new CsvFileReader(m_ValidSetting)) { test.Open(false, CancellationToken.None); Assert.IsTrue(test.Read()); test.Close(); Assert.IsFalse(test.Read()); } }
/// <summary> /// Rahandus /// </summary> /// <param name="kasutaja"></param> /// <returns></returns> public float KasutajaSaldo(string kasutaja) { using (CsvFileReader lugeja = new CsvFileReader(failiNimi)) { CsvRow rida = new CsvRow(); while (lugeja.ReadRow(rida)) { if (rida[0] == kasutaja) { string summa = rida[3]; lugeja.Close(); return(float.Parse(summa, CultureInfo.InvariantCulture.NumberFormat)); } } lugeja.Close(); } return(-1); }
public void CloseCleansUp() { var readerMock = new Mock <ICsvReader>(); readerMock.Setup(x => x.Dispose()); var sut = new CsvFileReader(readerMock.Object); sut.Close(); readerMock.Verify(x => x.Dispose(), Times.Once); }
public static void kToSqlCreateTable(string tblsFile, string sqlFile = cSqlCreateTblScriptFile) { string tSqlFile = string.Format("{0}k{1}.{2}", cScriptHomePath, sqlFile, cSqlFileExt); SqlScriptLogger scriptLogger = new SqlScriptLogger(tSqlFile); scriptLogger.kWriteLine("USE akm_m6dtx;" + Environment.NewLine); Console.WriteLine(string.Format("Creating {0} . . .", tSqlFile)); string tCsvFile = string.Format("{0}{1}_{2}.{3}", cDataHomePath, tblsFile, cDataPostfix, cCsvFileExt); CsvFileReader reader = new CsvFileReader(tCsvFile); Console.WriteLine(string.Format("Opening {0} . . .", tCsvFile)); Console.WriteLine("[Press the ENTER key to begin . . .]"); Console.ReadKey(); CsvRow row = new CsvRow(); bool isHeader = true; while (reader.ReadRow(row)) { if (isHeader) { isHeader = false; continue; } foreach (string tblSchema in row) { string script = string.Empty; try { string tTblSchemaFile = string.Format("{0}_{1}", tblSchema, cSchemaPostfix); scriptLogger.kWriteLineHeader(tblSchema); scriptLogger.kWriteLine(2); scriptLogger.kWriteLine(SqlScriptTrans.kToSqlCreateTable(tTblSchemaFile, string.Format("{0}{1}.{2}", cDataHomePath, tTblSchemaFile, cCsvFileExt))); scriptLogger.kWriteLine(2); scriptLogger.kWriteLineFooter(); } catch (FileNotFoundException) { scriptLogger.kWriteLine("## [ERROR::" + tblSchema + "] The table does not exists in the database."); continue; } scriptLogger.kWriteLine(4); } } reader.Close(); scriptLogger.kClose(); }
public void ReadData(ref CsvFileWriter writer, string filename) { // Read sample data from CSV file CsvFileReader reader = new CsvFileReader(filename); CsvRow row = new CsvRow(); while (reader.ReadRow(row)) { writer.WriteRow(row); } reader.Close(); }
private void openCSVToolStripMenuItem_Click(object sender, EventArgs e) { if (!this.openFileDialog1.ShowDialog().Equals(DialogResult.OK)) { return; } data = new DataTable(); this.listBox1.Items.Clear(); using (CsvFileReader cr = new CsvFileReader(this.openFileDialog1.FileName)) { CsvRow header = new CsvRow(); if (!cr.ReadRow(header)) { return; } this.listBox1.Items.AddRange(header.ToArray()); for (int i = 0; i < header.Count; i++) { string name = header[i].Trim(); if (name == "") { name = "V" + i; } data.Columns.Add(name); } int count = 1; while (true) { CsvRow row = new CsvRow(); if (!cr.ReadRow(row)) { break; } DataRow r = data.NewRow(); for (int i = 0; i < row.Count; i++) { r[i] = row[i]; } data.Rows.Add(r); if (count > 100) { break; } count++; } cr.Close(); } this.dataGridView1.DataSource = data; this.button1.Enabled = true; }
/// <summary> /// Kontrollime, et kas sellise nimega kasutaja konto on juba olemas. /// </summary> /// <param name="kontoId"></param> /// <returns></returns> public bool KasutajaKontoOlemas(string kontoId) { // Avame CSV faili lugemiseks using (CsvFileReader lugeja = new CsvFileReader(failiNimi)) { CsvRow rida = new CsvRow(); int i = 0; // see on ridade loendamiseks, et ei kontrollitaks kasutajat esimesest reast. // Loeme faili rida haaval ja kontrollime, et ega // esimene väärtus (kasutaja) juba ei ole olemas while (lugeja.ReadRow(rida)) { if (i > 0 && rida[3] == kontoId) { lugeja.Close(); return(true); } i++; } lugeja.Close(); } return(false); }
/// <summary> /// Leiame kasutajate arvu süsteemis. /// Selleks loeme läbi CSV failis olevad read ja lahutame maha 1. rea. (See on päis) /// </summary> /// <returns></returns> public int KasutajateArv() { int i = 0; // Ridade lugeja using (CsvFileReader lugeja = new CsvFileReader(failiNimi)) { CsvRow rida = new CsvRow(); while (lugeja.ReadRow(rida)) { i++; } lugeja.Close(); // Sulgeme faili lugeja. } return(i - 1); // vastus on 1-võrra väiksem kui kõik read kokku. }
public List <PlayerObject> ReturnObjects() { //Row to read values from Other files(dataset, new high score in 000001.csv) CsvRow readerRow; //Reader Object for New High Score (or old if run early) CsvFileReader reader = new CsvFileReader("HighScoreFile.csv"); //Array of Player Objects to fill with readerRow's values read List <PlayerObject> pastPlayers = new List <PlayerObject> (); //Loop through the reader till the end while (!reader.EndOfStream) { //if (reader.BaseStream.ReadByte() == -1) // break; //Build a new player Object to fill PlayerObject obj = new PlayerObject(); //Instatiate the CsvRow readerRow = new CsvRow(); //Build a string array to hold the CsvRow values string[] list = new string[2]; //Read the rows and Copy the data to the array reader.ReadRow(readerRow); readerRow.CopyTo(list); //Check for "Player" as the first column and skip it if (list [0].ToString().Contains("Player")) { readerRow.Clear(); readerRow = new CsvRow(); list = new string[2]; reader.ReadRow(readerRow); readerRow.CopyTo(list); } //Set player names by formatting the string, and parsing to a float obj.setPlayerName(string.Format("{0}", list[0].ToString())); obj.setPoints(float.Parse(list [1])); //Add the player Object to the array pastPlayers.Add(obj); readerRow.Clear(); } //End of while loop reader.Dispose(); reader.Close(); return(pastPlayers); }
/// <summary> /// Muudame kasutaja saldot. Vähendamisel anname summa miinusega. /// Kui pole piisavalt raha kontol saame tulemuseks -1. /// </summary> /// <param name="kasutaja"></param> /// <param name="SaldoMuutus"></param> /// <returns></returns> public float KasutajaSaldo(string kasutaja, float SaldoMuutus) { float j22k = KasutajaSaldo(kasutaja); if (SaldoMuutus < 0 && Math.Abs(SaldoMuutus) > j22k) { return(-1); } j22k += SaldoMuutus; // Kõigepealt loeme CSV faili sisse ja muudame soovitud rea. using (CsvFileReader lugeja = new CsvFileReader(failiNimi)) { CsvRow rida = new CsvRow(); int i = 0; while (lugeja.ReadRow(rida)) { if (rida[0] == kasutaja) { rida[3] = j22k.ToString().Replace(',', '.'); } using (CsvFileWriter writer = new CsvFileWriter(failiNimi + ".txt", i != 0)) { writer.WriteRow(rida); writer.Close(); } i++; } lugeja.Close(); } // Nimetame loodud uue faili ümber vanaks failiks. if (File.Exists(failiNimi)) { File.Delete(failiNimi); } File.Move(failiNimi + ".txt", failiNimi); return(j22k); }
public static void kToSqlInsert(string tblsFile, string sqlFile = cSqlInsertScriptFile) { string tSqlFile = string.Format("{0}{1}.{2}", cScriptHomePath, sqlFile, cSqlFileExt); // Console.WriteLine(string.Format("Creating {0} . . .", tSqlFile)); string tCsvFile = string.Format("{0}{1}_{2}.{3}", cDataHomePath, tblsFile, cDataPostfix, cCsvFileExt); CsvFileReader reader = new CsvFileReader(tCsvFile); Console.WriteLine(string.Format("Opening {0} . . .", tCsvFile)); Console.WriteLine("[Press the ENTER key to begin . . .]"); Console.ReadKey(); CsvRow row = new CsvRow(); bool isHeader = true; while (reader.ReadRow(row)) { if (isHeader) { isHeader = false; continue; } foreach (string tblName in row) { string tTblDataFile = string.Format("{0}_{1}.{2}", tblName, cDataPostfix, cCsvFileExt); try { SqlScriptTrans.kToSqlInsertTable(tTblDataFile, string.Format("{0}{1}", cDataHomePath, tTblDataFile)); } catch (FileNotFoundException) { Console.WriteLine("[ERROR::" + tblName + "]Reading a non-existent physical database table."); continue; } } } reader.Close(); }
//For test speed private int runAlgorithms() { controller.mAlgorithm = Algorithm.MidPoint_Line; CsvFileReader reader = new CsvFileReader("Testcase_Line.csv"); CsvFileWriter writer = new CsvFileWriter("Midpoint_Line_Runtime.csv"); CsvRow row = new CsvRow(); Random rnd = new Random(); int count = 0; while (reader.ReadRow(row)) { if (row.Count == 4) { int x1 = Int32.Parse(row[0]); int y1 = Int32.Parse(row[1]); int x2 = Int32.Parse(row[2]); int y2 = Int32.Parse(row[3]); controller.mShape = new Line(new Point(x1, y1), new Point(x2, y2)); Color color = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256)); try { Int64 runtime = this.DrawShape(); row.Add(String.Format(runtime.ToString())); writer.WriteRow(row); count++; } catch (Exception e) { Debug.WriteLine("failed at " + count.ToString()); } } else { break; } } reader.Close(); writer.Close(); return(count); }
static JArray parseCSVInputs(string infilename) { CsvFileReader inStream = new CsvFileReader(infilename); try { //Now parse the inputs. They are in csv format, so read a names into an array, and build a dictionary of each input set. //So, at the end of this we should have 1 or more input sets in the JArray inputsArray JArray inputsArray = new JArray(); //Will be set if the input file is a set of runs JArray outputsArray = new JArray(); List <object> headers = new List <object>(); inStream.ReadRow(headers); int lineNum = 1; List <object> data = new List <object>(); while (inStream.ReadRow(data)) { lineNum++; //Keep track of which line we're on for error checking JObject thisRunInputsDict = new JObject(); JObject outterDict = new JObject(); if (headers.Count != data.Count) { throw new System.IO.IOException(String.Format("Data line {0} has incorrect number of columns. Headers: {1} This Line: {2}", lineNum, headers.Count, data.Count)); } for (int ii = 0; ii < headers.Count; ++ii) { thisRunInputsDict.Add((string)headers[ii], Convert.ToDouble(data[ii])); //Should allow of strings I suppose } outterDict.Add("inputs", thisRunInputsDict); inputsArray.Add(outterDict); } return(inputsArray); } finally { inStream.Close(); } }
static void writeOutCsv(string outfilename, JArray outputsArray) { CsvFileReader inStream = new CsvFileReader(outfilename); List <object> headers = new List <object>(); inStream.ReadRow(headers); inStream.Close(); CsvFileWriter outStream = new CsvFileWriter(outfilename); outStream.WriteRow(headers); foreach (JObject run in outputsArray) { JObject thisOutputs = (JObject)run["outputs"]; List <object> csvOutputs = new List <object>(); for (int ii = 0; ii < headers.Count; ++ii) { csvOutputs.Add(thisOutputs[headers[ii]]["value"]); } outStream.WriteRow(csvOutputs); } outStream.Close(); }
/// <summary> /// Kontrollime kasutaja sisselogimis andmeid. /// </summary> /// <param name="kasutaja"></param> /// <param name="Pin"></param> /// <returns></returns> public bool KasutajaLogin(string kasutaja, string Pin) { using (CsvFileReader lugeja = new CsvFileReader(failiNimi)) { CsvRow rida = new CsvRow(); int i = 0; string PinKood = ""; while (lugeja.ReadRow(rida)) { if (i > 0) { PinKood = rida[1]; if (rida[0] == kasutaja && PinKood == Pin) { return(true); } } i++; } lugeja.Close(); } return(false); }
public MainForm() { InitializeComponent(); tasks = new List <string>(); if (!Directory.Exists(Extract + "Extract_ByDate")) { Directory.CreateDirectory(Extract + "Extract_ByDate"); } if (!Directory.Exists(ExtractGlobal)) { Directory.CreateDirectory(ExtractGlobal); } if (!File.Exists(ExtractGlobal + "Extract_Global.csv")) { File.WriteAllText(ExtractGlobal + "Extract_Global.csv", "Date,Task,Duration,Comments\n"); } CsvFileReader csvFileReader = new CsvFileReader(ExtractGlobal + "Extract_Global.csv"); CsvRow row = new CsvRow(); csvFileReader.ReadRow(row); while (csvFileReader.ReadRow(row)) { if (!tasks.Contains(row[1])) { tasks.Add(row[1]); } } csvFileReader.Close(); addTaskToolStripMenuItem_Click(null, null); this.SizeChanged += MainForm_SizeChanged; this.FormClosing += MainForm_FormClosing; }
private void button1_Click(object sender, EventArgs e) { OpenFileDialog _openFileDialog = new OpenFileDialog(); _openFileDialog.FileName = "SNPCC.csv"; _openFileDialog.Filter = "csv files (*.csv)|*.csv"; _openFileDialog.DefaultExt = "csv"; _openFileDialog.FilterIndex = 2; _openFileDialog.AddExtension = true; if (_openFileDialog.ShowDialog() == DialogResult.OK) { string fileName = _openFileDialog.FileName; CsvFileReader csv = new CsvFileReader(fileName); char[] _separators = new char[] { '\n', '"', ',' }; CsvRow row = new CsvRow(); bool entering = true; while (entering == true) { entering = csv.ReadRow(row); staters.Add(new Stater(row[1], row[2])); char[] bar = row[0].ToCharArray(); string bs = Convert.ToString(bar[0]) + Convert.ToString(bar[1]) + Convert.ToString(bar[2]) + Convert.ToString(bar[3]); staters[staters.Count - 1].Barcode = Convert.ToInt32(bs); staters[staters.Count - 1].City = row[3]; staters[staters.Count - 1].County = row[4]; } csv.Close(); } _openFileDialog.FileName = "MasterPhotoList.csv"; _openFileDialog.Filter = "csv files (*.csv)|*.csv"; _openFileDialog.DefaultExt = "csv"; _openFileDialog.FilterIndex = 2; _openFileDialog.AddExtension = true; if (_openFileDialog.ShowDialog() == DialogResult.OK) { string fileName = _openFileDialog.FileName; CsvFileReader csv = new CsvFileReader(fileName); char[] _separators = new char[] { '\n', '"', ',' }; CsvRow row = new CsvRow(); bool entering = true; while (entering == true) { entering = csv.ReadRow(row); if (entering == true) { photoList.Add(new Stater(row[1], row[0])); char[] bar = row[2].ToCharArray(); string bs = Convert.ToString(bar[0]) + Convert.ToString(bar[1]) + Convert.ToString(bar[2]) + Convert.ToString(bar[3]); photoList[photoList.Count - 1].Barcode = Convert.ToInt32(bs); } } csv.Close(); } SaveFileDialog MySaveFileDialog = new SaveFileDialog(); MySaveFileDialog.DefaultExt = "csv"; if (MySaveFileDialog.ShowDialog() == DialogResult.OK) { using (Stream myStream = MySaveFileDialog.OpenFile()) { if (myStream != null) { List<Stater> temp = new List<Stater>(); for (int i = 0; i < photoList.Count; i++) { temp.Add(new Stater(photoList[i].FirstName, photoList[i].LastName)); temp[temp.Count - 1].Barcode = photoList[i].Barcode; } for (int i = 0; i < photoList.Count; i++) { for (int j = 0; j < staters.Count; j++) { if (photoList[i].Barcode == staters[j].Barcode) { staters.RemoveAt(j); } } } for (int i = 0; i < photoList.Count; i++) { for (int j = 0; j < staters.Count; j++) { if (photoList[i].Barcode == staters[j].Barcode) { staters.RemoveAt(j); } } } using (StreamWriter myWritter = new StreamWriter(myStream, System.Text.Encoding.ASCII)) { for (int i = 0; i < staters.Count; i++) { myWritter.WriteLine(staters[i].FirstName + "," + staters[i].LastName + "," + staters[i].Barcode + "," + staters[i].City + "," + staters[i].County); } } } } } }
private void button2_Click(object sender, EventArgs e) { OpenFileDialog _openFileDialog = new OpenFileDialog(); _openFileDialog.FileName = "MasterPhotoList.csv"; _openFileDialog.Filter = "csv files (*.csv)|*.csv"; _openFileDialog.DefaultExt = "csv"; _openFileDialog.FilterIndex = 2; _openFileDialog.AddExtension = true; if (_openFileDialog.ShowDialog() == DialogResult.OK) { string fileName = _openFileDialog.FileName; CsvFileReader csv = new CsvFileReader(fileName); char[] _separators = new char[] { '\n', '"', ',' }; CsvRow row = new CsvRow(); bool entering = true; while (entering == true) { entering = csv.ReadRow(row); if (entering == true) { photoList.Add(new Stater(row[1], row[0])); char[] bar = row[2].ToCharArray(); string bs = Convert.ToString(bar[0]) + Convert.ToString(bar[1]) + Convert.ToString(bar[2]) + Convert.ToString(bar[3]); photoList[photoList.Count - 1].Barcode = Convert.ToInt32(bs); } } csv.Close(); } _openFileDialog.FileName = "Missing Staters.csv"; _openFileDialog.Filter = "csv files (*.csv)|*.csv"; _openFileDialog.DefaultExt = "csv"; _openFileDialog.FilterIndex = 2; _openFileDialog.AddExtension = true; if (_openFileDialog.ShowDialog() == DialogResult.OK) { string fileName = _openFileDialog.FileName; CsvFileReader csv = new CsvFileReader(fileName); char[] _separators = new char[] { '\n', '"', ',' }; counter = 0; CsvRow row = new CsvRow(); bool entering = true; while (entering == true) { entering = csv.ReadRow(row); if (entering == true) { check.Add(new Stater(row[0], row[1])); char[] bar = row[2].ToCharArray(); string bs = Convert.ToString(bar[1]) + Convert.ToString(bar[1]) + Convert.ToString(bar[2]) + Convert.ToString(bar[3]); check[counter].Barcode = Convert.ToInt32(bs); check[counter].City = row[3]; check[counter].County = row[4]; } counter++; } csv.Close(); } SaveFileDialog MySaveFileDialog = new SaveFileDialog(); MySaveFileDialog.DefaultExt = "csv"; if (MySaveFileDialog.ShowDialog() == DialogResult.OK) { using (Stream myStream = MySaveFileDialog.OpenFile()) { if (myStream != null) { for (int i = 0; i < counter-1; i++) { for (int j = 0; j < photoList.Count; j++) { bool contains = photoList.Contains(check[i]); if (contains==true) { check.RemoveAt(i); } } } using (StreamWriter myWritter = new StreamWriter(myStream, System.Text.Encoding.ASCII)) { for (int i = 0; i < check.Count; i++) { myWritter.WriteLine(check[i].FirstName + "," + check[i].LastName + "," + check[i].Barcode + "," + check[i].City + "," + check[i].County); } } } } } }
private void HarmonyToDB(string DefaultPath) { #region Get the directory if (!Directory.Exists(DefaultPath)) DefaultPath = ""; var dlg1 = new Ionic.Utils.FolderBrowserDialogEx(); dlg1.Description = "Select the folder of your experiment."; dlg1.ShowNewFolderButton = true; dlg1.ShowEditBox = true; if (DefaultPath != "") dlg1.SelectedPath = DefaultPath; //dlg1.NewStyle = false; //dlg1.SelectedPath = txtExtractDirectory.Text; dlg1.ShowFullPathInEditBox = true; dlg1.RootFolder = System.Environment.SpecialFolder.Desktop; // Show the FolderBrowserDialog. DialogResult result = dlg1.ShowDialog(); if (result != DialogResult.OK) return; string Path = dlg1.SelectedPath; if (Directory.Exists(Path) == false) return; #endregion #region Get the different files string[] ListFilesForPlates = null; try { ListFilesForPlates = Directory.GetFiles(Path, "Objects_Population - *.txt", SearchOption.AllDirectories); } catch (System.Exception excep) { MessageBox.Show(excep.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (ListFilesForPlates.Length == 0) { MessageBox.Show("The selected directory do not contain any Objects_Population files !", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string[] Sep = new string[1]; Sep[0] = "\\"; Dictionary<string, string> CurrentPlateDico = new Dictionary<string, string>(); // string[] FirstListImages = Directory.GetFiles(PlateDirectories[i], TmpPlateName + "_*.C01", SearchOption.AllDirectories); foreach (var item in ListFilesForPlates) { string[] Res = item.Split(Sep, StringSplitOptions.RemoveEmptyEntries); string CurrentName = Res[Res.Length-1]; if (CurrentPlateDico.ContainsKey(CurrentName.Remove(CurrentName.Length - 4))) continue; CurrentPlateDico.Add(CurrentName.Remove(CurrentName.Length-4), item); } string[] ListTypes = CurrentPlateDico.Keys.ToArray(); // plates selection GUI FormForPlateSelection FFP = new FormForPlateSelection(ListTypes,false); FFP.Text = "Object Types Selection"; if (FFP.ShowDialog() != System.Windows.Forms.DialogResult.OK) return; ListFilesForPlates = FFP.GetListPlatesSelected(); #endregion if (ListFilesForPlates.Length == 0) return; ListFilesForPlates = Directory.GetFiles(Path, ListFilesForPlates[0] + ".txt", SearchOption.AllDirectories); #region And now let's analyse the files adn create the CSV CsvRow CurrentRow = new CsvRow(); bool IsHeaderWritten = false; string OriginalHeader = ""; Sep[0] = "\\"; string[] TmpSplit = ListFilesForPlates[0].Split(Sep, StringSplitOptions.RemoveEmptyEntries); //TmpSplit[TmpSplit.Length-1].Replace(".txt",".csv"); string TPath = Path + "\\" + TmpSplit[TmpSplit.Length - 1].Replace(".txt", ".csv"); Sep[0] = ","; // specifically for the bounding box processing FormForProgress MyProgressBar = new FormForProgress(); MyProgressBar.progressBar.Maximum = ListFilesForPlates.Length; MyProgressBar.Show(); for (int i = 0; i < ListFilesForPlates.Length ; i++) { MyProgressBar.richTextBoxForComment.AppendText(ListFilesForPlates[i]); MyProgressBar.richTextBoxForComment.Update(); StreamWriter stream = new StreamWriter(TPath, true, Encoding.ASCII); #region process the header string CurrentFile = ListFilesForPlates[i]; CsvFileReader CSVReader = new CsvFileReader(CurrentFile); CSVReader.Separator = '\t'; CSVReader.ReadRow(CurrentRow); // let's take care of the header first while (CurrentRow[0]!="Plate Name") { CSVReader.ReadRow(CurrentRow); } string PlateName = CurrentRow[1]; // skip the rest of the header while (CurrentRow[0] != "[Data]") { CSVReader.ReadRow(CurrentRow); } // read the columns names CSVReader.ReadRow(CurrentRow); List<string> Descs = CurrentRow; string TobeWritten = "Plate Name,"; int IdxBoundingBox = -1; int IndexCol = -1; int IndexRow = -1; int IndexCompound = -1; int IndexConcentration = -1; int IndexCellcount = -1; int NumDesc = Descs.Count; for (int j = 0; j < Descs.Count; j++) { if (Descs[j] == "Bounding Box") { TobeWritten += "X_Min,Y_Min,X_Max,Y_Max,"; IdxBoundingBox = j; // NumDesc += 3; } else if (Descs[j] == "Row") { IndexRow = j; TobeWritten += "Well Position,"; } else if (Descs[j] == "Column") { IndexCol = j; } else if (Descs[j] == "Compound") { // skipped IndexCompound = j; } else if (Descs[j] == "Concentration") { // skipped IndexConcentration = j; } else if (Descs[j] == "Cell Count") { // skipped IndexCellcount = j; } else TobeWritten += Descs[j] + ","; } TobeWritten = TobeWritten.Remove(TobeWritten.Length - 1); if (IsHeaderWritten == false) { OriginalHeader = TobeWritten; stream.WriteLine(TobeWritten); IsHeaderWritten = true; } else { // inconsistency between the headers... skip the plate if (TobeWritten != OriginalHeader) { continue; } } #endregion // now let's process the data int IdxRow = 0; while (!CSVReader.EndOfStream) { CSVReader.ReadRow(CurrentRow); TobeWritten = PlateName+","; for (int j = 0; j < Descs.Count; j++) { if ((IdxBoundingBox > -1) && (j == IdxBoundingBox)) { // let's process the bounding box string BB = CurrentRow[j]; BB = BB.Remove(BB.Length - 1); BB = BB.Remove(0, 1); string[] Splitted = BB.Split(Sep, StringSplitOptions.None); TobeWritten += Splitted[0] + "," + Splitted[1] + "," + Splitted[2] + "," + Splitted[3] + ","; // j += 3; } else if (j == IndexRow) { TobeWritten += ConvertPosition(int.Parse(CurrentRow[IndexCol]), int.Parse(CurrentRow[IndexRow]))+","; } else if ((j == IndexCol)||(j==IndexCellcount)||(j==IndexCompound)||(j==IndexConcentration)) { // do nothing } else { if (CurrentRow[j] != "") TobeWritten += CurrentRow[j] + ","; else TobeWritten += "NaN,"; } } TobeWritten = TobeWritten.Remove(TobeWritten.Length - 1); stream.WriteLine(TobeWritten ); IdxRow++; } CSVReader.Close(); stream.Dispose(); MyProgressBar.progressBar.Value++; MyProgressBar.progressBar.Update(); } MyProgressBar.Close(); #endregion #region let's build the database now // if (CSVFeedBackWindow == null) return; // if (CSVFeedBackWindow.ShowDialog() != System.Windows.Forms.DialogResult.OK) return; string DBPath = Path + "\\DB"; Directory.CreateDirectory(DBPath); cConvertCSVtoDB CCTODB = CSVtoDB(TPath, ",", DBPath); if (CCTODB == null) { return; } else { // update image accessor cGlobalInfo.OptionsWindow.radioButtonImageAccessDefined.Checked = false; cGlobalInfo.OptionsWindow.radioButtonImageAccessHarmony35.Checked = true; cGlobalInfo.OptionsWindow.textBoxImageAccesImagePath.Text = Path; cGlobalInfoToBeExported GlobalInfoToBeExported = new cGlobalInfoToBeExported(); cGlobalInfo.OptionsWindow.TmpOptionPath = GlobalInfoToBeExported.Save(DBPath+"\\Options.opt"); //cGlobalInfo.OptionsWindow.sav } #endregion }
private void backgroundWorkerForCSVtoDB_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; CSVsr = new CsvFileReader(PathName); CSVsr.Separator = this.Delimiter.ToCharArray()[0]; CsvRow OriginalNames = new CsvRow(); if (!CSVsr.ReadRow(OriginalNames)) { CSVsr.Close(); return; } int ColPlateName = GetColIdxFor("Plate name", CSVWindow); int ColCol = GetColIdxFor("Column", CSVWindow); int ColRow = GetColIdxFor("Row", CSVWindow); int ColWellPos = GetColIdxFor("Well position", CSVWindow); int ColPhenotypeClass = GetColIdxFor("Phenotype Class", CSVWindow); int[] ColsForDescriptors = GetColsIdxFor("Descriptor", CSVWindow); FormForProgress ProgressWindow = new FormForProgress(); ProgressWindow.Text = "CSV -> DB : processing"; ProgressWindow.Show(); CsvRow CurrentDesc = new CsvRow(); int TotalPlateNumber = 0; int TotalObjectNumber = 0; int TotalWellNumber = 0; string OriginalPlatePlateName; string CurrentPlateName; string ConvertedName; this.CompleteReportString += "Source file: " + PathName + "\n"; this.CompleteReportString += OriginalNames.Count + " features selected.\n"; this.CompleteReportString += "Time stamp: " + DateTime.Now.ToString() + " \n"; if (CSVsr.ReadRow(CurrentDesc) == false) return; do { if (ColPlateName == -1) { ConvertedName = OriginalPlatePlateName = CurrentPlateName = "Generated Plate Name"; } else { OriginalPlatePlateName = CurrentDesc[ColPlateName]; CurrentPlateName = CurrentDesc[ColPlateName]; ConvertedName = ""; foreach (var c in System.IO.Path.GetInvalidFileNameChars()) ConvertedName = OriginalPlatePlateName.Replace(c, '-'); } List<string> ListNameSignature = new List<string>(); for (int idxDesc = 0/*Mode + 1*/; idxDesc < ColsForDescriptors.Length/* + Mode + 1*/; idxDesc++) { string TmpSignature = OriginalNames[ColsForDescriptors[idxDesc]]; TmpSignature = TmpSignature.Replace('[', '_'); TmpSignature = TmpSignature.Replace(']', '_'); ListNameSignature.Add(TmpSignature); } ListNameSignature.Add("Phenotype_Class"); ListNameSignature.Add("Phenotype_Confidence"); cSQLiteDatabase SQDB = new cSQLiteDatabase(SelectedPath + "\\" + ConvertedName, ListNameSignature, true); this.CompleteReportString += "\n" + CurrentPlateName + ":\n"; TotalPlateNumber++; do { string OriginalWellPos; int[] Pos = new int[2]; if (Mode == 1) { Pos = ConvertPosition(CurrentDesc[ColWellPos]); if (Pos == null) { if (MessageBox.Show("Error in converting the current well position.\nGo to Edit->Options->Import-Export->Well Position Mode to fix this.\nDo you want continue ?", "Loading error !", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == System.Windows.Forms.DialogResult.No) { CSVsr.Close(); return; } //else // goto NEXTLOOP; } OriginalWellPos = CurrentDesc[ColWellPos]; } else { if (int.TryParse(CurrentDesc[ColCol], out Pos[0]) == false) goto NEXTLOOP; if (int.TryParse(CurrentDesc[ColRow], out Pos[1]) == false) goto NEXTLOOP; OriginalWellPos = ConvertPosition(int.Parse(CurrentDesc[ColCol]), int.Parse(CurrentDesc[ColRow]));// "("+CurrentDesc[ColCol]+","+CurrentDesc[ColRow]+")"; } string CurrentWellPos = OriginalWellPos; cWellForDatabase WellForDB = new cWellForDatabase(OriginalPlatePlateName, Pos[0], Pos[1]); cExtendedTable ListData = new cExtendedTable(); // for (int idxDesc = 0; idxDesc < ColsForDescriptors.Length; idxDesc++) // ListData[idxDesc] = new List<double>(); ProgressWindow.richTextBoxForComment.AppendText(CurrentPlateName + " : " + CurrentWellPos + "\n"); //ProgressWindow.label.Refresh(); ProgressWindow.Refresh(); do { // CurrentWellPos = CurrentDesc[ColWellPos]; cExtendedList Signature = new cExtendedList(); for (int idxDesc = 0; idxDesc < ColsForDescriptors.Length; idxDesc++) { double Value; if (double.TryParse(CurrentDesc[ColsForDescriptors[idxDesc]], NumberStyles.Any, CultureInfo.InvariantCulture/*.CreateSpecificCulture("en-US")*/, out Value)) { if (double.IsNaN(Value)) Signature.Add(0); else Signature.Add(Value); } else { Signature.Add(0); } } // if the class of the phenotype is defined in the file then use it // if not, put it at 0 double ValueClass; if ((ColPhenotypeClass != -1) && (double.TryParse(CurrentDesc[ColPhenotypeClass], out ValueClass) == true)) { double IntValue = (int)(ValueClass) % cGlobalInfo.ListCellularPhenotypes.Count; Signature.Add(IntValue); } else { Signature.Add(0); } // finally add the classification confidence column (1 by default) Signature.Add(1); ListData.Add(Signature); // WellForDB.AddSignature(Signature); // manage the end of the file if (CSVsr.ReadRow(CurrentDesc) == false) { WellForDB.AddListSignatures(ListData); cFeedBackMessage FeedBackMessage = SQDB.AddNewWell(WellForDB); SQDB.CloseConnection(); // this.CompleteReportString += FeedBackMessage.Message + "\n"; goto NEXTLOOP; } if (ColPlateName == -1) CurrentPlateName = "Generated Plate Name"; else CurrentPlateName = CurrentDesc[ColPlateName]; if (Mode == 1) CurrentWellPos = CurrentDesc[ColWellPos]; else { int ResCol; int ResRow; if ((!int.TryParse(CurrentDesc[ColCol], out ResCol)) || (!int.TryParse(CurrentDesc[ColRow], out ResRow))) goto NEXTLOOP; CurrentWellPos = ConvertPosition(ResCol, ResRow); } TotalObjectNumber++; // NEXTSIGNATURE: ; } while (CurrentWellPos == OriginalWellPos); TotalWellNumber++; WellForDB.AddListSignatures(ListData); SQDB.AddNewWell(WellForDB); ReportTable.ListRowNames.Add(CurrentPlateName + " : " + CurrentWellPos); ReportTable[0].Add(ListData.Count); ReportTable[0].ListTags.Add(CurrentPlateName + " : " + CurrentWellPos + "\n" + ListData.Count + " objects"); this.CompleteReportString += "\t" + CurrentWellPos + " : " + ListData.Count + " objects\n"; NEXTSIGNATURE: ; } while (OriginalPlatePlateName == CurrentPlateName); SQDB.CloseConnection(); } while (true); NEXTLOOP: ; ProgressWindow.Close(); this.CompleteReportString += "\n-----------------------------\n"; this.CompleteReportString += TotalPlateNumber + " plates\n"; this.CompleteReportString += TotalWellNumber + " wells\n"; this.CompleteReportString += TotalObjectNumber + " objects\n"; this.CompleteReportString += "\nDataBase location:\n" + SelectedPath; // worker.ReportProgress(10); }
void LoadYesterdayLongRemains() { try { CsvFileReader reader = new CsvFileReader(_yesterdayLongRemainFileName_Input); Boolean header = true; while (true) { CsvRow row = new CsvRow(); if (reader.ReadRow(row)) { if (header) { header = false; continue; } DateTime dt = DateTime.ParseExact(row[0], "yyyy-MM-dd", null); long count = Convert.ToInt64(row[1]) * CommonConst._100_000_000; double rate = Math.Round(Convert.ToDouble(row[2]), 5); int price = Convert.ToInt32(row[3]); long notional = Convert.ToInt64(row[4]); KtbSpotPosition pos = new KtbSpotPosition(); pos.TradingDate = dt; pos.Long_2_Short_1 = 2; pos.Count = count; pos.Rate = rate; pos.Price = price; pos.Notional = notional; this.Longs.Add(pos); } else { break; } } reader.Close(); logger.Info("Yesterday Long Remain Position Load complete."); } catch (System.Exception ex) { logger.Error(ex.ToString()); } }
public static void Rearange(string path) { Dictionary <string, Dictionary <string, List <string> > > csvContent = new Dictionary <string, Dictionary <string, List <string> > >(); CsvFileReader csvFileReader = new CsvFileReader(path); CsvRow row = new CsvRow(); csvFileReader.ReadRow(row); while (csvFileReader.ReadRow(row)) { if (!csvContent.ContainsKey(row[0])) { csvContent[row[0]] = new Dictionary <string, List <string> >(); } if (!csvContent[row[0]].ContainsKey(row[1])) { csvContent[row[0]][row[1]] = new List <string>(); } if (csvContent[row[0]][row[1]].Count == 0) { csvContent[row[0]][row[1]].Add(""); } if (csvContent[row[0]][row[1]].Count == 1) { csvContent[row[0]][row[1]].Add(""); } csvContent[row[0]][row[1]][0] += row[2] + "|"; if (row.Count == 4) { csvContent[row[0]][row[1]][1] += row[3]; } } csvFileReader.Close(); File.WriteAllText(path, "Date,Task,Duration,Comments\n"); TextWriter csvFileWriter = new StreamWriter(File.Open(path, FileMode.Append)); foreach (var date in csvContent) { foreach (var task in date.Value) { DateTime time = new DateTime(0); foreach (var d in task.Value[0].Split('|')) { if (d == "") { continue; } time = time.AddHours(int.Parse(d.Split(':')[0])); time = time.AddMinutes(int.Parse(d.Split(':')[1])); time = time.AddSeconds(int.Parse(d.Split(':')[2])); } if (task.Value[1].Contains(',')) { task.Value[1] = "\"" + task.Value[1] + "\""; } csvFileWriter.WriteLine(date.Key + "," + task.Key + "," + time.ToString("HH:mm:ss") + "," + task.Value[1]); } } csvFileWriter.Close(); }
//Upload the stater list into the program. private void createStaterObjects() { staters.Clear(); string pathstring = loadStaterList(); CsvFileReader csv = new CsvFileReader(pathstring); char[] _separators = new char[] { '\n', '"', ',' }; CsvRow row = new CsvRow(); bool entering = true; while (entering == true) { entering = csv.ReadRow(row); if (row.Count != 5) { label1.Size = new Size(200, 30); label1.Location = new Point(50, 20); label1.Text = pathstring + " invalid format;\nCorrect Format: First Name, Last Name, Barcode"; error = true; } staters.Add(new Stater(row[1], row[2])); char[] bar = row[0].ToCharArray(); string bs = Convert.ToString(bar[0]) + Convert.ToString(bar[1]) + Convert.ToString(bar[2]) + Convert.ToString(bar[3]); staters[staters.Count - 1].Barcode = Convert.ToInt32(bs); staters[staters.Count - 1].City = row[3]; staters[staters.Count - 1].County = row[4]; if (staters.Count() > 1 && staters[staters.Count - 1].Barcode == staters[staters.Count - 2].Barcode) { staters.RemoveAt(staters.Count - 1); break; } } csv.Close(); SNPhasBeenLoaded = true; }
public static void kToSqlInsertTable(string tblFileName, string csvFilePath) { string cmdText = string.Empty; using (CsvFileReader reader = new CsvFileReader(csvFilePath)) { CsvRow row = new CsvRow(); bool isHeader = true; string tTblName = tblFileName.Substring(0, tblFileName.LastIndexOf("_data")); string tblFilePath = string.Format("{0}k{1}.{2}", SqlScriptGen.cScriptHomePath, tTblName, SqlScriptGen.cSqlFileExt); SqlScriptLogger scriptLogger = new SqlScriptLogger(tblFilePath); scriptLogger.kWriteLine("USE akm_m6dtx;" + Environment.NewLine); scriptLogger.kWriteLineHeader(tblFileName); scriptLogger.kWriteLine(2); cmdText = string.Format("INSERT INTO {0} (", tTblName) + Environment.NewLine; while (reader.ReadRow(row)) { string insertCmd = string.Empty; /** * Filter the columns of the table and translate to its template header script. */ if (isHeader) { isHeader = false; row.ForEach(col => { cmdText += string.Format("`{0}`,", col); }); cmdText = cmdText.Remove(cmdText.LastIndexOf(","), 1); cmdText += ") VALUES (" + Environment.NewLine; } else { insertCmd = cmdText; foreach (string col in row) { // TODO: Improve filtering by using Regex if ((col.IndexOf("AM") > 0 || col.IndexOf("PM") > 0) && col.IndexOf(@"/") > 0 && col.IndexOf(@":") > 0) { insertCmd += string.Format(@"STR_TO_DATE('{0}', '%m/%d/%Y %l:%i:%s %p'),", col); } else { insertCmd += string.Format("\t'{0}',", col.Replace('\'', '^')) + Environment.NewLine; } } insertCmd = insertCmd.Remove(insertCmd.LastIndexOf(","), 1); insertCmd += Environment.NewLine + ");"; Console.Write("c o d i n g . . . t r a n s c o d i n g . . . t r a n s . . . . . "); scriptLogger.kWriteLine(insertCmd); Console.WriteLine("DONE !!!"); } } scriptLogger.kWriteLine(2); scriptLogger.kWriteLineFooter(); scriptLogger.kClose(); reader.Close(); } }
private void button1_Click(object sender, EventArgs e) { if (data == null) { MessageBox.Show("Open a csv file first."); return; } if (selectedColumn == "") { MessageBox.Show("Select a text column."); return; } // DirectoryInfo dir = new DirectoryInfo(this.openFileDialog1.FileName); if (!this.folderBrowserDialog1.ShowDialog().Equals(DialogResult.OK)) { return; } string dirname = this.folderBrowserDialog1.SelectedPath + "\\CSV2Texts"; if (Directory.Exists(dirname)) { MessageBox.Show("Converted texts found at: " + dirname); return; } int lineCount = 0; using (StreamReader sr = new StreamReader(this.openFileDialog1.FileName)) { while (sr.Peek() > -1) { sr.ReadLine(); lineCount++; } sr.Close(); } int digits = 1; while (lineCount > 9) { digits++; lineCount /= 10; } DirectoryInfo saveDir = Directory.CreateDirectory(dirname); using (CsvFileReader cr = new CsvFileReader(this.openFileDialog1.FileName)) { CsvRow header = new CsvRow(); if (!cr.ReadRow(header)) { return; } int headIndex = -1; for (int i = 0; i < header.Count; i++) { if (header[i] == selectedColumn) { headIndex = i; } } if (headIndex < 0) { MessageBox.Show("Selected text column not found."); cr.Close(); return; } int count = 1; this.button1.Enabled = false; while (true) { CsvRow row = new CsvRow(); if (!cr.ReadRow(row)) { break; } string text = row[headIndex]; string s = count.ToString(); while (s.Length < digits) { s = "0" + s; } string filename = dirname + "\\" + s + ".txt"; using (StreamWriter sw = new StreamWriter(filename)) { sw.Write(text); sw.Close(); } count++; } MessageBox.Show((count - 1) + "files converted. Saved in " + dirname); cr.Close(); } }
private void generateDBFromCSVToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog CurrOpenFileDialog = new OpenFileDialog(); CurrOpenFileDialog.Filter = "csv files (*.csv)|*.csv";//|db files (*.db)|*.db|nc files (*.nc)|*.nc CurrOpenFileDialog.Multiselect = false; DialogResult Res = CurrOpenFileDialog.ShowDialog(); if (Res != DialogResult.OK) return; FormForImportExcel CSVWindow = CellByCellFromCSV(CurrOpenFileDialog.FileNames[0]); if (CSVWindow == null) return; if (CSVWindow.ShowDialog() != System.Windows.Forms.DialogResult.OK) return; if (CompleteScreening != null) CompleteScreening.Close3DView(); FolderBrowserDialog WorkingFolderDialog = new FolderBrowserDialog(); WorkingFolderDialog.ShowNewFolderButton = true; WorkingFolderDialog.Description = "Select the working directory"; if (WorkingFolderDialog.ShowDialog() != DialogResult.OK) return; //if (IsFileUsed(CurrOpenFileDialog.FileNames[0])) //{ // MessageBox.Show("File currently used by another application.\n", "Loading error !", MessageBoxButtons.OK, MessageBoxIcon.Error); // return; //} //Microsoft.Research.Science.Data.DataSet Datacsv = Microsoft.Research.Science.Data.CSV.CsvDataSet.Open(CurrOpenFileDialog.FileNames[0]); //int NumDesc = Datacsv.Variables.Count; //for (int IdxDesc = 0; IdxDesc < NumDesc; IdxDesc++) //{ // var DescInfo = Datacsv.Variables[IdxDesc]; // string NameDesc = DescInfo.Name; // var TypeData = DescInfo.TypeOfData; // string DataName = TypeData.Name; //} int NumPlateName = 0; int NumRow = 0; int NumCol = 0; int NumWellPos = 0; // int NumLocusID = 0; // int NumConcentration = 0; // int NumName = 0; // int NumInfo = 0; // int NumClass = 0; int numDescritpor = 0; for (int i = 0; i < CSVWindow.dataGridViewForImport.Rows.Count; i++) { string CurrentVal = CSVWindow.dataGridViewForImport.Rows[i].Cells[2].Value.ToString(); if ((CurrentVal == "Plate name") && ((bool)CSVWindow.dataGridViewForImport.Rows[i].Cells[1].Value)) NumPlateName++; if ((CurrentVal == "Row") && ((bool)CSVWindow.dataGridViewForImport.Rows[i].Cells[1].Value)) NumRow++; if ((CurrentVal == "Column") && ((bool)CSVWindow.dataGridViewForImport.Rows[i].Cells[1].Value)) NumCol++; if ((CurrentVal == "Well position") && ((bool)CSVWindow.dataGridViewForImport.Rows[i].Cells[1].Value)) NumWellPos++; if ((CurrentVal == "Descriptor") && ((bool)CSVWindow.dataGridViewForImport.Rows[i].Cells[1].Value)) numDescritpor++; } if (NumPlateName != 1) { MessageBox.Show("One and only one \"Plate Name\" has to be selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((NumRow != 1) && (GlobalInfo.OptionsWindow.radioButtonWellPosModeDouble.Checked == true)) { MessageBox.Show("One and only one \"Row\" has to be selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((NumCol != 1) && (GlobalInfo.OptionsWindow.radioButtonWellPosModeDouble.Checked == true)) { MessageBox.Show("One and only one \"Column\" has to be selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((NumWellPos != 1) && (GlobalInfo.OptionsWindow.radioButtonWellPosModeSingle.Checked == true)) { MessageBox.Show("One and only one \"Well position\" has to be selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((numDescritpor < 1) && (CSVWindow.IsImportCSV)) { MessageBox.Show("You need to select at least one \"Descriptor\" !", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } int Mode = 2; if (GlobalInfo.OptionsWindow.radioButtonWellPosModeSingle.Checked) Mode = 1; CsvFileReader CSVsr = new CsvFileReader(CurrOpenFileDialog.FileNames[0]); CsvRow OriginalNames = new CsvRow(); if (!CSVsr.ReadRow(OriginalNames)) { CSVsr.Close(); return; } int ColPlateName = GetColIdxFor("Plate name", CSVWindow); int ColCol = GetColIdxFor("Column", CSVWindow); int ColRow = GetColIdxFor("Row", CSVWindow); int ColWellPos = GetColIdxFor("Well position", CSVWindow); int[] ColsForDescriptors = GetColsIdxFor("Descriptor", CSVWindow); int WellLoaded = 0; int FailToLoad = 0; // CompleteScreening.Columns = (int)CSVWindow.numericUpDownColumns.Value; // CompleteScreening.Rows = (int)CSVWindow.numericUpDownRows.Value; // CompleteScreening.ListDescriptors.Clean(); FormForProgress ProgressWindow = new FormForProgress(); ProgressWindow.Show(); CsvRow CurrentDesc = new CsvRow(); if (CSVsr.ReadRow(CurrentDesc) == false) return; do { string OriginalPlatePlateName = CurrentDesc[ColPlateName]; string CurrentPlateName = CurrentDesc[ColPlateName]; string ConvertedName = ""; foreach (var c in System.IO.Path.GetInvalidFileNameChars()) { ConvertedName = OriginalPlatePlateName.Replace(c, '-'); } List<string> ListNameSignature = new List<string>(); for (int idxDesc = Mode + 1; idxDesc < ColsForDescriptors.Length + Mode + 1; idxDesc++) ListNameSignature.Add(OriginalNames[idxDesc]); cSQLiteDatabase SQDB = new cSQLiteDatabase(WorkingFolderDialog.SelectedPath + "\\" + ConvertedName, ListNameSignature, true); do { string OriginalWellPos = CurrentDesc[ColWellPos]; string CurrentWellPos = OriginalWellPos; int[] Pos = new int[2]; if (Mode == 1) { Pos = ConvertPosition(CurrentDesc[ColWellPos]); if (Pos == null) { if (MessageBox.Show("Error in converting the current well position.\nGo to Edit->Options->Import-Export->Well Position Mode to fix this.\nDo you want continue ?", "Loading error !", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == System.Windows.Forms.DialogResult.No) { CSVsr.Close(); return; } //else // goto NEXTLOOP; } } else { //if (int.TryParse(CurrentDesc[ColCol], out Pos[0]) == false) // // goto NEXTLOOP; //if (int.TryParse(CurrentDesc[ColRow], out Pos[1]) == false) // goto NEXTLOOP; } cWellForDatabase WellForDB = new cWellForDatabase(OriginalPlatePlateName, Pos[0], Pos[1]); List<List<double>> ListData = new List<List<double>>(); // for (int idxDesc = 0; idxDesc < ColsForDescriptors.Length; idxDesc++) // ListData[idxDesc] = new List<double>(); ProgressWindow.label.Text = OriginalWellPos; ProgressWindow.label.Refresh(); do { // CurrentWellPos = CurrentDesc[ColWellPos]; List<double> Signature = new List<double>(); for (int idxDesc = 0; idxDesc < ColsForDescriptors.Length; idxDesc++) { double Value; if ((double.TryParse(CurrentDesc[ColsForDescriptors[idxDesc]], out Value)) && (!double.IsNaN(Value))) { //cDescriptor CurrentDescriptor = new cDescriptor(Value, CompleteScreening.ListDescriptors[idxDesc/* + ShiftIdx*/], CompleteScreening); Signature.Add(Value); } /*else { FailToLoad++; goto NEXTLOOP; }*/ } ListData.Add(Signature); // WellForDB.AddSignature(Signature); if (CSVsr.ReadRow(CurrentDesc) == false) { WellForDB.AddListSignatures(ListData); SQDB.AddNewWell(WellForDB); SQDB.CloseConnection(); goto NEXTLOOP; } CurrentPlateName = CurrentDesc[ColPlateName]; CurrentWellPos = CurrentDesc[ColWellPos]; } while (CurrentWellPos == OriginalWellPos); WellForDB.AddListSignatures(ListData); SQDB.AddNewWell(WellForDB); } while (OriginalPlatePlateName == CurrentPlateName); SQDB.CloseConnection(); } while (true); NEXTLOOP: ; ProgressWindow.Close(); FormForPlateDimensions PlateDim = new FormForPlateDimensions(); PlateDim.Text = "Load generated screening"; PlateDim.checkBoxAddCellNumber.Visible = true; PlateDim.checkBoxIsOmitFirstColumn.Visible = true; PlateDim.labelHisto.Visible = true; PlateDim.numericUpDownHistoSize.Visible = true; if (PlateDim.ShowDialog() != System.Windows.Forms.DialogResult.OK) return; LoadCellByCellDB(PlateDim, WorkingFolderDialog.SelectedPath); }
public static void Init( string cultureStr) { _initialised = true; _phrases.Clear(); // Reset the list since we are building it again if (cultureStr != "") { try { _ci = new CultureInfo(cultureStr); Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = _ci; // Change the culture of the current application _localCulture = _ci.TwoLetterISOLanguageName; _localCulture3Letter = _ci.ThreeLetterISOLanguageName; } catch (Exception) { } } if (_localCulture == "en") return; // Nothing to do string phraseFileName = Path.Combine(GlobalDefs.LocalisationPath, _localCulture + ".txt"); string fixedPhraseFileName = Path.Combine(GlobalDefs.LocalisationPath, _localCulture + "-fixed.txt"); // User override language corrections Monitor.Enter(_phrases); // Get a lock before updating the list // Get the manually corrected translations if they exist if (File.Exists(fixedPhraseFileName)) { try { using (CsvFileReader reader = new CsvFileReader(fixedPhraseFileName)) { CsvRow row = new CsvRow(); while (reader.ReadRow(row)) { if (row.Count > 1) { string key = row[0].ToLower().Trim(); // Take care of special characters key = key.Replace("\\\\", "\\"); //Order matters first check for \\ key = key.Replace("\\r", "\r"); key = key.Replace("\\n", "\n"); key = key.Replace("\\\'", "\'"); if (!_phrases.ContainsKey(key)) // no duplicates { _phrases.Add(key, row[1]); // Create a sorted list of values with manual updates } } } reader.Close(); } } catch (Exception e) { Log.AppLog.WriteEntry("Unable to read localisation file " + fixedPhraseFileName + "\n" + e.Message, Log.LogEntryType.Error); } } // Get the automatic translations if (File.Exists(phraseFileName)) { try { using (CsvFileReader reader = new CsvFileReader(phraseFileName)) { CsvRow row = new CsvRow(); while (reader.ReadRow(row)) { if (row.Count > 1) { string key = row[0].ToLower().Trim(); // Take care of special characters key = key.Replace("\\\\", "\\"); //Order matters first check for \\ key = key.Replace("\\r", "\r"); key = key.Replace("\\n", "\n"); key = key.Replace("\\\'", "\'"); if (!_phrases.ContainsKey(key)) // Check if there is a user provided translation if so, skip it { _phrases.Add(key, row[1]); } } } } } catch (Exception e) { Log.AppLog.WriteEntry("Unable to read localisation file " + phraseFileName + "\n" + e.Message, Log.LogEntryType.Error); } } Monitor.Exit(_phrases); }
public void FillHighScores() { //Row to read values from Other files(dataset, new high score in 000001.csv) CsvRow readerRow; //Row to insert values into CsvFileWriter below for HighScoreFile good copy CsvRow row = new CsvRow(); //Reader Object for New High Score (or old if run early) CsvFileReader reader = new CsvFileReader("HighScoreFile.csv"); //Array of Player Objects to fill with readerRow's values read List <PlayerObject> pastPlayers = new List <PlayerObject> (); //Loop through the reader till the end while (!reader.EndOfStream) { //if (reader.BaseStream.ReadByte() == -1) // break; //Build a new player Object to fill PlayerObject obj = new PlayerObject(); //Instatiate the CsvRow readerRow = new CsvRow(); //Build a string array to hold the CsvRow values string[] list = new string[2]; //Read the rows and Copy the data to the array reader.ReadRow(readerRow); readerRow.CopyTo(list); //Check for "Player" as the first column and skip it if (list [0].ToString().Contains("Player")) { continue; } //Set player names by formatting the string, and parsing to a float obj.setPlayerName(string.Format("{0}", list[0].ToString())); obj.setPoints(float.Parse(list [1])); //Add the player Object to the array pastPlayers.Add(obj); readerRow.Clear(); } //End of while loop reader.Dispose(); reader.Close(); //Reader to loop through Dataset for run just taken. Keeps the values safe. reader = new CsvFileReader("000001.csv"); while (!reader.EndOfStream) { PlayerObject obj = new PlayerObject(); readerRow = new CsvRow(); string[] list = new string[2]; //Read the rows and Copy the data to the array reader.ReadRow(readerRow); readerRow.CopyTo(list); //Set player names by formatting the string, and parsing to a float obj.setPlayerName(string.Format("{0}", list [0].ToString())); obj.setPoints(float.Parse(list [1])); //Add the player Object to the array pastPlayers.Add(obj); readerRow.Clear(); } reader.Dispose(); reader.Close(); //Reader to loop through Dataset given for assignment, which pulls the values //of the name of the commodity in the list, and the value of the commodity. //It has taken a shortened version, at the behest of Professor Stanley Pieda //when asked if I needed to keep the 100K+ file or revise it slightly. /*reader = new CsvFileReader ("000000.csv"); * * while(!reader.EndOfStream){ * * PlayerObject obj = new PlayerObject(); * readerRow = new CsvRow(); * string[] list = new string[6]; * * reader.ReadRow (readerRow); * readerRow.CopyTo(list); * obj.setPlayerName(string.Format("{0}", list [2].ToString ())); * obj.setPoints (float.Parse(list[5])); * * pastPlayers.Add(obj); * readerRow.Clear (); * } * * reader.Dispose (); * reader.Close (); */ //CsvFileWriter Object to write the high score objects to the csv file CsvFileWriter writer = new CsvFileWriter("HighScoreFile.csv"); //Adding the headers for Player and Score in the table row.Add(string.Format("Player")); row.Add(string.Format("Score")); //Writing it to the file, and clearing the row which was written writer.WriteRow(row); row.Clear(); pastPlayers.Sort((x, y) => y.points.CompareTo(x.points)); //Looping through the number of playerObjects in the List. Printing each one //To it's own row and clearing that row after it's written. for (int i = 0; i < pastPlayers.Count; i++) { row.Add(string.Format("{0}", pastPlayers[i].getPlayerName())); row.Add(string.Format("{0}", pastPlayers[i].getPoints())); writer.WriteRow(row); row.Clear(); } //Clean up the writers writer.Dispose(); writer.Close(); //pastPlayers.Sort (0,pastPlayers.Count,pastPlayers [0].points); }
void LoadYesterdayLongRemains() { try { const string kRemainsFolder = @"remains\"; string fileName = String.Format("{0}_remains.csv", _yesterday.ToString("yyyy_MM_dd")); string remains_path = String.Format("{0}{1}{2}", kFolder, kRemainsFolder, fileName); logger.Info("{0} 읽기 시도", remains_path); CsvFileReader reader = new CsvFileReader(remains_path); Boolean header = true; while (true) { CsvRow row = new CsvRow(); if (reader.ReadRow(row)) { if (header) { header = false; continue; } DateTime dt = DateTime.ParseExact(row[0], "yyyy-MM-dd", null); long count = Convert.ToInt64(TextUtil.RemoveComma(row[1])); double rate = Math.Round(Convert.ToDouble(row[2]), 5); int price = Convert.ToInt32(TextUtil.RemoveComma(row[3])); long notional = Convert.ToInt64(TextUtil.RemoveComma(row[4])); KtbSpotPosition pos = new KtbSpotPosition(); pos.TradingDate = dt; pos.Long_2_Short_1 = 2; pos.Count = count; pos.Rate = rate; pos.Price = price; pos.Notional = notional; this.Longs.Add(pos); } else { break; } } reader.Close(); logger.Info("Yesterday Long Remain Position Load complete."); } catch (System.Exception ex) { logger.Error(ex.ToString()); } }
private void LoadingCSVProcedure(FormForImportExcel FromExcel) { int Mode = 2; if (cGlobalInfo.OptionsWindow.radioButtonWellPosModeSingle.Checked) Mode = 1; CsvFileReader CSVsr = new CsvFileReader(PathNames[0]); if (!CSVsr.BaseStream.CanRead) { MessageBox.Show("Cannot read the file !", "Process finished !", MessageBoxButtons.OK, MessageBoxIcon.Information); CSVsr.Close(); return; } CsvRow Names = new CsvRow(); if (!CSVsr.ReadRow(Names)) { CSVsr.Close(); return; } int ColSelectedForName = GetColIdxFor("Name", FromExcel); // int ColLocusID = GetColIdxFor("Locus ID", FromExcel); // int ColConcentration = GetColIdxFor("Concentration", FromExcel); // int ColInfo = GetColIdxFor("Info", FromExcel); // int ColClass = GetColIdxFor("Class", FromExcel); int ColPlateName = GetColIdxFor("Plate name", FromExcel); int ColCol = GetColIdxFor("Column", FromExcel); int ColRow = GetColIdxFor("Row", FromExcel); int ColWellPos = GetColIdxFor("Well position", FromExcel); int[] ColsForDescriptors = GetColsIdxFor("Descriptor", FromExcel); while (CSVsr.EndOfStream != true) { NEXT: ; CsvRow CurrentDesc = new CsvRow(); if (CSVsr.ReadRow(CurrentDesc) == false) break; string PlateName = CurrentDesc[ColPlateName]; //return; // check if the plate exist already cPlate CurrentPlate = cGlobalInfo.CurrentScreening.GetPlateIfNameIsContainIn(PlateName); if (CurrentPlate == null) goto NEXT; int[] Pos = new int[2]; if (Mode == 1) { Pos = ConvertPosition(CurrentDesc[ColWellPos]); } else { if (!int.TryParse(CurrentDesc[ColCol], out Pos[0])) { if (MessageBox.Show("Error in converting the current well position.\nGo to Edit->Options->Import-Export->Well Position Mode to fix this.\nDo you want continue ?", "Loading error !", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == System.Windows.Forms.DialogResult.No) { CSVsr.Close(); return; } else goto NEXTLOOP; } Pos[1] = Convert.ToInt16(CurrentDesc[ColRow]); } cWell CurrentWell = CurrentPlate.GetWell(Pos[0] - 1, Pos[1] - 1, false); if (CurrentWell == null) goto NEXT; if (ColSelectedForName != -1) { CurrentWell.SetCpdName(CurrentDesc[ColSelectedForName]); } else { CurrentWell.SetAsNoneSelected(); } //if (ColLocusID != -1) //{ // double CurrentValue; // if (!double.TryParse(CurrentDesc[ColLocusID], out CurrentValue)) // goto NEXTSTEP; // CurrentWell.LocusID = CurrentValue; //} //if (ColConcentration != -1) //{ // double CurrentValue; // if (!double.TryParse(CurrentDesc[ColConcentration], out CurrentValue)) // goto NEXTSTEP; // CurrentWell.Concentration = CurrentValue; //} NEXTSTEP: ; //if (ColInfo != -1) // CurrentWell.Info = CurrentDesc[ColInfo]; //if (ColClass != -1) //{ // int CurrentValue; // if (!int.TryParse(CurrentDesc[ColClass], out CurrentValue)) // goto NEXTLOOP; // CurrentWell.SetClass(CurrentValue); //} NEXTLOOP: ; } CSVsr.Close(); cGlobalInfo.CurrentScreening.GetCurrentDisplayPlate().DisplayDistribution(cGlobalInfo.CurrentScreening.ListDescriptors.GetActiveDescriptor(), false); MessageBox.Show("File loaded", "Process finished !", MessageBoxButtons.OK, MessageBoxIcon.Information); return; }
//Method to Load SNP for City Photos private void createSNPFromcsvToolStripMenuItem_Click(object sender, EventArgs e) { if (checkSwitchStatus()) { Picture.Text = ""; listBox1.Items.Clear(); listBox1.SelectionMode = SelectionMode.None; programRunning = "City Photos"; this.Text = programRunning; error = false; this.Controls.Remove(b); this.Controls.Remove(c); this.Controls.Remove(t); this.Controls.Remove(band); this.Controls.Remove(chorus); this.Controls.Remove(talent); this.Controls.Remove(activities); this.Size = new Size(282, 326); Picture.Text = ""; listBox1.Items.Clear(); Picture.Focus(); staters.Clear(); string pathstring = loadStaterList(); CsvFileReader csv = new CsvFileReader(pathstring); char[] _separators = new char[] { '\n', '"', ',' }; CsvRow row = new CsvRow(); bool entering = true; while (entering == true) { entering = csv.ReadRow(row); if (row.Count != 5) { label1.Size = new Size(200, 30); label1.Location = new Point(73, 24); label1.Text = pathstring + " invalid format;\nCorrect Format: First Name, Last Name, Barcode"; error = true; } staters.Add(new Stater(row[1], row[2])); char[] bar = row[0].ToCharArray(); string bs = Convert.ToString(bar[0]) + Convert.ToString(bar[1]) + Convert.ToString(bar[2]) + Convert.ToString(bar[3]); staters[staters.Count - 1].Barcode = Convert.ToInt32(bs); staters[staters.Count - 1].City = row[3]; if (staters.Count() > 1 && staters[staters.Count - 1].Barcode == staters[staters.Count - 2].Barcode) { staters.RemoveAt(staters.Count - 1); break; } } csv.Close(); rows(); SNPhasBeenLoaded = true; //checkStaterList(); if (error == false) { label1.Size = new Size(130, 30); label1.Location = new Point(73, 24); label1.Text = "Stater list successfully loaded."; Picture.Enabled = true; button1.Enabled = true; Picture.Focus(); } else { label1.Size = new Size(130, 30); label1.Location = new Point(73, 24); label1.Text = "The stater list contains an error"; } } }
void LoadTodayShort() { try { CsvFileReader reader = new CsvFileReader(_todayShortFileName_Input); Boolean header = true; while (true) { CsvRow row = new CsvRow(); if (reader.ReadRow(row)) { if (header) { header = false; continue; } DateTime dt = this.Today; long count = Convert.ToInt64(row[1]) * CommonConst._100_000_000; double rate = Math.Round(Convert.ToDouble(row[2]), 5); int price = Convert.ToInt32(TextUtil.RemoveComma(row[3])); long notional = Convert.ToInt64(TextUtil.RemoveComma(row[4])); KtbSpotPosition pos = new KtbSpotPosition(); pos.TradingDate = dt; pos.Long_2_Short_1 = 1; pos.Count = count; pos.Rate = rate; pos.Price = price; pos.Notional = notional; this.Shorts.Add(pos); } else { break; } } reader.Close(); logger.Info("Today Short Position Load complete."); } catch (System.Exception ex) { logger.Error(ex.ToString()); } }
public ActionResult UploadProducts() { string CSVFile = "", ImageFolder = ""; // Checking no of files injected in Request object if (Request.Files.Count > 0) { try { // Get folder Name HttpPostedFileBase file = Request.Files[0]; string fname = ""; if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER") { string[] testfiles = file.FileName.Split(new char[] { '\\' }); fname = testfiles[testfiles.Length - 1]; } else { fname = file.FileName; } //checking the files within the zipped folder ZipFile zip = ZipFile.Read(file.InputStream); //string filename = "", ext = ""; string uploadPath = Server.MapPath("~/Uploads"); //creating the directory string folderName = "upload" + DateTime.Now.Day + "#" + DateTime.Now.Month + "#" + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second; string path = Path.Combine(uploadPath, folderName); Directory.CreateDirectory(path); //Unzip CSV file and ZippedFolder from folder zip.ExtractAll(path, ExtractExistingFileAction.DoNotOverwrite); string [] subfiles = Directory.GetFiles(path); if (subfiles == null || subfiles.Length == 0) { fname = fname.Substring(0, fname.LastIndexOf('.')); fname = Path.Combine(path, fname); } else { fname = path; //string[] subdirs= Directory.GetDirectories(path); //if(subdirs != null) //{ // fname = Path.Combine(path, subdirs[0]); //} } ////Storage Folder Path DirectoryInfo dir = new DirectoryInfo(fname); FileInfo[] files = dir.GetFiles(); DirectoryInfo[] dirs = dir.GetDirectories(); foreach (FileInfo f in files) { if (f.Extension.ToLower() == ".csv") { CSVFile = Path.Combine(fname, f.FullName); break; } } List <Product> products = new List <Product>(); CsvFileReader CSV = new CsvFileReader(CSVFile); string csvData = CSV.ReadToEnd(); foreach (string row in csvData.Split('\n')) { Product p1 = new Models.Product(); if (!string.IsNullOrEmpty(row) && !row.Contains("ItemNumber")) { p1 = MapProduct(row, dirs); if (p1 != null) { products.Add(p1); } //SaveProduct(rowvalue, imagePath, itemnumber); } } // Returns message that successfully uploaded CSV.Close(); Directory.Delete(path, true); SaveToSql(products); DirectoryInfo tempdirectory = new DirectoryInfo(Server.MapPath("~/TempImages/")); foreach (var tempfile in tempdirectory.GetFiles()) { tempfile.Delete(); } return(Json("File Uploaded Successfully!")); } catch (Exception ex) { return(Json("Error occurred. Error details: " + ex.Message)); } } else { return(Json("No files selected.")); } //return View(); }
private FormForImportExcel CellByCellFromCSV(string FileName, char Delimiter) { FormForImportExcel FromExcel = new FormForImportExcel(); FromExcel.IsImportCSV = true; int Mode = 2; if (cGlobalInfo.OptionsWindow.radioButtonWellPosModeSingle.Checked) Mode = 1; CsvFileReader CSVsr = new CsvFileReader(FileName); CSVsr.Separator = Delimiter; CsvRow Names = new CsvRow(); if (!CSVsr.ReadRow(Names)) { CSVsr.Close(); return null; } int NumPreview = 4; List<CsvRow> LCSVRow = new List<CsvRow>(); for (int Idx = 0; Idx < NumPreview; Idx++) { CsvRow TNames = new CsvRow(); // if (TNames.Count == 0) break; if (!CSVsr.ReadRow(TNames)) { CSVsr.Close(); return null; } LCSVRow.Add(TNames); } // FromExcel.dataGridViewForImport.RowsDefaultCellStyle.BackColor = Color.Bisque; FromExcel.dataGridViewForImport.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige; DataGridViewColumn ColName = new DataGridViewColumn(); FromExcel.dataGridViewForImport.Columns.Add("Data Name", "Data Name"); DataGridViewCheckBoxColumn columnSelection = new DataGridViewCheckBoxColumn(); columnSelection.Name = "Selection"; FromExcel.dataGridViewForImport.Columns.Add(columnSelection); DataGridViewComboBoxColumn columnType = new DataGridViewComboBoxColumn(); if (cGlobalInfo.OptionsWindow.radioButtonWellPosModeDouble.Checked) columnType.DataSource = new string[] { "Plate name", "Column", "Row", "Descriptor", "Phenotype Class" }; else columnType.DataSource = new string[] { "Plate name", "Well position", "Descriptor", "Phenotype Class" }; columnType.Name = "Type"; FromExcel.dataGridViewForImport.Columns.Add(columnType); for (int i = 0; i < LCSVRow.Count; i++) { DataGridViewColumn NewCol = new DataGridViewColumn(); NewCol.ReadOnly = true; FromExcel.dataGridViewForImport.Columns.Add("Readout " + i, "Readout " + i); } if (LCSVRow[0].Count > Names.Count) { CSVsr.Close(); MessageBox.Show("Inconsistent column number. Check your CSV file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return null; } for (int i = 0; i < Names.Count; i++) { int IdxRow = 0; FromExcel.dataGridViewForImport.Rows.Add(); FromExcel.dataGridViewForImport.Rows[i].Cells[IdxRow++].Value = Names[i]; if (i == 0) FromExcel.dataGridViewForImport.Rows[i].Cells[IdxRow++].Value = true; else if (i == 1) FromExcel.dataGridViewForImport.Rows[i].Cells[IdxRow++].Value = true; else if ((i == 2) && (cGlobalInfo.OptionsWindow.radioButtonWellPosModeDouble.Checked)) FromExcel.dataGridViewForImport.Rows[i].Cells[IdxRow++].Value = true; else FromExcel.dataGridViewForImport.Rows[i].Cells[IdxRow++].Value = false; if (i == 0) { FromExcel.dataGridViewForImport.Rows[i].Cells[IdxRow++].Value = "Plate name"; } else if (i == 1) { if (cGlobalInfo.OptionsWindow.radioButtonWellPosModeDouble.Checked) { FromExcel.dataGridViewForImport.Rows[i].Cells[IdxRow++].Value = "Column"; } else { FromExcel.dataGridViewForImport.Rows[i].Cells[IdxRow++].Value = "Well position"; } } else if (i == 2) { if (cGlobalInfo.OptionsWindow.radioButtonWellPosModeDouble.Checked) { FromExcel.dataGridViewForImport.Rows[i].Cells[IdxRow++].Value = "Row"; } else FromExcel.dataGridViewForImport.Rows[i].Cells[IdxRow++].Value = "Descriptor"; } else { FromExcel.dataGridViewForImport.Rows[i].Cells[IdxRow++].Value = "Descriptor"; } for (int j = 0; j < LCSVRow.Count; j++) { if (i < LCSVRow[j].Count) FromExcel.dataGridViewForImport.Rows[i].Cells[IdxRow + j].Value = LCSVRow[j][i].ToString(); else FromExcel.dataGridViewForImport.Rows[i].Cells[IdxRow + j].Value = ""; } } FromExcel.dataGridViewForImport.Update(); // FromExcel.dataGridViewForImport.MouseClick += new System.Windows.Forms.MouseEventHandler(this.dataGridViewForImport_MouseClick); FromExcel.CurrentScreen = cGlobalInfo.CurrentScreening; FromExcel.thisHCSAnalyzer = this; return FromExcel; }