Read a table from a file with nullable columns - c#

I have a file with some rows and I can read everything, but I will get an error if one column has a empty cell.
What should I do?
while ((line = reader.ReadLine()) != null) {
FundPriceModel model = new FundPriceModel();
if (isColumn) {
model.Columns = line.Split(spliter[0]);
isColumn = false;
} else {
string[] row = line.Split(spliter);
model.LipperID = Int32.Parse(row[0]);
model.PriceDate = DateTime.Parse(row[1]);
model.PriceCode = row[2][0];
model.PriceType = row[3][0];
model.PriceCurrency = row[4];
model.PriceValueLC = float.Parse(row[5]);
model.Estimate = row[6][0];
Console.WriteLine(model.LipperID + "\t" + model.PriceDate + "\t" + model.PriceCode + "\t" + model.PriceType + "\t" + model.PriceCurrency + "\t" + model.PriceValueLC + "\t" + model.Estimate);
}
}
Table:

The error is probably when you try to parse something. This leads me to believe that you need to use TryParse instead or Parse :)
Something like this: int x; int? val=int.TryParse(row[0],out x)?x:(int?)null;
Also, row[3][0] gets the first letter in an existing string and returning an error when the string is empty. You could encapsulate it somewhat like this:
private T safeValue<T>(string text, Func<string,T> func) {
if (string.IsNullOrEmpty(text)) return default(T);
return func(text)
}
and you would use it like this:
model.LipperID = safeValue(row[0],v=>Int32.Parse(v));
model.PriceCode = safeValue(row[2], v=>v[0]);

Related

How can I do a header for a CSV using StringBuilder? C#

I will edit my post because I couldn't express very well.
I want to do this:
This
And I don't know how to do a unique header. I achieved this:
Achieved
but now I need to do the header. I will post more of my code here:
protected override void OnBarUpdate()
{
if (BarsInProgress != 0)
return;
if (CurrentBars[0] < Shift)
return;
string header = "Time" + ";" + "Close[0]" + ";" + "ATR_7" + ";" + "VOL_7" + ";" + "LABEL";
string Label = "NULL";
if(Alcista)
{
if(Open[0] >= Open[Shift - 1] && Open[0]/Open[Shift - 1] >= 1.0001)
{
Label = "UP";
}
else
{
Label = "DOWN";
}
}
switch(Indicar2_Sesgo)
{
case Sesgo.Alcista:
StringBuilder csvcontent = new StringBuilder();
csvcontent.AppendLine(Convert.ToString(Times[0][0].TimeOfDay + ";" + Close[0] + ";" + ATR1[0] + ";" + VOL1[0] + ";" + Label));
string csvpath = "D:\\xyz.csv";
File.AppendAllText(csvpath, csvcontent.ToString());
break;
}
}
It is a little difficult to know what your output is supposed to look like, but if you are simply trying to write a header, your code may look something like this:
var csvPath = "D:\\xyz.csv";
var csvHeader = "Time;Close;Atr1;Atr2";
File.WriteAllText(csvPath, csvHeader + Environment.NewLine);
As others have mentioned you would be better off using a helper library (like csvhelper) and setting the delimiter to a semicolon.

ArgumentOutOfRangeException when I think my code should work

I'm working on a bit of code for school but I keep getting an ArgumentOutOfRangeException
With this code I'm trying to read some data from a .csv file and if it equals the name of the image I want it to remove it from the .csv file whilst keeping the structure intact.
public void checkPair(Image card1, Image card2)
{
this.Image1 = card1;
this.Image2 = card2;
if (Convert.ToString(card1.Source) == Convert.ToString(card2.Source) && (card1 != card2))
{
getPoint(card1, card2);
string path = #"Save1.csv";
var reader = new StreamReader(File.OpenRead(path));
var data = new List<List<string>>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');
data.Add(new List<String> { values[0], values[1]
});
}
reader.Close();
string delimiter = ";";
for (int i = 1; i < 5; i++)
{
for (int x = 0; x < 4; x++)
{
if (data[i][x] == Convert.ToString(card1.Source))
{
data[i][x] = null;
}
}
}
File.WriteAllText(path, data[0][0] + delimiter + data[0][1] + Environment.NewLine + data[1][0] + delimiter + data[1][1] + delimiter + data[1][2] + delimiter + data[1][3] + Environment.NewLine + data[2][0] + delimiter + data[2][1] + delimiter + data[2][2] + delimiter + data[2][3] + Environment.NewLine + data[3][0] + delimiter + data[3][1] + delimiter + data[3][2] + delimiter + data[3][3] + Environment.NewLine + data[4][0] + delimiter + data[4][1] + delimiter + data[4][2] + delimiter + data[4][3] + Environment.NewLine + "ready");
I have no idea why I get this error and how to fix it
Initially, I'd change your last line from
File.WriteAllText(path, data[0][0] + delimiter + data[0][1] ....
to something like
var obj1 = data[0][0];
var obj2 = data[0][1];
File.WriteAllText(path, obj1 + delimiter + obj2 .... etc)
If you over inline functions or array accessing, when you get an exception the stack trace won't be that helpful. At least you'll have an idea of the statement that caused the issue.
This technique can prove to be very helpful, if you are looking at an in exception in the logs, after the fact.

Search anywhere in DataGridView

I'm trying to write a program which will made a datagridview based on a text file. See code below.
private void Button1_Click(object sender, EventArgs e)
{
ls_datenTabelle.Clear();
ls_datenTabelle.Columns.Clear();
string kdstr = (comboBox1.SelectedItem.ToString());
string fileName = "ls.txt";
string fileName2 = kdstr + ".txt";
string sourcePath = #"H:\import_directoy\customer\" + kdstr;
string tempPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string dmitempPath = #"program_name\";
string targetPath = Path.Combine(tempPath, dmitempPath);
File.Delete(targetPath + "output");
string sourceFileName = Path.Combine(sourcePath, fileName);
string destFile = Path.Combine(targetPath, fileName2);
Directory.CreateDirectory(targetPath);
File.Copy(sourceFileName, destFile, overwrite: true);
using (var output = File.Create(targetPath + "output"))
{
foreach (var file in new[] { "H:\\directoy1\\directoy2\\index.config", destFile })
{
using (var input = File.OpenRead(file))
{
input.CopyTo(output);
}
}
}
string[] raw_text = File.ReadAllLines(targetPath + "output", Encoding.Default);
string[] data_col = null;
int x = 0;
foreach (string text_line in raw_text)
{
data_col = text_line.Split(';');
if (x == 0)
{
for (int i = 0; i <= data_col.Count() - 1; i++)
{
ls_datenTabelle.Columns.Add(data_col[i]);
}
x++;
}
else
{
ls_datenTabelle.Rows.Add(data_col);
}
}
ls_dataGridView.DataSource = ls_datenTabelle;
this.Controls.Add(ls_dataGridView);
ls_dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
ls_dataGridView.AllowUserToAddRows = false;
}
Now I want to search all over this datatable/datagridview and I will show the rows if the search function found the searchvalue in any column.
But I dodn't know how. The header of the table could change every day. So this code doesn't work for me:
public void findingValue(object sender, EventArgs e)
{
string searchValue = textBox1.Text;
DataView data = ls_datenTabelle.DefaultView;
ls_dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
data.RowFilter = string.Format("Name like '" + searchValue + "%'");
}
The program will find only rows where the searchValue is in the "Name" column and not one of the other 18 (umknown) columns.
Here is an example which uses Linq to loop over the columns in the DataTable:
if (searchValue == "") data.RowFilter = "";
else
{
var cols = ls_datenTabelle.Columns.Cast<DataColumn>().Select(x => x.ColumnName);
var filter = cols.Select(x => x + " like '" + searchValue + "%'")
.Aggregate((a, b) => a + " OR " + b);
data.RowFilter = filter;
}
First we collect the column names and then we build a filter from them, each part connectd with a OR clause.
You could also use Join or good old loops..
Note that this assumes that all columns allow searching for strings, i.e. no numbers etc..
If this is not true you will want to either pick only the string columns or change the filter for non-string columns, if searching them makes any sense.
To restrict the search to string columns simply insert
.Where(x => x.DataType == typeof(string))
between Cast and Select, so that cols contains only searchable columns..
If instead you want to search numeric columns you could write the filter like this:
var filter = cols.Select(x => "Convert(" + x + ", 'System.String') like '"
+ searchValue + "%'").Aggregate((a, b) => a + " OR " + b);
This uses the Convert function of the expression syntax . But why would one search for numbers starting with some digits..?
Here is a test with 2 string, 1 numeric and one datetime columns. The filter works for all; note that for the test I have added an extra '%' to extend the search to the whole values, not just the start..

Pass multiple data from one function to label in C#

I have a function that retrieves multiple lines of data and I want to display them in a label. My function is as shown below.
public static string GetItemByQuery(IAmazonSimpleDB simpleDBClient, string domainName)
{
SelectResponse response = simpleDBClient.Select(new SelectRequest()
{
SelectExpression = "Select * from " + domainName
});
String res = domainName + " has: ";
foreach (Item item in response.Items)
{
res = item.Name + ": ";
foreach (Amazon.SimpleDB.Model.Attribute attribute in item.Attributes)
{
res += "{" + attribute.Name + ", " + attribute.Value + "}, ";
}
res = res.Remove(res.Length - 2);
}
return res;
}
So far I can only return a string which is the last line of the retrieved data. How can I retrieve all the records? I tries arraylist, but it seems that the AWS web application doesn't allow me to use arraylist. Can anyone please help me to solve this??
Return it as as a Enumberable,
List<String> Results ;
Your method would be
public static List<String> GetItemByQuery(IAmazonSimpleDB simpleDBClient, string domainName)
{
List<String> Results = null;
SelectResponse response = simpleDBClient.Select(new SelectRequest()
{
SelectExpression = "Select * from " + domainName
});
String res = domainName + " has: ";
foreach (Item item in response.Items)
{
Results = new List<String>();
res = item.Name + ": ";
foreach (Amazon.SimpleDB.Model.Attribute attribute in item.Attributes)
{
res += "{" + attribute.Name + ", " + attribute.Value + "}, ";
}
res = res.Remove(res.Length - 2);
Results.Add(res);
}
return Results;
}

Taglib array exception when setting Artist field

I keep getting an array out of bounds exception with Taglib.tag.Performers in this function that edits ID3 data. I read elsewhere that clearing tag.performers[] can help (if null) but I still get the error sometimes.
Error message:
"Index was outside the bounds of the array.Data:
'System.Collections.ListDictionaryInternal' for test.mp3"
var fileArr = Directory.GetFiles(BasePath, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".mp3") || s.EndsWith(".m4a")).ToArray();
foreach (var file in fileArr)
{
string fileName = Path.GetFileName(file);
string tagArtist = "";
string tagTitle = "";
string tempRegFilename = fileName;
string title = "";
//Apply to tag
TagLib.File mp3tag = TagLib.File.Create(file);
if (mp3tag.Tag.Title != null && mp3tag.Tag.Title.Length > 1)
{
title = mp3tag.Tag.Title;
}
else
{
mp3tag.Tag.Title = String.Empty;
}
if (mp3tag.Tag.Performers[0].Length < 1 || mp3tag.Tag.Performers[0] == null)
{
mp3tag.Tag.Performers[0] = null;
mp3tag.Tag.Performers = new[] { String.Empty };
mp3tag.Save();
}
if (mp3tag.Tag.Performers[0].Length > 1)
{
string[] performers = mp3tag.Tag.Performers;
if (title.Length > 2 && performers[0].Length > 1)
{
tagTitle = title;
tagArtist = performers[0].ToString();
Log.Info("ID3 Artist: " + "[" + tagArtist + "]");
Log.Info("ID3 Title: " + "[" + tagTitle + "]");
Log.Info("Tag data OK");
}
}
//Get artist from filename
if (mp3tag.Tag.Performers[0].Length < 1 || mp3tag.Tag.Performers == null)
{
mp3tag.Tag.Performers = new[] { String.Empty };
string prevArtist = String.Empty;
if (tempRegFilename.Contains("-"))
{
Log.Info("Artist data missing...");
string[] words = tempRegFilename.Split('-');
{
words[0] = words[0].Trim();
string perf = words[0];
mp3tag.Tag.Performers = new[] { perf };
Log.Info("Artists changed from \'" + prevArtist + "\' to " + "'" + perf + "'" + "\r\n");
mp3tag.Save();
}
}
mp3tag.Save();
}
}
catch (Exception ex)
{
Log.Error("TAG EXCEPTION: " + ex.Message + "Data: " + "'" + ex.Data + "'" + " for " + fileName + "\r\n" + ex.HelpLink);
}
Can anyone see what's wrong? I don't have much experience and could use the help. Thanks.
You seem to be assuming in a number of places that mp3Tag.Tag.Performers will have at least one element in it. If it doesn't, then you'll get the exception that you mention whenever you try to access mp3tag.Tag.Performers[0]
It looks like you may be trying to catch that possibility with this code:
if (mp3tag.Tag.Performers[0].Length < 1 || mp3tag.Tag.Performers[0] == null)
{
mp3tag.Tag.Performers[0] = null;
mp3tag.Tag.Performers = new[] { String.Empty };
mp3tag.Save();
}
But your logic is incorrect: you're getting the first element from the array (apparently a string) and checking its length, instead of checking the length of the array itself. Try this:
if (mp3tag.Tag.Performers.Length < 1 || mp3tag.Tag.Performers[0] == null)
{
mp3tag.Tag.Performers = new[] { String.Empty };
mp3tag.Save();
}
PS: It'll be much easier for you to see where your errors are if your log includes the stack trace of the exception, rather than just its message. I typically find it best to just use the ToString() on the exception itself.

Categories

Resources