Some more LINQ love

by Jon Sagara Thursday, June 4 2009 3:32 PM

Here's another example of how I feel LINQ improves the readability of my code. This is the before version, using standard looping to populate a list of objects:

private IEnumerable<Album> ReadAlbums(LLAlbum[] llAlbums)
{
	Album album;
	IList<Album> albums = new List<Album>(llAlbums.Length);

	foreach (LLAlbum llAlbum in llAlbums)
	{
		album = new Album()
		{
			AlbumId = llAlbum.Id
		};

		albums.Add(album);
	}

	return albums;
}

And here is the after version, using a LINQ query:

private IEnumerable<Album> ReadAlbums(LLAlbum[] llAlbums)
{
	return from llAlbum in llAlbums
		   select new Album
		   {
			   AlbumId = llAlbum.Id
		   };
}

Now, depending on your familiarity with LINQ, you may or may not agree with me, but I love it!

Tags: , ,

Blog

Project Euler: Problem 1

by Jon Sagara Saturday, May 23 2009 12:32 PM

I just put my son down for a nap, so since I had a little spare time, I thought I'd try my hand at Project Euler.

Problem 1 was very simple. Right off the bat, I knew how I wanted to solve it:

int sum = 0;
for (int ix = 0; ix < 1000; ix++)
{
	if (ix % 3 == 0 || ix % 5 == 0)
	{
		sum += ix;
	}
}

However, I've been reading Jon Skeet's excellent book, C# in Depth, so I wanted to see if I could solve it using LINQ:

int sum = Enumerable.Range(0, 1000)
	.Where(x => (x % 3 == 0 || x % 5 == 0))
	.Sum();

It still looks weird to me, but it works, so who am I to complain? :)

Tags: , , ,

Blog

ELMAH 1.0 Beta2 to 1.0 Beta3 upgrade gotcha

by Jon Sagara Thursday, December 11 2008 10:24 PM

In one of my projects, I upgraded ELMAH from 1.0 Beta2 to 1.0 Beta3.  I have 404 filtering turned on so that my log doesn't get flooded with 404 notifications (usually caused by legitimate, albeit a tad overzealous, monitoring applications).  Here is what the Web.config element looks like for Beta2:

<equal binding="HttpStatusCode" value="404" valueType="Int32" />

All of a sudden, when I fired up my site, I started getting a weird error message:

The Empty value type is invalid for a comparison.

It turns out that the XML schema has changed ever so slightly in 1.0 Beta3.  To fix the aforementioned error, you must change the "valueType" attribute to "type", like this:

<equal binding="HttpStatusCode" value="404" type="Int32" />

Hopefully this will save someone some pain. 

Tags: , ,

Blog

Ordered a new computer

by Jon Sagara Wednesday, November 19 2008 12:24 AM

But it can't get here soon enough.

I'm currently doing development on two machines, one with 512MB of RAM, and the other with 1GB.  It is PAINFUL.  Plus, on the latter, I'm running out of space on the OS drive, which makes it difficult to do anything at all.

The new box sports 4GB RAM, 500GB of disk space (and I'm going to add second 500GB drive), and a Quad Core that will eventually run Windows Server 2008.

I feel like a little kid again, waiting in agony for xmas day to come.

Tags:

Blog

A sign you've been working too many hours lately

by Jon Sagara Sunday, August 31 2008 8:29 PM

You get sloppy and write something like this:

if (string.IsNullOrEmpty(campaignId))

{

    throw new Exception(string.Format("Missing campaign ID in the query string: {0}", campaignId));

}

D'oh.

Tags:

Blog

Enumerating HttpModules

by Jon Sagara Sunday, August 24 2008 12:33 PM

One common ASP.NET performance tip is to remove any HttpModules that your application does not use.  You can take a peek at which modules are loaded by the framework on your behalf by examining the framework's Web.config file, but how do you find out which modules are actually loaded in the current context?

Fortunately, the HttpApplication instance provides a Modules collection that you can loop through:

// Get a collection of modules loaded for the current context.

HttpModuleCollection modules = HttpContext.Current.ApplicationInstance.Modules;

 

// Enumerate the loaded HttpModules and do something with them.  For example, you can

//  create a table, listing each module by key and full type name.

// NOTE: the key is the same key specified in Web.config to add the module.

foreach (string moduleKey in modules.Keys)

{

    IHttpModule module = modules[moduleKey];

 

    // Do something with the module key and/or the HttpModule.

}

You can then use the Modules collection create a table like this:  

And boom, there you have it: a list of HttpModules that are loaded for the current context.  You can use this information to determine which HttpModules are needed by your application, and which ones you can safely remove.

Tags: ,

Blog

Organize Usings

by Jon Sagara Sunday, August 24 2008 12:09 PM

In Visual Studio 2008, when you add a new Web form to your project, the "using" section of the code-behind contains a lot noise:

using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

You may very well need some of those namespace declarations, but odds are high that you don't need them all.  But which ones can you remove without breaking your page?

Visual Studio has a nice feature called Organize Usings, which you access by right-clicking anywhere in the code-behind page.  The menu looks like this:

When you click on "Remove and Sort", it removes any unused "using"s and sorts those that remain. 

So now, instead of the mess that we had before, we have a much cleaner "using" section in our source code file:

using System;

Pretty slick, huh?

Tags: ,

Blog

try/swallow

by Jon Sagara Thursday, August 21 2008 10:33 AM

Dear fellow coders,

Please don't ever do this:

private static void SomeFunc()

{

    try

    {

        DoSomething();

        DoSomethingElse();

    }

    catch

    {

        // eat the exception  <-- NO!  BAD CODER!

    }

}

Love,

Jon

Tags: ,

Blog

Microsoft Velocity

by Jon Sagara Tuesday, June 3 2008 10:33 AM

I've always been surprised that Microsoft never offered a distributed caching mechanism out of the box.  Their built-in ASP.NET caching works well, but only on one box.  memcached can run on Windows boxes, but for all intents and purposes, you're on your own if you choose to implement it.  There is at least one third party product I know of that can fill this space, but it is quite pricey.  Today, at last, Microsoft has announced a project codenamed "Velocity" that will be their distributed caching story for .NET:

Project “Velocity” is a distributed in-memory application cache platform for developing scalable, available, and high-performance applications. “Velocity” fuses memory across multiple computers to give a single unified cache view to applications.

Even though I have no immediate use for distributed caching, I certainly see the need for it.  I can't wait to muck around with it and see what it can do.

Tags:

Blog

HttpValueCollection.ToString() generates your nice query strings

by Jon Sagara Saturday, May 24 2008 6:43 PM

In an ASP.NET page, if you call Request.QueryString.ToString(), you'll get a nicely formatted query string back, like this:

 my=query&string=value&foo=bar

"That's nice," I thought.  "I wonder how they implemented it.  I'll fire up Reflector and take a look."

However, when you look at the declaration of QueryString in HttpRequest, you'll see that it is of type NameValueCollection, a class that has no ToString() override; at first glance, it looks like you'd simply be calling System.Object.ToString().

Obviously, this is not what is happening, so to find out how the query string is being generated, I had to dig just a little bit deeper.  Fortunately, VS2008 lets you step into the framework.

When you step in you'll see that HttpRequest.QueryString is indeed defined to be of type NameValueCollection, but when it actually gets instantiated, it is initialized to be of type HttpValueCollection, an internal class that derives from NameValueCollection. 

HttpValueCollection has a ToString() override that does the dirty work of constructing the nice query string that you see at the top of this post.

I'm so glad that Microsoft decided to allow us to step into the framework source code.  Otherwise, I probably would have spent a good hour trying to track down the magical NameValueCollection.ToString() call.

Tags:

Blog

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen