11/29/2007

Warning!: blockdelete.com- Protect Your Ass!

Those nasty spammers have apparently reappeared, using a private domain registration through GoDaddy.

What they do is capture your Windows Live Messenger credentials under the ruse that they will show you all your blocked contacts (which is easy enough to do yourself with libraries like DotMsn - without the security risks).

What they don't tell you is that if you do this, your account is now compromised -- and they'll send every one of your contacts a message (since it's your credentials, it appears from you, a trusted contact) that tells you to go visit their site and sucker for it too. There's only one solution if you suckered for it - you have to change your Live.com password immediately.

Just look at this:

"The longly[sic] awaited feature for MSN Messenger, completely for free[sic]!"

When you click on their Privacy page link, you get nada! What a scam. Unfortunately, from reading the newsgroup and forum posts, it appears that thousands of people are getting suckered for this social engineering scam from these total scumbags.

I'm seriously considering complaining to Google about this, because the bastards have a Google Adsense ad at the bottom of their page. Clearly a violation of Google's TOS. If enough people complain, Google will ban them and they'll have no financial incentive any longer. Incidentally, Google has recently begun actually soliciting reports of "bad" web sites. The form to do it is here. You can also visit Stop Badware, a consumer protection site sponsored by Google and other major firms.

We live in a dangerous world. Even cyberspace is dangerous. Protect Your Ass.

Getting the right client-side ID for ASP.NET Controls

This is really simple stuff, but judging by the number of forum and newsgroup posts I've seen asking the same question over and over again, it may not be very obvious to many newer developers: The ASP.NET infrastructure "mangles" control ID's based on the container hierarchy they are in. So for example if you have a Master Page and a Page that uses it, and you put a TextBox "TextBox1" on it, that's not what you'll get at the client side in the browser. So any javascript you write that is looking for "TextBox1" will fail. Here's the correct way to ensure that your script won't fail:

11/27/2007

The Top Nine Social Networking Sites

Q: Who was the pitcher to pitch the only perfect game in the World Series?
A: Don Larsen, October 8, 1956, as the New York Yankees beat the Brooklyn Dodgers, 2-0.

I've seen a few compilations on this subject, but the methodology in some cases seemed either flawed or not objective enough (surprise), so I though it would be useful to conduct my own research piece. If you take the "authority" approach on this, it makes it a lot easier to rank these various sites and eliminate the vast majority since they simply aren't strong enough to appear on the radar.

Basically I got lists of networking sites and did a Google PageRank on all of them. Everything below PageRank 7 was thrown away. That narrowed down the field to 9 sites (boy, that part was easy!). Then, I got the Quantcast.com visitor counts and the Compete.com visitor counts. Then I compiled a composite number of inlinks for each site. Finally, I got the Alexa rank for each.

What I did then was to try and come up with a "fair is fair" composite number that indicated the authority and value of each site. I added the inlinks, the Quantcast, and the Compete totals. This was then divided by the Alexa rank (divide, because the lower the Alexa number, the stronger the site). Then the computed result was multiplied by the PageRank to get a final "score".

One could certainly make the case that using Google PageRank to eliminate contenders has its flaws, but since Google drives up to 90% of search traffic, and since the SERPS (search engine results position) of what you're searching for is so much determined by PageRank, I felt it was, at the least, an educated starting point.

As can be seen in the table below, digg.com is the clear leader, with del.icio.us running a close second place. Technorati is actually a much stronger contender than I thought it would be. And, for example, while Slashdot sports a PageRank 9, its composite number just doesn't add up to make it even into the top 5.

Now, you may ask, "How can this help me"? Well, from an SEO standpoint, these top 9 sites represent the vast majority of "link juice" you can get. So if you focus on submitting and getting your "Stuff" - your articles, your site, your blog -- into these 9 and forget about the others, you are going to make your SEO optimization job one heck of a lot easier. You'll get a lot more "bang for the buck". Also, it makes it much easier to track where your referrer traffic is coming from.

In fact, I like this "short list" so much that I've put together another one of those "Social Link This" apps, a link to which you can find at the bottom left of each post on this UnBlog. There's a javascript "bookmarklet" for it that you can drag to Bookmarks or Add to Favorites. Using the page or the bookmarklet from your browser, you can submit your blog post, article or site to all nine of these top contenders in less than five minutes and get some serious link juice!

I present the sorted result for your viewing pleasure:

SITEINLINKSCOMPETEQUANTALEXAPRSCORE
digg.com11779608316964445870000098811711064
del.icio.us1715930511699128130000024885632006
Technorati.com753064373231709140000021682960672
StumbleUpon.com1905017713135866952393008561573
Bloglines.com507179483826631037118539540257
Netscape.com2158160048552328180175559441971
reddit.com4530757712264673443838527385151
Slashdot.org135550357244242698845799226156
Furl.net49595144148975575474112896890

11/25/2007

Visual Studio 2008 Solution / Project File Conversions And Tricks

"Always do sober what you said you'd do drunk. That will teach you to keep your mouth shut"
-- Ernest Hemingway

One thing I've learned to do pretty quickly with VIsual Studio 2008 is to make a backup of the original Visual Studio 2005 .soln and .csproj files and store them in a little .rar or .zip file in the Solution folder. This makes it easy to "go back to the future" as long as your work doesn't include namespaces that don't exist for VS 2005. Yes, I know you can choose to make a backup during the conversion. I'd just rather be safe.

I also learned that the conversion process when you load a 2005 Solution and go through the conversion wizard can be quite slow. Here's a neat way to speed it up. Devenv.exe has a /convert flag. So, make a little batch file that looks like this, and save it in your Solution / project folder:

"C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe /convert" %1

To run this, drop into a Command prompt in your solution folder, then type convert mysolutionname.sln or convert myprojectname.csproj

This command line conversion process is humongously faster. When I say "humongously" - I mean it is WAY FASTER!

The differences between .sln files in the two Visual Studio versions are not that great. Same with project files - anything that goes wrong can usually be fixed "by hand".

Hopefully, somebody will come out with a little back-and-forth conversion utility that will retarget a converted to 2008 solution and project files back to 2005.

I'm not gonna write it, but I know somebody will - soon!

BTW, if you are having any installation issues regarding Visual Studio 2008, here is the forum to visit!

Link of the Day:

If you create code-comment documentation (and you certainly should!) then you can't live without Roland Weigelt's GhostDoc. The Visual Studio 2008 Add in is ready. Roland used some of my code (with my happy permission) in an earlier release.

Google Suggest on your Google Home Page:

Google has an experimental page that let's you set your search textbox to display Google-Suggest like matches when you type in a search. Great for SEO keyword suggestions!

11/23/2007

419 Redux: Scamming the Scammer

Recently I've noticed a significant increase in the number of 419 scam emails that land in my junk mail folder before I clean it out daily - and occasionally a few don't even get dumped into the junk mail folder - they end up directly in the inbox!   Most of us already have learned to trash this utter bullshit, but it's a numbers game. The scammers know that if they send out 50,000 of these at a time (and believe you me, that's exactly what they do) -- that some poor uninitiated soul will respond, not knowing any better. And unwitting respondees do lose real money to these scumbags. As an old commodities trader once advised me as a rookie broker - "There are only two factors that control the market - fear, and greed" - and these scammers are finely honed experts at working the greed factor.

For those who aren't totally familiar with the iterations of this scam, it operates as follows: the target receives an unsolicited fax, email, or letter often concerning Nigeria or another African nation containing either a money laundering or other illegal proposal OR you may receive a Legal and Legitimate business proposal by normal means. Common variations on the Scam include "overinvoiced" or "double invoiced" oil or other supply and service contracts where your Bad Guys want to get the overage out of Nigeria (that's the Classic 419); crude oil and other commodity deals (a form of Goods and Services 419); a "bequest" left you in a will (Will Scam 419, e.g. the bank depositor died in a horrible plane crash - complete with links to the CNN.com article); "money cleaning" where your Bad Guy has a lot of currency that needs to be "chemically cleaned" before it can be used and he needs the cost of the chemicals (Black Currency 419) ; "spoof banks" where there is supposedly money in your name already on deposit; "paying" for a purchase with a check larger than the amount required and asking for change to be advanced (cashier's check and money order 419); fake lottery 419; chat room and romance 419 (usually coupled with one of the other forms of 419); employment 419 (including secret shopper 419) ; and ordering items and commodities off "trading" and "auction" sites on the web and then cheating the seller. The variations of Advance Fee Fraud (419) are very creative and virtually endless - the above is only a brief summary of possibilities.

.NEXT Web Security Services has a flow chart of how these deals pan out. At a minimum, it should be worthwhile web browsing.

The 419eater is a vigilante group that deliberately targets and foils the scammers. Just reading about what they do will warm your heart and give you some good chuckles. They are for real; you might consider giving them a small donation if you aren't inclined to become a professional scam - baiter.

Happy Thanksgiving Weekend, and don't be a Turkey.

11/21/2007

New .NET Service Packs Available

Microsoft .NET Framework 2.0 Service Pack 1 (x86):
http://www.microsoft.com/downloads/details.aspx?FamilyID=79bc3b77-e02c-4ad3-aacf-a7633f706ba5&DisplayLang=en

Microsoft .NET Framework 2.0 Service Pack 1 (x64):
http://www.microsoft.com/downloads/details.aspx?FamilyID=029196ed-04eb-471e-8a99-3c61d19a4c5a&DisplayLang=en

Note that the 2.0 Service Pack is actually a full Framework install. If you uninstall .NET 2.0 SP1 (even if you had .NET 2.0 installed beforehand) the whole .NET Framework is removed.
It does NOT revert you back to .NET 2.0 RTM.

Microsoft .NET Framework 3.0 Service Pack 1:
http://www.microsoft.com/downloads/details.aspx?FamilyID=ec2ca85d-b255-4425-9e65-1e88a0bdb72a&DisplayLang=en

When you install the .NET Framework 3.5, these service packs are required prerequisites and are installed automatically; these are available as separate downloads for those who aren't ready to deploy .NET Framework 3.5.

If you are installing Visual Studio 2008, you don't need to worry about the above.

Incidentally, if you want to keep up with Microsoft Downloads, this search page is a good way to do it:

http://www.microsoft.com/downloads/Results.aspx?displaylang=en&startDate=10/22/2007&period=30&nr=50

Note the "startdate" and "nr" in the querystring. I haven't found an RSS feed for this but it sure would be useful.

Links of the Day:

Temporarily Block Popups in IE 7.0 for downloading:

http://www.pluralsight.com/blogs/craig/archive/2007/11/21/49253.aspx

The trick is to hold down CTRL and ALT while clicking the link.

Grasshopper enables you to produce .NET Web and server applications that run on Linux & other Java-enabled platforms using ASP.NET 2.0 controls, role-based security, and C# generics.

Quick PageRank Bookmarklet: Add this to Favorites to get quick Google PageRank of any page you are on:



Quick PR Bookmarklet

11/16/2007

Visual Studio 2008 RTM - and Holiday Chili Recipe

"The kind of pictures they're making today, I'll stick with toilet paper" -- Dick Wilson (Mr. Whipple, R.I.P.)

Well, it's Monday AM Nov 19th and the good news is that VS 2008 RTM is available for download by MSDN subscribers. The bad news is that the traffic jam has long since started, so it's not likely too many people will be able to get their copy today. (Oops - spoke too soon, just got an FTM going at 8:50 AM)!

Also available is the Visual Studio 2008 and .NET Framework 3.5 Training kit. http://go.microsoft.com/?linkid=7602397 (120MB). This includes presentations, hands-on labs and demos -- and is designed to help you learn how to utilize the Visual Studio 2008 features and a variety of framework technologies including LINQ, C# 3.0, Visual Basic 9, WCF, WF, WPF, ASP.NET AJAX, VSTO, CardSpace, SilverLight, Mobile and Application Lifecycle Management.

There are some very specific instructions on what to do if you have pre-release versions of VS or any related programs:

--------------------------------------------------------------------------------------------

For best results, Visual Studio 2008 should be installed on a computer with no pre-release (Tech Preview, Beta, or CTP) versions of Visual Studio 2008/Codename Orcas, or supporting components.
If your computer has any of the pre-release (Tech Preview, Beta, or CTP) versions on it, they must be removed in the correct order BEFORE you begin installing the release version. This process is not officially supported. It is recommended that you run uninstall of the main product first (Microsoft Visual Studio 2008/Codename Orcas). In most cases this will remove majority of other optional pre-release components installed with it.
Go to the Control Panel and launch Add/Remove Programs
Remove all instances of Visual Studio 2008/Codename Orcas products
Remove any remaining supporting products in the specified order.
Remove "MSDN Library for Visual Studio 2008 Beta"
Remove "Microsoft SQL Server Compact Edition 3.5"
Remove "Microsoft SQL Server Compact Edition 3.5 Design Tools"
Remove "Microsoft SQL Server Compact Edition 3.5 for Devices"
Remove "Microsoft Visual Studio Performance Collection Tools"
Remove "Windows Mobile 5.0 SDK R2 for Pocket PC"
Remove "Windows Mobile 5.0 SDK R2 for Smartphone"
Remove "Crystal Reports 2007"
Remove "Visual Studio Asset System"
Remove "Microsoft Visual Studio Web Authoring Component / Microsoft Web Designer Tools"
Remove "Microsoft Visual Studio 2005 Tools for the 2007 Microsoft Office System Runtime"
Remove "Microsoft Visual Studio 2005 Tools for the 2007 Microsoft Office System Runtime Language Pack" (non-English editions only)
Remove "Microsoft Visual Studio Tools for Office Runtime 3.0"
Remove "Microsoft Document Explorer"
Remove "Microsoft Document Explorer 2005 Language Pack" (non-English editions only)
Remove "Microsoft Device Emulator 3.0"
Remove "Microsoft .NET Compact Framework 3.5"
Remove "Microsoft .NET Compact Framework 2.0 SP1"
Remove ".NET Framework 2.0 SDK"
Remove "Microsoft Visual Studio Codename Orcas Remote Debugger"
Remove "Microsoft Visual Studio 64bit Prerequisites Beta" (64-bit platforms only)
Remove "Microsoft .NET Framework 3.5"
Install the Visual Studio 2008 edition you wish to use

--------------------------------------------------------------------------------------

So, the best advice is always "RTFM". Don't complain if you didn't! You also need to "use your noodle" with these instructions- for example, one item in the above list says "Microsoft .NET Compact Framework SP1". If you have "SP2" - you still need to uninstall it!

NOTE: Visual Studio 2008 Solution (.sln) files are NOT backward-compatible with VS 2005 Solution files, but the project (e.g. .csproj) files are compatible. So if you need to be able to work on Solutions that you've migrated up to Visual Studio 2008 in Visual Studio 2005, all you should need to do is save a copy of the original Visual Studio 2005 .sln file, say as "mySolution2005.sln". You will have two Solution files, one for 2005, and one for 2008. As long as your solution doesn't use .NET 3.5 namespaces that aren't present in 2005, you should be "good to go". Jon Skeet has an excellent post that explores this in it's various iterations. His conclusions:

  • It's possible to share project files but not solution files between VS2005 and VS2008.
  • If you upgrade a solution file by mistake, it's very easy to fix it by hand.
  • If you decide to maintain different solution files, if there are big changes in one it may be easiest to just make them in one solution, then upgrade again.
  • Creating a project in VS2005 and then importing it into VS2008 is seamless; the other way round has slight issues which are fixable by hand.
  • I don't know of a way of forcing VS2008 to only use C# 2 while at the same time maintaining VS2005 compatibility.

NOTE2: During installation, some users may see dialogs that inform you to kill certain processes and a cryptic number is shown. This is the PID of the process. If you go into Task Manager and enable the PID column, you will see the PID represents "Setup.exe". You may safely ignore this and choose the option that lets you "continue" or "skip". Unfortunately, Setup halts until you make a decision on this dialog, so if you were planning to go get a nice spaghetti dinner with some wine, you'll need to bring it home to eat in front of your computer...

DO I STILL NEED 2005?: If you decide you are happy with Visual Studio 2008, there is really no need to keep Visual Studio 2005 around any longer -- 2008 can target the build runtime back to Framework 2.0. Aside from the Solution file issue addressed above, you can safely consider Visual Studio 2005 history! Users that need to maintain Visual Studio 2003 projects that target Framework 1.1 may not be as lucky - but somebody will probably come up with a simple converter app to keep solutions and project files in sync. One thing I'll say is this: there are a lot of bug fixes and performance enhancements in Visual Studio 2008 - and when I click the icon to start it, that sucker comes up ONE HELL of a lot faster than VS 2005 does!

On my system, the uninstallation of all the BETA 2 2008 "Stuff" that I had on there, and installation of Visual Studio 2008 RTM did not interfere with the operation of the existing Visual Studio 2005 installation in any way.

Finally, if you want to know where to go for help, try the Visual Studio Installation Forum on MSDN.

Now here is something fun for the holidays while you are waiting for your downloads to complete (or, er, to start):

Pete's Real Jewish Nuclear Bomb Vegetarian Chili [Beta 3 Version]

In the spirit of the Holidays, I thought it would be a nice gesture to post once again my secret family recipe for Vegetarian Chili that's been handed down over several thousand years by members of the Bromberg Tribe. This is great food for programmers, all the endorphins released into your brain by the cayenne and other pepper - type ingredients will enable you to solve virtually any programming challenge in near- record time! Wishing you a happy and productive 2008!

Pete's Real Jewish Nuclear Bomb Vegetarian Chili petechili

* Six large tomatoes, cut up in chunks
* One large can stewed tomatoes, DRAINED
* One large Onion, sliced
* Two large Green peppers, sliced
* One large Red pepper, sliced
* Two large cans black beans
* Two large cans dark red kidney beans
* Six large roasted jalapeno peppers, diced (canned is OK)
* Plenty of Mexene chili powder (you decide how much by taste)
* Fresh cilantro, chopped (about 20 stalks should be right)
* One large can tomato sauce
* One can tomato paste
* One 16 oz can beer (or about 8 oz good Vodka)
* 2 squares unsweetened Baker*s chocolate
* Three or four large cloves of fresh Elephant Garlic, diced
* Coriander seed (optional)
* Cayenne Pepper (optional)
* Cumin Powder (optional)
* A cup of raisins (optional)
* Six tablespoons extra-virgin Olive Oil

Throw a VERY BIG pot on the stove, turn up the flame, and throw in the Olive oil, the garlic, and the onions. Stir so as not to burn until the garlic and onions have started turning brown.

Throw in the green and red peppers and continue to cook until they are nice and soft. Now throw in the chopped tomatoes and cook some more.

Throw in the tomato sauce and some of the tomato paste, and the chopped jalapeno peppers. Throw in the cilantro. Stir it all up good, you don't want it to burn. Throw in the stewed tomatoes.

If it's starting to look like its getting cooked (about 20 - 30 minutes), then throw in all the beans, some of the beer, and the chocolate and as much of the Mexene chili powder as you dare (a good start would be six heaping tablespoons [I did say 'Nuclear Bomb', didn't I?] , unless you plan on using the optional cayenne, coriander and cumin).

You want to cook this so it looks like it's almost ready to boil,'(but not so high that the bottom layer burns) stirring it up good from the bottom every two minutes.' You want it to thicken up so it really looks like it has meat in it (believe me, when you tell people this is NO FAT VEGETARIAN, they won't believe you). If it's too watery you can add the rest of the tomato paste, or even throw in a whole new can of paste.'' If you've really screwed up and its still too watery, you can throw in some cornstarch. But --don't worry! It always comes out right!

If it's too thick, throw in more beer. If it's not NUCLEAR HOT, then throw in more chili powder, jalapenos, cayenne, coriander, etc.' I even put Louisiana Garlic Hot Sauce in mine, gives it a unique 'winey' taste. Don't forget to throw in your raisins last. You can even throw in some chopped nuts, gives it a nice crunch. Walnuts or Pecans are great. Now, if you aren't a beer lover, about 6 ounces of your favorite Vodka will give it a nice flavor. Don't worry about the alcohol, it all burns off during the cooking.

After this stuff has cooked about 45 minutes to an hour, turn off the heat. You are done.

Serve PETE'S NUCLEAR BOMB CHILI with some grated cheese and / or sour cream dolloped on top and bread or garlic bread on the side.' If people complain it's too hot, then serve some over rice for them. This goes down great with ice cold beer. You can eat two big bowls of this, and you'll wake up the next morning feeling like a million bucks. This stores great in a covered plastic thingy in the Fridge, and people tell me it actually tastes better on the second and third day after being reheated. Feeds six or more, its a whole meal.

RoundHouse Kick Politics Department

I see where Mike Huckabee has a campaign TV ad featuring Chuck Norris. Oh boy. I told you this Presidential Campaign may go down in history as being the most unremarkable ever. But wait! I just heard Hillary, not to be outdone, is getting one ready with Michael Moore!

11/06/2007

Pattern Madness, Anyone?

Here is an interesting newsgroup post that illustrates a common problem of programmers (usually new ones, but - not always!):

"I have just started to rewrite my application using the Presenter First Design Pattern to make sure my business logic is not in the Gui itself. I've got the general idea but I'm a bit unsure as to how I should be launching a dialogue window from my main application window.

What i have done is this in a nutshell. My main application window comprises of a Model, Presenter and a View. The Popup window also has a Model,
Presenter and View. This is the process of what happens when the button is clicked is as follows.

1. Button clicked, delegate function in presenter called from main View.
2. Method in main presenter calls a method in main model to open the window.
3. Method in main model instanciates popup view, popup model and binds with
popup presenter.
4. Method in main model calls method in popup model to open the window.
5. Method in popup model uses delegate function to call method in popup
presenter.
6. Method in popup presenter calls function in popup view to display the
window.

Can anybody tell me if what I am doing sounds right?"

-------------------------------------------------------------------------------

Not to be a downer on the MVP, but that sure sounds like having to go through a lot just to call ShowDialog! Patterns are useful, patterns are cool. But -- the question becomes "Do I really need to implement "all" of this pattern here? What's "best practices" anyway?

It's relative-- if you run FxCop against the Microsoft Enterprise Library, you'll get a list of errors that will keep you busy for hours.

I say, "it depends". Usually, if it ain't broke, then you don't need to fix it. In many cases a legitimate answer would be, "No, you don't - so don't sweat it - and you're still a Patterns Guy/Gal".

Music Education Department

I am always amazed at how many software developers are also musicians, especially in the jazz category. I myself am an ex flute and bass player, having done a stint with the Robert Hunt Trio in New York in my younger days. My flute teacher once made me transcribe Miles Davis' solo from Freddie the Freeloader (Kind of Blue) -- note for note, and be able to play it on the flute. Amazon now pays 20% on their MP3 downloads, they are DRM - free mp3s and they have a huge selection of classical and jazz. Here's an example:



Nordal is one of the most technically brilliant pianists you will ever hear. If you like top-flight piano jazz with hints of Keith Jarrett, Bill Evans, Oscar Peterson and others, yet totally unique, check out Marius Nordal.

Link of the Day: Sharepoint Blogs

11/05/2007

How to store a date in 4 bytes?

"My Karma ran over your dogma." - Unknown

This was an interesting little C# newsgroup nugget. User has a registration code with 4 unused bytes, and wants to know how to store a date in same. (Actually I believe the user was thinking of 4 extra characters in a string - not "bytes", but the exercise is still a good one).

Suggestions were made to store an integer representing the number of days from a fixed date. That would certainly do it, but it doesn't convey any context.

Here's my take:

using System;
using System.Collections.Generic;
using System.Text;

namespace _bytedate
{
class Program
{
static void Main(string[] args)
{
// this makes sorting by date on an integer value perfect,
// e.g. year+month+day, padded to make an integer
int myDate = 20071105;
byte[] b = BitConverter.GetBytes(myDate);
Console.WriteLine(b.Length.ToString() + " bytes.");
// reads "4 bytes"
// And -back again:
Console.WriteLine("Original: " +BitConverter.ToInt32(b, 0).ToString());
Console.ReadKey();

}
}
}

BitConverter has methods that can do all kinds of cool stuff like this -- both forwards, and back.

You could also write simple "conversion methods":

private static DateTime Int32ToDateTime(int myInt)
{
string s = myInt.ToString();
string yr = s.Substring(0, 4);
string mo = s.Substring(4, 2);
string dy = s.Substring(6, 2);
string theDate = string.Concat(yr, "/", mo, "/", dy);
return DateTime.Parse(theDate);
}
private static int DateTimeToInt32( DateTime dt)
{

string yr = dt.Year.ToString();
string mo = dt.Month.ToString();
if (mo.Length == 1) mo = "0" + mo;
string dy = dt.Day.ToString();
if (dy.Length == 1) dy = "0" + dy;
int myDate = int.Parse(yr + mo + dy);
return myDate;
}

Readers will of course observe that the Time component of the DateTime object needs to be conveniently left out of this exercise. Note that if a month or day component of the datetime is the equivalent of a one-character item, I prepend a zero ( 0) character into the resultant string to maintain sort capability on integer values.

11/02/2007

System.Web.Caching.Cache, HttpRuntime.Cache, and IIS Recycles

Recently I chimed in on a newsgroup thread to an OP (Original Poster) who was questioning why he was losing Cache items. This individual would load a dataset from the Cache object into a local object to use to perform processing. He had been using httpcontext.current.cache and noticed that sometimes he was not able to get the dataset out of the cache. He tried switching to HttpRuntime.Cache and it seemed to help.

The OP claimed that the application is under heavy hits, and once or twice every month he would see this error. He wanted to know why does the HttpContext.Current.Cache call work sometimes, while some other times does not.


A couple of posters replied, one of whom is a respected MVP who usually makes very astute, high-quality posts. He posted,"The cache is only valid during the life of the request. how is you[sic] code using the cache?"

Somebody else (also pretty astute, usually) responded, "Cache is valid during lifetime of application not request.....".

What's the answer?

Just to make sure, I posted some response information:

"ASP.NET applications recycle periodically, especially if there is a lot of memory pressure. When this happens, Cache goes away and is then resurrected.
While there could be other explanations, this is the most likely one. It should not matter whether you use HttpContext or HttpRuntime..."

I got a response:

"recycling doesn't effect [sic] HttpRuntime.Cache, which only exists for the request. during a recycle, currently running requests continue in the old
appdomain, so they still have this data."

That's only partially true. Yes, existing requests continue to finish up on the original AppDomain. However, that doesn't explain why the Cache item would be gone on any subsequent request, which is what the OP was really asking. So I responded in more detail:

"The System.Web.Caching.Cache class can be accessed either through the static property System.Web.HttpRuntime.Cache or through the helper instance properties System.Web.UI.Page and System.Web.HttpContext.Cache. (or HttpContext.Current.Cache) It is therefore available outside the context of a request. There is only one instance of this object throughout an entire application domain. Recycling an AppDomain (e.g. by touching web.config, or due to IIS causing the recycle due to memory pressure, etc.) will drop Application, Cache, and in-process Session information since that is stored in the AppDomain logical process. You can do this simple test:


protected void Page_Load(object sender, EventArgs e)
{
Cache["test"] = "Stuff in Cache";
System.Web.HttpRuntime.UnloadAppDomain(); // similar to an IIS AppDomain Recycle
Response.Redirect("Default2.aspx");
// Default2.aspx simply does: Response.Write((string) Cache["test"]); -- you should see nothing.
}

---"

The main point here is that if your Application is recycled either due to IIS health settings, the web tree contents being changed, or because your buggy code throws an unhandled exception, then your Session , Application, and Cache contents go "bye bye". There are no ifs, ands or buts about it. You are getting a new AppDomain, and it starts life with nothing in either Session, Application, or Cache.

The most efficient way to access the Cache is via the HttpRuntime.Cache object directly, the other methods involve extra parsing for the current HttpContext . It's a very minor optimization though. In point of fact, you can use the HttpRuntime.Cache class from Windows Forms or even a Windows Service, and it will work just fine. All you need is a reference to System.Web. It is very efficient and has neat Invalidation callbacks and other useful features that would be hard to duplicate. It's also much more lightweight than the Enterprise Library Caching framework and if you believe in traveling with "batteries included" as I do, this is the best way to go.

Politics: Her Hillarious Inner Self

Peggy Noonan, who I particularly admire, did a piece in the Wall Street Journal about Hillary Clinton revealing her "inner self". Rather than try to be a pundit, I'll just quote the pointillist paragraph:


"Giving illegal immigrants drivers licenses makes sense because it makes sense, but she may not be for it, but undocumented workers should come out of the shadows, and it makes sense. Maybe she will increase the payroll tax on Social Security beyond its current $97,500 limit, to $200,000. Maybe not. Everybody knows what the possibilities are. She may or may not back a 4% federal surcharge on singles making $150,000 a year and couples making $200,000. She suggested she backed it, said she didn't back it, she then called it a good start, or rather "I support and admire" the person proposing such a tax for his "willingness to take this on."

Noonan continues, "The problem for Mrs. Clinton is not that people sense she will raise taxes. It's that they don't think she'll raise them on the real and truly rich. The rich are her friends. They contribute to her, dine with her, have access to her. They have an army of accountants. They're protected even from her. But she can stick it to others, and in the way of modern liberalism for roughly half a century now, one suspects she'll define affluence down. That she would hike taxes on people who make $150,000 a year."

You know, I think it's too bad that this fellow Ron Paul is so extreme that he has deliberately made himself totally unelectable. He has great Libertarian ideas; it's just that you don't overtly put these into your platform and expect to become a Convention Nominee.

I think this is turning out to be one of the most unremarkable Presidential Campaigns in modern history. Really, on all three sides of the aisle.