Wednesday, December 30, 2009

Delete Type URL from AddressBar

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Permissions;
using Microsoft.Win32;
using System.Windows.Forms;
using System.IO;

[assembly: RegistryPermission(SecurityAction.RequestMinimum, ViewAndModify = "HKEY_CURRENT_USER\\SOFTWARE\\MICROSOFT\\INTERNET EXPLORER\\TYPEDURLS")]
[assembly: RegistryPermission(SecurityAction.RequestMinimum, ViewAndModify = "HKEY_CURRENT_USER\\SOFTWARE\\MICROSOFT\\INTERNET EXPLORER")]

then declare below static constant string varible:

public static SortedList historylinks = new SortedList();
public const string REG_URL = "SOFTWARE\\MICROSOFT\\INTERNET EXPLORER\\TYPEDURLS";
public const string REG_URL_SHORT = "SOFTWARE\\MICROSOFT\\INTERNET EXPLORER";

then here is the code for:

GetHistory();
int deletedhist = 0;
using (RegistryKey tempKey = Registry.CurrentUser.OpenSubKey(REG_URL, true))
{
if (tempKey == null)
{
System.Windows.Forms.MessageBox.Show("The registry entry for " + REG_URL + " does not exist!",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
} // if
else
{
foreach (histlink hl in historylinks.Values)
{
tempKey.DeleteValue(hl.URL);
deletedhist++;
}
}
}
GetHistory();
lbl_message.Text = "Typed URL's cleared";

and here is the code for gethistory function:

public void GetHistory()
{
historylinks.Clear();
using (RegistryKey tempKey = Registry.CurrentUser.OpenSubKey(REG_URL))
{
if (tempKey == null)
{

using (RegistryKey tempKeyShort = Registry.CurrentUser.OpenSubKey(REG_URL_SHORT, true))
{
if (tempKeyShort == null)
{
MessageBox.Show("The registry entry for " + REG_URL_SHORT + " does not exist!",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
tempKeyShort.CreateSubKey("TypedURLs", RegistryKeyPermissionCheck.ReadWriteSubTree);
}
}
}
}

using (RegistryKey tempKey = Registry.CurrentUser.OpenSubKey(REG_URL))
{
if (tempKey == null)
{
System.Windows.Forms.MessageBox.Show("The registry entry for " + REG_URL + " does not exist!",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}

string[] vals = tempKey.GetValueNames();
int itemcounter = 0;
foreach (string url in vals)
{
object keyValue = tempKey.GetValue(url);
if (keyValue != null)
{
histlink hl = new histlink();
string entry = keyValue.ToString();
if (entry.Length != 0)
{
itemcounter++;
hl.Entry = entry;
hl.URL = url;
historylinks.Add(itemcounter, hl);
}
}
}
}

Deleting historyfile

In this code the header files and assembly files are same as Delete Cache which i post early

and the code is:

//textBox is used for deleting particular history file

string enteredtext = txt_url.Text.Trim();
string lowertext = txt_url.Text.ToLower();
string uppertext = txt_url.Text.ToUpper();

string[] historyfile = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.History), "*", SearchOption.AllDirectories);
for (int i = 0; i < historyfile.Count(); i++)
{
try
{
File.Delete(historyfile.ElementAt(i));
lbl_message.Text = historyfile.ElementAt(i)+ " cleared";


}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}


//this is the function which I used :

public void GetHistory()
{
historylinks.Clear();
using (RegistryKey tempKey = Registry.CurrentUser.OpenSubKey(REG_URL))
{
if (tempKey == null)
{

using (RegistryKey tempKeyShort = Registry.CurrentUser.OpenSubKey(REG_URL_SHORT, true))
{
if (tempKeyShort == null)
{
MessageBox.Show("The registry entry for " + REG_URL_SHORT + " does not exist!",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
tempKeyShort.CreateSubKey("TypedURLs", RegistryKeyPermissionCheck.ReadWriteSubTree);
}
}
}
}

using (RegistryKey tempKey = Registry.CurrentUser.OpenSubKey(REG_URL))
{
if (tempKey == null)
{
System.Windows.Forms.MessageBox.Show("The registry entry for " + REG_URL + " does not exist!",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}

string[] vals = tempKey.GetValueNames();
int itemcounter = 0;
foreach (string url in vals)
{
object keyValue = tempKey.GetValue(url);
if (keyValue != null)
{
histlink hl = new histlink();
string entry = keyValue.ToString();
if (entry.Length != 0)
{
itemcounter++;
hl.Entry = entry;
hl.URL = url;
historylinks.Add(itemcounter, hl);
}
}
}
}

Delete Temp File from Browser

In this code the header files and assembly files are same as Delete Cache which i post early

and the code is:

//textBox is used for deleting particular Temp Files

string enteredtext = txt_url.Text.Trim();
string lowertext = txt_url.Text.ToLower();
string uppertext = txt_url.Text.ToUpper();

string[] tempfiles = Directory.GetFiles(Environment.GetEnvironmentVariable("TEMP"), "*", SearchOption.AllDirectories);
for (int i = 0; i < tempfiles.Count(); i++)
{
try
{
if (tempfiles.ElementAt(i).Contains(enteredtext) || tempfiles.ElementAt(i).Contains(lowertext) || tempfiles.ElementAt(i).Contains(uppertext))
{
File.Delete(tempfiles.ElementAt(i));
lbl_message.Text = "TEMP file cleared";
}

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Delete Cookies

In this code the header files and assembly files are same as Delete Cache which i post early

and the code is:

//textBox is used for deleting particular Cookies

string enteredtext = txt_url.Text.Trim();
string lowertext = txt_url.Text.ToLower();
string uppertext = txt_url.Text.ToUpper();

string[] cookiefile = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Cookies), "*", SearchOption.AllDirectories);
for (int i = 0; i < cookiefile.Count(); i++)
{
try
{
if (cookiefile.ElementAt(i).Contains(enteredtext) || cookiefile.ElementAt(i).Contains(lowertext) || cookiefile.ElementAt(i).Contains(uppertext))
{
File.Delete(cookiefile.ElementAt(i));
lbl_message.Text = "Cookie cleared";
}

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Delete Internet Cache

First Include Heder files and assembly files to your Web page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Permissions;
using Microsoft.Win32;
using System.Windows.Forms;
using System.IO;

[assembly: RegistryPermission(SecurityAction.RequestMinimum, ViewAndModify = "HKEY_CURRENT_USER\\SOFTWARE\\MICROSOFT\\INTERNET EXPLORER\\TYPEDURLS")]
[assembly: RegistryPermission(SecurityAction.RequestMinimum, ViewAndModify = "HKEY_CURRENT_USER\\SOFTWARE\\MICROSOFT\\INTERNET EXPLORER")]

Then use this code:

//below is the textBox for deleting particular Cache from your Browser

string enteredtext = txt_url.Text.Trim();
string lowertext = txt_url.Text.ToLower();
string uppertext = txt_url.Text.ToUpper();

string[] internetcachefile = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), "*", SearchOption.AllDirectories);
for (int i = 0; i < internetcachefile.Count(); i++)
{
try
{
if (internetcachefile.ElementAt(i).Contains(enteredtext) || internetcachefile.ElementAt(i).Contains(lowertext) || internetcachefile.ElementAt(i).Contains(uppertext))
{
File.Delete(internetcachefile.ElementAt(i));
lbl_message.Text = "Cache cleared";
}

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Get Sensex Stock data From Yahoo Finace

StockData stockData = new StockData();
List StockDatalist = new List();
string serverUrl = @"http://in.finance.yahoo.com/d/quotes.csv?s=" + stockCode +"&f=sl1d1t1c1ohgvj1pp2owern&e=.csv";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverUrl);

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

StreamReader reader = new StreamReader(response.GetResponseStream(),
Encoding.ASCII);

stockDataString = reader.ReadLine();
string[] stockDataContents = stockDataString.Split(',');

stockData.Code = stockCode;
stockData.Last = stockDataContents[1];
stockData.Date = stockDataContents[2];
stockData.Time = stockDataContents[3];
stockData.Change = stockDataContents[4];
stockData.Open = stockDataContents[5];
stockData.High = stockDataContents[6];
stockData.Low = stockDataContents[7];
stockData.Volume = stockDataContents[8];
stockData.MarketCapital = stockDataContents[9];
stockData.PreviousClose = stockDataContents[10];
stockData.PctChange = stockDataContents[11];
stockData.AnnRange = stockDataContents[12];
stockData.Earnings = stockDataContents[13];
stockData.PERatio = stockDataContents[14];
StockDatalist.Add(stockData);

response.Close();

return stockDataString;

Fetch the data from other website

// used to build entire input
StringBuilder sb = new StringBuilder();

// used on each read operation
byte[] buf = new byte[8192];

// prepare the web page we will be asking for
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("http://www.bseindia.com/mktlive/groupgain.asp");

// execute the request
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();

// we will read data via the response stream
Stream resStream = response.GetResponseStream();

string tempString = null;
int count = 0;

do
{
// fill the buffer with data
count = resStream.Read(buf, 0, buf.Length);

// make sure we read some data
if (count != 0)
{
// translate from bytes to ASCII text
tempString = Encoding.ASCII.GetString(buf, 0, count);

// continue building the string
sb.Append(tempString);

}
}
while (count > 0); // any more data to read?



Response.Write(sb.ToString());

Tuesday, August 25, 2009

Home » ASP.NET & Web Forms » Uploading Multiple Files in ASP.NET 2.0: Part II

In ASP.NET 2.0, the FileUpload control enables users to upload file from your web pages. The FileUpload control consists of a text box and a browse button. Clicking on the button allow users to select a file on the client and upload it to the server. Here in this article I give the right to user to upload any number of images.

Let us start how to upload multiple file on a single button click. Follow these 2 steps


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

<!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>Make Multiple Upload Images</title>

<script type="text/javascript" language="javascript">
function DecreaseRow(rowNo)
{
var hid = document.getElementById('<%= hidCurRow.ClientID %>');
hid.value = rowNo;
}
function IncreseRows()
{
var hid = document.getElementById('<%= hidCurRow.ClientID %>');
hid.value = "";
}
function SetZero()
{
var hid = document.getElementById('<%= hidCurRow.ClientID %>');
hid.value = "0";
}
</script>

</head>
<body>
<form id="form1" runat="server">
<table cellpadding="0" cellspacing="0" width="80%" align="center">
<tr>
<td>
<asp:Table ID="tblMin" runat="server">
<asp:TableHeaderRow>
<asp:TableHeaderCell>
File
</asp:TableHeaderCell>
<asp:TableHeaderCell>
Remove
</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableRow>
<asp:TableCell>
<asp:FileUpload ID="fu1" runat="server" />
</asp:TableCell>
<asp:TableHeaderCell>
<asp:Button ID="btn1" runat="server" Text="Remove" OnClientClick="return DecreaseRow('1');" />
</asp:TableHeaderCell>
</asp:TableRow>
</asp:Table>
<asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="Add" OnClientClick="return IncreseRows();" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click"
OnClientClick="SetZero();" /><br />
<asp:HiddenField ID="hidMax" runat="server" Value="1" />
<asp:HiddenField ID="hidRow" runat="server" Value="1" />
<asp:HiddenField ID="hidCurRow" runat="server" />
</td>
</tr>
</table>
</form>
</body>
</html>

This is the cs code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == true)
{
AddRows();
}
}
private void AddRows()
{
try
{
if (hidCurRow.Value != "" && hidCurRow.Value != "0")
{
DecreaseCount();
}
else if (hidCurRow.Value == "")
{
IncreaseCount();
}

for (int count = 1; count < tblMin.Rows.Count; count++)
{
tblMin.Rows.RemoveAt(1);
}

int maxRows = Convert.ToInt32(hidMax.Value);
string[] arrRows = hidRow.Value.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
for (int count = 1; count <= maxRows; count++)
{
Boolean isAdd = false;
for (int incount = 0; incount < arrRows.Length; incount++)
{
if (arrRows[incount] == count.ToString())
{
isAdd = true;
break;
}
}

if (isAdd == true)
{
TableRow tr = new TableRow();

TableCell tcfu = new TableCell();
FileUpload fup = new FileUpload();
fup.ID = "fu" + count.ToString();
tcfu.Controls.Add(fup);

TableCell tcbtn = new TableCell();
Button bt = new Button();
bt.ID = "btn" + count.ToString();
bt.Text = "Remove";
bt.Attributes.Add("onclick", "DecreaseRow('" + count.ToString() + "');");
tcbtn.Controls.Add(bt);
tr.Cells.Add(tcfu);
tr.Cells.Add(tcbtn);
tblMin.Rows.Add(tr);
}
}
}
catch
{
}
}

private void IncreaseCount()
{
string strVal = hidMax.Value;
if (strVal != "")
{
int iMax = Convert.ToInt32(strVal);
iMax = iMax + 1;
hidMax.Value = iMax.ToString();

if (hidRow.Value != "")
{
hidRow.Value = hidRow.Value + "," + iMax.ToString();
}
else
{
hidRow.Value = iMax.ToString();
}
}
}

private void DecreaseCount()
{
string strCurRow = hidCurRow.Value;
string[] arrRows = hidRow.Value.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
hidRow.Value = "";
for (int count = 0; count < arrRows.Length; count++)
{
if (arrRows[count] != strCurRow)
{
if (hidRow.Value == "")
{
hidRow.Value = arrRows[count];
}
else
{
hidRow.Value = hidRow.Value + "," + arrRows[count];
}
}
}
}

protected void btnAdd_Click(object sender, EventArgs e)
{

}

protected void btnSubmit_Click(object sender, EventArgs e)
{
if (hidRow.Value != "")
{
string[] strVal = hidRow.Value.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
for (int count = 0; count < strVal.Length; count++)
{
FileUpload fup = new FileUpload();
fup = (FileUpload)tblMin.FindControl("fu" + strVal[count]);
if (fup != null)
{
if (fup.PostedFile != null && fup.FileName != "")
{
fup.SaveAs(Server.MapPath("MyFiles") + "\\" + Path.GetFileName(fup.FileName));
}
}
}
}
}
}


Regard

Prateek

Tree View Control in Silverlight 3

Crating Silverlight Project

Fire up Visual Studio 2008 and create a Silverlight Application. Name it as TreeViewSL3.

The TreeView control displays data in a hierarchical manner.

Open the solution in Expression Blend 3.

Go ahead and a Tree View control to your application.

I have changed the Background to Linear Brush.

To add TreeView Item to the Tree View, just right click on it and add TreeViewItem.


Add several, and if you want to add children of any parent then select the particular TreeViewItem and add another Treeview Item.


Here is the XAML code behind for the TreeView:

<controls:TreeView x:Name="MyTreeView" HorizontalAlignment="Left" Width="197" Margin="0,0,0,202">
<controls:TreeView.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Gray" Offset="0"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</controls:TreeView.Background>
<controls:TreeViewItem Margin="0" Header="Item 1">
<controls:TreeViewItem Margin="0" Header="Sub Item 1"/>
</controls:TreeViewItem>
<controls:TreeViewItem Margin="0" Header="Item 2">
<controls:TreeViewItem Margin="0" Header="Sub Item 1"/>
<controls:TreeViewItem Margin="0" Header="Sub Item 2"/>
</controls:TreeViewItem>
<controls:TreeViewItem Margin="0" Header="Item 3">
<controls:TreeViewItem Margin="0" Header="Sub Item 1">
<controls:TreeViewItem Margin="0" Header="Sub Item 1"/>
</controls:TreeViewItem>
</controls:TreeViewItem>
</controls:TreeView>


Now if you run the application you can expand or collapse a particular TreeViewItem.


Regard

Prateek

File Upload in Silverlight

Step 1: First, create a Silverlight Web application in Visual Studio 2008. You will see your default Page.xaml.

Step 2: On Create Page.xaml, change your code by adding following Panel, Button, and TextBlock controls.

On buttin click event handler, I write code to call the OpenFileDialog that allows us to browse files and gives us the selected file name.

Here is the code.

public void Button_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Multiselect = false;
dlg.Filter = "All files (*.*)|*.*|PNG Images (*.png)|*.png";

bool? retval = dlg.ShowDialog();

if (retval != null && retval == true)
{
UploadFile(dlg.File.Name, dlg.File.OpenRead());
StatusText.Text = dlg.File.Name;
}
else
{
StatusText.Text = "No file selected...";
}
}


As you can see from the above code, I call a method UploadFile by passing the selected file name from the OpenFileDialog.

The UploadFile method looks like following. In this code, I use a WebClient class and a PushData method.


private void UploadFile(string fileName, Stream data)
{
UriBuilder ub = new UriBuilder("http://localhost:3840/receiver.ashx");
ub.Query = string.Format("filename={0}", fileName);

WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
PushData(data, e.Result);
e.Result.Close();
data.Close();
};
c.OpenWriteAsync(ub.Uri);
}

private void PushData(Stream input, Stream output)
{
byte[] buffer = new byte[4096];
int bytesRead;

while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, bytesRead);
}
}

Step 3: Add a new Generic Handler receiver.ashx.

Now let's add a class. Right click on the project and Add a new item by selecting Generic Handler in the right side templates as

And add the following code on the coe behind:



<%@ WebHandler Language="C#" Class="receiver" %>

using System;
using System.Web;
using System.IO;

public class receiver : IHttpHandler {

public void ProcessRequest (HttpContext context) {
string filename = context.Request.QueryString["filename"].ToString();

using (FileStream fs = File.Create(context.Server.MapPath("~/App_Data/" + filename)))
{
SaveFile(context.Request.InputStream, fs);
}
}

private void SaveFile(Stream stream, FileStream fs)
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
fs.Write(buffer, 0, bytesRead);
}
}

public bool IsReusable {
get {
return false;
}
}
}


Step 4: Build and Run

That's all. You are done. Now just build and run your project.

When you click the Select File button, you will see Browse files dialog that lets you browse the files.



Note: You need to make sure your folder on the Web has write permissions to upload files.

Wednesday, August 19, 2009

What is SQL Injection

SQL Injection is an attack of non-valid inputs passed through web application for execution by a backend database , simply It is a trick to inject data to SQL query/command as an input possibly via web pages.

Best example for this, when a user login the web page that user name and password and make SQL query to the database to check if a user has valid name and password. With SQL Injection, it is possible for us to send crafted user name and/or password field that will change the SQL query and grant us.


SQL Query :


sqlquery = “ SELECT USERNAME FROM USERLOGINTABLE WHERE USERNAME = ‘ “ + strusername + “ ’ AND PASSWORD = ‘“ + strpwd + “ ’ ”;

sqlqueryresult = GetQueryresult(sqlquery);

if (sqlqueryresult = string.empty)

{

Response.write(“User login failed”);

}

Else

{

Response.redirect(“home.aspx”);

}



User passes ‘VIJI’ and ‘PASS’ as username and password respectively. If the user is a valid by executing the above SQL command, web page redirect to home page.


Look here, if user passes the below inputs Strusername as ‘ OR ‘ ‘ = ‘ and Strpwd as ‘ OR ‘ ‘ = ‘ then dynamic query will be


“ SELECT USERNAME FROM USERLOGINTABLE WHERE USERNAME = ‘ OR ‘ ‘ = ‘ AND PASSWORD = ‘ OR ‘ ‘ = ‘ “


Few judgment of this query:



* There is no syntax error

* There is no conflict between the operators.

* Inputs are not valid.



Web application will redirect the home page even input are invalid because result of the query will be true. The query compares the first single quotation and another quotation (means nothing) then OR is an operator. When comparing nothing to =, it returns true. Same execution is applied for password. These kind inputs are called vulnerable inputs to SQL commands.


Disadvantages


SQL injection provides a facility to the net hackers to pull the data from the backend database by supplying the vulnerable inputs.




Will Continue writing on the

Attacks of the SQL Injection




* Select Command.

* Insert Command.

* Using SQL Stored Procedures.

Regard

Prateek

.Net Shortcuts

.Net Keyboard Shortcuts

Key board shortcut keys always help to increase your speed. So i am giving below some of the Keyboard Shortcuts which will be very useful.
Ctrl + N :- Opens the New Project Dialogue Box
Ctrl + Shift + O :- Opens the Open File Dialog Box
Ctrl + Shift + A :- Opens Add New Item window
Ctrl + D :- Opens Add Existing Item window
Ctrl + F :- Opens Find window
Ctrl + H :- Opens Find and Replace window
Ctrl + Shift + H :- Opens Replace in Files window
Ctrl + Alt + Shift + F12 :- Opens Find Symbol window
F7 :- Opens Code Designer window
Shift + F7 :- Gets you back to Design View
Ctrl + R :- Opens the Solution Explorer window
Ctrl + Alt + S :- Opens the Server Explorer window
Ctrl + Shift + C :- Opens the Class View window
F4 :- Opens the Properties window
Ctrl + Shift + E :- Opens the Resource view window
Ctrl + Alt + X :- Opens the Toolbar window
Shift + Alt + Enter :- Takes you to Full Screen View
Alt+F8 :- Opens Macro Explorer window
F2 :- Opens Object Browser window
Ctrl + Alt + T :- Opens Document Outline window
Ctrl + Alt + K :- Opens Task List window
Ctrl + Alt + A :- Opens Command window
Ctrl + Alt + O :- Opens Output window
Ctrl + Alt + Y :- Opens Find Symbol Results window
Ctrl + Alt + F :- Lists Items under the Favorites Menu in your
Ctrl + Shift + B :- Builds your project
Ctrl + Shift + F9 :- Clears All Breakpoints
Ctrl + Alt + P :- Opens the Processes Dialog box
Ctrl + T :- Opens Customize Toolbox window
Ctrl + Shift + P :- Runs Temporary Macro
Ctrl + Shift + R :- Records Temporary Macro
Alt + F11 :- Opens Macros IDE
F5 :- Runs your Application
Ctrl + F5 :- Runs your Application without Debugging
Ctrl + Alt + E :- Opens the Exceptions Dialog Box
F8 :- Used while Debugging Applications
Shift + F8 :- Used While Debugging Applications
Ctrl + B :- Inserts a New Breakpoint
F10:-Line By Line execution
Ctrl+Tab:-To Shift B/W .net Editor Pages


Regard

Prateek

Randomly selecting row from database

Selecting a Random Row From Databse:


Description:

If you want to select row randomly from the databse, you can use this.




Stored Procedure:


CREATE PROCEDURE PS_GetRandomProduct
AS
DECLARE @NoOfRows int
Begin
SELECT @NoOfRows = max(ProductId) FROM Products

SELECT QuantityPerUnit, ProductName FROM Products
WHERE ProductId = (SELECT CAST((RAND()* @NoOfRows) AS int) + 1)
End
GO

Explanation:


ProductId is the primary key of the table (Products). It is the identity field

(auto-incrementing).we are taking maximum value of identity field and assigning

this value into the variable @NoOfRows.A random number is then generated with a br>
maximum possible value of @NoOfRows.


<

The rand() function generates a random number between 0 and 1, which is multiplied

to the @NoOfRows variable.You may be wondering why 1 is added to the result. The

reason is that the rand() function may return 0 while the ProductId column starts at 1.



Regard

Prateek

Stored procedure and Trigger

Stored Procedure

A stored procedure is a subroutine available to applications accessing a relational database system. Stored procedures (sometimes called a sproc or SP) are actually stored in the database data dictionary.

Example



create procedure Empp @eusername nvarchar(20),@epassword nvarchar(20),@EEmpid nvarchar(20)
as
begin
insert into Emp (UserName,PassWord,EmpID) values(@eusername,@epassword,@EEmpid)
end


You can insert the values like this: empp 'Rengan','Nathan','1050'

Trigger

A database trigger is procedural code that is automatically executed in response to certain events on a particular table in a database. Triggers can restrict access to specific data, perform logging, or audit data modifications.

Trigger Example



create trigger tri_update on Emp
for update
as
begin
if update(EmpID)
begin
print'not update here'
rollback transaction
end
end


Regard

Prateek

Stored procedure and Trigger

Stored Procedure

A stored procedure is a subroutine available to applications accessing a relational database system. Stored procedures (sometimes called a sproc or SP) are actually stored in the database data dictionary.

Example



create procedure Empp @eusername nvarchar(20),@epassword nvarchar(20),@EEmpid nvarchar(20)
as
begin
insert into Emp (UserName,PassWord,EmpID) values(@eusername,@epassword,@EEmpid)
end


You can insert the values like this: empp 'Rengan','Nathan','1050'

Trigger

A database trigger is procedural code that is automatically executed in response to certain events on a particular table in a database. Triggers can restrict access to specific data, perform logging, or audit data modifications.

Trigger Example



create trigger tri_update on Emp
for update
as
begin
if update(EmpID)
begin
print'not update here'
rollback transaction
end
end


Regard

Prateek

Sending Emails from Google Server

Some time we need to send mails to others from our application, and fro this we need to use some free email server like GMAIL. here is the code using that we can use the gmail mail server to send the mails. I am simply specifying the g mail SMTP server name and the Port number in the code.. take a look…



MailMessage mailMessage = new MailMessage();

mailMessage.To.Add(”test@test.com”);

mailMessage.Subject = “Test”;

mailMessage.Body = “This is a test mail”;

mailMessage.IsBodyHtml = true;

// Create the credentials to login to the gmail account associated with my custom domain

string sendEmailsFrom = “abc@xyz.com”;

string sendEmailsFromPassword = “password”;


NetworkCredential cred = new NetworkCredential(sendEmailsFrom, sendEmailsFromPassword);

SmtpClient mailClient = new SmtpClient(”smtp.gmail.com”, 587);

mailClient.EnableSsl = true;

mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;

mailClient.UseDefaultCredentials = false;

mailClient.Timeout = 30000;

mailClient.Credentials = cred;

mailClient.Send(mailMessage);

Regard

Prateek

Tuesday, August 11, 2009

Credit Card CVV Code Validation

Credit Card CVV Code Validation in ASP.NET


What is CVV?

The Card Verification Value (CVV) is an extra code printed on your debit or credit card. It sometimes called Card Verification Value (CVV or CV2), Card Verification Value Code (CVVC), Card Verification Code (CVC), Verification Code (V-Code or V Code), or Card Code Verification (CCV).

CVV is a new authentication procedure established by credit card companies to further efforts towards reducing fraud for internet transactions. It consists of requiring a card holder to enter the CVV number in at transaction time to verify that the card is on hand.

CVV Code in Credit Cards

CVV for Visa, MasterCard, BankCard and Diners is the final three digits of the number printed on the signature strip on the back of your card. CVV for American Express appears as a separate 4-digit code printed on the front of your card.

CVV Code Validation

We will see how to validate a CVV number using JavaScript as well as C# in this article. I have written methods/functions in C# and JavasScript respectively for this validation.

The JavaScript function validateCvvCode() is used to validate a CVV code at client side. The ValidateCVVCode() written in C# is used to check the CVV code at server side. These functions determines number of digits required for the given card type and then checks if the CVV Code have the required count of digits and have only numeric digits 0 to 9 using a regular expression. The regular expression is formed dynamically based on the card type.

Validation Using JavaScript

The following code contains the javascript function to validation CVV code with HTML markup of the demo application.


&l;%@ Page Language="C#" AutoEventWireup="true" CodeFile="CVVValidationDemo.aspx.cs"
Inherits="CVVValidationDemo" %&g;

&l;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&g;
&l;html xmlns="http://www.w3.org/1999/xhtml"&g;
&l;head runat="server"&g;
&l;title&g;CVV Credit Card Number Validation &l;/title&g;

&l;script type="text/javascript" language="javascript"&g;

function validateCvvCode() {

//Get the text of the selected card type
var cardType = document.getElementById('ddlCardType').options[document.getElementById('ddlCardType').selectedIndex].text;
// Get the value of the CVV code
var cvvCode = document.getElementById('txtCVVCode').value;

var digits = 0;
switch (cardType.toUpperCase()) {
case 'MASTERCARD':
case 'EUROCARD':
case 'EUROCARD/MASTERCARD':
case 'VISA':
case 'DISCOVER':
digits = 3;
break;
case 'AMEX':
case 'AMERICANEXPRESS':
case 'AMERICAN EXPRESS':
digits = 4;
break;
default:
return false;
}

var regExp = new RegExp('[0-9]{' + digits + '}');
return (cvvCode.length == digits && regExp.test(cvvCode))
}

function checkCvvCode() {

var result = validateCvvCode();
if (result)
alert('Valid CVV Code');
else
alert('Invalid CVV Code');
}

&l;/script&g;

&l;style type="text/css"&g;
.style1
{
font-size: large;
font-weight: bold;
font-family: Arial;
}
&l;/style&g;
&l;/head&g;
&l;body&g;
&l;form id="form1" runat="server"&g;
&l;div&g;
&l;table width="100%" cellspacing="0" cellpadding="0"&g;
&l;tr&g;
&l;td width="200px"&g;
&l;/td&g;
&l;td class="style1"&g;
CVV Code Validation
&l;/td&g;
&l;/tr&g;
&l;tr&g;
&l;td width="200px"&g;

&l;/td&g;
&l;td&g;
&l;asp:ValidationSummary ID="vsCVVValidationSummary" runat="server" /&g;
&l;/td&g;
&l;/tr&g;
&l;tr&g;
&l;td width="200px"&g;
Card Type
&l;/td&g;
&l;td&g;
&l;asp:DropDownList ID="ddlCardType" runat="server" Width="250px"&g;
&l;/asp:DropDownList&g;
&l;/td&g;
&l;/tr&g;
&l;tr&g;
&l;td width="200px"&g;

&l;/td&g;
&l;td&g;

&l;/td&g;
&l;/tr&g;
&l;tr&g;
&l;td width="200px"&g;
CVV Code
&l;/td&g;
&l;td&g;
&l;asp:TextBox ID="txtCVVCode" runat="server"&g;&l;/asp:TextBox&g;
&l;asp:CustomValidator ID="custValidCVV" runat="server" ErrorMessage="Invalid CVV Code"&g;*&l;/asp:CustomValidator&g;
&l;/td&g;
&l;/tr&g;
&l;tr&g;
&l;td width="200px"&g;

&l;/td&g;
&l;td&g;

&l;/td&g;
&l;/tr&g;
&l;tr&g;
&l;td width="200px"&g;

&l;/td&g;
&l;td&g;
&l;asp:Button ID="btnCvvServerValidate" runat="server" Text="Server Side Validation"
OnClick="btnCvvServerValidate_Click" /&g;

&l;input id="hbtnCvvClientValidate" type="button" value="Client Side Validation" onclick="checkCvvCode()" /&g;
&l;/td&g;
&l;/tr&g;
&l;/table&g;
&l;/div&g;
&l;/form&g;
&l;/body&g;
&l;/html&g;



Validation Using C#


The following code snippet has server side written in C# to demonstrate the CVV code validation. I have loaded and checked the following card types in a dropdown list for demonstration purpose: MASTERCARD, EUROCARD, EUROCARD/MASTERCARD, VISA, DISCOVER and AMERICAN EXPRESS.


using System;
using System.Data;
using System.Text.RegularExpressions;

public partial class CVVValidationDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindCardType();
}

private void BindCardType()
{
System.Data.DataTable dtCardType = new System.Data.DataTable();
dtCardType.Columns.Add(new DataColumn("Card_Type_Id", typeof(int)));
dtCardType.Columns.Add(new DataColumn("Card_Type_Name", typeof(string)));

dtCardType.Rows.Add(new object[] { 1, "MASTERCARD" });
dtCardType.Rows.Add(new object[] { 2, "EUROCARD" });
dtCardType.Rows.Add(new object[] { 3, "EUROCARD/MASTERCARD" });
dtCardType.Rows.Add(new object[] { 4, "VISA" });
dtCardType.Rows.Add(new object[] { 5, "DISCOVER" });
dtCardType.Rows.Add(new object[] { 6, "AMEX" });
dtCardType.Rows.Add(new object[] { 7, "AMERICANEXPRESS" });
dtCardType.Rows.Add(new object[] { 8, "AMERICAN EXPRESS" });

ddlCardType.DataSource = dtCardType;
ddlCardType.DataValueField = "Card_Type_Id";
ddlCardType.DataTextField = "Card_Type_Name";
ddlCardType.DataBind();

}
protected void btnCvvServerValidate_Click(object sender, EventArgs e)
{
custValidCVV.ErrorMessage = "Invalid CVV Code";
custValidCVV.IsValid = ValidateCVVCode();
}

private bool ValidateCVVCode()
{
var cardType = ddlCardType.SelectedItem.Text;
var cvvCode = txtCVVCode.Text;

var digits = 0;
switch (cardType.ToUpper())
{
case "MASTERCARD":
case "EUROCARD":
case "EUROCARD/MASTERCARD":
case "VISA":
case "DISCOVER":
digits = 3;
break;
case "AMEX":
case "AMERICANEXPRESS":
case "AMERICAN EXPRESS":
digits = 4;
break;
default:
return false;
}

Regex regEx = new Regex("[0-9]{" + digits + "}");
return (cvvCode.Length == digits && regEx.Match(cvvCode).Success);
}
}


Regard

Prateek

Lock Statement in C#.net

Lock Statement in C#.net (much usefull for bank transaction)

In .NET we can lock some object while threading once execution over and then releasing the lock.Its very usefull for bank transaction
the following example guide you to learn about Lock Statement

Syntax:

Object myLock = new Object();
lock (myLock)
{
// code section like any bank transaction
}

Explanation
Lock statement ensures that one thread does not enter a code section while another thread is in the code section. If another thread attempts to enter

a locked code, it will wait, block, until the object is released.

Example:


namespace Lock
{
class Program
{
static void Main(string[] args)
{
Thread[] threads = new Thread[10];
Account acc = new Account(1000);
for (int i = 0; i < 10; i++)
{
Thread t = new Thread(new ThreadStart(acc.MyTransactions));
threads[i] = t;
}
for (int i = 0; i < 10; i++)
{
threads[i].Start();
}
Console.Read();
}
}

class Account
{
private Object myLock = new Object();
int Bal;

Random rnd = new Random();

public Account(int iniAmount)
{
Bal = iniAmount;
}

int Withdraw(int amt)
{

// This condition will never be true unless the lock statement
// is commented out:
if (Bal < 0)
{
throw new Exception("Negative Balance");
}

// Comment out the next line to see the effect of leaving out
// the lock keyword:
lock (myLock)
{
if (Bal >= amt)
{
Console.WriteLine("Balance before Withdrawal : " + Bal);
Console.WriteLine("Amount to Withdraw : -" + amt);
Bal = Bal - amt;
Console.WriteLine("Balance after Withdrawal : " + Bal);
return amt;
}
else
{
return 0; // transaction rejected
}
}
}

public void MyTransactions()
{
for (int i = 0; i < 100; i++)
{
Withdraw(rnd.Next(1, 100));
}
}
}

}

Regard

Prateek

Empty recycle bin

Description :

We can empty the recycle bin by using the bellow coding

Step 1

Following Namespace used


using System.Runtime.InteropServices;



Step 2

Create the enum


enum RecycleFlags : uint
{
SHERB_NOCONFIRMATION = 0x00000001,
SHERB_NOPROGRESSUI = 0x00000002,
SHERB_NOSOUND = 0x00000004
}



Step 3

Dll import


[DllImport("Shell32.dll", CharSet = CharSet.Unicode)]
static extern uint SHEmptyRecycleBin
(IntPtr hwnd,
string pszRootPath,
RecycleFlags dwFlags);



Step 4

Following is the code for empty the recyclebin


public static void Main()
{
uint MyResult = SHEmptyRecycleBin (IntPtr.Zero, null, 0);
Console.WriteLine ("Out put: {0}", MyResult);
}




Regard

Prateek

Create your own Web Browser

Description :

We can know about the browsers IE,Firefox..etc.
We can also create our own browser. It is very easy one.

We need the add following reference


AxInterop.SHDocVw



The name space used for creating your own browser


using AxSHDocVw;



The following is the sample code for creating the browser


public partial class Form1 : Form
{
private AxWebBrowser Mybrowser;
private Button MygoButton;
private TextBox SearhaddressBox;
private Panel Mypanel1;
private Panel Mypanel2;

public Form1()
{
InitializeComponent();
Mypanel1 = new Panel();
Mypanel2 = new Panel();
Mybrowser = new AxWebBrowser();
Mybrowser.BeginInit();

this.SuspendLayout();
Mypanel1.SuspendLayout();
Mypanel2.SuspendLayout();

this.Text = "My own Web Browser";
Mypanel1.Size = new Size(300, 30);
Mypanel1.Dock = DockStyle.Top;

Mypanel2.Size = new Size(285, 240);
Mypanel2.Location = new Point(5, 31);
Mypanel2.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;

Mybrowser.Dock = DockStyle.Fill;

SearhaddressBox = new TextBox();
SearhaddressBox.Size = new Size(260, 20);
SearhaddressBox.Location = new Point(5, 5);
SearhaddressBox.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Left;

MygoButton = new Button();
MygoButton.Location = new Point(270, 5);
MygoButton.Size = new Size(20, 20);
MygoButton.Anchor = AnchorStyles.Top | AnchorStyles.Right;

Mypanel1.Controls.AddRange(new Control[] { SearhaddressBox, MygoButton });
Mypanel2.Controls.Add(Mybrowser);
this.Controls.AddRange(new Control[] { Mypanel1, Mypanel2 });

Mybrowser.EndInit();
Mypanel1.ResumeLayout();
Mypanel2.ResumeLayout();
this.ResumeLayout();

MygoButton.Click += new EventHandler(goButton_Click);
Mybrowser.GoHome();

}
private void goButton_Click(object sender, EventArgs e)
{
object o = null;
Mybrowser.Navigate(SearhaddressBox.Text, ref o, ref o, ref o, ref o);
}



Code Explanation
1. Create instance of AxWebBrowser.
2. Assign the controls in it.
3. On the button click navicate the browser.

Regard

Prateek

Monday, August 3, 2009

Mobile Web Development in ASP.NET - Part 5

Introduction


The Part5 of the series on Mobile Web Development deals with the text-based, output-only controls like PhoneCall, Link and TextView.

PhoneCall Control


The PhoneCall control is an easy, text-based, output-only control that is used to represent a phone number to call.

Properties


AlternateFormat - Formatting string for the text value of the PhoneNumber property. This is used only for devices that are unable to initiate phone calls from Web content. The default value is {0} {1}, where {0} is the value of the Text property, and {1} is the value of the PhoneNumber property.
AlternateURL - This is used for devices that are unable to initiate phone calls from Web content. The default value is null.
PhoneNumber - Sets or returns a string that represents a phone number (required).
SoftKeylabel - Sets or returns the label used for the command when it is displayed on a soft key. The default value is an empty string.
Text (inherited from TextControl class) Specifies the text for a control to be rendered for devices that can initiate phone calls. The default value is Phone Number. The Text property can be specified through the Text attribute, or as inner text.

The following controls can contain one or more ObjectList controls.

System.Web.UI.MobileControls.Form

System.Web.UI.MobileControls.Panel



Device-Specific Behavior


Devices with telephony capability
On devices that support programmatically placing phone calls, the control's text is displayed as a command. Invoking that command dials the phone number or presents the user with a number of options for dialing the phone number (some cell phones automatically do the latter). If the text field is not defined, the PhoneNumber property is used.
The rendering behavior in this case is identical to that of a Link control for the specified device.

Devices without telephony capability
The AlternateFormat property is treated as a formatting string that generates the text for displaying the phone number based on the value of the AlternateURL property. When the AlternateURL property contains null, the PhoneCall control renders the number in as the Label control for the specified device. When the AlternateURL property contains a value other than null it renders the number in the same way as the Link control for the specified device.

Example7


The following example shows a phonecall control in a mobile form control.





AlternateFormat="{0} at {1}"
AlternateURL="http://www.xyz.com"
phoneNumber="123-456-7890">XYZ Company





Link Control


It represents a hyperlink to another Form control on a mobile page or an arbitrary URL displaying the value in the Text property.

When the link is clicked, control immediately changes to the page in the specified NavigateURL property. If the Text property is not defined, the default of the link is the AlternateURL property.

Device Specific Behavior - HTML


At run time, the Link control renders a link as a standard HTML tag (anchor)

Device Specific Behavior - WML


A link generates markup similar to the following.
TextProperty

In both the cases, if the value of the link starts with a number symbol (#), it is rendered as a postback event. A
tag (line break) follows the link.

Example8






NavigateURL="http://mobile.msn.com">Microsoft Mobile Site



TextView Control


The TextView control sets and displays arbitrary amounts of text, with optional markup tags. It alos supports internal pagination.
The text is rendered in the same way in both HTML and WML forms.


Example9






ForeColor="Blue" runat="server">
My TextView control Text.





Summary


This is the last of the series of articles published on mobile web development. There are plenty of other standard controls which the users have already aware of. Most of them are similar in feature and behavior as the other controls discussed in this article.



Regard

Prateek

Mobile Web Development in ASP.NET - Part 4

Introduction


The Part4 of the series on Mobile Web Development deals with the ObjectList control that offers you ways of listing data objects from data source or any other collection of items from an array or arraylist.

ObjectList Control


It provides a feature-rich view of a list of data objects. The ObjectList control inherits much of its behavior, including support for templated rendering by using device template sets, and internal pagination, from the List control. Although they are both lists, a ObjectList control differs in capabilities and scope from a List control.

Features of ObjectList control


Data bound

ObjectList control is strictly data bound. The only way to add items to an object list in a control is by binding the list to a data source.
Multiple-property view
It allows you to view multiple properties, or fields, associated with each item. Depending on device characteristics, the control can be rendered as a table that displays more than one property of each object, or UI can be provided to allow the user to view additional properties of an object.
Multiple item commands
It allows you to associate multiple commands with each item. The set of commands for an item can be either shared among all items or unique to the item.
Internal pagination and templating
is supported.

The following controls can contain one or more ObjectList controls.

System.Web.UI.MobileControls.Form

System.Web.UI.MobileControls.Panel


The ObjectList control can contain one or more of the following control.

System.Web.UI.MobileControls.ObjectList.Field

System.Web.UI.MobileControls.ObjectList.Command


Device Templates


The ObjectList control support the following device templates.

AlternatingItemTemplate
This template renders even-numbered items in a list view of an ObjectList object.
HeaderTemplate
The header template is rendered at the beginning of the list. In paginated mode, the header is rendered on each page.
FooterTemplate
The footer template is rendered at the end of the list. In paginated mode, the footer is rendered on each page.
ItemDetailsTemplate
This template replaces the rendering of the commands/details view for an ObjectList object.
ItemTemplate
The item template is rendered for each list item.
SeparatorTemplate
The separator template separates items from each other.

Device-Specific Behavior – HTML


On HTML devices, the object list is initially rendered as a table, with each list item (object) represented by a link. The default value for the link is a value associated with the first column in the dataset. You can set any column as a LabelField Property.

Device-Specific Behavior – WML


On WML devices, the object list is initially rendered as a select list, with each item represented by its label. By selecting the item, the user can view a menu of commands for the item, including a link labeled "Details". By clicking "Details", the user can view title and value of all fields.

Example6


The following example shows how to use Object list for viewing titles by author. It is bound to the dataset “dsAuthors”. The page has three mobile form controls and on the mobile form 1, ObjectList shows a list of all authors. On selecting a command to view the titles by author, mobile form 2 is activated where in user could see the list of titles. On selecting the Sales Trend Link, mobile form 3 is activated that displays a message.












BackColor="Turquoise">


Currently, this feature is not available for users!



private void Page_Load(object sender, System.EventArgs e)
{
if (Page.IsPostBack == false)
{
oleDbDataAdapter1.Fill(dsAuthors1);
ObjectList1.DataBind();
}
}
string authorid;
public void List1_Click(Object sender, ObjectListCommandEventArgs e)
{
authorid = e.ListItem[0];
if (e.CommandName == "Titles")
{
ActiveForm = Form2;
}
else if (e.CommandName == "Sales")
{
ActiveForm = Form3;
}
else
{
ActiveForm = Form1;
}
private void GetAuthorTitles()
{
string ssql = "select titles.title_id, title, type, price, notes from titleauthor, titles where titleauthor.au_id = '" + authorid + "' and titleauthor.title_id = titles.title_id";
DataSet ds1 = new DataSet();
OleDbDataAdapter Adapter = new OleDbDataAdapter(ssql,oleDbConnection1);
Adapter.Fill(ds1);
ObjectList2.DataSource = ds1;
ObjectList2.LabelField = "Title";
ObjectList2.DataBind();
}

private void Form2_Activate(object sender, System.EventArgs e)
{

GetAuthorTitles();
}




Summary


This part covered the most significant use of ObjectList control. The next part of the article would discuss about simple controls like PhoneCall, Link and TextView.



Regard

Prateek

Mobile Web Development in ASP.NET - Part 3

Introduction


The Part3 of the series on Mobile Web Development deals with the SelectionList control that offers you variety of choices of selecting an item or items from a list and act accordingly.

SelectionList Control


The SelectionList control provides the UI selection capability for a list control. Although they are both lists, a SelectionList control differs in capabilities and scope from a List control.

Features of SelectionList


An item selected from a SelectionList control does not generate a server event. You need to add a Command Control for submitting the form to the server.
SelectionList control allows multiple items to be selected.
SelectionList control manages only small lists and does not offer pagination.
SelectionList control supports different types with the SelectType attribute values: SelectType=DropDown|ListBox|Radio|MultiSelectListBox|CheckBox

The following controls can contain one or more SelectionList controls.

System.Web.UI.MobileControls.Form

System.Web.UI.MobileControls.Panel


The SelectionList control can contain one or more of the following control.

System.Web.UI.MobileControls.Item


Device Templates


The SelectionList control does not support device templates.

Example3


The following example shows how to create a selection list for hardware peripherals. When the user chooses a device, a second page displays the device name and its price.




<%@ Page Inherits="System.Web.UI.MobileControls.MobilePage"
Language="c#" %>
<%@ Register TagPrefix="mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>




For pricing, select a component:










Get the price!




Hardware Device Price Request







Example4


In this example, the DataSource property of the SelectionList class is an array called channels that is created and filled during the initial page load. You can set the SelectType property in the code and display the selection through two alternate means during postbacks



<%@ Page Inherits="System.Web.UI.MobileControls.MobilePage"
Language="c#" %>
<%@ Register TagPrefix="mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>












Both the List and SelectionList controls allow you to list items from a data source and provides the following properties:

DataMember="dataMember"
DataTextField="DataTextField"
DataValueField="DataValueField"
OnItemDataBind="itemDataBindHandler"

Example5





The following example shows a SelectionList control bound to a dataset that has rows from the Authors table. On selecting an item (AuthorId), user pushes the command button to display his name in a label control.

private void Form1_Load(object sender, System.EventArgs e)
{
if (Page.IsPostBack == false)
{
oleDbDataAdapter1.Fill (dataSet21);
SelectionList1.DataSource = dataSet21;
SelectionList1.DataBind();
}
}

private void Command1_Click(object sender, System.EventArgs e)
{
Label1.Text = "Name of the selected Author is: " + SelectionList1.Items[SelectionList1.SelectedIndex].Value.ToString();
}




Get Author Name





Summary


This part covers the most common uses of SelectionList control. The next part of the article would discuss about the the ObjectList control, a highly sophisticated control in the mobile list controls.


Regard

Prateek

Mobile Web Development in ASP.NET - Part 2

Introduction


The first part of the article dealt with the Microsoft Mobile Internet ToolKit and Visual Studio environment and configuration settings required for creating a mobile based web application in ASP.NET. In the second part, I discuss few mobile controls and how to develop mobile pages that run on a browser or emulator…

ASP.NET Mobile Controls


A developer can create ASP.NET mobile Web Forms pages consisting of controls either in the ASP.NET Mobile Designer or with any text editor. Many of the controls are similar to desktop controls in Web Forms and to GUI controls in other programming languages, such as Microsoft Visual Basic.

MobilePage


This is the base class for all mobile ASP.NET pages. As such, the MobilePage control provides the outermost layer of all the containers in an ASP.NET mobile Web application. It is the only container associated with a URL and primarily contains style and context information common to all controls.

<%@ Page Inherits="System.Web.UI.MobileControls.MobilePage" Language="c#" %>
<%@ Register TagPrefix="mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>

A mobile page requires two directives. The first directive instructs the ASP.NET page framework to use MobilePage as the base class for the page. The Inherits attribute is required. If the page inherits directly from a MobilePage object, the Inherits attribute must be set to the System.Web.UI.MobileControls.MobilePage namespace. If the page inherits from a code-behind class, the name of the class must be specified instead. The Language attribute is optional; you can set it to the language used on the page, as with any other Web Forms page.

The second directive registers the namespace used by ASP.NET mobile controls that have the mobile prefix. This allows you to declare mobile controls on the page by using the mobile prefix as below.




A MobilePage object can contain the following controls.

System.Web.UI.MobileControls.Form
A MobilePage object must contain at least one Form control and can contain more than more than one Form control.
System.Web.UI.MobileControls.Stylesheet
A style sheet is not required for a MobilePage object. A MobilePage control may or may not have a Stylesheet control.

Example1


This example creates a mobile page and a form, and then adds a label to the form.



<%@ Page Inherits= "System.Web.UI.MobileControls.MobilePage" %>
<%@ Register TagPrefix="mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>



My First MobilePage with some controls in it




List Control


It renders a list of items to a mobile device. This control supports templated rendering through device template sets, and it supports internal pagination just as you find it in datalist control in ASP.NET. For information on Template Sets and Templated Controls or Pagination, I will discuss them in the later part of the article.

List control has both Static and Interactive Modes

Static mode
- The control behaves like a static list. Static list items can be declared as item child elements.
Interactive mode
- The control renders items as interactive elements.

The behavior of these modes is based on the presence of an event handler. When an event handler is not present, the control is set to static mode. When an event handler is present, the control is set to interactive mode, in which each item is an interactive element that generates an event when clicked.

You can optionally place DeviceSpecific/Choice construct inside a list control

The following controls can contain one or more List controls.

System.Web.UI.MobileControls.Form
System.Web.UI.MobileControls.Panel


A List control may or may not contain the following controls.

System.Web.UI.MobileControls.DeviceSpecific

System.Web.UI.MobileControls.Item
.

Device Templates in List control

HeaderTemplate
The header template is rendered at the beginning of the list. In paginated mode, the header is rendered on each page.
FooterTemplate
The footer template is rendered at the end of the list. In paginated mode, the footer is rendered on each page.
ItemTemplate
The item template is rendered for each list item.
AlternatingItemTemplate
If defined, an alternating item template is rendered instead of the item template for even items. For example, the second item is an alternating template, as is the fourth item, as is every subsequent even-numbered item.
SeparatorTemplate
The separator template is rendered between two items.

Example2


The following example displays a list of fruit. When you select a fruit, the control displays its price.


<%@ Page Inherits= "System.Web.UI.MobileControls.MobilePage"
Language="C#" %>
<%@ Register TagPrefix="mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>




Select a Fruit!
OnItemCommand="ListFruit_Click" >











Summary


The second part of the series has discussed two mobile controls, List and Label, placed in a mobile form container. Note that the Example2 has two mobile forms in a mobile page. In the Part3 of the article, you would get to know about more of the mobile controls.

Regard

Prateek

Mobile Web Development in ASP.NET - Part 1

Introduction


The Microsoft® Mobile Internet Toolkit (MIT) provides the tools for creating new applications that target mobile devices. This toolkit allows developers to create a mobile application that will be adapted to the display of multiple mobile devices: Personal Digital Assistants (PDAs) such as the Pocket PC, Web-enabled cell phones, pagers, etc.

MMIT


The ASP.NET mobile forms and controls are formerly known as the Microsoft Mobile Internet Toolkit (MMIT). They extend the power of the Microsoft .NET Framework and Visual Studio .NET to build mobile Web applications by enabling ASP.NET to deliver markup to a wide variety of mobile devices. It contains server-side technology that enables ASP.NET to deliver content to a wide variety of mobile devices.

The .NET Framework version 1.1 provides support for mobile device development with ASP.NET mobile controls, support for Internet Protocol version 6, and ADO.NET classes for native communication with Open Database Connectivity (ODBC) and Oracle databases. It also enables the use of code access security to further lock down and isolate ASP.NET applications.

ASP.NET mobile controls consist of a set of ASP.NET server controls and device adapters that can intelligently render your application. Knowledge of ASP.NET and Web Forms helps you use mobile controls to build mobile Web applications. You can build mobile Web applications using the ASP.NET Mobile Designer in Microsoft Visual Studio .NET or a text editor, and any programming language supported by the common language runtime. The .NET Framework and the ASP.NET mobile controls together form a powerful, flexible, and extensible platform for developing and deploying mobile Web applications.

Testing the Mobile Application using Emulators


The manufacturers of most mobile devices provide emulators that simulate the operation of their hardware and browsers. Emulator software enables you to view your ASP.NET mobile Web Forms application as it might appear on the manufacturers' hardware devices.

To install an emulator as the Visual Studio application browser
1. Install and test the mobile device emulator on your development computer. See the emulator's documentation for instructions.
2. From the File menu, select Browse With. Visual Studio displays the Browse With dialog box.
3. Click the Add button to display the Add Program dialog box.
4. In the Program name field, enter the name of the emulator software's executable program file. Alternatively, select the Browse button to browse to the file's location.
5. If the emulator supports command-line arguments, supply them in the Program name field. For example, you can specify the starting URL of the application, select a "skin" for the browser, or supply other start-up information that your browser might use. For more information about skins and specific start-up information, see your emulator's documentation.
a. Use the %URL variable to specify where the application's start page should be substituted on the command line. This variable name is case sensitive.
b. If supported, specify a skin name. Testing with multiple skins requires multiple instances of the emulator in the browser list.
c. Supply any other arguments the emulator needs. See your emulator's documentation for details.
6. In the Add Program dialog box's Friendly name field, type the name of the browser as you would like it to appear in Visual Studio.
7. Click OK to close the Add Program dialog box.
8. In the Browse With dialog box, select the emulator from the list of browsers, and click the Set as Default button. Click Close to close the Browse With dialog box.
Note After you add an emulator to the list of browsers, you cannot modify its settings. You must delete it and add it again with the new settings.
9. In the Solution Explorer, click on the name of the project file.
10. From the Project menu, select Properties. The Property Pages dialog box appears.
11. Click Configuration Properties.
12. In the list of configuration properties, select Debugging. The dialog box displays the debugging configuration properties in the right-hand box.
13. Set the Always use Internet Explorer property to False.

Openwave Simulator


Mobile Web applications developed in ASP.NET (using the ASP.NET mobile controls), can be tested with Openwave mobile browser simulators without leaving Microsoft Visual Studio .NET. This is done by configuring Visual Studio .NET to take advantage of the command-line arguments supported by the Openwave SDK 4.1.1 and Openwave SDK 6.1. (These Openwave SDKs are available for free from the Openwave Developer Web site.)

Openwave SDK 4.1.1 contains a simulator for Openwave mobile browser 4.1, which adheres to the WAP 1.1 standard and renders content in WML. SDK 6.1 contains Openwave mobile browser 6.1, which adheres to the WAP 2.0 standard and renders content in XHTML Mobile Profile and CSS. You can use either or both simulators, depending on your needs and the target devices for your market.

Summary


The first part explained the basic ideas on Mobile ASP.NET environment and tools; the next part will take you how to develop simple mobile applications in ASP.NET.


Regard


Prateek

How to create SSL certificate for Web Development?

How to create SSL certificate for Web Development?


Microsoft provides a tool named “MakeCert.exe” which helps us to create a temporary SSL Certificate for development environment.

This tool comes with Visual Studio & also with Windows SDK.

If you installed Visual Studio, you can find it in this location: “C:\Program Files\Microsoft Visual Studio \SmartDevices\SDK\SDKTools”. If you installed Windows SDK, you will get it here: “C:\Program Files\Microsoft SDKs\Windows\\Bin”.

Now open Command Console (“cmd.exe”) & change your current directory to one of the location specified above. Type the following in Command Prompt & hit enter:

makecert -b 01/01/2009 -e 01/01/2020 -n "CN=Developers" -pe -r -sk "Microsoft Cryptographic Provider" -ss "Microsoft Cryptographic Store" c:\developerCertificate.cer

This will create a test certificate (valid from 01/01/2009 to 01/01/2020) named “developerCertificate.cer” in your ‘C’ drive, which you can use for development environment. You can change the validity period by changing the begindate (-b) & expirydate (-e). You can also change all the parameters specified above.

Here is the list of the parameters mentioned above:

Parameter Description
-b Begin Date
-e Expiry Date
-n Certificate Subject Name
-pe Mark Generated Private Key as Exportable
-r Configures MakeCert to create a self-signed root certificate
-sk Subject’s Key Container Name
-ss


Regard

Prateek

Crystal Report to PDF

There are situations when we want to export Crystal reports to .pdf format programmatically. In these situations we can use ExportOptions for export the Crystal Reports to .pdf format. Also we have to set PdfRtfWordFormatOptions and ExportFormatType. PortableDocFormat . In the following example you can see how to export a Crystal Reports as a PDF format file in C#.



private void button2_Click(object sender, EventArgs e)
{
try
{
ExportOptions CrExportOptions ;
DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
CrDiskFileDestinationOptions.DiskFileName = "c:\\csharp.net-informations.pdf";
CrExportOptions = cryRpt.ExportOptions;
{
CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
CrExportOptions.FormatOptions = CrFormatTypeOptions;
}
cryRpt.Export();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

Regard

Prateek

Sunday, August 2, 2009

JavaScript to select one checkbox at a time inside a gridview containing checkbox as template column

Many times we need JavaScript for controls inside a gridview.One such need is to check only one checkbox at a time.This code snippet illustrates how to do that and this can be a guideline for all such needs.

The below java script is for checkbox inside a gridview as template column.If one checkbox is selected, it should deselect other check boxes .In code behind u have to include JavaScript for each checkbox in rowdatabound event.



protected void dgprod_RowDataBound(object sender, GridViewRowEventArgs e)
{
CheckBox chkh = new CheckBox();
chkh=(checkbox)e.Row.FindControl("chkcat");
chkh.Attributes.Add("onclick", "javascript:return Selectone(this,'"+ dgprod.ClientID +"');");

}

javascript to select one checkbox at a time:

function selectone(chid,gridviewid)
{

var grid=document.getelementbyid("gridviewid");
for (i=1; i{
var inputs = grid.getElementsByTagName("input");
if (inputs.length>0)
{

for (i=1; i{
if(inputs[i].type=="checkbox")
{

var chk=$get(inputs[i].id);

if(chk.id!=chid.id)
{
chk.checked=false;
}

}
}

Regard

Prateek

Friday, July 31, 2009

Writing and Reading to a Text File.

Writing and Reading to a Text File:


Description:


When developers have large data in text box then it is not possible to insert into a database table.
So you can use the below code to write to a text and save file path in the database. So to read
a file use the below code by passing the file path.



Design View:




Code Behind:



//.....Below Method is for writing data from a textbox to a text file.


protected void WritingToTextFile()
{

//.....Generating a file name.

string concatstring = DateTime.Now.ToString("ddMMyyyy")+" "+DateTime.Now.Hour.ToString()+""+DateTime.Now.Minute.ToString()+""+DateTime.Now.Second.ToString()+""+DateTime.Now.Millisecond.ToString();
string fname = concatstring+".txt";
string filename = "D:\\"+concatstring+".txt";

//.....FileInfo class is for creating file.

FileInfo fnew = new FileInfo(filename);

//.....StreamWriter class is for writing text to the text file.

StreamWriter sw = fnew.CreateText();
sw.WriteLine(txtTemplate.Text);
sw.Close();
}

protected void ReadingTextFile(string sFileName)
{
string sframedata = "";
string datas = "";

//.....StreamReader class is for Reading text from the text file.

StreamReader sr = new StreamReader("D:\\"+sFileName);
while((datas = sr.ReadLine()) != null)
{
sframedata += datas;
}
txtTemplate.Text = sframedata.ToString();
}

Regard

Prateek

Xml File Read and Bind

XML File like this


< NewDataSet >
< Table >
< Country > British Indian Ocean Territory< /Country >
< City > Diego Garcia< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Ahmadabad< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Akola< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Aurangabad Chikalthan Aerodrome< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Bombay / Santacruz< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Bilaspur< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Bhuj-Rudramata< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Belgaum / Sambra< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Bhopal / Bairagarh< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Bhaunagar< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Goa / Dabolim Airport< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Indore< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Jabalpur< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Khandwa< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Kolhapur< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Nagpur Sonegaon< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Rajkot< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Sholapur< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Agartala< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Siliguri< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Bhubaneswar< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Calcutta / Dum Dum< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Car Nicobar< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Gorakhpur< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Gauhati< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Gaya< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Imphal Tulihal< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Jharsuguda< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Jamshedpur< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > North Lakhimpur< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Dibrugarh / Mohanbari< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Port Blair< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Patna< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > M. O. Ranchi< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Agra< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Allahabad / Bamhrauli< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Amritsar< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Varanasi / Babatpur< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Bareilly< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Kanpur / Chakeri< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > New Delhi / Safdarjung< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > New Delhi / Palam< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Gwalior< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Hissar< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Jhansi< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Jodhpur< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Jaipur / Sanganer< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Kota Aerodrome< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Lucknow / Amausi< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Satna< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Udaipur Dabok< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Bellary< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Vijayawada / Gannavaram< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Coimbatore / Peelamedu< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Cochin / Willingdon< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Cuddapah< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Hyderabad Airport< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Madurai< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Mangalore / Bajpe< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Madras / Minambakkam< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Tiruchchirapalli< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Thiruvananthapuram< /City >
< /Table >
< Table >
< Country > India< /Country >
< City > Vellore< /City >
< /Table >
< /NewDataSet >


client Side Code



< html xmlns="http://www.w3.org/1999/xhtml" >
< head runat="server" >
< title >Untitled Page< /title >
< /head >
< body >
< form id="form1" runat="server" >
< div >
< asp:DataGrid ID="dtg1" runat ="Server" AutoGenerateColumns ="false" >
< Columns >
< asp:TemplateColumn HeaderText ="Country" >
< ItemTemplate >
< asp:Label ID="lbl1" runat ="server" Text ='< %# Bind("Country") % >' >< /asp:Label >
< /ItemTemplate >
< /asp:TemplateColumn >


< asp:TemplateColumn HeaderText ="City" >
< ItemTemplate >
< asp:Label ID="lbl2" runat ="server" Text ='< %# Bind("City") % >' >< /asp:Label >
< /ItemTemplate >
< /asp:TemplateColumn >
< /Columns >
< /asp:DataGrid >

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


Server Side


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
cls1 = New ClsConnect
ds.ReadXml(Server.MapPath("XMLFile.xml"))
dtg1.DataSource = ds
dtg1.DataBind()
End Sub


Regard

Prateek

Thursday, July 30, 2009

Silverlight DataGrid Paging

Silverlight DataGrid does not have the built-in paging facility. So here is a small piece of code to implement paging in Silverlight DataGrid. For this custom paging
Calculate the number of pages based on total number of records and page size
Add those many buttons to a container like StackPanel and
On those buttons click events bind the DataGrid to desired range of records.



1.Define the following Properties and Variables
public partial class Page : UserControl

{

//Property to hold the value of total records

public int TotalRow { get; set; }

//Property to hold the value of page size

public int PageSize { get; set; }

//Number of rows that the DataGrid

int totalRowsInGrid = 0;

2. Initialize the values public Page()

{

InitializeComponent();

//Initialize the page size

PageSize = 10;

//Get the desired data

user = User.Get();

//Set the TotalRow cout to the number of rows returned for data

TotalRow = user.Count;



BindGrid(1);

DoPaging(this.PageSize, TotalRow);

}

3. Create a method to get the desired range of data based on page number///

/// Returns paged data based on page number

///


///

///

private List GetData(int pageNumber)

{

int Pagestart = (pageNumber - 1) * this.PageSize;

TextBlockStartPageNumber.Text = (Pagestart+1).ToString();

TextBlockEndPageNumber.Text = (Pagestart + totalRowsInGrid).ToString();

TextBlockTotalRecords.Text = TotalRow.ToString();

int i = TotalRow;

List PagedData;

//List PagedData = user.Skip((pageNumber - 1) * PageSize).Take(PageSize) as List;

//List PageedData = FullList.Skip((PageNumber - 1) * PageSize).Take(PageSize).ToList();

if ((i - ((pageNumber - 1) * this.PageSize)) >= this.PageSize)

PagedData = user.GetRange(Pagestart, this.PageSize);

else

PagedData = user.GetRange(Pagestart, (i % this.PageSize));

return PagedData;

}

4. Bind the DataGrid///

/// Bind grid to the desired range of records

///


///

private void BindGrid(int PageNumber)

{

if (this.PageSize * PageNumber > this.TotalRow)

{

totalRowsInGrid = this.TotalRow % this.PageSize;

}

else

{

totalRowsInGrid = this.PageSize;

}

dataGridPaging.ItemsSource = GetData(PageNumber);

}

5. Write the click event for the paging buttons///

/// Handles the click event of buttons having page numbers

///


///

///

void btn_Click(object sender, RoutedEventArgs e)

{

Button btn = sender as Button;

int iPageNumber = Convert.ToInt32(btn.Content.ToString());

BindGrid(iPageNumber);

}

Regard

Prateek