Tech – Noesis

The more you know, you know how little you know

Archive for the ‘technical’ Category

Moved to new location http://www.noesispedia.com

Posted by Pradeep Mishra on March 21, 2008

I have moved to new location http://www.noesispedia.com. Please visit this link for latest posts. Here is a small writeup about noesispedia..

What!

noesispedia is a entrepreneurial and a non profit organization, started by few working professionals, working towards growth of individual through motivating creative writing, knowledge sharing and collabaration. We provide a single online platform serving following purposes…

  • Group Blogging: Know what your friends are writing and be in touch with them
  • Motivate individual to donate some of their time to help grow others
  • Web log problems faced in routine work
  • Share solutions with others
  • Debate on new ideas
  • Post open source projects and tools

Why!

Because…

  • Very few people and publishing blog and on top that all information is scattered. We want to converge the knowledge and people together
  • There is no way to find out what technology/business domain your friends are working. We want to provide a platform to find like minded people and solutions through them
  • You want to know what’s going on in your circle
  • You face lots of problems and spend a fair amount of time in solution but you do not keep a track of them. In future may face the same problem again and spend the same effort and time. We want you to keep track of them to avoid putting the same effort again
  • Provide free information to all

But!

noesispedia is an organization build by its contributors. All group members belong to technical field but that doesn’t mean everything here is gonna be tech stuff. No not at all. You will surely have lots of fun stuff like cartoons, music reviews, movie reviews, puzzles etc.The primary purpose of Noesis is to grow people through people.

Posted in technical | Tagged: | 1 Comment »

How to show google mail like loading image/please wait… message while page data loads

Posted by Pradeep Mishra on March 4, 2008

For a better user experience you would your users to see please wait message while browser render the page completely. Here is the one solution to the same problem.

Let’s create a master page called Site.master and a web content form as demo.aspx.







    <title>Loading Demo</title>


    <form>
        
            
                
            
        

<div>

<!-- Page Header will go here... -->

</div>

<div>


                                            <!-- Page-specific content will go here... -->
                                        

</div>

<div>

<!-- Page Footer will go here... -->

</div>

Demo.aspx is the web content form which fetches data from a database.



<!-- Code to fetch data from a database -->

To show loading message add following code to the code behind of master file Site.master.cs

  protected override void OnLoad(EventArgs e)
  {
  if (!IsPostBack)
  {
  Response.Buffer = false;
  Response.Write(“

Please wait…

“);
  Response.Flush();
  }
  base.OnLoad(e);
  }
  protected override void Render(HtmlTextWriter writer)
  {
  if (!IsPostBack)
  {
  Response.Clear();
  Response.ClearContent();
  }
  base.Render(writer);
  }
in the Site.master.aspx file add following javascript at the end of the file.

 
    try{
 var divLoadingMessage =  document.getElementById("divLoadingMsg")
 if (divLoadingMessage != null && typeof(divLoadingMessage) != 'undefined')
        {
            divLoadingMessage.style.display="none";
            divLoadingMessage.parentNode.removeChild(divLoadingMessage);
        }
    }catch(e){}

That’s it now all your pages using Site.master will be showing Please wait.. message when the page starts loading. Of course instead of putting a message you can put a nice web2.0 loading image in between divLoadingMsg tags.
So how does this works?
The onLoad event of master page will be called before any of the content web form’s Onload event. as soon as master page loads div tag becomes visible. After the page has loaded completely the script written at the end of the master page hides the div tag. so simple isnt’t it.Hope this helps!

Posted in technical | Tagged: , , , | 27 Comments »

Linq to Sql: Dynamic Sorting without using Complete Dynamic Linq Libraries

Posted by Pradeep Mishra on March 3, 2008

This problem may occur while implementing sorting in GridView. If a storedprocedure is being used either dynamic sql can be created or multiple of case statements can be used. However what if you are just using linq queries. Here are the options

  1. Using Dynamic Linq
  2. Some work arround so that linq query can be generated at runtime.

Essentially 2nd approach is the same as that used in 1st one. But if you just want to implement sorting and do not want to digg into Dynamic Linq libraries you can follow the article…

Let’s assume following method expects sortExpression parameter directly passed by UI layer GridView.

public DataTable GetSomeData(par1, par2…., string sortExpression)
{
var query = (//Linq query goes here )
// We want something like this which is not possible as of now
var query = (some query) (OrderBy SortExpression)
}
Here is the extension method you would like to follow…

public DataTable GetSomeData(par1, par2…., string sortExpression)
{
var query = (//Linq query goes here )
// We want something like this which is not possible as of now
var query = (some query) (OrderBy SortExpression)
}
public static Util
{
//Thanks to Ernesto for pointing out a small correction in method signature.
public static IQueryable OrderBy(this IQueryable source, string sortExpression) where TEntity : class
{
var type = typeof(TEntity);
// Remember that for ascending order GridView just returns the column name and for descending it returns column name followed by DESC keyword
// Therefore we need to examine the sortExpression and separate out Column Name and order (ASC/DESC)
string[] expressionParts = sortExpression.Split(‘ ‘); // Assuming sortExpression is like [ColoumnName DESC] or [ColumnName]
string orderByProperty = expressionParts[0];
string sortDirection = “ASC”;
string methodName = “OrderBy”;

//if sortDirection is descending
if (expressionParts.Length > 1 && expressionParts[1] == “DESC”)
{
sortDirection = “Descending”;
methodName += sortDirection; // Add sort direction at the end of Method name
}
var property = type.GetProperty(orderByProperty);
var parameter = Expression.Parameter(type, “p”);
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExp = Expression.Lambda(propertyAccess, parameter);
MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName,
new Type[] { type, property.PropertyType },
source.Expression, Expression.Quote(orderByExp));
return source.Provider.CreateQuery(resultExp);
}
}
Usage will be as of follows…

public DataTable GetSomeData(par1, par2…., string sortExpression)
{
var query = (//Linq query goes here )
// We want something like this which is not possible as of now
var query = (some query)
return query.OrderBy(SortExpression).ToDataTable(rec => new object[] { query}));
}
Again OrderBy is an extension method. Hope this helps!

Posted in technical | 17 Comments »

Solution to Error: The data source ‘ods_DataSource’ does not support sorting with IEnumerable data. Automatic sorting is only supported with DataView, DataTable, and DataSet.

Posted by Pradeep Mishra on March 3, 2008

Suppose you have a grid view and associated datasource as ods_DataSource.

  

<!-- Some other code---->


The select method is defined as

public ISingleResult SelectMethod(){
//Get DAL Instance DALInstance
return DALInstance.GetDATA(){}
}
Now if you try to sort on some column the following error pops up.The data source ‘ods_DataSource’ does not support sorting with IEnumerable data. Automatic sorting is only supported with DataView, DataTable, and DataSet.This is because to implement sorting you must have datasource of type DataView/DataTable/DataSet. Now if you are using traditional 3 tier architecture and returning one of these three datatypes everything works fine. The problem arises when you are using Linq. There are two possible solution for this..

  1. Implement custom sorting.
  2. Change IEnumerable datatype into one of these datatypes.

Here we will try to follow 2nd approach. In our data access layer we will change IEnumerable into a DataTable using an static utility class. Here is the code to perform that operation

public static class Util
{
public static DataTable ToDataTable(this IEnumerable varlist, CreateRowDelegate fn)
{
DataTable dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
// Could add a check to verify that there is an element 0
foreach (T rec in varlist)
{
// Use reflection to get property names, to create table, Only first time, others will follow
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
// Note that we must check a nullable type else method will throw and error
Type colType = pi.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable)))
{
// Since all the elements have same type you can just take the first element and get type
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
//Iterate through each property in PropertyInfo
foreach (PropertyInfo pi in oProps)
{
// Handle null values accordingly
dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null);
}
dtReturn.Rows.Add(dr);
}
return (dtReturn);
}
public delegate object[] CreateRowDelegate(T t);
}
Changes in the Select method

public ISingleResult SelectMethod(){
//Get DAL Instance DALInstance
return DALInstance.GetSomeData(){}
}
public DataTable GetSomeData()
{
ISingle result = //code to get result;
return (result.ToDataTable(rec => new object[] { result}));
}
As you can see ToDataTable is an extenstion method and will be available to all IEnumerable types.Obviously there are some performance overhead due to use of reflection but still this approach can be used. However for real time applications performance testing must be performed.

Hope this helps!

Posted in technical | Tagged: , , | 14 Comments »