i want to do sorting in the listview from code behind, and i have done it by below code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindLV("");
}
public DataTable GetEmployee(string query)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
SqlDataAdapter ada = new SqlDataAdapter(query, con);
DataTable dtEmp = new DataTable();
ada.Fill(dtEmp);
return dtEmp;
}
private void BindLV(string SortExpression)
{
string UpdateQuery = "Select * from Employee" + SortExpression;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
lvEmployee.DataSource = GetEmployee(UpdateQuery);
lvEmployee.DataBind();
}
protected void lvEmployee_Sorting(object sender, ListViewSortEventArgs e)
{
ImageButton imEmpID = lvEmployee.FindControl("imEmpID") as ImageButton;
ImageButton imEmpName = lvEmployee.FindControl("imEmpName") as ImageButton;
string DefaultSortIMG = "~/img/asc.png";
string imgUrl = "~/img/desc.png";
if (ViewState["SortExpression"] != null)
{
if (ViewState["SortExpression"].ToString() == e.SortExpression)
{
ViewState["SortExpression"] = null;
imgUrl = DefaultSortIMG;
}
else
{
ViewState["SortExpression"] = e.SortExpression;
}
}
else
{
ViewState["SortExpression"] = e.SortExpression;
}
switch (e.SortExpression)
{
case "EmpID":
if (imEmpName != null)
imEmpName.ImageUrl = DefaultSortIMG;
if (imEmpID != null)
imEmpID.ImageUrl = imgUrl;
break;
case "EmpName":
if (imEmpID != null)
imEmpID.ImageUrl = DefaultSortIMG;
if (imEmpName != null)
imEmpName.ImageUrl = imgUrl;
break;
}
BindLV(" order by " + e.SortExpression + " " + ((ViewState["SortExpression"] != null) ? "ASC" : "DESC"));
}
but the problem is i'm using another function for data paging as below in code behind which is contain of sorting as well:
protected void DataPager1_PreRender(object sender, EventArgs e)
{
lvEmployee.DataSource = GetEmployee("Select * from Employee");
lvEmployee.DataBind();
}
and my data pager code which is located at LayoutTemplate in .aspx page:
<asp:DataPager ID="DataPager1" runat="server" PagedControlID="lvEmployee" PageSize="5" onprerender="DataPager1_PreRender">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="true" ShowLastPageButton="true"/>
</Fields>
</asp:DataPager>
Every time i click at the name to sort it, there will be no change in the list. E have traced the problem, and I have found out that the sorting function is working properly. But before the page come up, the DataPager1_PreRender function is called and again shows the list without sorting.
Could you please guide me how to do sorting and dataPaging together without this problem. Appreciate your consideration.
I have over come to this problem by using Session.
before i use session i found out every time i press the next page or anytime the page refresh it will execute the DataPager1_PreRender() and i have set the data source to
GetEmployee("Select * from Employee");
that's why the sorting never happens.
i have add Session["UpdateQT"] = UpdateQuery; to BindLV() to keep the update query and i have change the DataPager1_PreRender() to
string strtmp = Session["UpdateQT"].ToString();
if (strtmp == null)
{
strtmp = "Select * from Employee";
}
lvEmployee.DataSource = GetEmployee(strtmp);
lvEmployee.DataBind();
to keep the latest query after sorting.
i hope it helps somebody.
Related
I have an issue with my sorting when navigating between pages. When I go to a new page, the sorting order is lost and the user has to sort again.
I have ran through my code and know the issue lies in PageIndexChanging event of the gridview. Where am rebind the gridview with fresh data.
However, I am not sure how to avoid this? How do I store the sort order when rebinding the gridview? ViewState perhaps?
Any suggestions please?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateProductClass();
PopulateProduct();
PopulateOrderList();
}
}
private void PopulateOrderList()
{
DateTime d;
DateTime d2;
CustomerInfo ki = CustomerInfoProvider.GetCustomerInfoByUserID(CooneenHelper.GetUserImpersonisationID());
int nKustomerID = ki.CustomerID;
DataTable dts = new DataTable();
dts.Columns.Add("OrderDate", typeof(DateTime));
dts.Columns.Add("OrderNumber", typeof(string));
dts.Columns.Add("OrderItemSKUName", typeof(string));
dts.Columns.Add("SKUNumber", typeof(string));
dts.Columns.Add("OrderItemStatus", typeof(string));
dts.Columns.Add("OrderItemUnitCount", typeof(string));
dts.Columns.Add("mtrx_Code2", typeof(string));
QueryDataParameters qdp = new QueryDataParameters();
qdp.Add("#CustomerID", nKustomerID);
if (drpProductClass.SelectedValue.ToString() != "0" || drpProductClass.SelectedValue.ToString() == null) { qdp.Add("#OrderItemWRClass", drpProductClass.SelectedItem.ToString()); }
if (drpProduct.SelectedValue.ToString() != "0") { qdp.Add("#OrderItemSKUID", drpProduct.SelectedValue.ToString()); }
if (txtStartDate.Text != "") { d = DateTime.Parse(txtStartDate.Text); qdp.Add("#OrderItemDateFrom", d.ToString("yyyy-MM-dd")); }
if (txtEndDate.Text != "") { d2 = DateTime.Parse(txtEndDate.Text); qdp.Add("#OrderItemDateTo", d2.ToString("yyyy-MM-dd")); }
DataSet ds = gc.ExecuteQuery("CN_GetOrderItemByCustID", qdp, QueryTypeEnum.StoredProcedure, true);
foreach (DataRow dr in ds.Tables[0].Rows)
{
DataRow drNew = dts.NewRow();
drNew["OrderDate"] = ValidationHelper.GetDateTime(dr["OrderDate"], DateTime.Now).ToShortDateString();
drNew["OrderNumber"] = dr["OrderNumber"].ToString();
drNew["OrderItemSKUName"] = dr["OrderItemSKUName"].ToString();
drNew["SKUNumber"] = dr["SKUNumber"].ToString();
drNew["OrderItemStatus"] = dr["OrderItemStatus"].ToString();
drNew["OrderItemUnitCount"] = dr["OrderItemUnitCount"].ToString();
drNew["mtrx_Code2"] = dr["mtrx_Code2"].ToString();
dts.Rows.Add(drNew);
}
//Clear the TextBox
litResults.Text = String.Empty;
if (dts.Rows.Count == 1)
litResults.Text = "" + dts.Rows.Count.ToString() + " Order Items";
else
litResults.Text = "" + dts.Rows.Count.ToString() + " Order Items";
try
{
Session["Data"] = dts;
}
catch(Exception ex)
{
throw ex;
}
gvOrderItems.Visible = true;
gvOrderItems.DataSource = dts.DefaultView;
gvOrderItems.DataBind();
if (dts.Rows.Count > 1) litResults.Text += " - Showing page " + (gvOrderItems.PageIndex + 1).ToString() + " of " + gvOrderItems.PageCount.ToString();
}
private string SortCriteria
{
get
{
if (ViewState["sortCriteria"] == null)
{
ViewState["sortCriteria"] = "";
}
return ViewState["sortCriteria"].ToString();
}
set
{
ViewState["sortCriteria"] = value;
}
}
public SortDirection SortDirection
{
get
{
if (ViewState["SortDirection"] == null)
{
ViewState["SortDirection"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["SortDirection"];
}
set
{
ViewState["SortDirection"] = value;
}
}
protected void gvOrderItems_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
string direction = string.Empty;
DataTable dt = (DataTable)Session["Data"];
if (dt.Rows.Count > 0)
{
DataView dataView = new DataView(dt);
if (SortDirection == SortDirection.Ascending)
{
SortDirection = SortDirection.Descending;
direction = " DESC";
}
else
{
SortDirection = SortDirection.Ascending;
direction = " ASC";
}
dataView.Sort = sortExpression + direction;
gvOrderItems.DataSource = dataView;
gvOrderItems.DataBind();
}
}
protected void gvOrderItems_PageIndexChanging1(object sender, GridViewPageEventArgs e)
{
gvOrderItems.PageIndex = e.NewPageIndex;
PopulateOrderList();
}
Maybe you're databinding the GridView on every postback from Page_Load.
You should do that only at the first time. Use the Page.IsPostBack property:
protected void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
// GridBind here
}
Resolved my issue thanks to Vignesh on suggesting of using ViewState. However I choose to use a Session variable.
Inside the sorting event handler, after the sorting is carried out I stored the sorted list in a Session Session["SortedView"] = dataView;. Now during the PageIndexChanging1 I check if this session variable is empty and use accordingly.
protected void gvOrderItems_PageIndexChanging1(object sender, GridViewPageEventArgs e)
{
gvOrderItems.PageIndex = e.NewPageIndex;
if (Session["SortedView"] != null)
{
gvOrderItems.DataSource = Session["SortedView"];
gvOrderItems.DataBind();
}
else
{
PopulateOrderList();
}
}
I have a method called gridview1_Sorting which works correctly when I click on header in table, but I want to call it automatically after the text inside search box changes and when the table change to the next from paging footer.
I think I should call this method manually from grdView_PageIndexChanging and from the method which detects checkbox state changes:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
SetSortDirection(SortDireaction);
firstTable.DefaultView.Sort = e.SortExpression + " " + _sortDirection;
DataView dv = new DataView(firstTable);
GridView1.DataSource = firstTable;
GridView1.DataBind();
SortDireaction = _sortDirection;
int columnIndex = 0;
foreach(DataControlFieldHeaderCell headerCell in GridView1.HeaderRow.Cells)
{
if (headerCell.ContainingField.SortExpression == e.SortExpression)
{
columnIndex = GridView1.HeaderRow.Cells.GetCellIndex(headerCell);
}
}
GridView1.HeaderRow.Cells[columnIndex].Controls.Add(sortImage);
}
Image sortImage = new Image();
protected void SetSortDirection(string sortDirection)
{
if (sortDirection == "Asc")
{
_sortDirection = "Desc";
sortImage.ImageUrl = "~/images/u.png";
} else
{
_sortDirection = "Asc";
sortImage.ImageUrl = "~/images/d.png";
}
}
I tried the following two options:
this.GridView1.Sorting +=
new GridViewSortEventHandler(GridView1_Sorting);
and
this.GridView1.Sorting += GridView1_Sorting;
but none seems to work.
I solve d this problem by using gridview1.sort(e.SortExpression,SortDirection.Ascending);
but I think there is another solution by firing gridview.sorting event but I cant do it
I have a gridview and I'm trying to keep the state of. Currently I have it where the user can edit inline( from within the gridview). Regularly I got this working:
protected void GridViewTower_RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
GridViewTower.EditIndex = e.NewEditIndex;
//Bind/Re-LoadData data to the GridView control.
LoadData();
Populate();
}
protected void GridViewTower_CancelEditRow(object sender, GridViewCancelEditEventArgs e)
{
//Reset the edit index.
GridViewTower.EditIndex = -1;
//Bind/Re-LoadData data to the GridView control.
LoadData();
Populate();
}
Problem is, I have 3 other features such sorting, dropdown that filters gridview, and a button search which also filters the girdview. When inline editing within any 3 of those modes, I can't control the state in which the gridview is in. Inside my gridview tag, I have both EnableViewState and ViewStateMode set to true.
How can I keep the state of the gridview within these modes?
public void LoadData()
{
if (Session["GridView"] != null)
{
GridViewTower.DataSource = Session["GridView"];
GridViewTower.DataBind();
//Response.Redirect("TowerManagement.aspx"); //
//Session["GridView"] = null;
}
else
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var tower = (from t in context.Towers
where t.isDeleted == false
select new
{
t.TowerId,
t.TowerName,
RangeName = t.Range.RangeName
}).ToList();
GridViewTower.DataSource = tower;
GridViewTower.DataBind();
ViewState["Sort"] = 0;
}
}
protected void Gridview_Sort(object sender, GridViewSortEventArgs e)
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var towers = (from t in context.Towers
where t.isDeleted == false
select new
{
t.TowerId,
t.TowerName,
rangeName = t.Range.RangeName
}).ToList();
DataTable gridviewTable = towers.CopyToDataTable();
gridviewTable.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridViewTower.DataSource = gridviewTable;
GridViewTower.DataBind();
Session["GridView"] = GridViewTower.DataSource;
}
You don't need to store whole table in the Session or ViewState. Just store values of SortExpression, SortOrder etc. Here's an example how you can do it.
In my code I have added two private properties to store sortorder and sortexpression:
private string SortOrder
{
get
{
// Toggle order after sorting
string _order = "ASC";//Default
if( ViewState["SortOrder"] != null && ViewState["SortOrder"].ToString() =="DESC")
{
_order = "DESC";
ViewState["SortOrder"] = "ASC";
}
else
{
ViewState["SortOrder"] = "DESC";
}
return _order;
}
set
{
string _order = value.ToLower() == "descending"? "DESC" : "ASC";
ViewState["SortOrder"] = _order;
}
}
private string SortExpression
{
get
{
return ViewState["SortExpression"] != null ? ViewState["SortExpression"].ToString() : "";
}
set
{
ViewState["SortExpression"] = value;
}
}
I have changed your GridView_Sort method to store the sort expression and sort order in newly added properties and called LoadData() method:
protected void Gridview_Sort(object sender, GridViewSortEventArgs e)
{
SortExpression = e.SortExpression;
//Disabled sort direction to enable toggling
//SortOrder = e.SortDirection.ToString();
LoadData();
}
The LoadData() method will be called from many places, whenever we want to load data into GridView. So I have changed it to this:
public void LoadData()
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var towers = (from t in context.Towers
where t.isDeleted == false
select new
{
t.TowerId,
t.TowerName,
rangeName = t.Range.RangeName
}).ToList();
DataTable gridviewTable = new DataTable();
gridviewTable.Columns.Add("TowerId");
gridviewTable.Columns.Add("TowerName");
gridviewTable.Columns.Add("rangeName");
foreach (var t in towers)
{
gridviewTable.Rows.Add(new object[] { t.TowerId, t.TowerName, t.rangeName });
}
if (!String.IsNullOrEmpty(SortExpression))
{
gridviewTable.DefaultView.Sort = String.Format("{0} {1}", SortExpression, SortOrder);
gridviewTable = gridviewTable.DefaultView.ToTable();
}
GridViewTower.DataSource = gridviewTable;
GridViewTower.DataBind();
}
Initially I call the LoadData() method in Page_Load() :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData();
}
}
You can download the test project here.
I created a grid view application and outside of my template I have a Add new row button. When i add a new row , it gets placed with an Edit and delete button. What I'm trying to do is when I click the add new row button, i want it to open the new row in editing mode, so no blank rows can be added with empty information. So basically if I add a new row and dont input information it wont be created.
If I need to be more thorough on my explanation please ask.
Any help will be appreciated.
Thank you
I ended up figuring out the problem on my own. It works perfect now. I as well changedup the database but I'm providing my code. Im sure there is an easier way but this was the best I could do: If you guys can provide inputs on an easier way I would appreciate it.
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert") //- this is needed to explain that the INSERT command will only work when INSERT is clicked
{
gv.DataBind();
DataTable d = dbcon.GetDataTable("SELECT * FROM CIS.CIS_TRANS ORDER BY ID DESC", "ProjectCISConnectionString");
string transCode = "", fundCode = "", BSA_CD = "", DP_TYPE = "";
if (d.Rows.Count > 0)
{
transCode = d.Rows[0]["TRANS_CD"].ToString();
fundCode = d.Rows[0]["FUND_CD"].ToString();
BSA_CD = d.Rows[0]["BSA_CD"].ToString();
DP_TYPE = d.Rows[0]["DP_TYPE"].ToString();
if (transCode.Trim().Length > 0)
{
dbcon.Execute("INSERT INTO CIS.CIS_TRANS (TRANS_CD) VALUES('')", "ProjectCISConnectionString");
gv.DataBind();
}
}
gv.EditIndex = gv.Rows.Count - 1;
}
else if (e.CommandName == "Cancel")
{
DataTable d = dbcon.GetDataTable("SELECT * FROM CIS.CIS_TRANS ORDER BY ID DESC", "ProjectCISConnectionString");
string transCode = "";
if (d.Rows.Count > 0)
{
transCode = d.Rows[0]["TRANS_CD"].ToString();
if (transCode.Trim().Length == 0)
{
dbcon.Execute(string.Format("DELETE CIS.CIS_TRANS WHERE ID = '{0}'", d.Rows[0]["ID"]), "ProjectCISConnectionString");
gv.DataBind();
}
}
}
}
This is fairly simple, once you add the row:
You need to set the edit index of the newly added row:
gv.EditIndex = gv.Rows.Count-1;
Edit for OP
This is dirty code, I am just showing you what I mean and whipped it up fairly quickly.
Assume a gridview called GridView1 on your page:
namespace HelpSO3
{
public partial class _Default : System.Web.UI.Page
{
List<string> t = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string s = "hi";
t.Add(s);
GridView1.DataSource = t;
GridView1.DataBind();
Session["MyList"] = t;
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
t = (List<string>)Session["MyList"];
t.Add("Another String");
GridView1.DataSource = t;
GridView1.DataBind();
GridView1.EditIndex = GridView1.Rows.Count - 1;
GridView1.DataBind();
Session["MyList"] = t;
}
}
}
So the Button1_Click event adds a new row with the value "Another String" then we bind the grid view and set the EditIndex value to the newest row and rebind. Its that simple.
In your case your code would become:
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert") //- this is needed to explain that the INSERT command will only work when INSERT is clicked
{
dbcon.Execute("INSERT INTO PROJ_ASP (TRANS_CD) VALUES('')", "ProjectASPConnectionString");
gv.DataBind();
gv.EditIndex = gv.Rows.Count-1;
gv.DataBind();
}
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have been trying to cure this site of SQL injection and a page I have been working on has had me stopped for 2 days.
So far I am validating user input from the client site using. RegularExpressionValidator.
On this page this is the only typed input from the user. There is also a dynamic drop down that is being verified using server-side verification.
Data from the username textbox is also being validated on the client side using Regex.
Initially I converted all of the queries to be parametrized queries. Since I have converted all of the parametrized queries to stored procedures.
Now I am at a loss on where to go next. From searching forums the mix of client-side validation and parametrized queries will generally secure against injection.
I feel like I am missing something here.
Attached is the code for the page as well as the usercontrol in c#. Any direction would be greatly appreciated!
#
<%# Control Language="C#" AutoEventWireup="true" Inherits="EPayment.AdminSite.AssignUsersUC" %>
<script runat="server" type="text/javascript" >
</script>
<div style="float:left;width:120px"><asp:Label ID="UserNameLbl" runat="server" Text="User Logon:" CssClass="label"></asp:Label></div>
<div style="float:left; height: 22px;"><asp:TextBox ID="UserNameTxt" runat="server" OnTextChanged="UserNameTxt_TextChanged"></asp:TextBox>
<asp:RegularExpressionValidator id="RegularExpressionValidator1"
ControlToValidate="userNameTxt"
ValidationExpression="[a-zA-Zs0-9]{1,40}$"
AutoPostBack="true"
Display="Static"
ErrorMessage="Username must contain only Alpha-Numeric Characters"
EnableClientScript="False"
runat="server"/>
<div style="float:left"> <asp:DropDownList ID="ddlcompany" runat="server" AutoPostBack="true" DataTextField="CompanyName" DataValueField="CompanyId" OnSelectedIndexChanged="ddlcompany_SelectedIndexChanged" >
</asp:DropDownList></div>
</div>
<br />
<div style="clear:both"><asp:Label ID="companyLbl" runat="server" Text="Company:" CssClass="label"></asp:Label> </div>
<br />
<div> <asp:Button ID="btngetroles" Text="GetRoles" runat="server" Visible="false" OnClick="btngetroles_Click" /><asp:Button ID="btngetuserobject" Text="GetUserId" runat="server" Visible="false" OnClick="btngetuserobject_Click" /></div>
<div class="sectionRow" style="width:100%;">Roles:
</div>
<br />
<div style="width:600px">
<asp:GridView ID="GV" runat="server" DataKeyNames="RoleId" AutoGenerateColumns="false" Width="100%" ShowHeader="true" ShowFooter="false"
PageSize="100" CellPadding="7">
<HeaderStyle CssClass="gridHdr" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox id="CheckBox2" runat="server" AutoPostBack="True" ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Role Description" >
<ItemTemplate >
<%#
DataBinder.Eval(Container.DataItem, "RoleDesc").ToString().Trim()
%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<br />
<div style="float:left;width:120px"><asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
<asp:Button ID="btnReset" runat="server" Text="Reset" OnClick="btnReset_Click" />
</div>
<div>
<asp:Label ID="Result" runat="server" ForeColor="red"></asp:Label></div>
#
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 EPayment.DatabaseConnectors;
using EPayment.DataObjects;
using EPayment.Common;
using ESource.Security;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using ESource.Installation;
namespace EPayment.AdminSite
{
public partial class AssignUsersUC : System.Web.UI.UserControl
{
private string ConnectionString;
protected SYUserConnector syuserconnector;
protected SYTaskConnector sytaskconnector;
protected SYRoleConnector syroleconnector;
protected SYTask sytask;
protected SYUser syuser;
protected SYRole syrole;
protected SYUtility syutility;
private DBConnString dbconn;
private string dbFilePath;
private string logFilePath;
protected TextBox UserNameTxt;
protected DropDownList ddlcompany;
protected GridView GV;
//protected TextBox UserIdtxt;
protected Label Result;
private MerchantDBConnector mConnector;
private InstallationManager dbReg;
protected void Page_Load(object sender, EventArgs e)
{
UserNameTxt.AutoPostBack = true;
syuserconnector = new SYUserConnector();
syuserconnector.SetConnection(ConnectionString);
syroleconnector = new SYRoleConnector();
syroleconnector.SetConnection(ConnectionString);
sytaskconnector = new SYTaskConnector();
sytaskconnector.SetConnection(ConnectionString);
syutility = new SYUtility();
syutility.SetConnection(ConnectionString);
syuser = new SYUser();
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt = syutility.GetSYCompanies();
ddlcompany.DataSource = dt;
ddlcompany.DataBind();
ArrayList companies = mConnector.GetGPCompanyIds();
foreach (string[] company in companies)
{
ddlcompany.SelectedIndex = -1;
ddlcompany.Items.FindByText(company[1]);
//Context.Response.Write(ddlcompany.SelectedItem.Text + "<br>");
//Context.Response.Write("Before:" + company[1] + "<br>");
//Context.Response.Write("Before Company ID:" + company[0] + "<br>");
if (ddlcompany.SelectedItem.Text.Trim() == company[1].Trim())
{
//Context.Response.Write("if:" + ddlcompany.SelectedItem.Text.Trim() + "<br>");
//Context.Response.Write("Company Name:" + company[1] + "<br>");
//Context.Response.Write("Company ID:" + company[0] + "<br>");
}
else
{
//Context.Response.Write("else:" + ddlcompany.SelectedItem.Text.Trim() + "<br>");
//Context.Response.Write("Company ID:" + company[0] + "<br>");
DBConnString epConn = new DBConnString(logFilePath, dbFilePath);
dbReg.InsertGPCompanyIntoSYCompany(epConn.StrGPServer, epConn.StrGPUser, epConn.StrGPPass, ConfigurationManager.AppSettings["EPaymentDBName"], company[0], company[1]);
//ddlcompany.Items.Add(new ListItem(company[1], company[0]));
dt = syutility.GetSYCompanies();
ddlcompany.Items.Clear();
ddlcompany.DataSource = dt;
ddlcompany.DataBind();
}
}
//ddlcompany.Items.Insert(0, new ListItem("ViewAll", "ViewAll"));
string companyname = ConfigurationManager.AppSettings["EPaymentCompanyERPId"];
string companyID = syutility.GetCompanyId(companyname);
DataView dv = new DataView();
dv = syroleconnector.GetAllRoles(companyID, 0);
GV.DataSource = dv;
GV.DataBind();
}
}
protected void btngetroles_Click(object sender, EventArgs e)
{
}
protected void ddlcompany_SelectedIndexChanged(object sender, EventArgs e)
{
Getroles();
}
protected void Page_UnLoad(object sender, EventArgs e)
{
syuserconnector.CloseConnection();
syroleconnector.CloseConnection();
sytaskconnector.CloseConnection();
syutility.CloseConnection();
syuserconnector = null;
syroleconnector = null;
sytaskconnector = null;
syutility = null;
syuser = null;
}
private void Page_Init(System.Object sender, System.EventArgs e) //Handles page_init event
{
string serverPath = Request.PhysicalApplicationPath;
dbFilePath = serverPath + "include\\dbconn.txt";
logFilePath = serverPath + "logs\\azoxlog.txt";
dbconn = new DBConnString(logFilePath, dbFilePath);
ConnectionString = dbconn.StrEPConnString;
MerchantAccount m = new MerchantAccount();
mConnector = new MerchantDBConnector(dbFilePath, logFilePath, m);
dbReg = new InstallationManager();
dbReg.UseLogFile = true;
dbReg.LogFilePath = logFilePath;
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
syuser = new SYUser();
//Regex r = new Regex("^[a-zA-Z0-9]*$");
//if (r.IsMatch(UserNameTxt.Text.Trim()))
//{
string username = UserNameTxt.Text;
string companyID = ddlcompany.SelectedItem.Value;
ArrayList companies = mConnector.GetGPCompanyIds();
//bool found = companies.Contains(companyID);
//if (found == true)
//{
string userid = syuserconnector.GetUserId(username, companyID);
if (userid != null && userid != "")
{
Result.Text = "";
//string userId = UserIdtxt.Text;
Collection<string> idsList = new Collection<string>();
foreach (GridViewRow row in GV.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("CheckBox2");
if (chk != null && chk.Checked)
{
string secId = GV.DataKeys[row.RowIndex].Value.ToString();
idsList.Add(secId);
//Response.Write("TaskId: " +secId + "<br/>");
//Response.End();
}
}
syuserconnector.UpdateUserRoles(userid, idsList);
//Start Check if user is given access to BatchProcess and add user to ep database so that sql user has access to EP_BatchReport table which is public
UserDBConnector userConn = new UserDBConnector(dbFilePath, logFilePath, new EPayment.DataObjects.User());
userConn.CreateUserLogOnForBatchReportAccess(UserNameTxt.Text);
//End
Result.Text = "Roles are Assigned to the User";
}
else
{
Result.Text = "";
syuser = new SYUser();
syuser.UserName = UserNameTxt.Text;
string companyname = ddlcompany.SelectedItem.Text;
companyID = ddlcompany.SelectedItem.Value;
syuser.CompanyId = companyID;
syuser.StoreId = 0;
syuser.CreatedBy = Session["userLogon"].ToString();
syuser.ExpireDate = DateTime.Now;
userid = syuserconnector.SaveUser(syuser);
//UserIdtxt.Text = userid;
if (userid != null && userid != "")
{
//string userId = UserIdtxt.Text;
Collection<string> idsList = new Collection<string>();
foreach (GridViewRow row in GV.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("CheckBox2");
if (chk != null && chk.Checked)
{
string secId = GV.DataKeys[row.RowIndex].Value.ToString();
idsList.Add(secId);
//Response.Write("TaskId: " +secId + "<br/>");
//Response.End();
}
}
syuserconnector.UpdateUserRoles(userid, idsList);
Result.Text = "User is Added and Roles are assigned to the User";
}
//}
//}
}
}
//else
//{
// Result.Text = "Username can only contain alpha-numeric characters. ";
//}
}
protected void btnReset_Click(object sender, EventArgs e)
{
resetAllFields();
}
private void resetAllFields()
{
//UserIdtxt.Text = "";
UserNameTxt.Text = "";
Result.Text = "";
ddlcompany.SelectedIndex = ddlcompany.Items.IndexOf(ddlcompany.Items.FindByValue("E-Payment"));
foreach (GridViewRow row in GV.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("CheckBox2");
chk.Checked = false;
}
}
protected void btngetuserobject_Click(object sender, EventArgs e)
{
}
public void Getroles()
{
if (ValidatePage() == true)
{
Page.Validate();
if (Page.IsValid)
{
string companyID = ddlcompany.SelectedItem.Value;
//ArrayList companies = mConnector.GetGPCompanyIds();
//bool found = companies.Contains(companyID);
//if (found == true)
//{
Result.Text = "";
syuserconnector.UseLogFile = true;
syuserconnector.LogFilePath = Request.PhysicalApplicationPath + "logs\\azoxlog.txt";
Collection<string> idsList = new Collection<string>();
string companyname = ddlcompany.SelectedItem.Text;
companyID = ddlcompany.SelectedItem.Value;
// string ERPcompanyId;
//string companyID = "";
//if (companyname == "Fabrikam Inc")
//{
// ERPcompanyId = "-1";
// companyID = syutility.GetCompanyId(ERPcompanyId);
//}
//else
//{
// string companyID = syutility.GetCompanyId(companyname);
//}
//Response.Write(companyID);
Regex r = new Regex("[a-zA-Z]{1,40}");
string userid;
string username = UserNameTxt.Text;
if (username != null && r.IsMatch(UserNameTxt.Text.Trim()))
{
foreach (GridViewRow row in GV.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("CheckBox2");
chk.Checked = false;
}
userid = syuserconnector.GetUserId(username, companyID);
//UserIdtxt.Text = userid;
// Response.Write("Test:" + userid);
if (userid != null && userid != "")
{
syuser = new SYUser();
syuser = syuserconnector.GetUserObject(userid);
idsList = syuser.RoleIds;
foreach (GridViewRow row in GV.Rows)
{
string rolegv = GV.DataKeys[row.RowIndex].Value.ToString();
// Response.Write(securitygv + "<br>");
CheckBox chk = (CheckBox)row.FindControl("CheckBox2");
if (syuser.RoleIds.Contains(rolegv))
{
chk.Checked = true;
}
}
}
else
{
foreach (GridViewRow row in GV.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("CheckBox2");
chk.Checked = false;
}
Result.Text = "User not in any roles for " + companyname;
}
}
//else
// {
// Result.Text = "Enter Username";
// }
//}
}
}
}
protected void UserNameTxt_TextChanged(object sender, EventArgs e)
{
//string Username = UserNameTxt.Text;
//resetAllFields();
//UserNameTxt.Text = Username;
//Page.Validate();
//if (Page.IsValid)
//{
if (ValidatePage() == true)
{
//Regex r = new Regex("[a-zA-Z0-9]*$");
//if (r.IsMatch(UserNameTxt.Text.Trim()))
//{
Getroles();
//}
}
}
protected bool ValidatePage()
{
Page.Validate();
if (Page.IsValid)
{
Regex r = new Regex("[a-zA-Z0-9]");
if (r.IsMatch(UserNameTxt.Text.Trim()))
{
return true;
}
return false;
}
return false;
}
}
}
Initially I converted all of the queries to be parametrized queries. Since I have converted all of the parametrized queries to stored procedures.
Good. Now your code is (already) safe from SQL Injection attacks. This only means that the SQL commands are "safe" from having their structure altered. However, it does not ensure that the data is valid: data-validity is determined by business rules.
Now, the client should not be trusted so, always perform data validation on the back-end. This may be in the database (constraints, triggers) or DAL or some ORM or even just the ASP code-behind (e.g. "validators"). Additionally, validation can be performed on the front-end (e.g. JavaScript); this, however, is just a "first line of defense" and a way of giving the user more useful information. Some libraries/frameworks (e.g. WCF RIA) allow a "unified" way of describing these business rules.
In any case -- it's no longer an issue of an "injection attack" so much as defining what valid data is and preventing invalid data from being accepted. (Also note that how the data is consumed later is important.)
Ok...Sql injection can be done when your application is making database calls via sql that is formed as a result of concatenated text...instead you need to use parametrized querying...
Avoid creating sql as below:
string sql = "Select * from Customer where Name = " + txtName.Text;
Instead use Parameterized queries...something like
"Select * from Customer where Name = #Name"
Hope this helps...