dmdb/view/frmExportCsv.cs

116 lines
3.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Windows.Forms;
using dezentrale.model;
namespace dezentrale.view
{
public class frmExportCsv<T> : FormWithActionButtons
{
private List<T> entities;
private LvSelectFields lv;
public List<string> SelectedProperties { get; set; } = new List<string>();
private bool ExportCsv()
{
SaveFileDialog sfd = new SaveFileDialog(){
FileName = $"{typeof(T)}_{entities.Count}_items.csv",
Filter = "Comma-Separated-Value files (*.csv)|*.csv"
};
DialogResult dr = sfd.ShowDialog();
if (dr != DialogResult.OK)
return false;
try
{
CsvFile csv = new CsvFile() {
};
//Build headline
csv.FileContents.Add(SelectedProperties);
foreach (T t in entities)
{
List<string> t_csv = new List<string>();
foreach (string p in SelectedProperties)
{
//Get propertyinfo from T
PropertyInfo pi = typeof(T).GetProperty(p);
if (!pi.CanRead) continue;
try
{
object o = pi.GetValue(t, null);
string propVal = (o == null ? "null" : o.ToString());
t_csv.Add(propVal);
} catch(Exception ex)
{
t_csv.Add(ex.Message);
}
}
csv.FileContents.Add(t_csv);
}
csv.SaveFile(sfd.FileName);
} catch(Exception ex)
{
MessageBox.Show($"Error({ex.GetType()}):\r\n{ex.Message}");
return false;
}
return true;
}
private void FormLoad(object sender, System.EventArgs e)
{
this.Text = $"Export {entities.Count} entities of type \"{typeof(T).ToString()}\"";
this.Controls.Add(lv = new LvSelectFields()
{
Left = 0,
Width = this.ClientSize.Width,
Top = 0,
Height = this.ClientSize.Height - 60,
Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right,
});
foreach (var p in typeof(T).GetProperties())
{
lv.AddEntry(p.Name);
}
List<string> failToSelect = new List<string>();
foreach(string s in SelectedProperties)
{
if (!lv.ItemSelection(s, true)) {
failToSelect.Add(s);
}
}
foreach (string s in failToSelect) {
SelectedProperties.Remove(s);
}
this.AddButton("All fields", (se, ev) => {
SelectedProperties = lv.GetAllItems();
if (ExportCsv()) this.Close();
});
this.AddButton("Selected fields", (se, ev) => {
SelectedProperties = lv.GetSelectedItems();
if (ExportCsv()) this.Close();
});
this.AddButton("Cancel", (se, ev) => { this.Close(); });
}
public frmExportCsv(T t)
{
entities = new List<T> { t };
this.Load += FormLoad;
}
public frmExportCsv(List<T> l)
{
entities = l;
this.Load += FormLoad;
}
}
}