March 2008 Entries

What's Wrong With This Code (#19)

Leroy was shocked when the source code appeared. It was familiar yet strange, like an old lover's kiss. The code was five years old – an artifact of Leroy's first project. Leroy slowly scrolled through the code and pondered his next move. It wasn't a bug that was bothering Leroy – there were no race conditions or tricky numerical conversions. No performance problems or uncaught error conditions. It was all about design … public class BankAccount {     public void Deposit(decimal amount)     {         _balance += amount;         LogTransaction("Deposited {0} on {1}", amount, DateTime.Now);     }     public void Withdraw(decimal amount)     {         _balance -= amount;         LogTransaction("Withdrew {0} on {1}", amount, DateTime.Now);     }     public void AccumulateInterest(decimal baseRate)     {         decimal interest;         if (_balance...

Custom Aggregations In LINQ

Aggregate is a standard LINQ operator for in-memory collections that allows us to build a custom aggregation. Although LINQ provides a few standard aggregation operators, like Count, Min, Max, and Average, if you want an inline implementation of, say, a standard deviation calculation, then the Aggregate extension method is one approach you can use (the other approach being that you could write your own operator). Let's say we wanted to see the total number of threads running on a machine. We could get that number lambda style, or with a query comprehension, or with a custom aggregate. var processes =...

And Equality for All ... Anonymous Types

Given this simple Employee class: public class Employee {     public int ID { get; set; }     public string Name { get; set; }     } How many employees do you expect to see from the following query with a Distinct operator? var employees = new List<Employee> {     new Employee { ID=1, Name="Barack" },     new Employee { ID=2, Name="Hillary" },     new Employee { ID=2, Name="Hillary" },     new Employee { ID=3, Name="Mac" } }; var query =         (from employee in employees                  select employee).Distinct(); foreach (var employee in query) {     Console.WriteLine(employee.Name); } The answer is 4 – we'll see both Hillary objects. The docs for Distinct are clear – the method uses the default equality comparer to test for equality, and the default comparer...

Inner, Outer, Let's All Join Together With LINQ

The least intuitive LINQ operators for me are the join operators. After working with healthcare data warehouses for years, I've become accustomed to writing outer joins to circumvent data of the most … suboptimal kind. Foreign keys? What are those? Alas, I digress… At first glance, LINQ appears to only offer a join operator with an 'inner join' behavior. That is, when joining a sequence of departments with a sequence of employees, we will only see those departments that have one or more employees. var query =   from department in departments   join employee in employees       on department.ID equals employee.DepartmentID  ...

Mashups with SyndicationFeed and LINQ

I was experimenting with the new SyndicationFeed class in 3.5 earlier this year and devised a mashup LINQ query: string[] feedUrls = { "http://www.OdeToCode.com/blogs/scott/rss.aspx",                       "http://www.pluralsight.com/blogs/mainfeed.aspx",                       "http://feeds.feedburner.com/ScottHanselman"                         }; var items =     from url in feedUrls         let feed = SyndicationFeed.Load(XmlReader.Create(url))     from item in feed.Items     where item.PublishDate > DateTime.Now.AddDays(-30)     orderby item.PublishDate descending     select item; // display the most recent 15 items foreach (SyndicationItem item in items.Take(15)) {     Console.WriteLine("{0} : {1}",         item.PublishDate.Date.ToShortDateString(),         item.Title.Text); } The code is able to filter and sort RSS items from an arbitrary number of blogs with a 6 line query expression. I was thinking of this code when I ran across Scott Hanselman's Weekly Source Code 19 – LINQ and more What, Less...

Talks You Won’t See At the Local Code Camp

The Lost Art of TSR ProgrammingAbstract: Return to the glory days of DOS 2.0 and INT 21h as we write a simple Terminate and Stay Resident application using the latest software development techniques. We will construct our x86 assembler code using test driven development and mock extended memory managers. Why Am I Here On A Saturday?Abstract: Because even if you weren't here, you'd still be at the computer. Don't think you'd be doing chores at home, like dusting off the entertainment center, because chores are boring. Life of a GnatAbstract: This session has nothing to do with GNU software,...

Visitors and Multiple Dispatch

The visitor pattern is an elegant solution to a specific class of problems, but also comes with drawbacks in mainstream programming languages. There are various techniques one can us to minimize the drawbacks, however. This weekend I found some old but good articles harnessing the power of visitor while removing some of the pain: Brad Wilson (the .NET Guy) – Use Reflection for the Visitor Pattern. Daniel Cazzulino (kzu) – Visitor Design Pattern: revisited for .NET Both Brad and Kzu use reflection to effectively achieve multiple dispatch. The typical multiple dispatch mechanism used to implement the visitor pattern is a drag...

Travelogue: India

I spent the last week of February in Hyderabad, India. This was my first trip to India, and I thought I'd share some experiences. The Flight I flew from Washington D.C. to Hyderabad on Qatar Airlines. The longest leg, between D.C. and Doha, was on a Boeing 777-300ER – a long range jet with the largest engines in aviation history. The business class configuration on the plane made the time pass with relatively little agony. The lay-flat seats gave me 12 hours of sleep, and I used the on-demand entertainment system to pass the time with ...

Extension Methods for Profit

Some say we are living in the information age, but I say this is the advertisement age. Marketers strive to cover every square inch of the planet and outer atmosphere with slogans and promotions. We have ambient advertising and advergames, human billboards and celebrity branding. My prediction is that marketers will become more aggressive in placing advertisements directly inside the software used by information workers who are laden with disposable income. Microsoft is well positioned for the next wave of advertising with the addition of extension methods in C# and Visual Basic. Just imagine the number of eyeballs that...