Sunday, July 31, 2011

Don't We All


I was parked in front of the mall wiping off my car. I had just come from the car wash and was waiting for my wife to get out of work. Coming my way from across the parking lot was what society would consider a bum. From the looks of him, he had no car, no home, no clean clothes, and no money.
There are times when you feel generous but there are other times that you just don’t want to be bothered. This was one of those “don’t want to be bothered times.”
“I hope he doesn’t ask me for any money,” I thought. He didn’t.
He came and sat on the curb in front of the bus stop but he didn’t look like he could have enough money to even ride the bus. After a few minutes he spoke. “That’s a very pretty car,” he said. He was ragged but he had an air of dignity around him. His scraggly blond beard keeps more than his face warm. I said, “Thanks,” and continued wiping off my car. He sat there quietly as I worked. The expected plea for money never came.
As the silence between us widened something inside said, “Ask him if he needs any help.”
I was sure that he would say “yes” but I held true to the inner voice.
“Do you need any help?” I asked.
He answered in three simple but profound words that I shall never forget. We often look for wisdom in great men and women. We expect it from those of higher learning and accomplishments.
I expected nothing but an outstretched grimy hand. He spoke the three words that shook me.
“Don’t we all?” he said.
I was feeling high and mighty, successful and important, above a bum in the street, until those three words hit me like a twelve gauge shotgun. Don’t we all?
I needed help. Maybe not for bus fare or a place to sleep, but I needed help. I reached in my wallet and gave him not only enough for bus fare, but enough to get a warm meal and shelter for the day. Those three little words still ring true. No matter how much you have, no matter how much you have accomplished, you need help too. No matter how little you have, no matter how loaded you are with problems, even without money or a place to sleep, you can give help.
Even if it’s just a compliment, you can give that. You never know when you may see someone that appears to have it all. They are waiting on you to give them what they don’t have. A different perspective on life, a glimpse at something beautiful, a respite from daily chaos, that only you through a torn world can see. Maybe the man was just a homeless stranger wandering the streets.
Maybe he was more than that. maybe he was sent by a power that is great and wise, to messenger to a soul too comfortable in themselves. Maybe God looked down, called an Angel, dressed him like a bum, and then said, “Go messenger to that man cleaning the car, that man needs help.” Don’t we all?
“.....Even a smile can be charity.....” Holy Prophet Muhammad (Peace be upon him)"

Saturday, July 9, 2011

Linq to Sql/Entities Table values using Reflection

The following function takes input table name, data field column name and data value column name and returns list of ListItem so developer can use this list in dropdown and other list control. the following function uses reflection to access table and column for values.

 public List<ListItem> GetListOfValue(string dataFieldName, string dataFieldValue, string tableName)  
{
List<ListItem> listItemList = new List<ListItem>();
ListItem listItem = null;
MetaTable table = _dataContext.Mapping.GetTables().Where(t => t.TableName.ToUpper().Equals("DBO." + tableName.ToUpper())).FirstOrDefault();
if (table == null)
throw new NullReferenceException("table");
ITable iTable = _dataContext.GetTable(table.RowType.Type);
if (iTable == null)
throw new NullReferenceException("iTable");
List<object> objectList = iTable.OfType<object>().ToList();
foreach (object obj in objectList)
{
listItem = new ListItem();
foreach (PropertyInfo property in obj.GetType().GetProperties())
{
if (property.Name.ToUpper().Equals(dataFieldName.ToUpper()))
{
listItem.Text = property.GetValue(obj, null).ToString();
}
if (property.Name.ToUpper().Equals(dataFieldValue.ToUpper()))
{
listItem.Value = property.GetValue(obj, null).ToString();
}
}
listItemList.Add(listItem);
}
return listItemList;
}

Thursday, July 7, 2011

Request.QueryString Extension Method

Below are two extension methods that I have created for Request.QueryString.. as I am passing many parameters and playing with querystring a lot and every where i had to put IF condition for null and other things..

In order save myself from checking and validating again and again i have designed these two extension Method using some help from internet to save time and reduce number of lines of code.. kindly check them and you are welcome to criticize in constructive way.

I have some more functions in my mind to overload for Request.QueryString and will add later As following two functions have fulfilled my need

How to use..
byte? valueByte  
Guid? valueGuid

//check if "Server" key exits if yes then return value else return default value of null that we have passed

valueByte = Request.QueryString.GetValue<byte?>(Constants.FilterServer, null);
valueGuid = Request.QueryString.GetValue<Guid?>(Constants.FilterGuid, null);

//checks if "Server" Key exists then out value to provided variable and return true to if condition, else return false and assign default value to provided out variable
if(Request.TryParse<byte?>(Constants.FilterServer, null, out valueByte)){}

if(Request.TryParse<Guid?>(Constants.FilterGuid, null, out valueGuid)){}



public static T GetValue<T>(this NameValueCollection collection, string key, T defaultValue)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
var value = collection[key];
if (value == null) { return defaultValue; }
var converter = TypeDescriptor.GetConverter(typeof(T));
if (!converter.CanConvertFrom(typeof(string))) {
throw new ArgumentException(String.Format("Cannot convert ' {0} ' to {1} ", value, typeof(string))); }
return (T)converter.ConvertFrom(value); }


public static bool TryParse<T>(this NameValueCollection collection, string key, T defaultValue, out T returnValue)
{
returnValue = default(T);
try
{ if (collection == null) {
throw new ArgumentNullException("collection"); }
var value = collection[key];
if (value == null)
{ return false;}
var converter = TypeDescriptor.GetConverter(typeof(T)); if (!converter.CanConvertFrom(typeof(string)))
{ throw new ArgumentException(String.Format("Cannot convert ' {0}' to {1} ", value, typeof(string))); }
returnValue = (T)converter.ConvertFrom(value);
return true; }
catch (ArgumentNullException ex) { return false;}
catch (ArgumentException ex) { return false;}
catch (NotSupportedException ex) {return false;} }

Saturday, July 2, 2011

THE DAY I MET A LIVING SAINT by Peter Oborne


Sixty years ago, Abdul Sattar Edhi, 82, gave up everything to devote his life to helping Pakistan’s poorest. Here, Peter Oborne hails a truly selfless spiritual sage.
By Peter Oborne

In the course of my duties as a reporter, I have met presidents, prime ministers and reigning monarchs. Until meeting the Pakistani social worker Abdul Sattar Edhi, I had never met a saint. Within a few moments of shaking hands, I knew I was in the presence of moral and spiritual greatness.

Mr Edhi’s life story is awesome, as I learnt when I spent two weeks working at one of his ambulance centres in Karachi. The 82-year-old lives in the austerity that has been his hallmark all his life. He wears blue overalls and sports a Jinna cap, so named because it was the head gear of Muhammad Ali Jinna, the founder of Pakistan.

No Pakistani since Jinna has commanded the same reverence, and our conversations were constantly interrupted as people came to pay their respects. Mr Edhi told me that, 60 years ago, he stood on a street corner in Karachi and begged for money for an ambulance, raising enough to buy a battered old van. In it, he set out on countless life-saving missions. Gradually, Mr Edhi set up centres all over Pakistan. He diversified into orphanages, homes for the mentally ill, drug rehabilitation centres and hostels for abandoned women. He fed the poor and buried the dead. His compassion was boundless.

He was born in 1928, when the British Empire was at its height, in Gujarat in what is now western India. But he and his family were forced to flee for their lives in 1947 when the division of India and creation of Pakistan inspired terrible communal tensions: millions were killed in mob violence and ethnic cleansing. This was the moment Mr Edhi, finding himself penniless on the streets of Karachi, set out on his life’s mission.

Just 20 years old, he volunteered to join a charity run by the Memons, the Islamic religious community to which his family belonged. At first, Mr Edhi welcomed his duties; then he was appalled to discover that the charity’s compassion was confined to Memons. He confronted his employers, telling them that humanitarian work loses its significance when you discriminate between the needy”.

So he set up a small medical centre of his own, sleeping on the cement bench outside his shop so that even those who came late at night could be served.

But he also had to face the enmity of the Memons, and became convinced they were capable of having him killed. For safety, and in search of knowledge, he set out on an overland journey to Europe, begging all the way. One morning, he awoke on a bench at Rome railway station to discover his shoes had been stolen. He was not bothered, considering them inessential. Nevertheless, the next day an elderly lady gave him a pair of gumboots, two sizes too large, and Mr Edhi wobbled about in them for the remainder of his journey.

In London, he was a great admirer of the British welfare state, though he presciently noted its potential to encourage a culture of dependency. He was offered a job but refused, telling his benefactor: I have to do something for the people in Pakistan.

On return from Europe, his destiny was set. There was no welfare state in Fifties Pakistan: he would fill the gap. This was a difficult period in his life. Shabby, bearded and with no obvious prospects, seven women in rapid succession turned down his offers of marriage. He resigned himself to chastity and threw all of his energy into work.

He would hurtle round the province of Sindh in his poor man’s ambulance, collecting dead bodies, taking them to the police station, waiting for the death certificate and, if the bodies were not claimed, burying them himself. Mr Edhi’s autobiography, published in 1996, records that he recovered these stinking cadavers from rivers, from inside wells, from road sides, accident sites and hospitals… When families forsook them, and authorities threw them away, I picked them up… Then I bathed and cared for each and every victim of circumstance.” There is a photograph of Mr Edhi from this formative time. It could be the face of a young revolutionary or poet: dark beard, piercing, passionate eyes. And it is indeed the case that parts of his profound and moving autobiography carry the same weight and integrity as great poetry or even scripture.

Mr Edhi discovered that many Pakistani women were killing their babies at birth, often because they were born outside marriage. One newborn child was stoned to death outside a mosque on the orders of religious leaders. A furious Mr Edhi responded: Who can declare an infant guilty when there is no concept of punishing the innocent?

So Mr Edhi placed a little cradle outside every Edhi centre, beneath a placard imploring: Do not commit another sin: leave your baby in our care.” Mr Edhi has so far saved 35,000 babies and, in approximately half of these cases, found families to cherish them. Once again, this practice brought him into conflict with religious leaders. They claimed that adopted children could not inherit their parents’ wealth. Mr Edhi told them their objections contradicted the supreme idea of religion, declaring: Beware of those who attribute petty instructions to God.

Over time, Mr Edhi came to exercise such a vast moral authority that Pakistan’s corrupt politicians had to pay court. In 1982, General Zia announced the establishment of a shura (advisory council) to determine matters of state according to Islamic principles. Mr Edhi was suspicious: “I represented the millions of downtrodden, and was aware that my presence gave the required credibility to an illegal rule.”

Travelling to Rawalpindi to speak at the national assembly, he delivered a passionate denunciation of political corruption, telling an audience of MPs, including Zia himself: “The people have been neglected long enough. One day they shall rise like mad men and pull down these walls that keep their future captive. Mark my words and heed them before you find yourselves the prey instead of the predator.”

Mr Edhi did not distinguish between politicians and criminals, asking: “Why should I condemn a declared dacoit [bandit] and not condemn the respectable villain who enjoys his spoils as if he achieved them by some noble means?” This impartiality had its advantages. It meant that a truce would be declared when Mr Edhi and his ambulance arrived at the scene of gun battles between police and gangsters. “They would cease fire,” notes Mr Edhi in his autobiography, “until bodies were carried to the ambulance, the engine would start and shooting would resume.”

Mr Edhi eventually found a wife, Bilquis, but his personal austerity was all but incompatible with married life. When the family went on Hajj, a vast overland journey in the ambulance, he forbade Bilquis to bring extra clothes, because he was determined to fill the vehicle with medical supplies. Reaching Quetta in northern Baluchistan, with the temperature plunging, he relented enough to allow her to buy a Russian soldier’s overcoat. Later on, when their children grew up, Mr Edhi would not find time to attend his daughter’s marriage.

But Mr Edhi’s epic achievement would not have been possible but for this inhuman single-mindedness. Today, the influence of the Edhi Foundation stretches far outside Pakistan and Mr Edhi has led relief missions across the Muslim world, providing aid at every international emergency from the Lebanon civil war in 1983 to the Bangladesh cyclone in 2007. There are no horrors that Mr Edhi and his incredibly brave army of ambulance men have not witnessed, and the numerous lives they have saved.

The story of Mr Edhi coincides with the history of the Pakistan state. More than any other living figure, he articulates Jinna’s vision of a country which, while based on Islam, nevertheless offers a welcome for people of all faiths and sects. Indeed, the life of Mr Edhi provides a sad commentary on the betrayal of Jinna’s Pakistan by a self-interested political class.

One evening, as the sun set over Karachi, I asked Mr Edhi what future he foresaw. “Unless things change,” he said, “I predict a revolution.”

Sunday, May 1, 2011

Data grid row bind without post back and AJAX





Introduction

This article basically describes how to get a DataGrid row value without postback or calling AJAX.

Background

There are scenarios when we have to populate fields from a child window to a parent window after selecting a particular row from a DataGrid. The idea is to pass the DataGrid value to the parent window without postback or calling AJAX. I did ask this question in different forums, but everyone ended up suggesting to use AJAX. After some searching and exploring, I found some trick to do this otherwise.

Using the code

I have created a scenario in which the parent window has some fields that can be populated from the child window. After getting the search results on the DataGrid, we select the result and the parent window fields will be populated with the selected result.

This can be done by using the OnItemDataBound event. In the event handler function, we register the OnMouseOver, OnMouseOut functions for decoration purposes, and the OnClick function registers a SetMouseClick function, passing the parameters to the parent window.


 private void dgEmployee_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType ==
ListItemType.AlternatingItem)
{
e.Item.Attributes["onmouseover"] = "javascript:setMouseOverColor(this);";
e.Item.Attributes["onmouseout"] = "javascript:setMouseOutColor(this);";
string FirstName = e.Item.Cells[0].Text.ToString();// first column value
string LastName = e.Item.Cells[1].Text.ToString() ;// Second
string HireDate = e.Item.Cells[2].Text.ToString() ;// third
string Job = e.Item.Cells[3].Text.ToString() ;// fourth
string Publisher = e.Item.Cells[4].Text.ToString() ; // fifth
string City = e.Item.Cells[5].Text.ToString() ; // sixth
e.Item.Attributes["onclick"] =
"javascript:setMouseClick('"+FirstName+"','"+LastName+"','" +
HireDate+"','"+Job+"','"+Publisher+"','"+City+"');";
}
}


Now, we have a JavaScript function hat passes the parameters to parent window on the DataGrid Click event. Since this is a modal popup, we can return the selected row value to the parent window through window.returnValue.

//JavaScript Function
 function setMouseClick(first_name,last_name,hire_date,job,publisher,city ) {
var array = new Array();
array[0]=first_name;
array[1]=last_name;
array[2]=hire_date;
array[3]=job;
array[4]=publisher;
array[5]=city;
window.returnValue=array;
window.close();
}

On the parent window side, we have a JavaScript function that accepts the return value from the child window and shows up the return value on text boxes. The OnSearch function fires on clicking the search hyperlink.
Collapse


//JavaScript Function
 function OnSearch()
{
var value = window.showModalDialog('\Popup.aspx','','');
if(value != null)
{
document.getElementById('txtFirstName').value = value[0];
document.getElementById('txtLastName').value = value[1];
document.getElementById('txtHireDate').value = value[2];
document.getElementById('txtJob').value = value[3];
document.getElementById('txtPublisher').value = value[4];
document.getElementById('txtCity').value = value[5];
}
}


That's all. Thanks!