SingingEels : Development Community & Resource

Login

Articles

  • ADO.NET (2)
  • ASP.NET (35)
  • LINQ (4)
  • Security (2)
  • Silverlight (2)
  • SQL (7)
  • Standards (5)
  • WCF (2)

Syndication

  • Articles RSS
  • Blogs RSS

Contribute

  • Our Authors List
  • Member Sign-Up
  • Suggestions Box
ASP.NET Hosting with MS SQL 2008 – Click Here!
Wednesday, March 26, 2008 : 7:34 AM - (3 comments)

Dynamic LINQ OrderBy using String Names!

Quick Overview of LINQ and Lambda Expressions

LINQ is a new enhancement to the .NET framework (version 3.5 and up) that gives powerful query capabilities against any enumerable object. This means that no matter what the data source (whether SQL, XML, or objects such as a generic list or ArrayList) you can do things like sorting (OrderBy), selecting, joining etc.

If you're not already familiar with LINQ, then you can Learn the Basics of LINQ from that article. Also, to appreciate this new gem that I discovered (actually, I've been trying to do this since I first started using LINQ), you'll need to understand lambda expressions with LINQ.

How To Sort using LINQ and Lamdba

First, let's look at a quick example of a data source that you would possibly want to sort, perhaps in a GridView. For the sake of simplicity, I'm just going to populate a generic list in code. If the code that I'm using looks funny, it's probably because you're not familiar with automatic properties (a new C# 3 only feature), lambda (a new language feature in C# 3 and VB9) or anonymous types.

Try not to get lost in the code about how to build my person class. The good stuff is at the end with the dyanmic LINQ! Here is my basic "Person" class that will hold our data:

public class Person
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public DateTime DateOfBirth { get; set; }
}

Now I'll create a list with 3 people in there. Then I'll show how to sort it using regular old LINQ. After that, I'll show you how to make your own Expression Tree to dynamically sort it using LINQ (it's exciting)! By the way, it took a lot of reverse engineering and reflecting to figure this out... and in case you're wondering, this is NO WHERE else on the internet right now.

// Here's my list that I am going to sort.
List<Person> people = new List<Person>();

people.Add(new Person { FirstName = "Moses",
   LastName = "McRoses",
   DateOfBirth = new DateTime(1801, 1, 23) });

people.Add(new Person { FirstName = "Timothy",
   LastName = "Khouri",
   DateOfBirth = new DateTime(1985, 6, 20) });

people.Add(new Person { FirstName = "Jonathan",
   LastName = "Carter",
   DateOfBirth = new DateTime(1984, 6, 12) });

As you can see, our list has 3 people that are not in any particular order. Now, I'll sort them by age:

// To do this, you have to have using System.Linq and must
// reference the System.Core assembly.


Person[] sortedPeople = people.OrderBy(person =>
   person.DateOfBirth).ToArray();

That was simple enough. But what if you bound your "people" list to a GridView that had sorting turned on. The problem here is that you are going to get a STRING that is the NAME of the field that the user wants to sort by. So what do we do?

// This won't work!

Person[] sortedPeople = people.OrderBy(person =>
   "DateOfBirth").ToArray();

The reason why the above won't work is because you're trying to sort by a literal string "DateOfBirth". Since "DateOfBirth" and "DateOfBirth" and "DateOfBirth" are all the same words, then LINQ will ignore this OrderBy alltogether. To achieve what we want, you have to create your own expression tree.

// First we define the parameter that we are going to use
// in our OrderBy clause. This is the same as "(person =>"

// in the example above.

var param = Expression.Parameter(typeof(Person), "person");

// Now we'll make our lambda function that returns the

// "DateOfBirth" property by it's name.

var mySortExpression = Expression.Lambda<Func<Person, object>>(Expression.Property(param, "DateOfBirth"), param);

// Now I can sort my people list.

Person[] sortedPeople = people.OrderBy(mySortExpression).ToArray();

Dynamic Expression Explaination

The code sample above does exactly what the original lambda expression was doing. The reason why I chose to do "Person, object" for my types instead of "Person, DateTime" is because if this was truely dynamic, I wouldn't know the data type of the column being sorted.

Actually, I should mention that I also wouldn't know the "Person" datatype, so I'd have to use "object, object"... but I'm not going to get into that right now as you'd have to do a pretty hefty chunk of reflection to get the right parameters.

The more I look into LINQ and expression trees, the more I like it. This stuff may look daunting at first, but when you "get it", you'll really see and appreciate the power it brings.

Monday, March 24, 2008 : 5:56 PM - (0 comments)

SingingEels Update DONE! - I Can't Believe It

After battling with the database for the past hour, I'm finally done uploading all of the previous content (as well as the new code files) to the public SingingEels server! We've re-shaped the site to be a better community experience for everyone, and hopefully it will prove to do so.

What Has Been Removed

If you'll notice, we no longer have the "Top Authors" section on the right, nor do we have the "Poll of the Day". The reasons for both of these changes is that the "Top Authors" didn't bring any content to the page, and the "Poll of the Day" was more like the poll of the year... that thing got hard to maintain.

We also removed the "comments RSS" link on the left under the Syndication section. We're going to be adding RSS for comments on an article and blog post basis. This way you can be intuned with a particular subject, rather than just recieving everyone's comments about everything.

What We've Added

This is the exciting part. First of all, we've added a few more categories: LINQ, Silverlight and WCF for starters. We will likely be changing some of the old categories, and we'll probably also add more. Also, along with the "more categories" is a switch that we made to the category system alltogether. Instead of being "one to one", you can now specify multiple categories for an article.

Also, blog posts are able to be categorized in the same categories as articles can be. The purpose of this is to provide "related" blog posts next to the article that users are reading. This will help to keep old articles up to date by providing the most recent posts on the topic that users are reading about.

Community Experts

We have also added a "People to Follow" section (that appears when you're reading an article or blog post). This is a new feature that we are looking to explore to recommend proven community leaders in the topics that you're reading about.

This list will be kept clean to ensure that we don't recommend random bloggers who consider themselves "the server side guy" or whatever other rediculous self made titles they aquire.

Look and Feel

We've changed the look and feel a bit. We moved the "recent blogs" section to the right of the main content as we realize that articles (scrutinized content) was being put at a lesser importance. There have been a few other design changes, but not much.

Misc and Closing

As a side note, we've rewritten the entire site in .NET 3.5 using LINQ (LINQ to SQL in particular). This doesn't mean anything to you (the end user), but it was fun.

If you have any comments, please feel free to... comment on this blog post! Or you could always drop us a line through the Suggestions Box (link in the left nav). I'm going to focus back on quality articles now.

Thursday, March 6, 2008 : 8:29 AM - (1 comment)

Silverlight Beta Has WCF, LINQ, Windows Controls!

I can't stress enough how amazing this is. When the Silverlight alpha came out, I was very disappointed due to the fact that there was no standard windows controls (TextBox, DropDownBox, etc). There was also no WCF support, meaning you're basically stuck with glorified JavaScript application. I was consistantly reassured by a good friend of mine who works for Microsoft (Jonathan Cater) that the beta would fix all of that, but I was still skeptical.

Why WCF in Silverlight is Great

Silverlight (as you may already know) brings amazing power to the web world in that you get beautiful rich content abilities, embedded audio and video codecs, cross-browser and cross-platform abilities and more. But many argued that you got the same with Adobe's Flash.

Where Silverlight destroys Flash and Java Applets is in version 2.0 (currently in beta) which brings a powerful slew of .NET support including WCF. WCF (Windows Communication Foundation) gives you the ability to build client / server applications on a TCP based connection, HTTP based connection and more. It's so incredibly easy to use verses the traditional "write it yourself TCP client", that I predict we are going to see a complete change in the Internet as a whole.

Be prepaired for MMORPGs (online video games) that have a Silverlight client end. Be prepaired for big corporations to drop windows apps and build robust (SoA based architecture) applications in Silverlight. Seriously, buy stock in Microsoft right now... and in 2 years cut me a check with a percentage of your profits... I'll accept personal checks.

Silverlight Windows Controls

I'm also pleased with the "windows controls" that are in Silverlight so far. I will admit that I haven't looked too much into them, so don't expect me to give an exhaustive list. But what I will say is that when the alpha came out, I was thinking "what happened to Microsoft!?" But, after seeing the TextBox, DatePicker, Calendar and ListBox I realize that they will not disappoint me with the release version.

Visual Studio 2008 and Silverlight

Another great thing that I forgot to mention is that there is much better Visual Studio support now for Silverlight. There's intellisense, a nicer editor and the like. Also, when starting a project, you have the ability to create a Web Site, Web Application or just an HTML file, whereas in the alpha, you could only start with a basic HTML file.

Wednesday, March 5, 2008 : 4:26 PM - (3 comments)

LINQ to SQL is My Hero!

I've been using LINQ for a while now (LINQ to Objects, and LINQ to SQL mainly) and I just saw something absolutely beautiful that I've never seen before. First, though, I'll give you a little history on the problem that I had (and everyone else in the world who uses Microsoft SQL Server will at some point run into).

Now, don't get me wrong, I love Microsoft SQL Server (2005 in particular), and I know that it is absolutely the best database out there... but there is one task in particular that comes up often, but is difficult to do.

The Scenario

Imagine if you had a website dedicated to top quality development articles (much like this one), and you wanted to display a "related blogs" section on your site. This would allow users to see blog posts that are similar to the article they are reading. Sounds simple enough, and it is... the only problem is that your articles can belong to multiple categories!

If you don't see the problem yet, then it's probably because you haven't run into it. So I'll show you by an example here why my simple desire won't work. If articles could only belong to one category, then your "get related blog posts" SQL code would look something like this:

SELECT
   *
FROM
   dbo.BlogPosts
WHERE
   Category = @SelectedCategory

But, we want to be able to search multiple categories... So, we need to do something like this:

SELECT
   *
FROM
   dbo.BlogPosts
WHERE
   Category = @SelectedCategoryA
       OR Category = @SelectedCategoryB

The problem here is that there can be any number of selected categories... so unless you want to dynamically build a SQL string, your out of luck. Also, if you made a stored procedure to house your code, there's little you can do (that isn't a nasty hack) to get the job done.

LINQ to SQL Builds Dynamic Queries

So, to get to the good stuff, what I realized is that LINQ to SQL does the nasty deed of building a SQL string for you. So, here is my LINQ code (in C#):

// I'm hardcoding these categories as an example... but the point
// is that they can be selected by a user dynamically.

string[] selectedCategories = new string[] { "ASP.NET", "LINQ", "WCF" }

var blogPosts = from blogPost in context.BlogPosts
   where selectedCategories.Contains(blogPost.CategoryName)
   select blogPost;

And here is the SQL code that will be built on the fly by LINQ:

-- This is not an exact example here, but I'm basically "roughing" it.
SELECT * FROM dbo.BlogPosts WHERE CategoryName IN (@p0, @p1, @p2)

You guessed it; LINQ to SQL is parameterizing the categories and using an "IN" statement... beautiful!

Conclusion

If you have no idea what I'm talking about above, it's probably because you're not familiar with LINQ or SQL... but all I can say is, you should really start getting into .NET 3.5 and LINQ. Hopefully I can finish up this re-write soon and start getting back to development articles.

Developer / Architect / Author

Blog Archives

  • November 2008 - (1)
  • October 2008 - (2)
  • September 2008 - (2)
  • August 2008 - (3)
  • July 2008 - (1)
  • June 2008 - (3)
  • May 2008 - (2)
  • April 2008 - (2)
  • March 2008 - (4)
  • February 2008 - (2)
  • December 2007 - (2)
  • November 2007 - (1)
  • October 2007 - (4)
  • September 2007 - (9)
  • August 2007 - (7)

Related Ads

SingingEels.com as of Nov 21 2008 - 07:27:19 PM - (0.0624984)