async private void downloadCSVToolStripMenuItem_Click(object sender, EventArgs e) { var cells = dataGridView1.SelectedCells; Console.WriteLine("Number of cells: " + dataGridView1.SelectedCells.Count); List <int> indexes = new List <int>(); if (dataGridView1.SelectedCells.Count < 0) // Check if nothing is selected { return; } // ------------- FIND FIRST AND LAST (SELECTED) INDEX IN DATAGRID foreach (DataGridViewTextBoxCell item in cells) { int temp = item.RowIndex * 96 + item.ColumnIndex - 1; // Convert to data array index if (temp < 0) // Check if header is selected { return; } indexes.Add(temp); } // Find min and max indexes int indexMin = indexes.First(); int indexMax = indexes.First(); foreach (var item in indexes) { if (indexMin > item) { indexMin = item; } } foreach (var item in indexes) { if (indexMax < item) { indexMax = item; } } // ---------- INDEXES FOUND //DEBUG Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); // debug // Now select time period based on min-max var startDate = dataPtr.data[indexMin].date; var endDate = dataPtr.data[indexMax].date; // Get username and password from textboxes string username = textBoxUsername.Text; string password = textBoxPassword.Text; // Create array of date pairs if xml data needs to be fragmented List <CustomXmlDatePair> datePeriodsList = CustomXmlDatePair.FragmentDate(startDate, endDate); // ----- Instantiate ntpm object string ip; try { // Get IP and Port from database ip = GetIPAndPort(); } catch (Exception) { MessageBox.Show("Couldn't get IP and Port from database"); return; // abort } // ----------------------------------- Get and parse report.xml string reportRes; XDocument reportDoc; try { reportRes = await NTPMControllerClass.GetReport(ip); // Get xml report from NTPM reportDoc = XDocument.Parse(reportRes); } catch (Exception) { MessageBox.Show("Couldn't get or parse report.xml"); return; // abort } // Create header dates string headerStartTime = HelperClass.ConvertToNtpmCustomXmlTime(startDate); string headerEndTime = HelperClass.ConvertToNtpmCustomXmlTime(endDate); string csvHeader = NTPMControllerClass.CreateCSVHeader(headerStartTime, headerEndTime, reportDoc); FormCustomConsole.WriteLine("StartTime: " + headerStartTime); FormCustomConsole.WriteLine("EndTime: " + headerEndTime); // now we only need to fill values with each row // --------------------------------Get and parse measurement.xml List <XDocument> measurementDoc = new List <XDocument>(); List <string> measurementRows = new List <string>(); foreach (var datePeriod in datePeriodsList) { Console.WriteLine("Parsing period: " + datePeriod.startHeader + "---" + datePeriod.endHeader); await HelperRetryClass.DoWithRetryAsync(async() => { FormCustomConsole.WriteLine("Loading: " + datePeriod.startHeader + "---" + datePeriod.endHeader); List <KeyValuePair <string, string> > pairs = NTPMControllerClass.GetPairsForCustomXmlPostMethod(datePeriod.startHeader, datePeriod.endHeader, username, password); string measurementRes = await HTTPClientClass.PostRequest("http://" + ip + "/custom.xml", pairs); XDocument tempMeasure = XDocument.Parse(measurementRes); NTPMControllerClass.CheckErrorTag(tempMeasure); string measureRow = NTPMControllerClass.CreateCSVMeasurementRow(tempMeasure); // At this point, download and parsing is ok measurementRows.Add(measureRow); measurementDoc.Add(tempMeasure); }, TimeSpan.FromSeconds(1)); } // now form whole string (HEADER + TAGS + MEASUREMENT ROWS) StringBuilder sFinal = new StringBuilder(); sFinal.Append(csvHeader); foreach (var item in measurementRows) { sFinal.Append(item); sFinal.Append("\r\n"); } sFinal.Remove(sFinal.Length - 2, 2); // Remove last new line // Write elapsed time stopWatch.Stop(); FormCustomConsole.WriteLine("XML fetching operation finished in: " + (stopWatch.ElapsedMilliseconds / 1000).ToString() + "seconds"); // --------------------------------------- Finaly save file string fileName = XmlHelper.FindFirstDescendant("hostname", reportDoc).Trim(); string fileMac = XmlHelper.FindFirstDescendant("mac", reportDoc).Replace(':', '-'); string fileType = "by_15min"; SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Excel File|*.csv"; // Create file name (based on downloaded data) sfd.FileName = fileName + "_" + fileMac + "_" + headerStartTime + "_" + headerEndTime + "_" + fileType; if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string path = sfd.FileName; StreamWriter sw = new StreamWriter(File.Create(path)); sw.Write(sFinal.ToString()); sw.Dispose(); } }
async void DEBUGFUNC() { try { #warning CHANGE DATE FORMAT DateTime startDate = new DateTime(2017, 10, 10, 0, 0, 0); DateTime endDate = new DateTime(2017, 10, 10, 23, 45, 0); // Create array of date pairs if xml data needs to be fragmented List <CustomXmlDatePair> datePeriodsList = CustomXmlDatePair.FragmentDate(startDate, endDate); string ip = "192.168.2.21"; string reportRes; XDocument reportDoc; try { reportRes = await NTPMControllerClass.GetReport(ip); reportDoc = XDocument.Parse(reportRes); } catch (Exception) { MessageBox.Show("Couldn't get or parse report.xml"); return; // abort } // Create header dates string headerStartTime = HelperClass.ConvertToNtpmCustomXmlTime(startDate); string headerEndTime = HelperClass.ConvertToNtpmCustomXmlTime(endDate); string csvHeader = NTPMControllerClass.CreateCSVHeader(headerStartTime, headerEndTime, reportDoc); // now we only need to fill values with each row // ---- Get and parse measurement.xml List <XDocument> measurementDoc = new List <XDocument>(); List <string> measurementRows = new List <string>(); foreach (var datePeriod in datePeriodsList) { Console.WriteLine("Parsing period: " + datePeriod.startHeader + "---" + datePeriod.endHeader); await HelperRetryClass.DoWithRetryAsync(async() => { // Generate the random number between 1-2 Random rnd = new Random(); var result = rnd.Next(1, 10); if (result == 2) { throw new Exception("Random throw for debug"); } List <KeyValuePair <string, string> > pairs = NTPMControllerClass.GetPairsForCustomXmlPostMethod(datePeriod.startHeader, datePeriod.endHeader, "neticoadmin", "neticoadmin"); string measurementRes = await HTTPClientClass.PostRequest("http://" + ip + "/custom.xml", pairs); XDocument tempMeasure = XDocument.Parse(measurementRes); //FormCustomConsole.WriteLine(tempMeasure.ToString()); NTPMControllerClass.CheckErrorTag(tempMeasure); string measureRow = NTPMControllerClass.CreateCSVMeasurementRow(tempMeasure); // At this point, download and parsing is ok measurementRows.Add(measureRow); measurementDoc.Add(tempMeasure); }, TimeSpan.FromSeconds(2)); } StringBuilder sFinal = new StringBuilder(); sFinal.Append(csvHeader); foreach (var item in measurementRows) { sFinal.Append(item); sFinal.Append("\r\n"); } sFinal.Remove(sFinal.Length - 2, 2); // Remove last new line Console.WriteLine("After task create CSV"); } catch (Exception ex) { MessageBox.Show(ex.Message); } }