Reputation: 127
I am experimenting with caching data and keep failing. As you can see in the code below, I call upon a web service to return an array called 'categories'. This call is successful and I get information back. Right after populating the dropdown list with the results, I use an Insert to store the information to cache. Upon page refresh (I guess I should say anything other than a postback), I check the cache to see if the information is there. It never is. Scratching my head on this one...
if (! IsPostBack)
{
//See if the results have been cached. With arrays and checking for null, you have to
//check the array itself before its elements can be checked.
string[] saveCatList = Cache.Get("Categories" + Session["sessionID"]) as string[];
if (saveCatList == null || string.IsNullOrEmpty(saveCatList[0]))
{
WBDEMOReference.getcatlist_itemcategories[] categories;
strResult = callWebServ.getcatlist(Session["sessionID"].ToString(),
out strResultText, out dNumOfCat, out categories);
for (int i = 0; i < categories.Length; i++)
{
//ddCat is the ID number of the category drop down list
ddCat.Items.Add(new ListItem(categories[i].categorydesc.ToString(),
categories[i].categorynumber.ToString()));
}
//Store the array into cache. 'Cache.Remove' will remove the cache for that key
Cache.Insert("Categories" + Session["sessionID"], categories, null,
DateTime.Now.AddMinutes(5), System.Web.Caching.Cache.NoSlidingExpiration);
}
}
Upvotes: 3
Views: 3479
Reputation: 2394
I think sJhonny got it in the comments. You put categories
(an array of WBDEMOReference.getcatlist_itemcategories
)in the cache, but do an as string[]
when you take it back out. A mismatch of type with the as keyword will result in a null value. Try changing as string[]
to as WBDEMOReference.getcatlist_itemcategories[]
or add a check to see if it exists without using the as string[]
cast.
Upvotes: 3
Reputation: 11201
Looks like you are using HttpContext Cache which is not use in webcontext can be null so the suggestion would be to HttpRuntime Cache. The runtime cache will always be available in your application for e.g. even in a console app
Even the HttpContext use HttpRuntime Cache under the hood but in your scenario looks the runtime cache might do the job
I will be happy to delete my answer if some one corrected me the advise given is wrong
Upvotes: 1