Tuesday, May 12, 2009

ASP.Net Tips n Tricks

1) Get the full file path (with name) in ASP.Net's FileUpload control.

FileUpload1.PostedFile.FileName returns full file path (including file name),
FileUpload1.FileName returns only file name.

2) Password Validation

Following code snippet display password validation at Client side (JavaScript).
Here password must contains Non-AlphaNumeric character(s) and length should be greater than 6.


<asp:TextBox ID="txtPassword" runat="server" Width="270px"
Enabled="true"></asp:TextBox>
<asp:CustomValidator ID="valPasswd" runat="server"
ControlToValidate="txtPassword" ClientValidationFunction="validatePassword"
Display="Dynamic"
ErrorMessage="* Inadequate password strength."></asp:CustomValidator>

<script type="text/javascript">

function validatePassword(oSrc,args)
{
var isValid = false;

var regExp = /\W/; // /[^a-zA-Z0-9]/;
if( (regExp.test(args.Value)) && (args.Value.length > 6) )
isValid = true;

args.IsValid = isValid;
}

</script>



3) How to get GridView's RowIndex (current row index) in GridView's RowCommand event:

There are two ways to find rowindex, as per me second is comparatively good one
because we need not to do control.Parent.Parent




int rowIndex
= ((GridViewRow)((Control)e.CommandSource).Parent.Parent).RowIndex;

int rowIndex
= ((GridViewRow)((Control)e.CommandSource).NamingContainer).RowIndex;




4) How to search a particular object in a Generic List:

Consider we have a generic list that holds an organization's employees objects,
and we find to a particular employee object based on some input like employee ID.
Here is the code:



List employees = ""; //Logic to fill employees list.
//Search a particular employee based on employee code
//[Here EmployeeCode is one of the variable or properties in Employee class]
Employee employee = employees.Find(delegate(Employee emp)
{ return emp.EmployeeCode == inputValue; });





5) How to find control(s) in ASP.Net GridView's EmptyDataTemplate?

If we are using ASP.Net GridView for displaying records, then to display GridView with no record we have to use EmptyDataTemplate. Inside that we will write all our required controls.

Consider a case... in which EmptyDataTemplate contains a textbox and a button.
If we click button, then GridView's OnRowCommand event will fire.

In GridView_OnRowCommand method to get textbox control we can follow one of the following approaches:


//Approach 1
TextBox txt
= (TextBox)gridviewSP.Controls[0].Controls[0].Controls[0].Controls[1];

//Approach 2
GridViewRow row
= (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
TextBox txt = row.FindControl("txtName");


As per me second approach is good one, because we need to do blind control search.

In second approach first we are getting GridViewRow, that contains textbox and button. Then in that GridViewRow, with FindControl function find our required textbox.


6) ASP.Net's GridView sorting logic




//C# code

//Call to get GridView's SortOrder and SortExpression...
string sortExpression = e.SortExpression;
bool sorting = GetSortDirection(sortExpression) == "ASC" ? true : false;
.
.


.
.
/// <summary>
/// Gets sort direction for gridview sorting
/// </summary>
/// <param name="column"></param>
/// <returns></returns>
string GetSortDirection(string column)
{
// By default, set the sort direction to ascending.
string sortDirection = "ASC";

// Retrieve the last column that was sorted.
string sortExpression = ViewState["SortExpression"] as string;

if (sortExpression != null)
{
// Check if the same column is being sorted.
// Otherwise, the default value can be returned.
if (sortExpression == column)
{
string lastDirection = ViewState["SortDirection"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection = "DESC";
}
}
}

// Save new values in ViewState.
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;

return sortDirection;
}




7) Operation related to ASP.Net's TextBox with TextMode set to Password :
If we set the TextMode property of ASP:TextBox to Password, then we can't directly access the Text property of TextBox after page postback. Its a known issue and one of the solution is to use Attributes of textbox. We can set the TextBox's Attributes in TextBox_PreRender event and consume its value anywhere we want by using the stored value in Attributes.



<!-- HTML code -->
<asp:TextBox ID="TextBoxPassword" OnPreRender="TextBoxPassword_PreRender"
TextMode="Password" runat="server" Width="150px"></asp:TextBox>


//C# code

protected void TextBoxPassword_PreRender(object sender, EventArgs e)
{
TextBoxPassword.Attributes.Add("value", TextBoxPassword.Text);
}

protected void ButtonAddUser_Click(object sender, EventArgs e)
{
String password = TextBoxPassword.Attributes["value"];
}





8) Operation related to ASP.Net's GridView and DataTable :
This section covers DataTable and its usage in ASP:GridView, especially the Primary Key column and Find functionality of DataTable. [Code are self-explainatory with comments]



//C# code

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Get the DataTable instance and store it
//in ViewState to be used later on.
if (ViewState["EmpDataTable"] == null)
{
ViewState["EmpDataTable"] = CreateDataTable();
}

dataTableEmps = (DataTable)ViewState["EmpDataTable"];

//Set the DataSource and Bind the Grid
GridViewEmps.DataSource = dataTableEmps;
GridViewEmps.DataBind();
}
}


//Create and return a DataTable and its schema.
DataTable CreateDataTable()
{
//Create a DataTable, then add two Columns in it.
DataTable dataTable = new DataTable("Employeess");

dataTable.Columns.Add("EmployeeName", Type.GetType("System.String"));

DataColumn primaryColumn
= new DataColumn("EmployeeID", Type.GetType("System.String"));
dataTable.Columns.Add(primaryColumn);

//Set the PrimaryKey in DataTable
//(to be used in Find functionality of DataTable)
primaryColumn.Unique = true;
dataTable.PrimaryKey = new DataColumn[] { primaryColumn };

return dataTable;
}

//GridView's OnRowDeleting event
protected void GridViewEmps_RowDeleting(object sender
, GridViewDeleteEventArgs e)
{
//Get the control value
string empID
= ((Label)GridViewEmps.Rows[e.RowIndex]
.FindControl("LabelGridViewEmpID")).Text;

//Get the DataTable instance
if (ViewState["EmpDataTable "] == null)
ViewState["EmpDataTable "] = CreateDataTable();
else
dataTableEmps = (DataTable)ViewState["EmpDataTable "];

//Find the row, which we want to delete.
//Only pass the value of Primary key column.
DataRow row = dataTableEmps.Rows.Find(empID);

dataTableEmps.Rows.Remove(row);
GridViewEmps.DataSource = dataTableEmps;
GridViewEmps.DataBind();
}


<!-- HTML code -->
<asp:GridView ID="GridViewEmps" runat="server"
AutoGenerateColumns="false"
OnRowDeleting="GridViewEmps_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="LabelGridViewEmpName" runat="server"
Text='<%# Bind("EmployeeName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LoginName" Visible="false">
<ItemTemplate>
<asp:Label ID="LabelGridViewEmpID" runat="server"
Text='<%# Bind("EmployeeID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>






9) Function to convert a image/text file into byte array

private byte [] StreamFile(string filename)
{
FileStream fs = new FileStream(filename, FileMode.Open,FileAccess.Read);

// Create a byte array of file stream length
byte[] dataArray = new byte[fs.Length];

//Read block of bytes from stream into the byte array
fs.Read(dataArray,0,System.Convert.ToInt32(fs.Length));

//Close the File Stream
fs.Close();
return dataArray; //return the byte data
}




10) Code to add a new XmlNode / XmlElement in XmlDocument:

string strFilename = "Employees.xml";
XmlDocument xmlDoc = new XmlDocument();

if (File.Exists(strFilename))
{
xmlDoc.Load(strFilename);

XmlElement xElement = xmlDoc.CreateElement("Employee");
string strNewEmployee = "<ID>9</ID>" +
"<Name>Avi</Name>" +
"<Age>25</Age>";

xElement.InnerXml = strNewEmployee;
xmlDoc.DocumentElement.AppendChild(xElement);

xmlDoc.Save("Employees.xml");
}

No comments:

Google