Pages

Monday, May 16, 2011

Optimized way to check if a dataset has any value

Working with datasets and we should make sure that object contains some data within.
Here is the optimized way to check if a dataset has any data within by using advanced .Net concepts like extension methods and Linq.

public static bool IsEmpty(this DataSet dataSet)
{
return dataSet == null || !(from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any();
}

And we can use this extension method as follows:

DataSet dset = ... // Populate dataset by business method or logic
if (!dset.IsEmpty())
{
   ...
}

Extension methods provide a simple mechanism to extend types in the system (value, reference, and interface types) with new methods. These methods extend the original type and can be called like regular, defined instance methods, but they leave the original type and its methods untouched. Extension methods create the illusion that they are defined on a real type, but, in reality, no changes are made to the original types.

.NET Language-Integrated Query defines a set of general purpose standard query operators that allow traversal, filter, and projection operations to be expressed in a direct yet declarative way in any .NET-based programming language.

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

Error "unable to evaluate expression because the code is optimized or a native frame is on top of the call stack" appears within asp.net using C#.

I noticed this error whenever I try to redirect to a page from within try catch block.

To fix this issue we need to use some extra code (marked in red color) within Response.Redirect method:

Response.Redirect("~/NewPage.aspx" , false);

Specifying whether the current page execution will end immediately or not.