Monday, July 21, 2008

Using LINQ to Read a CSV File

I recently wrote a windows application which plots my checking account balance on a graph. In this application, I needed to import the financial data from a CSV (comma separated values) file. LINQ's ability to iterate over a collection of objects made this task easy:

IEnumerable lines = File.ReadAllLines("c:\checking.csv");

var query = from line in lines
let x = line.Split(',') //x will be a new, anonymous type
where x[0].Length > 0 //skip blank lines
select new
{
Date = DateTime.Parse(x[0].Replace("\"", string.Empty)), //remove double quotes
Description = x[4].Replace("\"", string.Empty),
Amount = Convert.ToDecimal(x[1].Replace("\"", string.Empty))
};

foreach(var i in query)
{
Console.WriteLine("Date: " + i.Date.ToString());
Console.WriteLine("Desc: " + i.Description);
Console.WriteLine("Amount: " + i.Amount.ToString());
}

Wednesday, January 30, 2008

Programmatically read AssemblyInfo attributes in a .NET 2.0 web application

As a developer, I can set version information for an application in the AssemblyInfo.cs file in a .NET application. I like to make the version number visible to someone who doesn't have access to the source or compiled code.

Here are a couple of ways to retrieve this information programmatically in C# using classes from the System.Reflection namespace:

.NET 1.1 ASP.NET Web Project, .NET 1.1 Windows Application, .NET 2.0 Windows Application
string version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

.NET 2.0 ASP.NET Web Project
string version = System.Reflection.Assembly.Load("AssemblyName").GetName().Version.ToString();
where "AssemblyName" matches the assembly name in the web project's application properties (to open the project properties, right-click your web application, click Properties, click the Application tab, and view or change the Assembly name)

Comments or suggestions? Post below.