Skip to content

Instantly share code, notes, and snippets.

@hatelove
Created August 24, 2017 11:14
Show Gist options
  • Save hatelove/fedb7242490ecfb23ebfc479c83a903a to your computer and use it in GitHub Desktop.
Save hatelove/fedb7242490ecfb23ebfc479c83a903a to your computer and use it in GitHub Desktop.
CsvReportGenerator
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace CsvReportGeneratorTests
{
public class CsvReportAttribute : Attribute
{
public CsvReportAttribute(string name)
{
Name = name;
}
public string Name { get; }
}
public class Person
{
[CsvReport("Name")]
public string Name { get; set; }
[CsvReport("WhatEver")]
public int Age { get; set; }
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var people = new List<Person>
{
new Person {Name = "Scot", Age = 18},
new Person {Name = "Joey", Age = 20},
new Person {Name = "Flash", Age = 36},
};
var csvContent = GetResult(people);
File.WriteAllLines(@"E:\report.csv", csvContent);
var expected = new List<string>
{
"Name,WhatEver",
"Scot,18",
"Joey,20",
"Flash,36"
};
CollectionAssert.AreEqual(expected, csvContent.ToList());
}
private static IEnumerable<string> GetAttributeNamesFromProperty()
{
foreach (var p in typeof(Person).GetProperties())
{
yield return p.GetCustomAttributes().Cast<CsvReportAttribute>().First().Name;
}
}
private static IEnumerable<string> GetLineFromPerson(Person person)
{
foreach (var p in typeof(Person).GetProperties())
{
yield return Convert.ToString(p.GetValue(person));
}
}
private string GetFirstLine()
{
return string.Join(",", GetAttributeNamesFromProperty());
}
private IEnumerable<string> GetResult(List<Person> people)
{
yield return GetFirstLine();
foreach (var person in people)
{
yield return string.Join(",", GetLineFromPerson(person));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment