public static void Convert(DataGridView grid, string file) { using (CsvFileWriter writer = new CsvFileWriter(file)) { CsvRow csvRow = new CsvRow(); for (int r = 0; r < grid.Rows.Count; ++r) { if (!grid.Rows[r].Visible) { continue; } csvRow.Clear(); for (int c = 0; c < grid.Columns.Count; ++c) { int c0 = grid.Columns[c].DisplayIndex; object objValue = grid[c0, r].Value; string value = (null != objValue) ? objValue.ToString() : string.Empty; csvRow.Add(value); } writer.WriteRow(csvRow); } } }
//Netstat WMI Function. Cycles to identify new TCP connections and exports it to CSV. static void CollectNetworkConnections(ManagementScope scope, CsvFileWriter writer) { try { scope.Options.Timeout = TimeSpan.FromSeconds(1); scope.Connect(); if (!scope.IsConnected) { Console.WriteLine("Error connecting to remote machine"); return; } ObjectQuery oqConns = new ObjectQuery("SELECT LocalAddress,LocalPort,RemoteAddress,RemotePort FROM MSFT_NetTCPConnection WHERE state = 5 AND RemoteAddress != '127.0.0.1' AND RemoteAddress != '::1' AND (RemotePort < 49152 OR LocalPort < 49152)"); ManagementObjectSearcher mgmtObjSearcherConns = new ManagementObjectSearcher(scope, oqConns); ManagementObjectCollection colConns = mgmtObjSearcherConns.Get(); CsvRow row = new CsvRow(); foreach (ManagementObject objConns in colConns) { row.Add((string)objConns["LocalAddress"]); row.Add(objConns["LocalPort"].ToString()); row.Add((string)objConns["RemoteAddress"]); row.Add(objConns["RemotePort"].ToString()); writer.WriteRow(row); row.Clear(); } return; } catch (Exception e) { Console.WriteLine("{0} Expection Caught.", e); } }
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); }
private int callback(ref AgSalLib.SegmentData dataHeader, IntPtr data) { Marshal.Copy(data, amplitudeData, 0, (int)dataHeader.numPoints); //Leaving for CSV writier, not needed in new implementation. can remove later. for (int i = 0; i < dataHeader.numPoints; i++) { if (firstRow == true) { double mhz = (dataHeader.startFrequency + (i * dataHeader.frequencyStep)) / 1e6; double rndMhz = Math.Round(mhz, 3); tempRow.Add("RF" + rndMhz.ToString() + "MHZ"); } else { //Console.WriteLine("adding data to string"); tempRow.Add(amplitudeData[i].ToString()); } } //For Writing Json and taking average FFT value for given freq. double TotalFreq = 0; for (int i = 0; i < dataHeader.numPoints; i++) { TotalFreq += amplitudeData[i]; } double totalFreqRounded = Math.Round(TotalFreq / dataHeader.numPoints, 3); fftFreqAverage[dataHeader.segmentIndex] = totalFreqRounded; if (dataHeader.segmentIndex == segments.Length - 1) { if (firstRow == true) { firstRow = false; Console.WriteLine("firstRow=false"); } Console.WriteLine("Writing line"); WriteRow(tempRow); tempRow.Clear(); } return(1); }
public void StopTimesWriter() { { // Write sample data to CSV file using (CsvFileWriter writer = new CsvFileWriter("stop_times.txt")) { CsvRow RowValues = new CsvRow(); for (int i = 0; i < 10; i++) { RowValues.Add(StopTimesDataList[i]); } writer.WriteRow(RowValues); CsvRow RowData = new CsvRow(); int j = 0; for (int i = 10; i < StopTimesDataList.Count; i++) { RowData.Add(StopTimesDataList[i]); if (j == 9) { RowData.Add(""); writer.WriteRow(RowData); RowData.Clear(); j = 0; } else { j++; } } } } }
public void CalendarDatesWriter() { { // Write sample data to CSV file using (CsvFileWriter writer = new CsvFileWriter("calendar_dates.txt")) { CsvRow RowValues = new CsvRow(); for (int i = 0; i < 3; i++) { RowValues.Add(CalendarDatesDataList[i]); } writer.WriteRow(RowValues); CsvRow RowData = new CsvRow(); int j = 0; for (int i = 3; i < CalendarDatesDataList.Count; i++) { RowData.Add(CalendarDatesDataList[i]); if (j == 2) { RowData.Add(""); writer.WriteRow(RowData); RowData.Clear(); j = 0; } else { j++; } } } } }
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); }
private static void PerformAction(ref int intCurrState, char chrInputChar, ref StringBuilder strElem, ref CsvRow alParsedCsv) { string strTemp = null; switch (intCurrState) { case 0: //Seperate out value to array list strTemp = strElem.ToString(); alParsedCsv.Add(strTemp); strElem = new StringBuilder(); break; case 1: case 3: case 4: //accumulate the character strElem.Append(chrInputChar); break; case 5: //End of line reached. Seperate out value to array list strTemp = strElem.ToString(); alParsedCsv.Add(strTemp); break; case 6: //Erroneous input. Reject line. alParsedCsv.Clear(); break; case 7: //wipe ending " and Seperate out value to array list strElem.Remove(strElem.Length - 1, 1); strTemp = strElem.ToString(); alParsedCsv.Add(strTemp); strElem = new StringBuilder(); intCurrState = 5; break; case 8: //wipe ending " and Seperate out value to array list strElem.Remove(strElem.Length - 1, 1); strTemp = strElem.ToString(); alParsedCsv.Add(strTemp); strElem = new StringBuilder(); //goto state 0 intCurrState = 0; break; } }
/// <summary> /// Writes a .json file containing all the test plans (and their cases) migrated using TCM.exe /// The test cases inside the plans use our custom book keeping structure, MigrationWorkItem. /// Also writes a CSV File performing the same thing. /// </summary> /// <param name="jsonPath">Path of the JSON, originally defined in app.config or altered at runtime</param> /// <param name="csvPath">Path of the csv, originally defined in app.config or altered at runtime</param> /// <param name="testPlans">A collection of test plans, each with MigrationWorkItems inside</param> private static void WritePlansAndAllLinks(string jsonPath, string csvPath, List<MigrationTestPlan> testPlans) { Trace.WriteLine("\nWriting Plans and Cases to: \n\t" + jsonPath + "\n\tand\n\t" + csvPath); CsvRow row = new CsvRow(); row.AddRange(new string[] { "Test Plan Name", "Old ID", "New ID", "Old Area Path" }); using (FileStream csvStream = File.Open(csvPath, FileMode.OpenOrCreate)) using (CsvFileWriter cw = new CsvFileWriter(csvStream)) using (FileStream jsonStream = File.Open(jsonPath, FileMode.OpenOrCreate)) using (StreamWriter sw = new StreamWriter(jsonStream)) using (JsonWriter jw = new JsonTextWriter(sw)) { cw.WriteRow(row); foreach (var testPlan in testPlans) { jw.Formatting = Formatting.Indented; JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(jw, testPlan); foreach (var testCase in testPlan.TestCases) { row.Clear(); row.AddRange(new string[] { testPlan.TestPlanName, testCase.OldID, testCase.NewID, testCase.OldItemAreaPath }); cw.WriteRow(row); } } } }
//Generate profile CSV of targets. Includes IP, hostname, domain, loggedon user, and domainrole static void GenerateTargetCSV(ManagementScope scope, CsvFileWriter writer) { try { scope.Options.Timeout = TimeSpan.FromSeconds(1); scope.Connect(); if (!scope.IsConnected) { Console.WriteLine("Error connecting to remote machine"); return; } int iInterfaceIndex = 0; string sDomainRole = null; string sDNSHostname = null; string sUsername = null; string sDomain = null; String[] sIPAddress = null; //Find the Interface Index with the default route ObjectQuery oqRoute = new ObjectQuery("Select InterfaceIndex from Win32_IP4RouteTable WHERE destination = '0.0.0.0'"); ManagementObjectSearcher mgmtObjSearcherRoute = new ManagementObjectSearcher(scope, oqRoute); ManagementObjectCollection colRoute = mgmtObjSearcherRoute.Get(); foreach (ManagementObject objRoute in colRoute) { iInterfaceIndex = (int)objRoute["InterfaceIndex"]; } //Find the IP address of the interface ObjectQuery oqIPAddr = new ObjectQuery("Select IPAddress from Win32_NetworkAdapterConfiguration WHERE InterfaceIndex = " + iInterfaceIndex); ManagementObjectSearcher mgmtObjSearcherIP = new ManagementObjectSearcher(scope, oqIPAddr); ManagementObjectCollection colIP = mgmtObjSearcherIP.Get(); foreach (ManagementObject objIP in colIP) { sIPAddress = (String[])objIP["IPAddress"]; } //Grab profile information - Hostname, Domain, LoggedOn User, and DomainRole ObjectQuery oqCompSys = new ObjectQuery("SELECT DNSHostName, Domain, Username, DomainRole FROM Win32_ComputerSystem"); ManagementObjectSearcher mgmtObjSearcher = new ManagementObjectSearcher(scope, oqCompSys); ManagementObjectCollection colCompSys = mgmtObjSearcher.Get(); foreach (ManagementObject objSysInfo in colCompSys) { switch (Convert.ToInt32(objSysInfo["DomainRole"])) { case 0: sDomainRole = "StandAlone_Wks"; break; case 1: sDomainRole = "DomainMember_Wks"; break; case 2: sDomainRole = "StandAlone_Svr"; break; case 3: sDomainRole = "DomainMember_Svr"; break; case 4: sDomainRole = "BackupDC"; break; case 5: sDomainRole = "PrimaryDC"; break; default: sDomainRole = "Dunno"; break; } sDNSHostname = (string)objSysInfo["DNSHostName"]; sDomain = (string)objSysInfo["Domain"]; sUsername = (string)objSysInfo["Username"]; } //Craft CSV for Profile CsvRow row = new CsvRow(); row.Add(sDNSHostname); row.Add(sDomain); if (sUsername == null) { row.Add("NoLoggedInUser"); } else { row.Add(sUsername); } row.Add(sDomainRole); row.Add(sIPAddress[0]); writer.WriteRow(row); row.Clear(); return; } catch (Exception e) { Console.WriteLine("{0} Expection Caught.", e); } }