Thursday, October 8, 2009

nettiers dynamic search query

I am using nettiers 2.3.0 now in a project and then i faced a problem where i have to make a search function that takes a string and search in each entity of the string fields of it to get the results.

nettiers has a good functions like GetPaged that takes the where clause and search with it. but come on how to make this search with generic code and powerful!!!!

the solution is a magic word, "Reflection"!!! ta da .... you have to make your development framework ideal enough to do that. How?

As I said i am using nettiers this make me support the following: each entity has an interface describes each property. and a good naming convention that I can follow in naming the UI elements such as typed data sources, that nettiers generates, and so i wrote this code...


List<string> lookFor = new List<string>();

Type t = Type.GetType(string.Format("Entities.I{0}, Entities", EntityName));

foreach (PropertyInfo info in t.GetProperties())

{

if (info.PropertyType == Type.GetType("System.String"))

{

lookFor.Add(string.Format(" [{0}] Collate SQL_Latin1_General_CP1_CI_AS like '%{1}%' ", info.Name, txtName.Text));

}

}

string whereClause = string.Join(" OR ", lookFor.ToArray()) ;

DataSourceControl ds = WebFormUtil.GetControlByID(Page.Controls, EntityName + "DataSource") as DataSourceControl;

PropertyInfo filterProperty = ds.GetType().GetProperty("Parameters");

Object collection = filterProperty.GetValue(ds, null);

if (collection is ParameterCollection)

{

((CustomParameter)((ParameterCollection)collection)["WhereClause"]).Value = whereClause;

}

ds.DataBind();


with just the entity name as a variable, and the well formed structure of the tiers and the good structure of the any form that contains a list and a search box this code rocks. I am able to get the typed data source and attach a value to its attributes and finally get works done and generic.

Thanks to Reflection, it made it possible.