Timothy Khouri - SingingEels.com

I subscribe to the "take it apart and rebuild it" approach to learning.

September 2007 - Posts

LINQ, Lamda and Extension Methods Work Together!

Thanks to the new language features such as LINQ, Extension Methods and Lambda in .NET 3.5, working with arrays is as easy as one line. Just by including a reference to the System.Linq namespace in your .Net 3.5 project you automatically get so much functionality it's not even funny.

Let's take for example this very simple task and see how including these above language featuers cut the work by 80%! Assuming we have some sort of list (or in this case a simple array is fine) of "Sales" items, and we want to build a function that will return the number of sales in a particular zip code.

Examples Here: LINQ, Lamda and Extension Methods Work Together!

LINQ, Entity Framework, and Project Astoria by Jonathan Carter

Last night I attended the Sarasota .NET Developers Group monthly meeting and got to hear another great talk by Jonathan Carter (who has also spoken at the Tampa and Jacksonville code camps recently). Most of the talk was spent on LINQ, starting off with LINQ to Objects and then building from there into LINQ to SQL, and even more impressively, LINQ to Entities (and the Entity Framework).

As I've been using LINQ for a little while now (and since I've already heard an earlier talk by Jonathan on that subject in Tampa, Florida), I didn't think I would learn much more on that subject. But of course, I did.

You can see some samples, and my "take" on that talk here: http://www.singingeels.com/Blogs/Nullable/2007/09/20/LINQ_Entity_Framework_and_Project_Astoria_by_Jonathan_Carter.aspx

How To Use .NET 3.5 "Extension Methods" for Validation

The new language feature (Extension Methods) brought to C# and VB.NET in Visual Studio 2008 (.NET framework 3.5) is a great tool to speed up validation routines. At first I didn't think that this feature would really be used a lot, but I'm really loving it.

Obviously, the benefits that come with extension methods for the purpose of LINQ are great, but here's something that I have long wished I could do in the past, and now I can thanks to extension methods!

I have some code examples here: How To Use .NET 3.5 "Extension Methods" for Validation

IE7 Dev Toolbar = Great CSS / Semantic Markup Tool

I know there are a million toolbars out there (every FireFox user will remind you so)... but I still love the simplicity and functionality of the IE7 Dev Toolbar Beta 3, and especially one of it's features that really help with CSS and semantic markup design - "Disable -> All CSS".

A "Pure CSS" design first requires good markup... so, the way you can tell if you're markup is good is by disabling all CSS styles with the dev toolbar. Here is an example of how a Pure CSS designed site will "degrade" into a proper way when you disable CSS. You can see how to do a pure CSS design from this article (How To: Pure CSS Design) which is where these images below come from. Notice how the web page below degrades.

Webpage with CSS styling:
A web page with a CSS layout and design with a right-side bar

After disabling CSS:
A plain web page with no styling applied

New Article -> AJAX: Client Side Actions Before and After PostBack

I always enjoy reading articles from Rob Meade... his writing style is simple and easy to follow. State the problem (with real world example) > Show what doesn't work > Show the solution!

If you're new to AJAX, or want to get into it... take a few minutes to read: http://www.singingeels.com/Articles/AJAX_Client_Side_Actions_Before_and_After_PostBack.aspx

URL Re-Writing The Right Way (It's Easy)!

Recently (actually about 4 hours ago) I wrote a blog post about how to fake URL re-writing in ASP.NET. In fact, I even used that method on Eels for a long time as a very lazy work around until I decided how I wanted the structure of things to work. So, after writing that post, I realized the time had come and gone for allowing sloppy code, and that now I had to fix it.

Rather than writing the same thing twice (or copying and pasting), I've posted what I should have done in the first place on Eels. You can read it here if you are interested: http://www.singingeels.com/Blogs/Nullable/2007/09/14/URL_ReWriting_The_Right_Way_Its_Easy.aspx

URL Re-Writing (and how to FAKE it!)

SingingEels.com has a custom article engine and a custom blog engine which, like many others, uses a database to store the entries, but accesses them through friendly "named" urls such as : http://www.singingeels.com/Articles/Custom_Controls_And_Control_Builders.aspx

Well, someone emailed me (via the Suggestion Box on Eels) asking how I decided to handle that. So here is my reply email that gives away my cheating secret:

(My Email Reply Starts Here >>) Actually, you have a good question that I'll probably blog about later, but for now I'll let you in on my "url re-writing" secret... I cheat :)

When you submit an article on SingingEels (or a blog entry for that matter), I take the article "Title" text and I strip out all non alpha-numeric characters with a Regex. Basically it's as simple as:

string articleName = Regex.Replace(article.Title, @"[^\w]", "_"); // <-- replace all non-word characters with an underscore.

Then, when I insert the record into the database, I have a field called "ArticleName" to which I will use as the identifyer for the article (so I can pull it up later).
 
Now the only part that remains is knowing when (and how) to pull up that article and display it when someone comes to my site. Well, the "right" way to do this would be to make your own HttpHandler and skim through each request as it comes... but like I said, I cheat, so what I'm about to say is not the "right" way... it's just the easy way :P
 
In the "Global.asax" file in your web applications, you can tap into the "Application_Error" event (really it's a method). This method is called whenever there is an error in your application... including 404 errors for pages with the ".aspx" extension.
 
So, here goes some nasty cheating in ASP.NET:
 
void Application_Error(object sender, EventArgs e)
{
    // Hmmm, an error you say... that's funny, we don't even have
    // a page yet! This tells me that it's probably a "404" error
    // because the file they requested can't be found.
    if (this.Context.Handler == null)
    {
        // Hey ASP.NET, where *WOULD* the file be if one existed?
        string physicalPath = this .Request.PhysicalPath.ToLower();

        // Hmmm... that file *WOULD* be in my "Articles" directory!
        if (physicalPath.StartsWith(global_asax .articlesDirectoryPath))
        {
            // Don't worry lil-ASP.NET, I'll vouch for that request...
            // and I'll point it to the only real page in my "Articles" directory.
            this.Context.Handler = PageParser .GetCompiledPageInstance("~/Articles/Default.aspx",
                 Server.MapPath(
"~/Articles/Default.aspx"), HttpContext .Current);

            // Oh yeah, and ignore that lil 404 error, would ya?
            this.Server.ClearError();
        }
    }
}
 
Now, in my "Default.aspx" page in my articles folder, I check (in the "OnLoad" method) if there is an enrty in the database with the requested "articleName" (which I get from removing the extension from the RequestUrl and then strip out the non-alpha-numeric chars).
 
Then I just populate some basic placeholders and the like with the body of the article (or blog post).
 
Enjoy :P)
LINQ To SQL and Extension Methods

As I continue to use LINQ more and more, I'm learning some neat things that I never knew before (obviously)... so today's little "gotcha" was something that I found to be very insightful. Basically, without boring anyone with too many details, I made my own C# 3.0 extension method that adds a method to the System.String class that would allow me to return a "phone number" formatted string.

The reason for this is that we have our "PhoneNumber" field in the database as a VARCHAR(10) (meaning if you entered your phone number, it would be with no spaces, hyphons, etc). So, because the phone number would be returned in an ugly format - 9417080905 - my extension method would return it nicely formatted - (941) 708-0905.

Even though my code complied without errors, what I didn't know was that at runtime, LINQ to SQL would try to build T-SQL statements out of my LINQ expression including my custom function! Needless to say, there is no T-SQL equivilant for "ReturnAsPhoneNumber", so the whole thing bombed out :)

public IQueryable FindCustomers(string searchFirstName, string searchLastName, string searchZip)
{
    return from customer in MyLinqDataContext.Customers
        where customer.FirstName.Contains(searchFirstName)
            && customer.LastName.Contains(searchLastName)
            && customer.Zip.Contains(searchZip)
        select new
        {
            FirstName = customer.FirstName,
            LastName = customer.LastName,
            Zip = customer.Zip,
            PhoneNumber = customer.PhoneNumber.ReturnAsPhoneNumber()
        };
}

That above was my function, which would bomb out with this error: Method 'System.String ReturnAsPhoneNumber(System.String)' has no supported translation to SQL.

I thought that the string value would be returned, and THEN my "ReturnAsPhoneNumber" method would be called, but that's not the way LINQ expressions work. Instead, they translate all that above into SQL statements FIRST, and then they return the processed result set directly from SQL.

The solution? Simple... don't use an extension method. If I change the "PhoneNumber = ..." line slightly, it works fine. Example:

select new
{
    FirstName = customer.FirstName,
    LastName = customer.LastName,
    Zip = customer.Zip,
    PhoneNumber = ReturnAsPhoneNumber(customer.PhoneNumber)
};

That is totaly acceptable as far as LINQ is concerned... Learn something new every day!

Apple iPhone Hype Breads New Development Mentality

With the launch of the Apple iPhone, a lot of developers have refocussed their attention on smaller applications. Now, I'm not talking about programming for portable devices, but rather ASP.NET web applications that simply display smaller images and pages.

Because the iPhone comes with a full version of Safari, you don't have to develop "mobile apps" for them, you can just do a full web site. However, since the screen is smaller (and since it's a touch screen), some creative tools have come out of the wood work.

One developer in particular noticed that the built in calculator on the iPhone was lacking some features, so he built his own JavaScript version that seems to work out very well.

I think with all of the new and powerful tools Microsoft is coming out with (ASP.NET AJAX being one of the "prettiest"), a lot more people will be focusing on web development. I think the web is in for another boom.

Any Authors Out There (free article / blogging system)?

Since the launch of www.SingingEels.com about four months ago, we've had a few different developers from around the world contribute some nice articles to the development community. While I'm a firm believer in the "slow and steady" methodology of internet communities... I am still trying hard to find (and encourage) any of you developers out there to take a little time and formulate an article on a subject that you love. You can even get published on ASP.NET's front page (as 75% of our authors have been so far).

Eels has a custom built article engine that parses and highlights code to reflect the way VisualStudio does it. That and the images and file downloads makes it a pretty solid way to teach your topic. These two articles in particular that were very popular for a while (and were both published by ASP.NET) are good examples of contributions from developers like you:

Yuriy Solodkyy - Dynamically Created Controls In ASP.NET

Rob Meade - Populating Related Drop Down Lists With AJAX

Rob is currently finishing up his second article (also about AJAX), so I'm excited about that. But if there are any of you out there who are at the point in their programming career where you can actually help others by sharing your experiences, please SIGN UP! and share (either with the free blogging system, or better yet, an article).

Hope to see you there!

Posted: Sep 10 2007, 10:45 PM by Nullable | with no comments
Filed under:
More Posts Next page »