How to overcome Cross Site Scripting vulnerability in Asp.net c# - c#

The part of the code am working on is vulnerable to stored XSS. Below is the code.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_OnRowDeleting" OnPageIndexChanging="GridView1_PageIndexChanging" Width ="1000px" class="grid">
<Columns>
<asp:TemplateField HeaderText="User Name">
<ItemTemplate>
<asp:Label ID="lbl_Name" runat="server" Text='<%#Eval("Uname") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_Name" runat="server" Text='<%#Eval("Uname") %>'></asp:TextBox> //this is the line vulnerable to XSS
</EditItemTemplate>
</asp:TemplateField> </columns>
</asp:GridView>
code behind
DataTable dt = new DataTable();
try
{
SqlConnection con = new SqlConnection(conn);
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter("Select Uid,Uname,Utype,Uemail,ClientName,ProjectName,Ulog from usrtable where ClientName='" + clientname + "' and Utype='Admin' or ClientName='" + clientname + "'and Utype='Normal'", con);
adapt.Fill(dt);
con.Close();
}
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
Can you let me know where am going wrong. Is it on the client side where I am binding the column names to textbox in gridview?

Related

Dropdownlist displaying two gridviews

I currently have a drop down list that on selected index changed it displays data in a GridView based of the value of the drop down list. However, it is displaying the data in the existing GridView and then displaying another gridview next to the existing one with the exact information. I am just trying to display the data in the existing open.
C# Code:
protected void DropDownList1_SelectedIndexChanged(object sender,
EventArgs e)
{
DataTable table = new DataTable();
using (SqlConnection con = new SqlConnection(#"Data Source=
(local)\;Initial Catalog=SmallBatch;Integrated Security=True;"))
{
con.Open();
SqlDataAdapter DataAdapter = new SqlDataAdapter(string.Format("SELECT Item.ItemID, Item.ItemDesc, Stock_Take_Item.BarQuantity, Stock_Take_Item.StorageQuantity FROM Item INNER JOIN Stock_Take_Item ON Item.ItemID = Stock_Take_Item.ItemID INNER JOIN Stock_Take ON Stock_Take_Item.StockTakeIDNew = Stock_Take.StockTakeIDNew where Stock_Take.Username = '" + DropDownList1.SelectedValue + "'"), con);
DataAdapter.Fill(table);
}
GridView1.DataSource = table;
GridView1.DataBind();
}
}
Existing Gridview:
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal">
<Columns>
<asp:TemplateField HeaderText="Item ID" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="itemIDAdmin" Text='<%# Eval("ItemID")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Description" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="itemDescAdmin" Text='<%# Eval("ItemDesc")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Bar Quantity" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="barQuantityAdmin" Text='<%# Eval("BarQuantity")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Storage Quantity" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="storageQuantityAdmin" Text='<%# Eval("StorageQuantity")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

GridView in LoginView giving wrong row count

I have a GridView within a LoginView that I am getting an Index Out Of Range error with. When I display the # of rows in the GridView it always shows 0 which is causing this error.
Is there something specific that I need to be doing to get a GridView
to properly work within a LoginView?
Below is the code that is being run when I click on a button in the GridView and the error only comes up on the GridView row = gv.Rows[e.RowIndex]; line. If I use only e.RowIndex I do not get the error and it will actually return the proper number. If I do gv.DataKeys.Count it will return the correct count. If I do gv.Rows.Count it will always be 0. I think it has something to do with a PostBack because if I do a row count in my page_load then it returns the correct count. Please let me know if there is anything else that you need for me to post?
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
GridView gv = ReviewLoginView.FindControl("gvReview") as GridView;
GridViewRow row = gv.Rows[e.RowIndex];
string Id = (row.FindControl("lblID") as Label).Text;
string constr = System.Configuration.ConfigurationManager.AppSettings["ObservationCardCS"];
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("cardReview"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", Id);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
gv.EditIndex = -1;
this.BindGrid();
}
catch (Exception ex)
{
GridView gv = ReviewLoginView.FindControl("gvReview") as GridView;
int index = e.RowIndex;
lblError.ForeColor = System.Drawing.Color.Red;
lblError.Text = ex.Message + " " + index.ToString() + " " + gv.Rows.Count;
}
}
Below is the LoginView from the aspx page.
<asp:LoginView runat="server" ViewStateMode="Disabled" ID="ReviewLoginView">
<LoggedInTemplate>
<%--<AnonymousTemplate>--%>
<div>
<asp:GridView ID="gvReview" runat="server" AutoGenerateColumns="false" DataKeyNames="ID"
OnRowDataBound="OnRowDataBound" OnRowDeleting="OnRowDeleting" EnableViewState="true"
EmptyDataText="No records have been added." AllowSorting="true" ShowHeaderWhenEmpty="true"
AlternatingRowStyle-BackColor="#e0e0e0" HeaderStyle-BackColor="#d0d0d0" ViewStateMode="Disabled"
EnableSortingAndPagingCallbacks="false">
<Columns>
<asp:TemplateField HeaderText="ID" ShowHeader="false" Visible="true">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("ID") %>' CssClass="cmsID"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User">
<ItemTemplate>
<asp:Label ID="lblSubmittedBy" runat="server" Text='<%# Eval("submittedBy") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%# Eval("location") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:Label ID="lblSubmittedDate" runat="server" Text='<%# Eval("submittedDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="What Was Observed?">
<ItemTemplate>
<asp:Label ID="lblWhatWasObserved" runat="server" Text='<%# Eval("whatWasObserved") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="What Action Was Taken?">
<ItemTemplate>
<asp:Label ID="lblWhatActionWasTaken" runat="server" Text='<%# Eval("whatActionWasTaken") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="What Agreement Was Reached?">
<ItemTemplate>
<asp:Label ID="lblWhatAgreementWasReached" runat="server" Text='<%# Eval("whatAgreementWasReached") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button ID="btnSubmit" runat="server" Text="Edit" CssClass="editbutton" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Review" ButtonType="Button" ShowDeleteButton="true" DeleteText="Review" />
</Columns>
</asp:GridView>
</div>
</LoggedInTemplate>
<%--</AnonymousTemplate>--%>
<AnonymousTemplate>
You must login to view submitted Observation Cards.
</AnonymousTemplate>
</asp:LoginView>
Below is the BindGrid()
private void BindGrid()
{
try
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ObservationCardCS"]);
{
SqlCommand comm = new SqlCommand("cardSelectNew2", conn);
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = comm;
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.AddWithValue("#Begin", "1/1/1950");
comm.Parameters.AddWithValue("#End", "12/31/2049");
comm.Parameters.AddWithValue("#Reviewed", "0");
comm.Parameters.AddWithValue("#OrderBy", "CH.id");
comm.Parameters.AddWithValue("#AscDesc", "Asc");
comm.Parameters.AddWithValue("#DateRange", "Last 30 Days");
comm.Connection = conn;
sda.SelectCommand = comm;
DataTable dt = new DataTable();
sda.Fill(dt);
GridView gv = ReviewLoginView.FindControl("gvReview") as GridView;
gv.DataSource = dt;
gv.DataBind();
}
}
catch (Exception ex)
{
lblError.ForeColor = System.Drawing.Color.Red;
lblError.Text = ex.Message;
}
}
Below is my page_load
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
lblError.ForeColor = System.Drawing.Color.Black;
lblError.Text = "";
}
}
You are on the right track! But without seeing the whole class and markup we can only speculate.
Check that you are not clearing or rebuilding the data on the page load event handler, if the Grid and datasource is defined in the markup then it should cache or requery the data between page postbacks, check that you have set EnableRowCache on the GridView so that you dont have to re-query for the data during postbacks.
It looks like you are using the #OldSchool BindGrid() data load pattern, perhaps the simplest solution may be to ensure that the data is loaded first by calling BindGrid before you try to access the rows:
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
this.BindGrid();
try
{
... delete logic
this.BindGrid(); // re-load after the change
}
catch (Exception ex)
{
...
}
}
Without enabling the row cache though you have to ensure that the same data is loaded into the grid in the same order or delete logic like this based on row index (instead of the primary key of the row) could result in you deleting the wrong data row.

Container.DisplayIndex not working with paging in ASP.NET

I have a gridview that is bound with data from code behind. Paging is applied in gridview. Everything works fine. For showing Row-Index i use Container.DisplayIndex.
When i go to next page through paging, every time gridview bind perfectly but DisplayIndex start with 1 to pagesize. I don't know what is wrong with the code.
Here is Asp.NET Code:
<asp:GridView runat="server" ID="dlAddress" AutoGenerateColumns="false" AllowPaging="True" OnPageIndexChanging="dlAddress_PageIndexChanging" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblRowNumber" Text='<%# Container.DisplayIndex + 1 %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle HorizontalAlign="Center"/>
</asp:GridView>
C# Code:
public void bindGridView()
{
DBACon.Open();
SqlCommand Cmd = new SqlCommand("getAddresses", DBACon);
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter AHadp = new SqlDataAdapter(Cmd);
AHadp.Fill(DS);
dlAddress.DataSource = DS;
dlAddress.DataBind();
}
protected void dlAddress_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
dlAddress.PageIndex = e.NewPageIndex;
bindGridView();
}
Here,
ASPX:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="5" AutoGenerateColumns="False" DataKeyNames="AddressID" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField HeaderText="RowNumber">
<ItemTemplate>
<%# (GridView1.PageSize * GridView1.PageIndex) + Container.DisplayIndex + 1%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

How to save gridview each row value in table?

How to insert gridview each row value into database.I use below code but null values are pass in strings.
foreach (GridViewRow gvrow in GridView1.Rows)
{
con.Open();
string datetime = Request.Form["txtdate"];
str += GridView1.DataKeys[gvrow.RowIndex].Value.ToString() + ',';
Id += gvrow.Cells[0].Text;
fName += gvrow.Cells[1].Text;
FaName += gvrow.Cells[2].Text;
LName += gvrow.Cells[3].Text;
attendance += gvrow.Cells[4].Text;
remarks += gvrow.Cells[5].Text;
SqlCommand cmd = new SqlCommand("INSERT INTO [first].[dbo].[Staff_Attendance]([Id],[Department],[Date],[First_name],[Father_name],[Last_name],[Attendance],[Remarks]) VALUES(#Id, #Department, #Date, #First_name, #Father_name, #Last_name, #Attendance, #Remarks)", con);
cmd.Parameters.AddWithValue("#Id", Id);
cmd.Parameters.AddWithValue("#Department", DropDownList1.SelectedItem .ToString ());
cmd.Parameters.AddWithValue("#Date", datetime.ToString());
cmd.Parameters.AddWithValue("#First_name", fName);
cmd.Parameters.AddWithValue("#Father_name", FaName);
cmd.Parameters.AddWithValue("#Last_name", LName);
cmd.Parameters.AddWithValue("#Attendance", attendance);
cmd.Parameters.AddWithValue("#Remarks", remarks);
cmd.ExecuteNonQuery();
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Data Have Been Saved')", true);
con.Close();
}
Gridview code:-
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" onpageindexchanging="GridView1_PageIndexChanging"
PageSize="5" AutoGenerateColumns="False" DataKeyNames ="srno">
<PagerSettings FirstPageText="First" LastPageText="Last"
Mode="NumericFirstLast" PageButtonCount="5" />
<Columns >
<asp:TemplateField HeaderText="Sr.No.">
<ItemTemplate>
<asp:Label ID="lblsrno" runat="server" Text='<%#Eval("srno") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="lblFname" runat="server" Text='<%#Eval("first_name") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Father Name">
<ItemTemplate>
<asp:Label ID="lblFaName" runat="server" Text='<%#Eval("father_name") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="lblLName" runat="server" Text='<%#Eval("last_name") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Attendance">
<ItemTemplate>
<asp:DropDownList ID="ddlDesignation" runat="server" Width ="80px">
<asp:ListItem Text ="--Select--" ></asp:ListItem>
<asp:ListItem Text ="P"></asp:ListItem>
<asp:ListItem Text ="A"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remarks">
<ItemTemplate>
<asp:DropDownList ID="ddlRemark" runat="server" Width ="80px">
<asp:ListItem Text ="--Select--" ></asp:ListItem>
<asp:ListItem Text ="Paid Leave"></asp:ListItem>
<asp:ListItem Text ="Unpaid Leave"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In database it stored null values
You can try using following code, have written a sample code ,
foreach (GridViewRow row in GridView1.Rows) {
Label lblFname = (Label)row.FindControl("lblFname");
Label lblFaName = (Label)row.FindControl("lblFaName");
Label lblLName = (Label)row.FindControl("lblLName");
DropDownList ddl_att = (DropDownList)row.FindControl("ddlDesignation");
DropDownList ddl_rmk = (DropDownList)row.FindControl("ddlRemark");
dataInsert(lblFname.Text,lblFaName.Text,ddl_att.SelectedValue);
}
public void dataInsert(string First_name,string Father_name,string Attendance)
{
using (SqlConnection con = new SqlConnection(conn.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "yourInsertQuery";
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#First_name", First_name);
cmd.Parameters.AddWithValue("#Father_name", Father_name);
cmd.Parameters.AddWithValue("#Attendance", Attendance);
...
...
con.Open();
cmd.ExecuteNonQuery();
}
con.Close();
}
}
Also you can save data into datatable and if your DataTable schema and table schema are matched, then using SqlBulkCopy you can do bulk insert into your database.
First You can find the controls in gridview then get Text. May be your problem will solve.
fName += ((Label)gvrow.Cells[1].FindControl("lblFname")).Text;
FaName +=((Label)gvrow.Cells[2].FindControl("lblFaName").Text);
LName += ((Label)gvrow.Cells[3].FindControl("lblLName")).Text;
attendance +=((DropDownList)gvrow.Cells[4].FindControl("ddlDesignation")).SelectedItem.Text;
remarks += ((DropDownList)gvrow.Cells[5].FindControl("ddlRemark")).SelectedItem.Text;

Why is my data not showing in my GridView? [duplicate]

This question already exists:
how to show data in gridview from arraylist in asp.net?
Closed 8 years ago.
I have a database where there is userid, problemname and status column. I am retrieving this data from database in an ArrayList and returning it. Now to show in GridView I have taken a DataTable and in the DataTable I have put three columns and I just want to show my data that is saved in the ArrayList in these columns by making one row.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
ArrayList myArrayList = ConvertDataSetToArrayList();
// Display each item of ArrayList
DataTable dt = new DataTable();
dt.Columns.Add("User Id");
dt.Columns.Add("Problem Name");
dt.Columns.Add("Status");
foreach (Object row in myArrayList)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["User Id"] = ((DataRow)row)["userid"].ToString();
dt.Rows[dt.Rows.Count - 1]["Problem Name"] = ((DataRow)row) ["problemname"].ToString();
dt.Rows[dt.Rows.Count - 1]["Status"] = ((DataRow)row)["status"].ToString();
}
GridView1.DataSource =dt;
GridView1.DataBind();
}
public ArrayList ConvertDataSetToArrayList()
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
SqlCommand cmd = new SqlCommand("SELECT userid,problemname,status FROM problemtable", objsqlconn);
cmd.ExecuteNonQuery();
cmd.CommandType = CommandType.Text;
SqlDataAdapter myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = cmd;
DataSet myDataSet = new DataSet();
myAdapter.Fill(myDataSet);
ArrayList myArrayList = new ArrayList();
foreach (DataRow dtRow in myDataSet.Tables[0].Rows)
{
myArrayList.Add(dtRow);
}
objsqlconn.Close();
return myArrayList;
}
Here is my html:
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderText="cdd">
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
Why is my data is not showing in my GridView?
You need to bind your data to specific controls in your gridview. For example, you need to have labels in your gridview itemtemplate to bind your data to. Here is an example:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderText="cdd">
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User Id">
<ItemTemplate>
<asp:Label ID="lbl_userid" runat="server" Text='<%# Eval("User Id") %>' CssClass="lbl"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Problem Name">
<ItemTemplate>
<asp:Label ID="lbl_problemname" runat="server" Text='<%# Eval("Problem Name") %>' CssClass="lbl"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="status">
<ItemTemplate>
<asp:Label ID="lbl_status" runat="server" Text='<%# Eval("Status") %>' CssClass="lbl"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I agree that an ArrayList is a poor choice, but, regardless of how you're binding the data, you need to tell the gridview what it's supposed to show. You can do this using inline tags or by using an onitemdatabound trigger. I recommend you look up some more examples of gridviews.

Categories