How to Monitor ASP.NET Cache

We make extensive use of the Cache in our ASP.NET projects. Some projects keep as much as 20,000 items in the Cache. For test and debug purposes, sometimes it becomes necessary to look inside the Cache and remove items from the Cache on demand.

While the ASP.NET Cache is very powerful and easy to use, it is not very flexible when it comes to monitoring. We needed the ability to view a list of all items in the Cache, Item Key, Item Type, and when the item is a Collection, show how many items are in the Collection. We also wanted to be able to remove items from the Cache as necessary by simply clicking on Delete button on the list.

Thanks to Linq, a single statement can be used to prepare a list that can be bound to a GridView control. Here is an example:

Now you can assign this cacheItems to the DataSource of a GridView. With a few lines of code, you can also implement the functionality to Delete individual items from the list. If the project keeps a large number of items in Cache you may also need to implement paging.

We include this in the Admin section of any ASP.NET Project that makes extensive use of the Cache. If this is something of a more common requirement, I will post a User Control that will encapsulate the complete functionality.

Please post a comment if you think it will help.

Posted on March 1, 2010 04:20 by Haider

C# RSS Feed Fetcher - Display RSS Feed with 2 lines of Code

There is a new set of classes under the System.ServiceModel.Syndication Namespace. These classes are designed to work with RSS and ATOM Feeds, whether you want to generate or consume Feeds in ASP.NET or WinForms applications.

However, if you are looking to simply fetch and display RSS feed from any source, it can be done with just two lines of Code. This uses Linq, so ASP.NET 3.5+ is needed for it to work.

     //www.haiders.net | Jan 2010
     //C# Example: Fetch and Shape RSS Feed
     string rssUri = "http://some.feed.uri.xml";
     var doc = System.Xml.Linq.XDocument.Load(rssUri);
     var rssFeed = from el in doc.Elements("rss").Elements("channel").Elements("item")
                   select new { Title = el.Element("title").Value, Link = el.Element("link").Value,
                   Description = el.Element("description").Value };
     //The data is ready, assuming we have a ListView to display the Feed named lvFeed
     //Lets bind the Feed to the ListView
     lvFeed.DataSource = rssFeed;
     lvFeed.DataBind();
     //Thats all!

In order to display the Feed on an ASP.NET Page, you may use a ListView Control with a simple Template:

RSS Feed Fetcher Sample

The sample ListView here only displays a list of Post Titles with Links, but you can modify it to show the Description and other attributes available in the Feed.

You can see a live example of this on the Home Page of www.dojolocator.com, look at the "What's New?" section on the right panel. Another Page showing the Same RSS Feed in detail: www.dojolocator.com/news/

Posted on February 4, 2010 07:09 by Haider

Dictionary Lookup and avoiding "KeyNotFound" Exception

In the old days when we used Hashtable, we would safely look up any item without having to worry about an Exception and crash. Code like the following was very common.

//where htable is a populated Hashtable
mValue = htable["some key"] as SomeType;
if(mValue != null)
{
    //Item was found in the Hashtable, process it
}
else
{
    //No Item was found with the Key
    //Do something else
}

With the generic Dictionary, this is no longer an option. If you try to look-up an item with a Key that does not exist, instead of returning null, a Dictionary will throw a KeyNotFound Exception. Because of this, simply replacing a Hashtable with a Dictionary in an existing Project is not safe. This is annoying, why does the Dictionary throw an Exception? Why not return a null just like the Hashtable? First I thought this was a feature by design, not by choice. But when we look into the implementation of this functionality, it appears to be a choice. Here is the code for the Indexer of Generic Dictionary:

As you can see, it was about to return default(TValue), and then like an after thought, the KeyNotFound Exception was added before that line! Anyways, The .Net Framework Documentation outlines two methods for looking up Items in a generic Dictionary: Either wrap the lookup within a try...catch block, or use the TryGetValue() Method. In any case, checking for null with a lookup to find out if an item exists for that Key is not an option. If you simply need to know if an Item exists for a given Key, you should use the Dictionary.ContainsKey(TKey) Method which return a boolean.

Avoiding the KeyNotFound Exception

The Dictionary will always throw a KeyNotFound Exception if the Key does not exist, if there is any chance of a look up with non existent Key, the only safe way is to wrap a look-up within a try...catch block. The Framework documentation suggests that if there is possibility of frequent lookups of non existent Key, you should rather use the TryGetValue() Method. My Tests indicate that initiating a try...catch block is not really more expensive (in terms of speed) unless you are catching the Exception. Here is what I mean:

Another option to avoid the KeyNotFound Exception could be the following approach:

//Where dictionary is a populated Dictionary<>
if (dictionary.ContainsKey("some key"))
{
    //Item exists
    mValue = dictionary["some key"];
}
else
{
   //Item does not exist!
}
//No chance of KeyNotFound Exception
//But this method is twice expensive!

While the Exception is avoided this way, this approach effectively results in two lookups, takes twice the time and should be avoided.

Using the TryGetValue() Method

The TryGetValue() Method is recommended when you are frequently looking up a Dictionary with keys that don't exist. This is similar to the TryParse() Methods. It always takes multiple lines of code, as follows:

//Using the Dictionary.TryGetValue() Approach
//Customer is the Value Type in the dictionary
Customer c = null;
if (dictionary.TryGetValue("some key", out c))
{
    //Item exists, and c now holds a reference to the item...
}
else
{
    //Item does not exist with the key
}

Alternative to Dictionary.TryGetValue(): the ValueOrDefault() Extension Method

Since TryGetValue() does not throw any Exception, no need to wrap it with a try...catch block. But If you don't like this idea of declaring and initializing a variable to use as an "out" parameter as much as I do, here is an Extension method to take us back to the Hashtable days:

Keeping with the MethodOrDefault() convention of Linq Extension Methods, this ValueOrDefault() Method returns an Item if available, otherwise returns null for reference Types, and default value for Value Types. With this, we can safely use a one line approach like we did with a Hashtable:

This concludes the discussion of efficient Dictionary Lookup. Was it any help to you?

Posted on January 27, 2010 11:49 by Haider

Hashtable vs Generic Dictionary : Performance Comparison

The Generic Dictionary<TKey,TValue> was introduced in .Net 2.0 as a replacement for the Hashtable. However, the implementation and behavior of the generic Dictionary is not exactly the same as a Hashtable, and it always bothered me. I felt that the generic Dictionary was not going to be as fast and efficient as a raw Hashtable. When speed was the utmost concern, I chose to use a Hashtable despite the lack of strongly typed Key and Value. And it kept bothering me, why was a different implementation chosen for the Dictionary, why not just wrapping around a Hashtable?

So finally I took the time to write some test code and compare the speed of Dictionary vs Hashtable. To my surprise, the Dictionary is faster! It is not only faster than the Hashtable, but also more consistent in the lookup times compared to a Hashtable. My focus here is look-up time, no comparison was done for the time it takes to add items.

Without going into the details, I will just outline the test setup:

A set of about 16,000 objects were added to a Hashtable and a Dictionary, with string of various length as the Key. Time was clocked for 50,000 lookups with the same Key from both Dictionary and Hashtable. This process was repeated with Keys of different length, as well as for items towards the beginning, middle and end of the list. In all cases, the Dictionary showed better performance (speed). Depending on the size of the key, and to which end of the list that item was located, the difference in speed varied, but I was able to clock anywhere between 10% to 40% faster lookups on the Dictionary.

Also, as I mentioned before, besides being faster, the Dictionary showed more consistent result while the Hashtable's speed varied over multiple runs. Don't ask me why.

Bottom line, there is no reason not to use the Dictionary over the concern of speed. Now I know.

Posted on January 15, 2010 05:03 by Haider

Find if a Collection (IEnumerable) has any Item

If a Method or Property returns IEnumerable or Inumerable<T> Types, the only thing that is inherently possible on them is to Loop through (foreach{}). Sometimes it helps to know if the Collection has any items, without having to initiate a loop. The IEnumerable Interface is bare minimum for a collection and does not expose any properties at all. LINQ provides a convenient Extension Method called Any(), that you can call on any IEnumerable Type. Internally, this Method checks if any item is available in the Collection using the following code:

If you do not have LINQ in the project, or want a shortcut of this without having to call the Any() method, here is an alternative:

However, if we know the underlying Type of the Collection also implements ICollection Interface, we can simply cast it to ICollection and check the Count Property:

bool hasItems = ((ICollection)products).Count > 0;

The Count Property is maintained very efficiently by the Framework Collection classes. It would be preferable than having to call any Method.

Combining these two approach, here is another Extension Method that can be used for the same purpose:

//An alternate to the IEnumerable.Any() Method
public static bool HasItem(this IEnumerable source)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    if( source is ICollection)
        return ((ICollection)source).Count > 0;
    else
        return source.GetEnumerator().MoveNext();
}

Ideally, an IEnumerator should be wrapped within a using{...} block, like it is shown in the Framework's implementation of Any() Method above. Also note that there is an overload of the IEnumerable.Any() Method. It takes a Func<TSource, bool> and returns true only if any of the Collection items match the given condition. Here is an example:

//Lets assume there is a variable called products, with a collection of Product objects
//Product object has a boolean property called OnBackOrder
//We want to find out if any of the products is on back order
bool IsAnyOnBackorder = products.Any(p => p.OnBackOrder);
Posted on January 8, 2010 09:51 by Haider