How Good is Hyper-V based Virtual Servers?

It has been over two years since the initial release of Hyper-V. Many minor enhancements have been made to Hyper-V while the core remained the same. The initial Marketing push of Hyper-V seem to have slowed down on Microsoft's part, now that Windows Server 2008 is fairly old and most people in the industry would be familiar with Hyper-V.

I wonder what type of systems are being used on Hyper-V based Virtual Servers. Is it still primarily for test, development and prototyping?

While some large scale applications like SQL Server may not be most suitable for Virtual Server Instances, it is perfectly possible for Hyper-V based Virtual Machines to carry out production level work.

We know it because we have had a Virtual Server Instance hosting over 275 Websites!

As far as CPU and Memory utilzation goes, Hyper-V Machines are almost as good as a real server. The memory is dedicated to the server, and CPU is real. However, as the number of guest instances grow, it can put a strain on the storage sub system. The overall performance of the guest machines will be limited by the performance of the storage system.

If the storage system can keep up with the demands of all guest machines, all Hyper-V based Virtual Servers will perform like stand alone servers.

We have run performace tests on both the Hyper-V Host and Guest Machines to verify this. There is negligible difference between the physical and virtual server.

If you are considering deployment of production Sites on a Hyper-V based Virtual Server, it is perfectly viable.

Posted on June 15, 2010 10:04 by Haider

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

Accessing Cookie with Javascript

The document.cookie Property is available in DOM for accessing cookie values in javascript. This Property returns all of the cookies in a long semicolon separated string. For example:

cookie1=value1; cookie2=value2; cookie3=value3; ...

There is no way of accessing individual cookie values like we access Request variables on the server side. You must extract the required cookie value from one long string. It can be easily done with a few lines of code, but if you like the way things work on the server side, here is a small helper Javascript function I wrote to prepare a dictionary with all cookie values. Now instead of trying to extract value from a long string, you can use the following code:

var cookies = getCookies();
var value1 = cookies["cookieName"];
//Now value1 holds the value of cookie "cookieName"

Makes things easier especially when multiple cookies are in use. Here is the helper function that prepares a dictionary with all available cookies and values:

    
    function getCookies()
    {
        var cks = new Object();
        var ckList = document.cookie.split("; ");
        for (var i=0; i < ckList.length; i++)
        {
            var ck = ckList[i].split("=");
            cks[ck[0]] = unescape(ck[1]);
        }
        return cks;
    }

This code has been used in several places without any problems. If you encounter any issue, please post a comment.

Posted on February 11, 2010 09:50 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