I have csv file with data:
1,1671790171,75
0,1671790182,11
1,1671790193,11
0,1671790212,19
1,1671790239,27
0,1671790248,97
1,1671790342,94
0,1671790361,19
1,1671790368,79
0,1671790408,40
1,1671790417,90
0,1671790432,15
I need create application to show chart where first data is "work" or "not work", second data is linuxtimestamp data and time, third data is the number of seconds the process took.
I wrote something like this:
// Use OpenFileDialog to allow the user to select a CSV file
var openFileDialog = new OpenFileDialog
{
Filter = "CSV files (*.csv)|*.csv"
};
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
// Clear the chart
chart1.Series.Clear();
// Read the CSV file
using (var reader = new StreamReader(openFileDialog.FileName))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
// Parse the values
var working = values[0] == "1";
var timestamp = long.Parse(values[1]);
var duration = int.Parse(values[2]);
// Convert the Unix timestamp to a DateTime
var date = DateTimeOffset.FromUnixTimeSeconds(timestamp).UtcDateTime;
// Create a new series in the chart
var series = new System.Windows.Forms.DataVisualization.Charting.Series
{
Name = date.ToString("dd-MM-yyyy HH:mm:ss"),
Color = working ? Color.Red : Color.Green,
BorderColor = Color.Black,
ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Bar,
IsXValueIndexed = false,
XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.DateTime
};
series.Points.AddXY(date, duration);
chart1.Series.Add(series);
}
}
// Set the bar width for all series
foreach (var series in chart1.Series)
{
foreach (var point in series.Points)
{
// point.Width = 20;
point.BorderWidth = 0;
}
}
However, I need help with replacing so that on line X there are all occurrences (i.e. each line) with preferably a vertical entry of the date of occurrence, and on line Y there is time of operation (i.e. the last data from each line)
Related
I have this program that supposed to reads multiple text files on the same folder, in that folder there's 2 text files which are supposed to be read, ok now I have to generate a new TextBox based on the total numbers of text files in that folder.
Main Goal
Load the contents of those files in each textbox
File1.txt contents will be loaded into TextBox1.
File2.txt contents will be loaded into TextBox2.
Content of File1.txt:
Title 1
ABCDEFG
Content of File2.txt:
Title 2
1234567890
The problem
Loading the contents of those files into each TextBoxes works fine, but the problem is that the newline isn't created on the TextBoxes.
Instead I got this on each textboxes:
TextBox 1:
Title 1ABCDEFG
TextBox 2:
Title 21234567890
Do the necessary stuff as soon the program loads:
private void Form1_Load(object sender, EventArgs e) {
flowLayoutPanel1.AutoScroll = true;
var dirs_notes = #"C:\MAIN_LOC\DATA_LOC\";
var count_notes = Directory.GetFiles(dirs_notes,"*.*",SearchOption.AllDirectories).Count();
string setup_path = #"C:\MAIN_LOC\DATA_LOC\";
if(Directory.Exists(setup_path)) {
string[] get_notes = Directory.GetFiles(dirs_notes, "*.txt", SearchOption.AllDirectories);
string[] get_texts = get_notes.Select(x => File.ReadAllText(x)).ToArray();
for(int i=0; i<count_notes; i++) {
int top = 25;
int h_p = 170;
var load_note = new Guna2TextBox() {
Text = "\n" + get_texts[i],
Name = "Note" + i,
Multiline = true,
AcceptsTab = true,
AcceptsReturn = true,
WordWrap = false,
Width = 230,
Height = 145,
BorderRadius = 8,
Font = new Font("Bahnschrift", 13),
ForeColor = Color.White,
FillColor = ColorTranslator.FromHtml("#1E1E1E"),
BorderColor = ColorTranslator.FromHtml("#2C2C2C"),
Location = new Point(450, top)
};
top += h_p;
flowLayoutPanel1.Controls.Add(load_note);
}
} else {
MessageBox.Show("There's problem with loading notes..", "Flow Notes System");
}
}
A fix could be using the Lines property instead of the Text property.
var dirs_notes = #"C:\MAIN_LOC\DATA_LOC\";
// Be sure to count only txt files here...
var count_notes = Directory.GetFiles(dirs_notes,"*.txt",SearchOption.AllDirectories).Count();
string setup_path = #"C:\MAIN_LOC\DATA_LOC\";
if(Directory.Exists(setup_path)) {
string[] get_notes = Directory.GetFiles(dirs_notes, "*.txt", SearchOption.AllDirectories);
var get_texts = get_notes.Select(x => File.ReadLines(x));
for(int i=0; i<count_notes; i++) {
....
var load_note = new Guna2TextBox() {
Lines = "\n" + get_texts[i].ToArray(),
But a better approach is to use this instead:
// No counting here (counting means load all
// files names in a memory array and the get its length
var files = Directory.EnumerateFiles(dirs_notes,"*.txt",SearchOption.AllDirectories)
int i = 1;
// Enumerate files one by one without loading all names in memory
foreach(string file in files) {
int top = 25;
int h_p = 170;
var load_note = new Guna2TextBox() {
// Set the textbox with the current file lines content
// again one by one without loading all texts in memory
Lines = File.ReadLines(file).ToArray(),
Name = "Note" + i,
...
}
i++;
.....
}
I have a list of column headers that are read from a file into a List:
// Read column headers from text file
List<string> colHeads = new List<string>();
string[] lines = File.ReadAllLines("C:\\DATA\\MLData\\colHeads.txt");
string[] spl = new string[100];
foreach (string line in lines)
{
spl = line.Split('=');
colHeads.Add(spl[0].Trim());
}
I would like to then read a CSV file but only read the columns that are in the list:
// Read CSV file
string[] lines = File.ReadAllLines("C:\\DATA\\MLData\hist.csv");
string[] spl = new string[500];
foreach (string line in lines)
{
spl = line.Split(',');
var rec = new Record()
{
Name = spl[1],
ident = float.Parse(spl[4], CultureInfo.InvariantCulture.NumberFormat),
location = float.Parse(spl[5], CultureInfo.InvariantCulture.NumberFormat),
...
...
};
}
Example of colHeads.txt....
Name
ident
location
...
Example of hist.csv...
Name,yob,ident,level,location,score1
John B,1981,23,3,GB,54
There are more columns in hist.csv than colHeads.txt so I need a way to read the csv file by column name rather than column number, ignoring the columns that are not in the list. The variables I'm assigning to match the column names exactly.
Assuming that colHeads contains a list of header names, you can try something like this.
location = colHeads.Contains("location") ? float.Parse(spl[5], CultureInfo.InvariantCulture.NumberFormat) : 0
If the set of available columns are always the same, and you just want to change the columns you read, this will probably work fine for basic use.
var colHeads = File.ReadLines("colHeads.txt").ToHashSet();
var lines = File.ReadLines("hist.csv");
var headers = lines.First().Split(',');
var indexes = new Dictionary<string, int>();
var records = new List<Record>();
for (int i = 0; i < headers.Length; i++)
{
indexes[headers[i]] = colHeads.Contains(headers[i]) ? i : -1;
}
int nameIndex = indexes[nameof(Record.Name)];
int identIndex = indexes[nameof(Record.ident)];
int locationIndex = indexes[nameof(Record.location)];
//...
foreach (var line in lines.Skip(1))
{
var values = line.Split(',');
var record = new Record();
records.Add(record);
if (nameIndex >= 0) record.Name = values[nameIndex];
if (identIndex >= 0) record.ident = float.Parse(values[identIndex]);
if (locationIndex >= 0) record.location = values[locationIndex];
//...
}
First we read the header from the hist.csv file and assign indexes.
Next, using these indexes, we set the properties of the record.
I am attempting to convert a text file to a pdf using GemBox. I can get the text imported correctly but the font type and size aren't being applied and the sentence spacing seems to be doubled.
This is what I have so far:
public static void CreateDoc(string ebillpath)
{
using (var sr = new StreamReader(ebillpath))
{
var doc = new DocumentModel();
doc.DefaultCharacterFormat.Size = 10;
doc.DefaultCharacterFormat.FontName = "Courier New";
var section = new Section(doc);
doc.Sections.Add(section);
string line;
var clearedtop = false;
while ((line = sr.ReadLine()) != null)
{
if (string.IsNullOrEmpty(line) && !clearedtop)
{
continue;
}
clearedtop = true;
Paragraph paragraph2 = new Paragraph(doc, new Run(doc, line));
section.Blocks.Add(paragraph2);
}
PageSetup pageSetup = new PageSetup(); // section.PageSetup;
var pm = new PageMargins();
pm.Bottom = 36;
pm.Top = 36;
pm.Right = 36;
pm.Left = 36;
pageSetup.PageMargins = pm;
doc.Save(#"d:\temp\test.pdf");
}
}
This text file uses spaces to format the text correctly so I need to set the font to Courier New.
This is an example of what the text file looks like with correct formatting:
And this is what it comes out to look like in pdf form:
Each line seems to be doubled and the font isn't being applied.
Any suggestions?
Try this:
public static void CreateDoc(string ebillpath)
{
DocumentModel doc = new DocumentModel();
CharacterFormat charFormat = doc.DefaultCharacterFormat;
charFormat.Size = 10;
charFormat.FontName = "Courier New";
ParagraphFormat parFormat = doc.DefaultParagraphFormat;
parFormat.SpaceAfter = 0;
parFormat.LineSpacing = 1;
// It seems you want to skip first line with 'clearedtop'.
// So maybe you could just use this instead.
string text = string.Concat(File.ReadLines(ebillpath).Skip(1));
doc.Content.LoadText(text);
Section section = doc.Sections[0];
PageMargins margins = section.PageSetup.PageMargins;
margins.Bottom = 36;
margins.Top = 36;
margins.Right = 36;
margins.Left = 36;
doc.Save(#"d:\temp\test.pdf");
}
I hope it helps.
by using following code I am only formatting the respective cell but while I am selecting the whole column it's showing the general format as label please see the attach imageenter image description here
enter image description here
var ws = wb.Worksheets.Add("Contacts");
//Adding text
//Title
ws.Cell("B2").Value = "Contacts";
//First Names
ws.Cell("B3").Value = "FName";
ws.Cell("B4").Value = "John";
ws.Cell("B5").Value = "Hank";
ws.Cell("B6").SetValue("Dagny"); // Another way to set the value
//Last Names
ws.Cell("C3").Value = "LName";
ws.Cell("C4").Value = "Galt";
ws.Cell("C5").Value = "Rearden";
ws.Cell("C6").SetValue("Taggart"); // Another way to set the value
//Adding more data types
//Is an outcast?
ws.Cell("D3").Value = "Outcast";
ws.Cell("D4").Value = true;
ws.Cell("D5").Value = false;
ws.Cell("D6").SetValue(false); // Another way to set the value
//Date of Birth
ws.Cell("E3").Value = "DOB";
ws.Cell("E4").Value = new DateTime(1919, 1, 21);
ws.Cell("E5").Value = new DateTime(1907, 3, 4);
ws.Cell("E6").SetValue(new DateTime(1921, 12, 15)); // Another way to set the value
//Income
ws.Cell("F3").Value = "Income";
ws.Cell("F4").Value = 2000;
ws.Cell("F5").Value = 40000;
ws.Cell("F6").SetValue(10000); // Another way to set the value
//Defining ranges
//From worksheet
var rngTable = ws.Range("B2:F6");
//From another range
var rngDates = rngTable.Range("D3:D5"); // The address is relative to rngTable (NOT the worksheet)
var rngNumbers = rngTable.Range("E3:E5"); // The address is relative to rngTable (NOT the worksheet)
//Formatting dates and numbers
//Using a OpenXML's predefined formats
rngDates.Style.NumberFormat.NumberFormatId = 15;
//Using a custom format
rngNumbers.Style.NumberFormat.Format = "$ #,##0";
I found an implementation of a parallel coordinates application in c#. What I am trying to achieve is that I want to be able to read a CSV file and map the values and Labels onto the coordinates. The method mapping the values is assigning the values manually. Instead, I want those values to be read from the CSV file.
Here is the current method:
public void DataBind()
{
IList<DemoInfo> infos = new List<DemoInfo>();
for (int i = 0; i < ObjectsCount; i++)
{
var x = new DemoInfo();
x.X = m_Random.NextDouble() * 400 - 100;
x.Y = m_Random.NextDouble() * 500 - 100;
x.Z = m_Random.NextDouble() * 600 - 300;
x.V = m_Random.NextDouble() * 800 - 100;
x.K = 1.0;
//x.M = i % 2 == 0 ? 1.0 : -20.0;
x.M = i;
x.Tag = i + 1;
infos.Add(x);
}
var dataSource = new MultiDimensionalDataSource<DemoInfo>(infos, 6);
dataSource.MapDimension(0, info => info.X);
dataSource.MapDimension(1, info => info.Y);
dataSource.MapDimension(2, info => info.Z);
dataSource.MapDimension(3, info => info.V);
dataSource.MapDimension(4, info => info.K);
dataSource.MapDimension(5, info => info.M);
//dataSource.MapDimensionToOpacity(0, 0.5);
dataSource.MapTag(info => info.Tag);
dataSource.Labels[0] = "X";
dataSource.Labels[1] = "Y";
dataSource.Labels[2] = "Z";
dataSource.Labels[3] = "V";
dataSource.Labels[4] = "K";
dataSource.Labels[5] = "M";
dataSource.HelperAxisLabel = "Helper axis";
DataSource = dataSource;
}
Here is some of the data in the CSV File:
SWW Institutions Undergradutes Postgraduates
University College 2085 250
Metropolitan University 4715 1135
Would really appreciate your help !!
Thanks.
I am not sure how your CSV file is mapping to the DemoInfo class. Also, the example below is based on a CSV file, but your sample data is showing a TSV file. If it is a TSV file, just replace ',' with '/t'. Also, something watch out for is if any strings contain your delimiter, such as a SWW Institutions string like "Univeristy, Madison".
You can open the file to read the lines of text and split the line based on your delimiter.
using (var sr = File.OpenText(path))
{
var line = string.Empty;
while ((line = sr.ReadLine()) != null)
{
var dataPoints = line.Split(',');
// Create Your Data Mappings Here
// dataPoints[0]...
}
}