Correct using Cache in ASP.NET

Posted by Dmytro Shteflyuk on under ASP.NET

Often in ASP.NET application we see a code which looks like this one:

1
2
3
4
5
if (Cache["SomeData"] != null)
{
    string name = ((SomeClass) Cache["SomeData"]).Name;
    //.....
}

Experienced developer, even if he is not a paranoiac, will find possible problem immediately — NullReferenceException. That’s because of caching implementation in ASP.NET. In ideal case an object, that has been cached, will stay there up to application restart, but in real world it could be deleted between two calls: by the garbage collector when memory is over (because cache uses weak references WeakReference); by another thread to refresh cached data.

So the code I have mentioned before works in 99% of all cases, but sometimes you will get errors in your log, which can not be reproduced easily. Here is right cache usage approach:

1
2
3
4
5
6
SomeClass someClass = Cache["SomeData"] as SomeClass;
if (someClass != null)
{
    string name = someClass.Name;
    //.....
}

Do not relax your vigilance, it’s exactly what they are waiting for! (about bugs)

Correct Last-Modified header processing

Posted by Dmytro Shteflyuk on under PHP

This is quick post about Last-Modified header. Please imagine following situation: you have image stored in your database and you need to send it to the browser on some request. But image extraction from database takes some time, and if there are more than one image you Web-server’s productivity will decrease dramatically. Is this case you need to implement caching functionality in your application. All images can be changed therefor you need to have ability to check image modified date (for example, this date can be stored in same database).

Read the rest of entry »

Why does IE save pictures from the Web in bitmap format?

Posted by Dmytro Shteflyuk on under PHP

Today I found very strange problem with Internet Explorer. I’ve generated GIF-image with PHP GD2 and sent results for client browser. In IE I’ve tried to store picture in my local file system but the only option was to save the picture as a .BMP file instead of as a native .gif file! The same problem is described in Microsoft Knowledge Base, but it does not help me.

Read the rest of entry »