Sunday, October 9, 2011

Moving,Sorting and Searching Items between two Generic Listbox controls

 

I will explain you how to create user control using two listbox control and moving,filtering and searching items between them.First of all you should add two listbox and add the buttons like given below.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ucListBox.ascx.cs" Inherits="ucListBox" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<script type="text/javascript" language="javascript">
var ddlText, ddlValue, ddl, lblMesg;
function CacheItems() {

ddlText = new Array();
ddlValue = new Array();
ddl = document.getElementById("<%=lstAvailable.ClientID %>");

for (var i = 0; i < ddl.options.length; i++) {
ddlText[ddlText.length] = ddl.options[i].text;
ddlValue[ddlValue.length] = ddl.options[i].value;
}
}

window.onload = CacheItems;

function FilterItems(value) {

ddl.options.length = 0;
for (var i = 0; i < ddlText.length; i++) {
if (ddlText[i].toLowerCase().indexOf(value) != -1) {
AddItem(ddlText[i], ddlValue[i]);
}
}

if (ddl.options.length == 0) {
AddItem("", "");
}
}

function AddItem(text, value) {

var opt = document.createElement("option");
opt.text = text;
opt.value = value;
ddl = document.getElementById("<%=lstAvailable.ClientID %>");
ddl.options.add(opt);
}

</script>

<table width="100%" border="0">
<tr>
<td style="width: 19%; height: 24px;" runat="server" id="tdd">
<span style="font-size: 8pt"><strong>
<asp:Label runat="server" Text="Search" ID="lblSearch" meta:resourcekey="lblSearchResource1"></asp:Label>
</strong></span>
</td>
<td>
<asp:TextBox ID="txtSearch" runat="server" onkeyup="FilterItems(this.value)" meta:resourcekey="txtSearchResource1"></asp:TextBox><br />
</td>
</tr>
</table>
<table width="60%">
<tr>
<td>
</td>
</tr>
<tr align="center">
<td align="center">
<!-- Start list box-->
<table width="100%">
<tr>
<td valign="top">
<table border="0" width="100%">
<tr>
<td>
<span style="font-size: 8pt"><strong>
<asp:Label runat="server" ID="lblAvailable" Text="Available" meta:resourcekey="lblAvailableResource2"></asp:Label>
</strong></span>
</td>
</tr>
<tr>
<td style="height: 200px">
<asp:ListBox ID="lstAvailable" runat="server" Font-Size="8pt" Height="100%" SelectionMode="Multiple"
Width="300px" meta:resourcekey="lstAvailableResource1"></asp:ListBox>
</td>
</tr>
</table>
</td>
<td align="center" valign="top">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<asp:ImageButton ID="btnAddAll" runat="server" ImageUrl="~/Images/Last.png" CausesValidation="False" />
</td>
</tr>
<tr>
<td>
<asp:ImageButton ID="btnAdd" runat="server" ImageUrl="~/Images/Next.png" CausesValidation="False" />
</td>
</tr>
<tr>
<td>
<asp:ImageButton ID="btnRemove" runat="server" CausesValidation="False" ImageUrl="~/Images/Previous.png" />
</td>
</tr>
<tr>
<td>
<asp:ImageButton ID="btnRemoveAll" runat="server" CausesValidation="False" ImageUrl="~/Images/First.png" />
</td>
</tr>
</table>
</td>
<td valign="top">
<table width="100%">
<tr>
<td>
<span style="font-size: 8pt"><strong>
<asp:Label runat="server" ID="lblAdded" Text="Added" meta:resourcekey="lblAddedResource2"></asp:Label>
</strong></span>
</td>
</tr>
<tr>
<td style="height: 200px">
<asp:ListBox ID="lstAdded" runat="server" Font-Size="8pt" Height="100%" SelectionMode="Multiple"
Width="300px" meta:resourcekey="lstAddedResource1"></asp:ListBox>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
</td>
<td>
<table width="100%">
<tr>
<td>
<asp:ImageButton ID="btnMoveUp" runat="server" CausesValidation="False" ImageUrl="~/Images/MoveUp.png" />
</td>
</tr>
<tr>
<td>
<asp:ImageButton ID="btnMoveDown" runat="server" CausesValidation="False" ImageUrl="~/Images/Movedown.png" />
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-- end list box-->
</td>
</tr>
</table>



Now let’s, create a method for Moving the items between two ListBox. Here’s the code block below:



using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

public partial class ucListBox : System.Web.UI.UserControl
{

#region Property
private IList _DataSourceAvailable = null;
private IList _DataSourceAdded = null;
private string _dataTextFieldAvailable = string.Empty;
private string _dataValueFieldAvailable = string.Empty;
private string _dataTextFieldAdded = string.Empty;
private string _dataValueFieldAdded = string.Empty;
private string _availableItemText = "Available Items";
private string _addedItemText = "Added Items";
protected ArrayList arlList = new ArrayList();

/// <summary>
/// Gets or sets the available item text.
/// </summary>
/// <value>The available item text.</value>
///

public string AvailableItemText {
get { return _availableItemText; }
set { _availableItemText = value; }
}

/// <summary>
/// Gets or sets the added items text.
/// </summary>
/// <value>The added items text.</value>
public string AddedItemsText
{
get { return _addedItemText; }
set { _addedItemText = value; }
}

/// <summary>
/// Gets the available items.
/// </summary>
/// <value>The available items.</value>
public ListItemCollection AvailableItems
{
get { return lstAvailable.Items; }
}

/// <summary>
/// Gets the added items.
/// </summary>
/// <value>The added items.</value>
public ListItemCollection AddedItems
{
get { return lstAdded.Items; }
}

/// <summary>
/// Gets or sets the data source for the available items listbox.
/// </summary>
/// <value>The data source for available items.</value>
public IList DataSourceAvailable
{
get { return _DataSourceAvailable; }
set { _DataSourceAvailable = value; }
}

/// <summary>
/// Gets or sets the data source for the added items listbox.
/// </summary>
/// <value>The data source for added items.</value>
public IList DataSourceAdded
{
get { return _DataSourceAdded; }
set { _DataSourceAdded = value; }
}

/// <summary>
/// Gets or sets the data text field available.
/// </summary>
/// <value>The data text field available.</value>
public string DataTextFieldAvailable
{
get { return _dataTextFieldAvailable; }
set { _dataTextFieldAvailable = value; }
}

/// <summary>
/// Gets or sets the data value field available.
/// </summary>
/// <value>The data value field available.</value>
public string DataValueFieldAvailable
{
get { return _dataValueFieldAvailable; }
set { _dataValueFieldAvailable = value; }
}

/// <summary>
/// Gets or sets the data text field added.
/// </summary>
/// <value>The data text field added.</value>
public string DataTextFieldAdded
{
get { return _dataTextFieldAdded; }
set { _dataTextFieldAdded = value; }
}

/// <summary>
/// Gets or sets the data value field added.
/// </summary>
/// <value>The data value field added.</value>
public string DataValueFieldAdded
{
get { return _dataValueFieldAdded; }
set { _dataValueFieldAdded = value; }
}
#endregion

#region Method
protected void Page_Load(object sender, EventArgs e)
{


}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Initializer();

}
public void Initializer()
{
btnAdd.Click += new ImageClickEventHandler(btnAdd_Click);
btnAddAll.Click += new ImageClickEventHandler(btnAddAll_Click);
btnRemove.Click += new ImageClickEventHandler(btnRemove_Click);
btnRemoveAll.Click += new ImageClickEventHandler(btnRemoveAll_Click);
btnMoveUp.Click += new ImageClickEventHandler(btnMoveUp_Click);
btnMoveDown.Click += new ImageClickEventHandler(btnMoveDown_Click);
lblAdded.Text = this.AddedItemsText;
lblAvailable.Text = this.AvailableItemText;
}



public void BindAvailableList()
{
//Set the Header Text of the Available and Added Items
lblAdded.Text = this.AddedItemsText;
lblAvailable.Text = this.AvailableItemText;

//Bind the Added List Control
lstAvailable.DataSource = this.DataSourceAvailable;
lstAvailable.DataTextField = this.DataTextFieldAvailable;
lstAvailable.DataValueField = this.DataValueFieldAvailable;
lstAvailable.DataBind();
}
public void BindAddedList()
{
//Set the Header Text of the Available and Added Items
lblAdded.Text = this.AddedItemsText;
lblAvailable.Text = this.AvailableItemText;

//Bind the Available List Control
lstAdded.DataSource = this.DataSourceAdded;
lstAdded.DataTextField = this.DataTextFieldAdded;
lstAdded.DataValueField = this.DataValueFieldAdded;
lstAdded.DataBind();
}

public void BindList()
{
//Set the Header Text of the Available and Added Items
lblAdded.Text = this.AddedItemsText;
lblAvailable.Text = this.AvailableItemText;

//Bind the Available and Added List Controls
lstAdded.DataSource = this.DataSourceAdded;
lstAdded.DataTextField = this.DataTextFieldAdded;
lstAdded.DataValueField = this.DataValueFieldAdded;
lstAdded.DataBind();

lstAvailable.DataSource = this.DataSourceAvailable;
lstAvailable.DataTextField = this.DataTextFieldAvailable;
lstAvailable.DataValueField = this.DataValueFieldAvailable;
lstAvailable.DataBind();


#region Remove intersection Record
ArrayList ary = new ArrayList();

for (int i = 0; i < lstAvailable.Items.Count; i++)
{
for (int j = 0; j < lstAdded.Items.Count; j++)
{

if (lstAvailable.Items[i].Value == lstAdded.Items[j].Value)
{
// lstAvailable.RemoveAt(i);
if (!ary.Contains(lstAvailable.Items[i]))
{
ary.Add(lstAvailable.Items[i]);
j = -1;
}
break;
}

}

}
for (int i = 0; i < ary.Count; i++)
{
lstAvailable.Items.Remove(((ListItem)ary[i]));

}

#endregion

ScriptManager.RegisterStartupScript(Page, typeof(Page), "myscript", "CacheItems();", true);
//ScriptManager.RegisterStartupScript(Page, typeof(Page), "myscript", "UploadFileToParent();", true);
}

#endregion

#region Navigation

/// <summary>
/// Add all the selected items from the Available Items to the Added Items
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void btnAdd_Click(object sender, EventArgs e)
{
if (lstAvailable.SelectedIndex >= 0)
{
for (int i = 0; i < lstAvailable.Items.Count; i++)
{
if (lstAvailable.Items[i].Selected)
{
if (!arlList.Contains(lstAvailable.Items[i]))
arlList.Add(lstAvailable.Items[i]);
}
}
for (int i = 0; i < arlList.Count; i++)
{
if (!lstAdded.Items.Contains((ListItem)arlList[i]))
lstAdded.Items.Add((ListItem)arlList[i]);
lstAvailable.Items.Remove((ListItem)arlList[i]);
}
}
}

/// <summary>
/// Add all the items from the Available items to the Added Items
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void btnAddAll_Click(object sender, EventArgs e)
{
foreach (ListItem list in lstAvailable.Items)
{
lstAdded.Items.Add(list);
}
lstAvailable.Items.Clear();
}

/// <summary>
/// Moves the Selected items from the Added items to the Available items
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void btnRemove_Click(object sender, EventArgs e)
{
if (lstAdded.SelectedIndex >= 0)
{
for (int i = 0; i < lstAdded.Items.Count; i++)
{
if (lstAdded.Items[i].Selected)
{
if (!arlList.Contains(lstAdded.Items[i]))
arlList.Add(lstAdded.Items[i]);
}
}
for (int i = 0; i < arlList.Count; i++)
{
if (!lstAvailable.Items.Contains((ListItem)arlList[i]))
lstAvailable.Items.Add((ListItem)arlList[i]);
lstAdded.Items.Remove((ListItem)arlList[i]);
}
}
}

/// <summary>
/// Moves all the items from the Added items to the Available items
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void btnRemoveAll_Click(object sender, EventArgs e)
{
foreach (ListItem list in lstAdded.Items)
{
lstAvailable.Items.Add(list);
}
lstAdded.Items.Clear();
}

/// <summary>
/// Move item to upwards
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnMoveDown_Click(object sender, ImageClickEventArgs e)
{
try
{
int startindex = lstAdded.Items.Count - 1;
for (int i = startindex; i > -1; i--)
{
if (lstAdded.Items[i].Selected)//identify the selected item
{
//swap with the lower item(move down)
if (i < startindex && !lstAdded.Items[i + 1].Selected)
{
ListItem bottom = lstAdded.Items[i];
lstAdded.Items.Remove(bottom);
lstAdded.Items.Insert(i + 1, bottom);
lstAdded.Items[i + 1].Selected = true;
}

}
}
}
catch (Exception ex)
{

}
}

/// <summary>
/// Move Item To down Words
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnMoveUp_Click(object sender, ImageClickEventArgs e)
{
try
{
for (int i = 0; i < lstAdded.Items.Count; i++)
{
if (lstAdded.Items[i].Selected)//identify the selected item
{
//swap with the top item(move up)
if (i > 0 && !lstAdded.Items[i - 1].Selected)
{
ListItem bottom = lstAdded.Items[i];
lstAdded.Items.Remove(bottom);
lstAdded.Items.Insert(i - 1, bottom);
lstAdded.Items[i - 1].Selected = true;
}
}
}

}
catch (Exception ex)
{

}
}

#endregion
}

Sunday, August 28, 2011

Textual description of firstImageUrl

FileUpload Control File Type and File Size Validations

Normally we need validation to restrict the user for uploading any kind of files on a Web Server due to security or application requirement also we need to limit the file size to upload on web server.There are many ways to implement validation on file upload control its depend upon application requirement which method you can used .Here I will explain only three validation method you can implement on file upload controls.
 

Upload Control

Validation using Custom Validator on Client Side

You can used custom validator to implement fileupload validation on client side.This validation is faster and easy to implement.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">

<script language="javascript" type="text/javascript">
function ValidateAttachment(Source, args)
{
var UploadControl = document.getElementById('<%= UploadControl.ClientID %>');

var FilePath = UploadControl.value;

if(FilePath =='')
{
args.IsValid = false;//No file found
}
else
{
var Extension = FilePath.substring(FilePath.lastIndexOf('.') + 1).toLowerCase();

if (Extension == "doc" || Extension == "txt")
{
args.IsValid = true; // Valid file type
}
else
{
args.IsValid = false; // Not valid file type
}
}
}


</script>

<div>
<asp:FileUpload ID="UploadControl" runat="server" />
&nbsp;<asp:Button ID="btnUpload" runat="server" Text="Upload"
onclick="btnUpload_Click" style="height: 26px" />
<br />
<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="ValidateAttachment"
ErrorMessage="Please select valid .doc or .txt file"
onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
<asp:Label runat="server" ID="StatusLabel" Text="Upload status: " />

</div>
</form>
</body>
</html>

Validation using Custom Validator on Server Side


You can also apply validation on server using custom validator its slower than client side but its more secure than client side.

 protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{

string UploadFileName = UploadControl.PostedFile.FileName;

if (string.IsNullOrEmpty(UploadFileName))
{
args.IsValid = false;
}
else
{
string Extension = UploadFileName.Substring(UploadFileName.LastIndexOf('.') + 1).ToLower();

if (Extension == "doc" || Extension == "txt")
{
if (UploadControl.PostedFile.ContentLength < 102400)
{
args.IsValid = true;

}
else
{
args.IsValid = false;
CustomValidator1.ErrorMessage = "File size should be less than 100 kb";
}
}
else
{
args.IsValid = false; // Not valid file type
CustomValidator1.ErrorMessage = "File Type should be .doc or .txt";
}
}



}

By default, the maximum size of a file to be uploaded to the server using the FileUpload control is around 4MB. You cannot upload anything that is larger than this limit.




Change File Upload Limit


In the web.config file, find a node called <httpRuntime> that looks like the following:

<httpRuntime 
executionTimeout="110"
maxRequestLength="4096"
requestLengthDiskThreshold="80"
useFullyQualifiedRedirectUrl="false"
minFreeThreads="8"
minLocalRequestFreeThreads="4"
appRequestQueueLimit="5000"
enableKernelOutputCache="true"
enableVersionHeader="true"
requireRootedSaveAsPath="true"
enable="true"
shutdownTimeout="90"
delayNotificationTimeout="5"
waitChangeNotification="0"
maxWaitChangeNotification="0"
enableHeaderChecking="true"
sendCacheControlHeader="true"
apartmentThreading="false" />



lot is going on in this single node, but the setting that takes care of the size of the files to be uploaded is the maxRequestLength attribute. By default, this is set to 4096 kilobytes (KB). Simply change this value to increase the size of the files that you can upload to the server. If you want to allow 10 megabyte (MB) files to be uploaded to the server, set the maxRequestLength value to 11264, meaning that the application allows files that are up to 11000 KB to be uploaded to the server.


for futher detail check this Working Around File Size Limitations.


Direct Validation on Upload Button


In this method you don’t need to used custom validator you can directly write the code on button click and manually show message using label control.



 protected void btnUpload_Click(object sender, EventArgs e)
{

if (UploadControl.HasFile)
{
try
{
if (UploadControl.PostedFile.ContentType == "image/jpeg")
{
if (UploadControl.PostedFile.ContentLength < 102400)
{
string filename = Path.GetFileName(UploadControl.FileName);
UploadControl.SaveAs(Server.MapPath("~/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
else
StatusLabel.Text = "Upload status: The file has to be less than 100 kb!";
}
else
StatusLabel.Text = "Upload status: Only .doc or .txt files are accepted!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}

}

Wednesday, August 17, 2011

Dynamic Load or Add User Control and Maintain the View State

In this post I will explain you how to add or load user control in a page or any other user control and maintain the view state.Normally we are facing problem when we load user control on button click or any business condition in this case when page will post back control will lost its view state or in other words losing form field values on post back.This is happen because we are adding user control after page Load View State Stage for further detail you should learn asp.net page lifecycle.That means, if we want our dynamic controls to persist view state itself we must add them to the control hierarchy in the page's Init event.

Here, I will explain the example when we want to add user control on any event.I have two user controls one is Grid view and second I will take login control and load on it into two submit buttons.
 
Adding Reference or Directive on a Webpage
 
The first thing we have to do, is declare our UserControls. It can be done either in each page where it's used, or globally in the web.config file. There is no performance difference, but when declaring UserControls in the web.config file, the controls have to reside in a different directory than the page(s) using it for further detail check my pervious post Register Custom User Control in Web.Config File

So in the webform, add the following directive:

<%@ Register src="Controls/GridView.ascx" tagname="GridView" tagprefix="uc1" %>

<%@ Register src="Controls/LoginControl.ascx" tagname="LoginControl" tagprefix="uc2" %>

Loading dynamically

For loading user control on a page you should need to drag and drop the place holder where you want to show user control.

<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

Also add the two buttons to add user control on button click .
<asp:Button ID="btnGrindControl" runat="server" Text="Button" />
<asp:Button ID="btnLoginControl" runat="server" Text="Button" />
your aspx page look like this,

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Src="Controls/GridView.ascx" TagName="GridView" TagPrefix="uc1" %>
<%@ Register Src="Controls/LoginControl.ascx" TagName="LoginControl" TagPrefix="uc2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">

<asp:Button ID="btnGrindControl" runat="server" Text="Button" />
<asp:Button ID="btnLoginControl" runat="server" Text="Button" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

</asp:Content>



Code Behind

In the Code Behind of the page, we add the control like this:
PlaceHolder1.Controls.Add(LoadControl("~/UserControl.ascx"));


In order to maintain the Viewstate of user control you should maintain the UserControl complete path and used this path every time on postback and load the control.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
public string ControlPath
{
get
{
if (ViewState["controlPath"] != null)
return Convert.ToString(ViewState["controlPath"]);
else
return null;
}

set
{
ViewState["controlPath"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
LoadUserControl();

}
private void LoadUserControl()
{
if (!string.IsNullOrEmpty(ControlPath))
{
PlaceHolder1.Controls.Clear();
UserControl uc = (UserControl)LoadControl(ControlPath);
PlaceHolder1.Controls.Add(uc);
}
}



protected void btnGrindControl_Click(object sender, EventArgs e)
{
ControlPath = "Controls/GridView.ascx";
LoadUserControl();
}
protected void btnLoginControl_Click(object sender, EventArgs e)
{
ControlPath = "Controls/LoginControl.ascx";
LoadUserControl();
}
}


In above example I create one property name “ControlPath” for maintaining the Url of user control on button click .In LoadUserContol() I am just clearing the placeholder and adding the user control.In postback user control is adding everytime beacuse  user control was added after the page load and view state stage .There are few good articles written by Scott Mitchell on dynamically loading Controls which you will find in the following links:


Conclusion

In this article we saw how to work with dynamic controls so that their values and view state can be correctly persisted across postbacks.

Wednesday, August 3, 2011

Debugging Asp.net application using XML Serialization

 

Debugging on Test or Production server is very difficult task for developers.First of all developers do not have any rights to touch the Test or Production environment and he received the list of bugs mainly due to data problem on production or Test Server.When developers try to reproduce the bugs on development environment is not possible because data development environment is accurate.So I have found out the solution of this problem through XML Serialization techniques which describe as below:-

In this article I am taking a example of simple Employee Detail.I will explain how we can debug using XML Serialize data.

Example

First I have declare a Employee class and create one method for creating employee details.

public class Employee
{
public string EmployeeName { get; set; }
public string Address { get; set; }
public int MobilNo { get; set; }


public List<Employee> GetEmployees()
{
List<Employee> Emplst = new List<Employee>();

for (int i = 0; i < 5; i++)
{
Employee emp = new Employee();
emp.EmployeeName = "Employee" + "-" + i.ToString();
emp.Address = "Address" + "-" + i.ToString();
emp.MobilNo = 9899 + (i + 2);
Emplst.Add(emp);
}
return Emplst;
}

}



 



Now create one page and call the GetEmployee() Method and fill the grid.



 public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Employee objEmp= new Employee();

GridView1.DataSource = objEmp.GetEmployees();
GridView1.DataBind();
}
}





Scenario 1



It is very simple code to populate grid from GetEmployees() method but you assume that data is coming from the database and populating the grid and at this time you are facing problem .Now you can track or debug the application with XML Serialization.



protected void Page_Load(object sender, EventArgs e)
{
Employee objEmp = new Employee();

SaveXMLData(objEmp.GetEmployees(), "Employee.XML");
GridView1.DataSource = ReadXMLData<Employee>("Employee.XML");
GridView1.DataBind();
}


#region For Serialization Code

public void SaveXMLData<T>(List<T> list, string fileName)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
{
TextWriter writer = new StreamWriter(Server.MapPath("~\\XMLFiles") + "\\" + fileName);
serializer.Serialize(writer, list);
writer.Close();

}
}

public List<T> ReadXMLData<T>(string filename)
{
XmlSerializer deserializer = new XmlSerializer(typeof(List<T>));
TextReader textReader = new StreamReader(Server.MapPath("~\\XMLFiles") + "\\" + filename);
List<T> list;
list = (List<T>)deserializer.Deserialize(textReader);
textReader.Close();

return list;
}

#endregion
}


If you see the code on page load I have save the data first into XML and then retrieve and display into the grid due to this every time save data into XML So if  you find any problem in module you will get the XML file from Production or Test Server and Load into development environment through ReadXMLData() method and debug it.



Here is the XML Generate file from the above SaveXMLData() method.



<?xml version="1.0" encoding="utf-8" ?> 
- <ArrayOfEmployee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
- <Employee>
<EmployeeName>Employee-0</EmployeeName>
<Address>Address-0</Address>
<MobilNo>9901</MobilNo>
</Employee>
- <Employee>
<EmployeeName>Employee-1</EmployeeName>
<Address>Address-1</Address>
<MobilNo>9902</MobilNo>
</Employee>
- <Employee>
<EmployeeName>Employee-2</EmployeeName>
<Address>Address-2</Address>
<MobilNo>9903</MobilNo>
</Employee>
- <Employee>
<EmployeeName>Employee-3</EmployeeName>
<Address>Address-3</Address>
<MobilNo>9904</MobilNo>
</Employee>
- <Employee>
<EmployeeName>Employee-4</EmployeeName>
<Address>Address-4</Address>
<MobilNo>9905</MobilNo>
</Employee>
</ArrayOfEmployee>




Scenario 2



If you are thinking for every time save and read data from XML then application performance will affected so you can change the code like this only when exception will raise it will save the data into xml and then if you want to debug write ReadXMLData() method in a code where you want.



protected void Page_Load(object sender, EventArgs e)
{
try
{
Employee objEmp = new Employee();
GridView1.DataSource = objEmp.GetEmployees();
GridView1.DataBind();
}
catch (Exception ex)
{
SaveXMLData(objEmp.GetEmployees(), "Employee.XML");
throw;
}

}



Conclusion






We have seen in above samples that how we can take advantage of serialization mechanism provided by .Net. In this tutorial I have tried to keep things as simple as possible so you can understand and using the basic concepts of XML serialization for debugging the application. Feel free to share your comments.

Saturday, July 23, 2011

Validate different controls on different buttons in a same page

 

Normally developers have a requirement to validate different controls on different buttons in this situation developers face problem when user click on any button all validation will be fire which are not belongs to that button functionality.

ASP.NET V2 introduces a new “ValidationGroup” property on validation and input controls that now makes this possible. This allows page developers to group different controls together for more granular validation behavior.

For example two groups – a “Group1” and a “Group2” of validators. There are then two buttons on the page – when button1 is clicked, the first group of validators will fire. When button2 is clicked, the second group of validators will fire. Postback will be blocked client-side by default if the validation fails:

 

Client Side Validation

<html>
<body>
     <form runat=“server”>
          <asp:textbox id=“TextBox1” runat=“server”/>
          <asp:requiredfieldvalidator ValidationGroup=“Group1” ErrorText=“Need to Fill in Value!” ControlToValidate=“TextBox1” runat=“server”/>
            <asp:textbox id=“TextBox2” runat=“server”/>
            <asp:requiredfieldvalidator ValidationGroup=“Group2” ErrorText=“Need to Fill in Value!” ControlToValidate=“TextBox2” runat=“server”/>
            <asp:button text=“Group1” ValidationGroup=“Group1” runat=“server”/>
            <asp:button text=“Group2” ValidationGroup=“Group2” runat=“server”/>
     </form>
</body>
 
</html>
 

The code given above has two validation groups. The first validation groups is identified as “First” and the second validation group is identified as “Second”. Each validation group has two textboxes, a RequiredField validator and a button. If you look at the code you might see that each control has a property called “ValidationGroup” and its value is set to the name of the validation group to which that control belongs.


Clicking the “Submit1” button initiates the validation of the first group and throws an error message if the TextBox1 is left blank. Since this button belongs to the ‘First’ validation group, it initiates the validaton controls that belongs to that group. Similarly clicking the ‘Submit2’ button throws an error message if the TextBox3 is left blank. Thus the validation groups help in grouping the controls in a single web page allowing you to have separate validations for different controls while allowing you to submit values in a particular group.


 


Server Side Validation


If you want to validate on server side just call page.Validate(“Group Name”) on button click event it will automatically call respective group.You don’t have need to define specific group on html code.



<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" Runat="server" ValidationGroup="First"></asp:TextBox>
<asp:TextBox ID="TextBox2" Runat="server" ValidationGroup="First"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" Runat="server" ValidationGroup="First"ErrorMessage="TextBox1 should not be blank" ControlToValidate="TextBox1"> </asp:RequiredFieldValidator>
<asp:Button ID="Submit1" Runat="server"  Text="Submit 1" />
 <br /><br /> 
<asp:TextBox ID="TextBox3" Runat="server" ValidationGroup="Second"></asp:TextBox> 
<asp:TextBox ID="TextBox4" Runat="server" ValidationGroup="Second"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" Runat="server" ErrorMessage=" TextBox3 should not be blank"ControlToValidate="TextBox3" ValidationGroup="Second"></asp:RequiredFieldValidator>
 <asp:Button ID="Submit2" Runat="server"  Text="Submit 2" />
 </div>
</form>
</body> 

 



protected void Submit1_Click(object sender, EventArgs e)
{
 
Page.Validate("First");
 
if(Page.IsValid)
    {
        // Continue
    }
}
 
protected void Submit2_Click(object sender, EventArgs e)
{
 
Page.Validate("Second");
 
if(Page.IsValid)
    {
        // Continue
    }
}
  




      

PDF Arabic watermark using MVC and iTextSharp

PDF full page Arabic watermark using MVC and iTextSharp Download :  Source Code Most of the time we have requirement to  gen...