SingingEels : Development Community & Resource

Login

Articles

  • ADO.NET (2)
  • ASP.NET (36)
  • LINQ (4)
  • Security (2)
  • Silverlight (3)
  • 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!
Thursday, September 27, 2007 : 7:47 PM - (0 comments)

LINQ, Lambda 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.

This is very common and simple functionality and it could be done like this:

public int GetNumberOfSalesByZip(string zipCode)
{
   int totalSales = 0;

   foreach (Sale saleItem in this.Sales)
   {
       if (saleItem.Zip == zipCode)
       {
           totalSales++;
       }
   }

   return totalSales;
}

There's nothing wrong with that code above. It's very simple and straight forward. But I mentioned above that we could drop these 5 lines of code down by 80% (meaning, I'm about to pull this functionality out in a one liner here)! Let's see how we would do this same function using LINQ, and Lambda (and Extension Methods which I'll explain in a minute):

public int GetNumberOfSalesByZip(string zipCode)
{
   return this.Sales.Count(saleItem => saleItem.Zip == zipCode);
}

There you have it, one line of code. Now, if you are an avid .NETer you'll be quick to point out that arrays DO NOT have a function called "Count". This is true, but that's where Extension Methods come in. Just by making a reference to System.Linq (a "using" statement in C# or a "imports" statement in VB.NET) we will automatically get functions added on to EVERY array, generic list or other type of "IEnumerable" class. Here are some sample functions that I love:

  • Any - Returns true if any items meet the criteria.
  • Average - Returns an average of the field specified.
  • Count - Pretty straight forward (as shown above).
  • Where - Just like SQL, you can return a subset based on a condition.
  • OrderBy - Also just like SQL.

These are just a handful of the many functions built in just by switching to .NET 3.5.

Thursday, September 20, 2007 : 7:22 PM - (0 comments)

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.

LINQ to Mindset

One of the points that was stressed was that LINQ allows you to have a different mind set about how to "query" information. Jonathan brought out the fact that most people think of SQL when they hear LINQ. This kind of "pigeon hole" is reflected by a recent poll that was taken on this site. It showed that about 30% of developers are still leery of LINQ, and the biggest reason for that is the mentality that this is another SQL.

A few examples that he showed that take your mind off of LINQ to SQL were querying against the file system and against open processes (very interesting). Here is the gist of the first one:

var myLocalXmlFiles = from currentFile in Directory.GetFiles(@"C:\someFolder")
   where Path.GetExtension(currentFile) == "xml"
   select currentFile;

This is a very un-traditional way of thinking of a query, but that's the beauty of LINQ. Now, you might say that the System.IO.Directory class already has a way of returning a list of files with a certain extension, and that's true. But the beauty here is that you don't have to know of specialized functions that do standard query operations. And also, this next example has no better way of achieving the desired results:

var myProcesses = from dah_current_process in Process.GetProcesses()
   orderby dah_current_process.BasePriority descending
   select new
   {
       Name = dah_current_process.ProcessName,
       Instance = dah_current_process
   };

That example above uses the new "annonymous types" that are in both C#-3 and VB-9 (.NET framework 3.5). Almost all of his examples used some sort of new feature from Visual Studio 2008. He mentioned that he's going to try to put his powerpoint material and some samples up on his site (which is still heavily under construction). Here's the link, I don't know if it's ready yet: Lost In Tangent

The Future With Astoria

Another topic that he discussed (briefly due to time constraints) was one of Microsoft's upcoming projects, Astoria. There wasn't much to say at this point, but what he demonstrated has huge potential. Here's a link if you'd like to see more: Astoria Online Service. If I'm not mistaken, Jonathan will be traveling to meet with some of the Astoria team to learn more... so we'll stay tuned on that.

In other exciting news, I won a full copy of Microsoft Office 2007 that night (random number generator picked me!), so I have to say my first Sarasota development group experience was a great one!

Wednesday, September 19, 2007 : 7:38 AM - (0 comments)

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!

if (this.PhoneNumberTextbox.Text.IsPhoneNumber() == false)
{
   // Display some error message...

}

Or how about this:

if (this.BidPriceTextBox.Text.IsDecimal() == false)
{
   // Display some error message...

}

Now, you could say that I could just use a RegularExpressionValidator (which I could) to accomplish those above functions. But, when inserting the item into a database, I can also do this:

DataAccessLayer.UpdateBidPrice(this.BidPriceTextBox.Text.ReturnAsDecimal());

How to Make an Extension Method

It's really easy to make your own extension methods. Basically, you just make a public static method on ANY CLASS in your project and you make the first parameter be the type that you want to "extend" (which in my examples above I'm extending the "string" type). Also, you need to add the "this" keyword. Here's how to make my "ReturnAsDecimal" method above:

public static decimal ReturnAsDecimal(this string input)
{
   decimal result;

   return (decimal.TryParse(input, out result)) ? result : 0;
}
Saturday, September 15, 2007 : 8:04 AM - (0 comments)

File downloads & image bugs fixed!

Recently we've made a few changes to the site that caused some images not to appear and nearly all file-download links to be broken. We've since then fixed the issue (as it was brought to our attention via the suggestion-box).

The problem was with the way we are handling our "URL Rewriting" scheme now (as is reflected in my last blog post). Basically, when I made the change that I stated in my last article, Eels would try to translate "UserImage.aspx" and "UserFile.aspx" into articles and since those are real pages, not articles in the database, the site would redirect you back to the home page.

Thanks again for those of you who brought the issue to our attention, and I'm gald it was a quick fix!

Friday, September 14, 2007 : 12:05 AM - (2 comments)

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.

So, I wanted to recap what I did in order to map your own HTTP requests, and how I've now fixed my bad ways (and how easy it was to do so). So, first of all, what I was doing before was tapping into the "Application_Error" method in the Global.asax file. If an exception was thrown in my web app, and there was no "Handler" assigned (which happens in a 404 scenario), I would then check the URL and if it was an attempt to read an article, I would redirect them to the right page myself.

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();
       }
   }
}

This was a very poor design and was supposed to only be a work around until I decided how I wanted the structure of Eels to be. Well, months have passed and now I've fixed the above to do what I should have done in the first place - make my own HttpHandlers. So here is what I added to my web.config:

<httpHandlers>
   <add verb="*"
       path="Articles/*.aspx"
       type="EelsArticleHandler" />
</httpHandlers>

And here is my HttpHandler class (which I have in my App_Code directory of course):

using System;
using System.Web;
using System.Web.UI;

public class EelsArticleHandler : IHttpHandler
{
   public bool IsReusable
   {
       get
       {
           return false;
       }
   }

   public void ProcessRequest(HttpContext context)
   {
       context.Handler = PageParser.GetCompiledPageInstance("~/Articles/Default.aspx", context.Server.MapPath("~/Articles/Default.aspx"), context);

       context.Handler.ProcessRequest(context);
   }
}

I guess doing things the right way isn't that hard now is it :)

Tuesday, September 11, 2007 : 11:03 PM - (0 comments)

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!

Saturday, September 8, 2007 : 8:25 PM - (0 comments)

Downloading and uploading to an FTP the easy way!

One of my biggest passions when it comes to programming has always been communication between computers (and networks), whether it be with raw communication with Sockets, Web Services, remoting or whatever. Just the thought of all that's going on behind the scenes to "connect" everyone together really blows my mind.

Along that line of thought is one of my favorite classes in the .NET framework, the WebClient class (in the System.Net namespace). I've always known of this class to upload and download files from a web server, but you can also use it for FTP servers too.

So without boring with too much talking, I'll show you how easy it is with some code:

// Make an instance of the WebClient class.
WebClient myLilWebClient = new WebClient();

// Since my FTP requires authentication, I'll have to supply my

// UserName and Password.

myLilWebClient.Credentials = new NetworkCredential("userName", "p@ssw0rd");

// Now I'll download a file from my FTP right to my desktop.

myLilWebClient.DownloadFile("ftp://myFtpAddress.com/somefile.txt", @"c:\documents and settings\tkhouri\desktop\somefile.txt");

I don't think it could get any easier than that! Oh, and if you wanted to Upload a file to an FTP... you'd simply call mYLilWebClient.UploadFile.

Gotta love .NET!

Saturday, September 1, 2007 : 7:51 PM - (1 comment)

301 Redirects For SEO And PageRank!

The company that I work for has hired a consulting agency to review our public website and make suggestions for search engine optimization (SEO) and other things. Since I've been in the web marketing field in a previous job, I already have a strong grasp of a lot of the key concepts. But one of the suggestions that they made was something that I didn't know how to do with ASP.NET until now.

301 Redirects in ASP.NET

A "301 redirect" tells browsers and search engines that a resource has been PERMANENTLY moved to another location. This is useful in domain canonicalization (which is a big word that basically means "www" and "non-www" are counted together). So here's the code that I added in my Global.asax file for SingingEels that will ensure that "singingeels.com" will redirect to "www.singingeels.com" as I want it to. Not only will it redirect, but it will add the appropriate "301" header which will tell Google, Yahoo, MSN, ASK.com (and any other search engine) to credit any links or info that they have to the main URL.

Here's how I did it in C# in my Global.asax file:

void Application_BeginRequest(object sender, EventArgs e)
{
   if (this.Request.Url.Host == "singingeels.com")
   {
       UriBuilder redirectToBuilder = new UriBuilder(this.Request.Url);

       redirectToBuilder.Host = "www.singingeels.com";
       
       this.Response.Status = "301 Moved Permanently";

       this.Response.AppendHeader("Location", redirectToBuilder.ToString());
   }
}

I intentionally do not do a "Response.End" after that in case the browser or search engine doesn't know how to do the redirect. But what this does is it makes it so ANY request that comes to my application under the "singingeels.com" domain will be moved to "www.singingeels.com". I also intentionally chose to only redirect that one domain for now.

Saturday, September 1, 2007 : 8:51 AM - (0 comments)

How to Teach New Developers About Programming

We've hired another entry level developer at my company who is "computer savvy", but has never done programming before. Well, he's done a little PHP, but that's about the extent of it. His job requirements are very basic, but of course we want everyone to expand in their skills and "move up" (both in the company, and in productivity).

Since I've been programming for several years, I figured it would be an easy task to teach someone how to program. But for a while I've been almost at a complete loss as to how to begin. The problem is not with the new guy as he is very quick to learn and remember things, but rather the problem is with me not being able to relate to "I have no idea what I'm doing, or why I am typing this code."

My Failed Attempts

I figured at first that we should start of in a C# console application. That seemed to me to be the "easiest" thing to do. A few basic "Console.WriteLine" calls, maybe change the BackColor of the console, read a string with ReadLine - things like that. But as I was telling him what to do and explaining what we were doing, I realized that this was not working.

Console applications (while easy to make) are not very intuitive to new developers. So I figured since he had done PHP, we should do some web development. That worked out a little better, but "inline" languages like PHP, ColdFusion and 'classic' ASP are such a far cry from real object-oriented programming with ASP.NET that it was still a little difficult.

The Break-Through

What helped the most was when one of the other developers (who is aiding in his training) tasked the new guy with building a program that would connect to an FTP and download all the files in a specified folder (specified in a TextBox by the user). So Windows Forms Programming was the way to go here.

Even though I didn't think this was the best choice at first, I'm starting to see how easy it is to explain programming due to the very "interactive" way Windows forms are. Think about it; you drag a button on your form, you name it, you double-click it (which in Visual Studio will wire up a "Click" event for you), and then you write code in the MyButton_Click code block. Now things are making sense. "OK, when I click this button, then my code will run... cool!"

If you have new developers, or if you are trying to teach someone about programming (or how to program), you might want to try this approach.

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 Jan 06 2009 - 03:15:02 AM - (0.078123)